diff --git a/docs/AI-driver/02-auth.md b/docs/AI-driver/02-auth.md
index c284bb6e..131228cc 100644
--- a/docs/AI-driver/02-auth.md
+++ b/docs/AI-driver/02-auth.md
@@ -133,13 +133,24 @@ route does this; copy that pattern, do not let a parse throw reach the outer cat
## Private keys on the client
-- Client signing goes through `useSessionSigning` (the unified entry — the callers migrated in
- A6-T2/T3a/T3b: transfer, the eight active-class wallet operations, and the four remaining
- wallet-domain callers: claim rewards, communities, change password, recovery warning) or
- directly through `SteemSigner` (`client.ts`) for the T4 callers (market/proposals/witnesses),
- the login challenge, the recovery pages, and the two no-session-key remnants (the claim
- banner's remembered-posting-key branch and the communities hivemind setup ops — see
- 09-vault.md's "who still signs directly" inventory).
+- Client signing goes through `useSessionSigning` (the unified entry — every business
+ caller is migrated: A6-T2 transfer; A6-T3a the eight active-class wallet operations;
+ A6-T3b claim rewards, communities, change password, recovery warning; A6-T4 market limit
+ orders, proposals vote/create/remove and witness vote/proxy — all at the ACTIVE floor
+ except the documented posting/owner floors in 09-vault.md). `SteemSigner` (`client.ts`)
+ remains ONLY for the login challenge + key derivation, the recovery pages' dual-sign
+ flow, the non-signing derive/validate helpers, and the two no-session-key remnants (the
+ claim banner's remembered-posting-key branch and the communities hivemind setup ops —
+ see 09-vault.md's final "who still signs directly" inventory).
+ AUTHORITY NOTE (T4): update_proposal_votes is an ACTIVE-class Steem operation — the
+ legacy postingOps whitelist never listed it and the chain's active authority covers it —
+ so proposals votes sign at the active floor exactly like the pre-T4 active-or-owner key
+ resolution; do NOT "downgrade" it to posting.
+ LOGIN-DIALOG CONTRACT (T4): the market / proposals / witnesses embedded sign-in dialogs
+ pass `requiredAuthTypes: ['active']` with NO fixedUsername (session-account pages:
+ unauthenticated visitors may log in as any account), so a privateKey login is fit for
+ purpose the first time; the account-pinned classic re-auth dialogs (every caller's
+ `needsClassicReauth` surface) keep `fixedUsername` + `requiredAuthTypes`.
CHANGE-PASSWORD KEY SOURCE (T3b): the account_update signs with the SESSION
owner key, not the owner WIF the form's account password used to derive —
a privateKey session without an owner key gets the `ownerKeySessionRequired`
diff --git a/docs/AI-driver/06-frontend.md b/docs/AI-driver/06-frontend.md
index 246292f4..10dd186d 100644
--- a/docs/AI-driver/06-frontend.md
+++ b/docs/AI-driver/06-frontend.md
@@ -88,11 +88,15 @@ canonical lowercase.
`useSessionSigning` (09-vault.md module map): it applies this lowest-at-or-above-the-floor
rule for privateKey sessions itself (posting → active → owner for a posting floor, active →
owner for an active floor) and routes vault identity sessions through the per-key password
- dialog. After A6-T3b every wallet-domain caller is on it (transfer pilot + the eight
- active-class ops + claim / communities / change-password / recovery-warning); the remaining
- direct signers are the T4 market/proposals/witnesses callers, the two no-session-key
+ dialog. After A6-T4 EVERY business signing caller is on it (transfer pilot + the eight
+ active-class ops + claim / communities / change-password / recovery-warning + the five
+ T4 callers — market limit orders, proposals vote/create/remove, witness vote/proxy —
+ EACH of the five T4 callers at the ACTIVE floor; the earlier callers' posting/owner
+ floors are the documented exceptions in 09-vault.md's A6 progress note); the only
+ remaining direct signers are the two no-session-key
remnants (claim remembered-key branch, communities hivemind setup ops) and the permanent
- login-challenge/recovery paths — see 09-vault.md's "who still signs directly" inventory.
+ login-challenge/recovery paths — see 09-vault.md's final "who still signs directly"
+ inventory.
## Legacy-parity watchlist (verified drifts from `wallet-legacy`)
diff --git a/docs/AI-driver/09-vault.md b/docs/AI-driver/09-vault.md
index 5e189f26..64fd93c5 100644
--- a/docs/AI-driver/09-vault.md
+++ b/docs/AI-driver/09-vault.md
@@ -22,10 +22,12 @@
> encryption), and the R3 vault identity login (mode-dispatched login form,
> two-select identity picker over the public directory, key-free
> `sessionKind: 'vault'` sessions).
-> Not implemented: the REMAINING A6 caller migration (T3b: claim /
-> communities / change-password / recovery-warning; T4: market / proposals /
-> witnesses — signing with a vault identity for the wallet operations landed
-> in A6-T2/T3a) and the B-phase dapp — this doc grows with each task package.
+> Not implemented: the B-phase dapp. The A6 caller migration is COMPLETE
+> (T2 transfer pilot; T3a the eight active-class wallet ops; T3b claim /
+> communities / change-password / recovery-warning; T4 market / proposals /
+> witnesses) — every business signing caller now routes through
+> `useSessionSigning` except the documented permanent exceptions (see the
+> A6 progress note's final "who still signs directly" inventory).
## Module map
@@ -226,8 +228,11 @@ src/hooks/use-session-signing.tsx A6-T2 unified consumer signing entry — the
the pilot; A6-T3a migrated the eight wallet-op
callers; A6-T3b migrated claim-rewards-banner,
communities-section, change-password-section and
- recovery-warning-banner; T4 = market/proposals/
- witnesses): `sign({ operations,
+ recovery-warning-banner; A6-T4 migrated the last
+ five: market-page-client limit orders,
+ proposals-page-client votes,
+ proposal-creator-dialog, proposal-remove-dialog
+ and witness-vote-form): `sign({ operations,
accountName, role })` → discriminated outcome
`signed` (SignResult) | `cancelled` | `needsClassicReauth`
(privateKey session lacks a key at-or-above the floor
@@ -305,26 +310,37 @@ src/components/vault/work-mode-events.ts R3 leaf module holding
-> login form -> vault login form -> layout)
src/components/auth/login-form.tsx R3 MODE DISPATCHER (`LoginForm`): reads the
persisted signing mode via useVaultRuntime +
- useSigningMode. 'vault' -> VaultLoginForm; 'vault' +
- embedded re-auth (fixedUsername / requiredAuthTypes)
- -> explicit "not available in Vault Mode yet" notice
- + Work Mode shortcut. A6-T3a narrowing: the notice now
- covers only the consumers whose callers have NOT
- migrated to useSessionSigning (witness vote and claim
- rewards until T3b/T4; the permissions key reveal
- permanently — showing the raw WIF can never be served
- by the signing path). Since A6-T3a NO wallet-action
- re-auth gate fires for a page-matching vault session
- (wallet-transfers-modals hands it every hosted form
- directly); the migrated wallet forms' own in-form
- re-auth dialogs (delegate / power up / power down)
- remain as the defensive path for the divergent
- mode/session edge (a privateKey session that lost its
- key); EVERY other state (privateKey, mode still
- loading, failed read, runtime unavailable, no
- provider) -> the module-private PrivateKeyLoginForm,
- whose body is byte-identical to the pre-R3 LoginForm
- (the R3 diff is insert-only)
+ useSigningMode. 'vault' -> VaultLoginForm — including
+ embedded dialogs that only declare
+ `requiredAuthTypes` (the market / proposals /
+ witnesses sign-in dialogs since A6-T4: the floor
+ applies to the privateKey branch, and after identity
+ login the per-action password dialog enforces it);
+ 'vault' + embedded ACCOUNT-PINNED re-auth
+ (`fixedUsername`) -> explicit "not available in
+ Vault Mode yet" notice + Work Mode shortcut. A6-T4
+ narrowing: `requiredAuthTypes` alone no longer
+ triggers the notice — identity selection + the
+ per-key password path CAN satisfy an authority
+ floor, so the notice is reserved for account-pinned
+ re-auth (a privateKey session that needs ITS
+ account's key back; identity selection would switch
+ accounts). The permissions key reveal keeps the
+ notice PERMANENTLY — showing the raw WIF can never
+ be served by the signing path. Since A6-T3a NO
+ wallet-action re-auth gate fires for a page-matching
+ vault session (wallet-transfers-modals hands it
+ every hosted form directly); the migrated wallet
+ forms' own in-form re-auth dialogs (delegate / power
+ up / power down / market / proposals / creator /
+ remove / witness) remain as the defensive path for
+ the divergent mode/session edge (a privateKey
+ session that lost its key); EVERY other state
+ (privateKey, mode still loading, failed read,
+ runtime unavailable, no provider) -> the
+ module-private PrivateKeyLoginForm, whose body is
+ byte-identical to the pre-R3 LoginForm (the R3 diff
+ is insert-only)
src/components/auth/vault-login-form.tsx R3 identity selection: two NATIVE
selects — vaults (manager.listVaults) and the
selected vault's account names (manager.getAccounts,
@@ -770,19 +786,25 @@ the V1 hierarchical shape and its non-negotiable rules. The type contracts in
default; login must not hard-depend on IndexedDB). Inside Vault Mode the
reverse holds: storage errors show mapped errors + Retry, never a silent
PrivateKey fallback.
- - Embedded re-auth callers (`fixedUsername` / `requiredAuthTypes`) cannot
- be satisfied by identity selection and get an explicit "not available
- in Vault Mode yet" notice with a Work Mode shortcut. Since A6-T2 the
- notice is the TEMPORARY state of consumers whose callers have not been
- migrated to useSessionSigning (witness vote remains, T4; the
- permissions key reveal stays PERMANENTLY — it needs the raw WIF
- displayed, which the signing path never exposes); since A6-T3a NO
+ - Embedded ACCOUNT-PINNED re-auth callers (`fixedUsername`) cannot be
+ satisfied by identity selection (it would switch accounts) and get an
+ explicit "not available in Vault Mode yet" notice with a Work Mode
+ shortcut. Since A6-T4 `requiredAuthTypes` ALONE no longer triggers the
+ notice: the market / proposals / witnesses sign-in dialogs declare the
+ active floor for the PRIVATEKEY branch while Vault Mode keeps identity
+ selection — the per-key password path enforces the floor after login,
+ so identity selection IS fit for purpose for vault mode now. The
+ permissions key reveal keeps the notice PERMANENTLY (it needs the raw
+ WIF displayed, which the signing path never exposes). Since A6-T3a NO
wallet-action re-auth gate fires for a page-matching vault session
(wallet-transfers-modals shows every hosted form directly — transfer,
power up/down, cancel power down, delegate, withdraw routes, convert —
- and each form signs through the per-key password path), and since A6-T3b
+ and each form signs through the per-key password path); since A6-T3b
the claim-rewards banner's re-auth dialog is likewise unreachable for a
- vault session (the claim signs through the password path directly).
+ vault session; since A6-T4 the witness-vote login dialog (which used to
+ conditionally pin `fixedUsername` and could surface the notice) opens
+ only for unauthenticated visitors and no T4 surface reaches the notice
+ for an authenticated vault session.
Migrating a caller = routing its action through useSessionSigning and
dropping its notice reachability — never a silently degraded form.
- The claim-rewards banner's device-remembered posting-key restore
@@ -804,19 +826,23 @@ the V1 hierarchical shape and its non-negotiable rules. The type contracts in
form may READ the remembered USERNAME to prefill (no key read, no
write); (b) a successful change-password clears the remembered posting
key because the chain just invalidated it — a removal, never a borrow.
- - Known UX gaps still open (no key exposure; T4 will close them): the
- `delegate-form` "Not authenticated" dead-end for a keyless vault session
- CLOSED in A6-T3a (with the seven other wallet-op callers — see the A6
- progress note below; the transfer-form's copy of that gap CLOSED in
- A6-T2); the claim-rewards / communities / change-password /
+ - Known UX gaps: NONE left for vault sessions. The historical list, all
+ CLOSED: the `delegate-form` "Not authenticated" dead-end for a keyless
+ vault session CLOSED in A6-T3a (with the seven other wallet-op callers
+ — see the A6 progress note below; the transfer-form's copy of that gap
+ CLOSED in A6-T2); the claim-rewards / communities / change-password /
recovery-warning vault gaps (keyless notice or dead gate) CLOSED in
A6-T3b — the claim banner's "skip restore → re-auth dialog →
vaultUnsupported notice" chain is gone and each of the four callers
- signs through the per-key password path; login dialogs opened from the
- market and proposals pages pass
- neither `fixedUsername` nor `requiredAuthTypes`, so in Vault Mode they
- show identity selection and a later order/vote finds no key and reopens
- the dialog.
+ signs through the per-key password path; the market / proposals /
+ witnesses gap CLOSED in A6-T4 — those sign-in dialogs now declare
+ `requiredAuthTypes: ['active']` (every action on the three pages is
+ active-class) without pinning a username, Vault Mode keeps identity
+ selection there, and an authenticated vault session orders / votes /
+ creates / removes / witness-votes straight through the per-key password
+ path instead of reopening the login dialog. The one PERMANENT notice
+ consumer is the permissions key reveal (raw WIF display — outside the
+ signing path by design).
## Error taxonomy (17 codes, types.ts order)
@@ -1020,19 +1046,22 @@ into, or changePassword on, a vault with zero key ciphertext).
login). `HomeRedirectOrLogin` instead WAITS for the mode before its
Legacy remembered-username jump (so a vault user is never redirected by
PrivateKey-era device data) and skips the jump entirely in Vault Mode.
- - Embedded re-auth (`fixedUsername` / `requiredAuthTypes`) + Vault Mode =
+ - Embedded ACCOUNT-PINNED re-auth (`fixedUsername`) + Vault Mode =
the explicit `vaultUnsupported*` notice with a Work Mode shortcut —
chosen over "silently guide to identity selection" because identity
- selection cannot satisfy an authority requirement. Status after A6-T3b:
- the TRANSFER re-auth gate no longer reaches the notice (a vault session
- gets the form directly and signs through the per-key password path);
- the CLAIM-REWARDS re-auth dialog likewise retired in A6-T3b (a vault
- session claims through the password path); the witness-vote notice
- retires when that caller migrates to `useSessionSigning` (T4); the
- permissions key-reveal
- notice stays PERMANENTLY (revealing a key must display the raw WIF,
+ selection would switch accounts and cannot hand a specific session its
+ key back. Since A6-T4 `requiredAuthTypes` ALONE no longer triggers the
+ notice: the market / proposals / witnesses sign-in dialogs declare the
+ active floor for the privateKey branch while Vault Mode keeps identity
+ selection (the per-action password dialog enforces the floor after
+ login). Final status after A6-T4: NO business-action surface reaches
+ the notice for an authenticated vault session; the only remaining
+ consumers are the account-pinned re-auth dialogs' divergent
+ mode/session edge (a privateKey session that lost its key while the
+ device mode says vault) and the permissions key-reveal notice, which
+ stays PERMANENTLY (revealing a key must display the raw WIF,
which the signing path never exposes). Plain embedded usage
- (header / market / proposals login modals) already gets VaultLoginForm.
+ (header / market / proposals login modals) gets VaultLoginForm.
- `sessionKind` is OPTIONAL on `AuthState` (absent = 'privateKey') so every
pre-R3 AuthState value stays valid; read it via `sessionKindOf`.
- `VAULT_WORK_MODE_OPEN_EVENT` (and the new `VAULT_WORK_MODE_CLOSED_EVENT`)
@@ -1051,7 +1080,8 @@ into, or changePassword on, a vault with zero key ciphertext).
no-vault / empty-vault / unsupported copy) plus `vault.verifyAuthorityDiffers`
(R2 batch), all four locales.
- **A6 progress — the vault-session signing path EXISTS (A6-T2 pilot +
- A6-T3a wallet-ops batch + A6-T3b remaining wallet callers)** — the
+ A6-T3a wallet-ops batch + A6-T3b remaining wallet callers + A6-T4
+ market/proposals/witnesses) and the caller migration is COMPLETE** — the
privateKey backend has been wired into the facade since A6-T1
(`vault-manager.tsx` composes
`createLegacyPrivateKeySigner(createSessionKeyGetter())`, which reads the
@@ -1082,7 +1112,21 @@ into, or changePassword on, a vault with zero key ciphertext).
master password) now gets explicit re-authenticate guidance instead of the
old silent success with the form-derived owner key — re-authenticating
with the master password or owner WIF derives the very same owner key, so
- the signed transaction is unchanged once the session holds it. Every
+ the signed transaction is unchanged once the session holds it. A6-T4
+ migrated the LAST five business callers (market-page-client
+ limit_order_create/limit_order_cancel, proposals-page-client
+ update_proposal_votes, proposal-creator-dialog create_proposal,
+ proposal-remove-dialog remove_proposal, witness-vote-form
+ account_witness_vote/account_witness_proxy) — all ACTIVE-floor (NOTE:
+ update_proposal_votes is active-class on Steem, matching the pre-T4
+ active-or-owner key resolution and the legacy postingOps whitelist which
+ never listed it), byte-identical tuples, each caller's action gate widened
+ to "authenticated session" (vault sessions act through the password
+ dialog; the witness login dialog's conditional fixedUsername — the last
+ business `vaultUnsupported` notice reachability — retired), and the
+ market/proposals/witnesses sign-in dialogs now declare
+ `requiredAuthTypes: ['active']` so a privateKey login is fit for purpose
+ the first time. Every
privateKey path signs through the hook's STATIC
legacy signer — NO pre-check, NO extra network calls, and NO
vault-runtime/IndexedDB dependency, a round-1-review hard contract; every
@@ -1090,15 +1134,20 @@ into, or changePassword on, a vault with zero key ciphertext).
`wallet-transfers-modals` hands a page-matching vault session EVERY
wallet action directly (the classic re-auth gate stays for mismatched
sessions and keyless privateKey sessions).
- Direct `SteemSigner` consumers after A6-T3b (the "who still signs
- directly" inventory): T4 = market-page-client (limit order create/cancel),
- proposals-page-client / proposal-creator-dialog / proposal-remove-dialog,
- witness-vote-form; PERMANENT/deliberate = login-form (challenge + key
- derivation), the two recovery pages (`signRecoverAccount` dual-sign —
- invariant 20), account-keys.ts + change-password.ts validation helpers
- (non-signing), claim-rewards-banner's remembered-key branch and
+ Direct `SteemSigner` consumers after A6-T4 — FINAL "who still signs
+ directly" inventory, no business callers remain: PERMANENT/deliberate =
+ login-form (challenge + key derivation), the two recovery pages
+ (`signRecoverAccount` dual-sign — invariant 20),
+ recover-account-step-1-page verify helpers + account-keys.ts +
+ change-password.ts validation helpers (derive/validate only, never
+ broadcast), claim-rewards-banner's remembered-key branch and
communities-section's hivemind setup ops (keys that exist in no session —
- see the module map note under use-session-signing). Never build a signer
+ see the module map note under use-session-signing). The seven T4 builders
+ (`signLimitOrderCreate` / `signLimitOrderCancel` /
+ `signUpdateProposalVotes` / `signCreateProposal` / `signRemoveProposal` /
+ `signWitnessVote` / `signWitnessProxy`) now have NO production callers —
+ deleting them (with the rest of the retired builder batch) is a separate
+ cleanup decision. Never build a signer
at a component; never query `/api/query/accounts` outside the vault
signer.
(b) R3 vault sessions (`sessionKind: 'vault'`, zero keys in Redux) sign per
diff --git a/src/components/auth/login-form.tsx b/src/components/auth/login-form.tsx
index e6a7ed0a..e2afea2d 100644
--- a/src/components/auth/login-form.tsx
+++ b/src/components/auth/login-form.tsx
@@ -61,13 +61,20 @@ export interface LoginFormProps {
* Mode dispatcher (R3) — decides WHICH login surface the persisted signing
* mode (settings row, default `'privateKey'`) gets:
*
- * - `'vault'` + plain usage -> VaultLoginForm (identity selection);
- * - `'vault'` + embedded caller that pins an account or requires specific
- * authorities (`fixedUsername` / `requiredAuthTypes` — the re-auth
- * dialogs) -> an explicit "not available in Vault Mode yet" notice with a
- * shortcut to the Work Mode modal. Identity selection cannot satisfy a
- * per-key authority requirement; the real path is the per-key password +
- * signing flow that A6 wires. Deliberately LOUD, never a silent swap.
+ * - `'vault'` + plain usage, including embedded dialogs that only declare
+ * `requiredAuthTypes` (the market / proposals / witnesses "sign in to
+ * trade / vote" dialogs since A6-T4) -> VaultLoginForm (identity
+ * selection). The declared authority is NOT checked at identity-selection
+ * time: after login the caller's action goes through `useSessionSigning`,
+ * whose per-key password dialog offers exactly the keys at-or-above the
+ * action's role floor — identity selection IS fit for purpose for vault
+ * mode now.
+ * - `'vault'` + embedded caller that PINS an account (`fixedUsername` — the
+ * account-locked re-auth dialogs) -> an explicit "not available in Vault
+ * Mode yet" notice with a shortcut to the Work Mode modal. An account-
+ * pinned re-auth means a privateKey session needs ITS account's key back;
+ * identity selection would switch accounts and cannot serve that.
+ * Deliberately LOUD, never a silent swap.
* - everything else -> PrivateKeyLoginForm below.
*
* The PrivateKey branch must stay byte-identical in behavior: when the mode
@@ -82,7 +89,7 @@ export interface LoginFormProps {
* surface storage errors with Retry instead of quietly showing this form.
*/
export function LoginForm(props: LoginFormProps = {}) {
- const { embedded = false, fixedUsername, requiredAuthTypes } = props;
+ const { embedded = false, fixedUsername } = props;
const runtime = useVaultRuntime();
const { mode } = useSigningMode(runtime.state === 'ready' ? runtime.facade : null);
@@ -90,9 +97,10 @@ export function LoginForm(props: LoginFormProps = {}) {
return ;
}
- // Embedded re-auth consumers pin an account and/or require key authorities
- // that identity selection cannot provide (A6 wires the real path).
- if (embedded && (fixedUsername !== undefined || (requiredAuthTypes?.length ?? 0) > 0)) {
+ // Embedded account-pinned re-auth cannot be satisfied by identity
+ // selection (it would switch accounts); `requiredAuthTypes` alone CAN —
+ // the per-action password dialog enforces the floor after login (A6-T4).
+ if (embedded && fixedUsername !== undefined) {
return ;
}
@@ -100,10 +108,11 @@ export function LoginForm(props: LoginFormProps = {}) {
}
/**
- * Explicit dead-end for embedded re-auth dialogs while the device is in Vault
- * Mode: states that this flow needs a specific key authority, which identity
- * selection cannot satisfy yet, and offers the Work Mode modal to switch back
- * to PrivateKey Mode. Never renders a silently-degraded form.
+ * Explicit dead-end for embedded ACCOUNT-PINNED re-auth dialogs while the
+ * device is in Vault Mode: states that this flow needs this account's key
+ * back, which identity selection (a different login model that would switch
+ * accounts) cannot satisfy, and offers the Work Mode modal to switch back to
+ * PrivateKey Mode. Never renders a silently-degraded form.
*/
function VaultModeUnsupportedNotice() {
const t = useTranslations('auth');
diff --git a/src/components/market/market-page-client.tsx b/src/components/market/market-page-client.tsx
index 4cd3cd4e..44db2971 100644
--- a/src/components/market/market-page-client.tsx
+++ b/src/components/market/market-page-client.tsx
@@ -4,7 +4,8 @@ import { Suspense, useCallback, useState } from 'react';
import { useTranslations } from 'next-intl';
import { LoginForm } from '@/components/auth/login-form';
import { toast } from 'sonner';
-import { useAuth, useActiveSigningKey } from '@/hooks/use-auth';
+import { useAuth } from '@/hooks/use-auth';
+import { useSessionSigning } from '@/hooks/use-session-signing';
import { useMarketData } from '@/hooks/use-market-data';
import { useSteemAccount } from '@/hooks/use-steem-account';
import { MarketDepthChart } from '@/components/market/market-depth-chart';
@@ -28,22 +29,31 @@ import {
} from '@/lib/market/constants';
import { formatAssetAmount } from '@/lib/market/utils';
import { nextMarketOrderId } from '@/lib/market/order-id';
+import { unixSecToSteemIsoTimestamp } from '@/lib/steem/chain-time';
import { invalidateWalletCache } from '@/lib/cache/client-invalidate';
-import { apiClient, SteemSigner } from '@/lib/steem/client';
+import { apiClient } from '@/lib/steem/client';
+import type { Operation } from '@/lib/steem/types';
export function MarketPageClient() {
const t = useTranslations('wallet.marketPage');
const tAuth = useTranslations('auth');
+ const tWallet = useTranslations('wallet');
const { username, isAuthenticated } = useAuth();
- const activeKey = useActiveSigningKey();
+ // Unified signing entry (A6-T4): privateKey sessions sign through the
+ // facade's legacy backend exactly as before (active key, owner fallback);
+ // vault identity sessions get the per-key password dialog. `signing.dialog`
+ // mounts it.
+ const signing = useSessionSigning();
const { data: account } = useSteemAccount(username ?? '');
const { orderbook, ticker, history, openOrders, loading, error, refresh } =
useMarketData(username);
const [cancellingId, setCancellingId] = useState(null);
const [selectedPrice, setSelectedPrice] = useState(null);
const [loginOpen, setLoginOpen] = useState(false);
+ /** Classic re-auth for a privateKey session that lacks an active/owner key. */
+ const [reauthOpen, setReauthOpen] = useState(false);
- const canTrade = isAuthenticated && !!username && !!activeKey;
+ const canTrade = isAuthenticated && !!username;
const placeOrder = useCallback(
async (
@@ -56,7 +66,7 @@ export function MarketPageClient() {
marketRefPrice: number;
}
) => {
- if (!username || !activeKey) {
+ if (!username) {
toast.error(t('signInToTrade'));
setLoginOpen(true);
return;
@@ -93,16 +103,50 @@ export function MarketPageClient() {
const expiration = Math.floor(Date.now() / 1000) + DEFAULT_LIMIT_ORDER_EXPIRATION_SEC;
try {
- const signedTx = await SteemSigner.signLimitOrderCreate(
- username,
- amountToSell,
- minToReceive,
- orderid,
- expiration,
- activeKey
- );
+ // The exact operation tuple SteemSigner.signLimitOrderCreate built
+ // internally — field order, fill_or_kill default and the ISO
+ // expiration conversion (condenser_api expects a time_point_sec
+ // string, not unix seconds) are byte-identical.
+ const operations: Operation[] = [
+ [
+ 'limit_order_create',
+ {
+ owner: username,
+ amount_to_sell: amountToSell,
+ min_to_receive: minToReceive,
+ fill_or_kill: false,
+ expiration: unixSecToSteemIsoTimestamp(expiration),
+ orderid,
+ },
+ ],
+ ];
+
+ // limit_order_create is an active-class operation.
+ const outcome = await signing.sign({
+ operations,
+ accountName: username,
+ role: 'active',
+ });
+
+ if (outcome.status === 'cancelled') {
+ // User aborted the vault dialog — back to the form, no error.
+ return;
+ }
+ if (outcome.status === 'needsClassicReauth') {
+ // privateKey session without an active/owner key: the classic
+ // re-auth dialog locked to this account.
+ setReauthOpen(true);
+ return;
+ }
+ if (outcome.status === 'error') {
+ toast.error(t('orderFailed'));
+ return;
+ }
- const res = await apiClient.broadcastLimitOrderCreate(signedTx, username);
+ const res = await apiClient.broadcastLimitOrderCreate(
+ outcome.result.signedTx,
+ username
+ );
if (!res.success) {
toast.error(res.error ?? t('orderFailed'));
return;
@@ -120,17 +164,44 @@ export function MarketPageClient() {
toast.error(t('orderFailed'));
}
},
- [username, activeKey, t, refresh]
+ [username, t, refresh, signing]
);
const cancelOrder = useCallback(
async (orderid: number) => {
- if (!username || !activeKey) return;
+ if (!username) return;
if (!window.confirm(t('cancelConfirm', { orderId: orderid, user: username }))) return;
setCancellingId(orderid);
try {
- const signedTx = await SteemSigner.signLimitOrderCancel(username, orderid, activeKey);
- const res = await apiClient.broadcastLimitOrderCancel(signedTx, username);
+ // The exact operation tuple SteemSigner.signLimitOrderCancel built.
+ const operations: Operation[] = [
+ ['limit_order_cancel', { owner: username, orderid }],
+ ];
+
+ // limit_order_cancel is an active-class operation.
+ const outcome = await signing.sign({
+ operations,
+ accountName: username,
+ role: 'active',
+ });
+
+ if (outcome.status === 'cancelled') {
+ // User aborted the vault dialog — release the spinner, no error.
+ return;
+ }
+ if (outcome.status === 'needsClassicReauth') {
+ setReauthOpen(true);
+ return;
+ }
+ if (outcome.status === 'error') {
+ toast.error(t('orderFailed'));
+ return;
+ }
+
+ const res = await apiClient.broadcastLimitOrderCancel(
+ outcome.result.signedTx,
+ username
+ );
if (!res.success) {
toast.error(res.error ?? t('orderFailed'));
return;
@@ -147,7 +218,7 @@ export function MarketPageClient() {
setCancellingId(null);
}
},
- [username, activeKey, t, refresh]
+ [username, t, refresh, signing]
);
return (
@@ -182,11 +253,47 @@ export function MarketPageClient() {
}
>
- setLoginOpen(false)} />
+ {/* Unauthenticated visitors may log in as any account; the
+ active-authority requirement keeps a privateKey login fit for
+ trading the first time (limit orders are active-class). In
+ Vault Mode this dialog still offers identity selection — the
+ per-action password dialog enforces the floor after login. */}
+ setLoginOpen(false)}
+ />
+
+
+ {signing.dialog}
+
{error && (
{error}
diff --git a/src/components/proposals-page-client.tsx b/src/components/proposals-page-client.tsx
index f4c04334..e8d3adbe 100644
--- a/src/components/proposals-page-client.tsx
+++ b/src/components/proposals-page-client.tsx
@@ -4,7 +4,8 @@ import { Suspense, useMemo, useState } from 'react';
import { useTranslations } from 'next-intl';
import Link from 'next/link';
import { toast } from 'sonner';
-import { useAuth, useActiveSigningKey } from '@/hooks/use-auth';
+import { useAuth } from '@/hooks/use-auth';
+import { useSessionSigning } from '@/hooks/use-session-signing';
import { useProposals } from '@/hooks/use-proposals';
import { useProposalsMeta } from '@/hooks/use-proposals-meta';
import { LoginForm } from '@/components/auth/login-form';
@@ -31,8 +32,8 @@ import {
DialogTitle,
} from '@/components/ui/dialog';
import { cn } from '@/lib/utils';
-import { apiClient, SteemSigner } from '@/lib/steem/client';
-import type { Proposal, ProposalOrderBy, ProposalStatus } from '@/lib/steem/types';
+import { apiClient } from '@/lib/steem/client';
+import type { Operation, Proposal, ProposalOrderBy, ProposalStatus } from '@/lib/steem/types';
import { parseSteemAsset } from '@/lib/steem/parse-asset';
import { sameSteemAccount } from '@/lib/steem/username';
import {
@@ -234,9 +235,15 @@ function ProposalRow({
export function ProposalsPageClient() {
const t = useTranslations('wallet.proposalsPage');
const tAuth = useTranslations('auth');
+ const tWallet = useTranslations('wallet');
const { username, isAuthenticated } = useAuth();
- const activeKey = useActiveSigningKey();
+ // Unified signing entry (A6-T4): privateKey sessions sign through the
+ // facade's legacy backend exactly as before (active key, owner fallback);
+ // vault identity sessions get the per-key password dialog.
+ const signing = useSessionSigning();
const [loginOpen, setLoginOpen] = useState(false);
+ /** Classic re-auth for a privateKey session that lacks an active/owner key. */
+ const [reauthOpen, setReauthOpen] = useState(false);
const [votingId, setVotingId] = useState(null);
const [searchTerm, setSearchTerm] = useState('');
const [createOpen, setCreateOpen] = useState(false);
@@ -274,10 +281,10 @@ export function ProposalsPageClient() {
[proposals, searchTerm]
);
- const canVote = isAuthenticated && !!username && !!activeKey;
+ const canVote = isAuthenticated && !!username;
const onVoteToggle = async (proposalId: number, approve: boolean) => {
- if (!username || !activeKey) {
+ if (!username) {
toast.error(t('signInToVote'));
setLoginOpen(true);
return;
@@ -291,13 +298,39 @@ export function ProposalsPageClient() {
setProposalVotedLocally(proposalId, approve);
const rollback = () => setProposalVotedLocally(proposalId, !approve);
try {
- const signedTx = await SteemSigner.signUpdateProposalVotes(
- username,
- [proposalId],
- approve,
- activeKey
- );
- const res = await apiClient.broadcastProposalVote(signedTx, username);
+ // The exact operation tuple SteemSigner.signUpdateProposalVotes built
+ // internally. update_proposal_votes is an ACTIVE-class operation on
+ // Steem (the legacy postingOps whitelist never included it and the
+ // chain's active authority covers it), so the floor stays 'active'.
+ const operations: Operation[] = [
+ ['update_proposal_votes', { voter: username, proposal_ids: [proposalId], approve }],
+ ];
+
+ const outcome = await signing.sign({
+ operations,
+ accountName: username,
+ role: 'active',
+ });
+
+ if (outcome.status === 'cancelled') {
+ // User aborted the vault dialog — roll the optimistic flip back, no error.
+ rollback();
+ return;
+ }
+ if (outcome.status === 'needsClassicReauth') {
+ // privateKey session without an active/owner key: the classic re-auth
+ // dialog locked to this account.
+ rollback();
+ setReauthOpen(true);
+ return;
+ }
+ if (outcome.status === 'error') {
+ rollback();
+ toast.error(t('voteFailed'));
+ return;
+ }
+
+ const res = await apiClient.broadcastProposalVote(outcome.result.signedTx, username);
if (!res.success) {
rollback();
toast.error(res.error ?? t('voteFailed'));
@@ -442,7 +475,7 @@ export function ProposalsPageClient() {
-
+
+
+
+
+ {signing.dialog}
+ >
);
}
diff --git a/src/components/proposals/proposal-remove-dialog.tsx b/src/components/proposals/proposal-remove-dialog.tsx
index 49ee9c6f..a16c7e47 100644
--- a/src/components/proposals/proposal-remove-dialog.tsx
+++ b/src/components/proposals/proposal-remove-dialog.tsx
@@ -13,9 +13,11 @@ import {
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
-import { apiClient, SteemSigner } from '@/lib/steem/client';
+import { LoginForm } from '@/components/auth/login-form';
+import { apiClient } from '@/lib/steem/client';
import { normalizeSteemUsername } from '@/lib/steem/username';
-import { useActiveSigningKey } from '@/hooks/use-auth';
+import { useSessionSigning } from '@/hooks/use-session-signing';
+import type { Operation } from '@/lib/steem/types';
type ProposalRemoveDialogProps = {
open: boolean;
@@ -35,15 +37,21 @@ export function ProposalRemoveDialog({
onNeedLogin,
}: ProposalRemoveDialogProps) {
const t = useTranslations('wallet.proposalsPage');
- const activeKey = useActiveSigningKey();
+ const tWallet = useTranslations('wallet');
+ // Unified signing entry (A6-T4): privateKey sessions sign through the
+ // facade's legacy backend exactly as before; vault identity sessions get
+ // the per-key password dialog.
+ const signing = useSessionSigning();
const [confirmId, setConfirmId] = useState('');
const [submitting, setSubmitting] = useState(false);
+ /** Classic re-auth for a privateKey session that lacks an active/owner key. */
+ const [reauthOpen, setReauthOpen] = useState(false);
const idMatches = confirmId.trim() === String(proposalId);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
- if (!username || !activeKey) {
+ if (!username) {
onNeedLogin();
return;
}
@@ -59,8 +67,34 @@ export function ProposalRemoveDialog({
// submit site normalizes again as defense-in-depth — mirrors
// proposal-creator-dialog (#341 residual).
const ownerName = normalizeSteemUsername(username);
- const signedTx = await SteemSigner.signRemoveProposal(ownerName, [proposalId], activeKey);
- const res = await apiClient.broadcastProposalRemove(signedTx, username);
+ // The exact operation tuple SteemSigner.signRemoveProposal built
+ // internally. remove_proposal is an active-class operation.
+ const operations: Operation[] = [
+ ['remove_proposal', { proposal_owner: ownerName, proposal_ids: [proposalId] }],
+ ];
+
+ const outcome = await signing.sign({
+ operations,
+ accountName: username,
+ role: 'active',
+ });
+
+ if (outcome.status === 'cancelled') {
+ // User aborted the vault dialog — back to the form, no error.
+ return;
+ }
+ if (outcome.status === 'needsClassicReauth') {
+ // privateKey session without an active/owner key: the classic re-auth
+ // dialog locked to this account.
+ setReauthOpen(true);
+ return;
+ }
+ if (outcome.status === 'error') {
+ toast.error(t('removeFailed'));
+ return;
+ }
+
+ const res = await apiClient.broadcastProposalRemove(outcome.result.signedTx, username);
if (!res.success) {
toast.error(res.error ?? t('removeFailed'));
return;
@@ -77,8 +111,9 @@ export function ProposalRemoveDialog({
};
return (
-
+
+
+
+
+ {tWallet('reauthTitle')}
+ {tWallet('reauthDescription')}
+
+ setReauthOpen(false)}
+ />
+
+
+
+ {signing.dialog}
+ >
);
}
diff --git a/src/components/wallet/witness-vote-form.tsx b/src/components/wallet/witness-vote-form.tsx
index a8db4108..96f6642e 100644
--- a/src/components/wallet/witness-vote-form.tsx
+++ b/src/components/wallet/witness-vote-form.tsx
@@ -4,10 +4,11 @@ import { Suspense, useCallback, useEffect, useMemo, useRef, useState, useTransit
import { useTranslations } from 'next-intl';
import { useSelector } from 'react-redux';
import type { RootState } from '@/lib/store';
-import { useActiveSigningKey, useAuth } from '@/hooks/use-auth';
+import { useAuth } from '@/hooks/use-auth';
+import { useSessionSigning } from '@/hooks/use-session-signing';
import { useAccountData } from '@/hooks/use-account-data';
-import { SteemSigner, apiClient } from '@/lib/steem/client';
-import type { Witness } from '@/lib/steem/types';
+import { apiClient } from '@/lib/steem/client';
+import type { Operation, Witness } from '@/lib/steem/types';
import { LoginForm } from '@/components/auth/login-form';
import { DISABLED_SIGNING_KEY } from '@/lib/steem/constants';
import { toast } from 'sonner';
@@ -17,7 +18,13 @@ import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Card, CardContent } from '@/components/ui/card';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
-import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+} from '@/components/ui/dialog';
function compareWitnessByVotes(a: Witness, b: Witness): number {
try {
@@ -39,14 +46,17 @@ export function WitnessVoteForm() {
const t = useTranslations('witnesses');
const tAuth = useTranslations('auth');
const tCommon = useTranslations('common');
+ const tWallet = useTranslations('wallet');
const { isAuthenticated } = useAuth();
const username = useSelector((state: RootState) => state.auth.username);
- const signingKey = useActiveSigningKey();
+ // Unified signing entry (A6-T4): privateKey sessions sign through the
+ // facade's legacy backend exactly as before (active key, owner fallback);
+ // vault identity sessions get the per-key password dialog. The pre-A6
+ // signingKey gate (and the vaultUnsupported notice its login dialog could
+ // reach) is retired — an authenticated vault session signs through the
+ // per-key password path instead of re-opening a login dialog.
+ const signing = useSessionSigning();
const [isPending] = useTransition();
- const signingKeyRef = useRef(null);
- useEffect(() => {
- signingKeyRef.current = signingKey ?? null;
- }, [signingKey]);
const { data: account, refetch: refetchAccount, loading: isAccountLoading } = useAccountData();
@@ -57,6 +67,8 @@ export function WitnessVoteForm() {
const [actionLoading, setActionLoading] = useState(false);
const [loginOpen, setLoginOpen] = useState(false);
+ /** Classic re-auth for a privateKey session that lacks an active/owner key. */
+ const [reauthOpen, setReauthOpen] = useState(false);
const [pendingAction, setPendingAction] = useState<
| { type: 'vote'; witnessName: string; approve: boolean }
| { type: 'proxy'; proxy: string }
@@ -141,25 +153,85 @@ export function WitnessVoteForm() {
const hasVoted = (witnessName: string): boolean => userVotes.includes(witnessName);
const ensureAuthOrOpenDialog = useCallback((): boolean => {
- if (isAuthenticated && username && !!signingKeyRef.current) return true;
+ // Key availability is the unified signing entry's business now: a vault
+ // session (no Redux keys) signs through the per-key password path, a
+ // privateKey session without an active/owner key gets the classic re-auth
+ // dialog from the `needsClassicReauth` outcome.
+ if (isAuthenticated && username) return true;
setLoginOpen(true);
return false;
}, [isAuthenticated, username]);
+ /**
+ * Sign + broadcast one witness vote through the unified entry.
+ * Resolves `true` when the vote was signed, broadcast and recorded;
+ * `false` when the flow aborted (vault dialog cancelled, classic re-auth
+ * opened, or no session) — callers must skip their success side effects.
+ * Throws on signing/broadcast failure for the existing error surfaces.
+ */
const doVote = useCallback(
- async (witnessName: string, approve: boolean) => {
- const key = signingKeyRef.current;
- if (!username || !key) return;
- const signedTx = await SteemSigner.signWitnessVote(username, witnessName, approve, key);
- const response = await apiClient.broadcastWitnessVote(signedTx, username);
+ async (witnessName: string, approve: boolean): Promise => {
+ if (!username) return false;
+ // The exact operation tuple SteemSigner.signWitnessVote built
+ // internally. account_witness_vote is an active-class operation.
+ const operations: Operation[] = [
+ ['account_witness_vote', { account: username, witness: witnessName, approve }],
+ ];
+ const outcome = await signing.sign({
+ operations,
+ accountName: username,
+ role: 'active',
+ });
+ if (outcome.status === 'cancelled') return false;
+ if (outcome.status === 'needsClassicReauth') {
+ setReauthOpen(true);
+ return false;
+ }
+ if (outcome.status === 'error') {
+ throw new Error(approve ? t('voteError') : t('unvoteError'));
+ }
+ const response = await apiClient.broadcastWitnessVote(outcome.result.signedTx, username);
if (!response.success) {
throw new Error(
response.error || (approve ? t('voteError') : t('unvoteError'))
);
}
userActionRecord('account_witness_vote', { username, witness: witnessName });
+ return true;
+ },
+ [t, username, signing]
+ );
+
+ /**
+ * Sign + broadcast one witness proxy change — same abort contract as doVote.
+ */
+ const doSetProxy = useCallback(
+ async (nextProxy: string): Promise => {
+ if (!username) return false;
+ // The exact operation tuple SteemSigner.signWitnessProxy built
+ // internally. account_witness_proxy is an active-class operation.
+ const operations: Operation[] = [
+ ['account_witness_proxy', { account: username, proxy: nextProxy }],
+ ];
+ const outcome = await signing.sign({
+ operations,
+ accountName: username,
+ role: 'active',
+ });
+ if (outcome.status === 'cancelled') return false;
+ if (outcome.status === 'needsClassicReauth') {
+ setReauthOpen(true);
+ return false;
+ }
+ if (outcome.status === 'error') {
+ throw new Error(tCommon('error'));
+ }
+ const resp = await apiClient.broadcastWitnessProxy(outcome.result.signedTx, username);
+ if (!resp.success) throw new Error(resp.error || tCommon('error'));
+ userActionRecord('account_witness_proxy', { username, proxy: nextProxy });
+ return true;
},
- [t, username]
+ [tCommon, username, signing]
);
const handleVote = async (witnessName: string, approve: boolean) => {
@@ -171,7 +243,8 @@ export function WitnessVoteForm() {
setActionLoading(true);
try {
- await doVote(witnessName, approve);
+ const done = await doVote(witnessName, approve);
+ if (!done) return;
setLocalVotes((prev) => {
const set = new Set(prev);
if (approve) set.add(witnessName);
@@ -207,15 +280,11 @@ export function WitnessVoteForm() {
setPendingAction({ type: 'proxy', proxy: nextProxy });
return;
}
- const key = signingKeyRef.current;
- if (!username || !key) return;
setActionLoading(true);
try {
- const signedTx = await SteemSigner.signWitnessProxy(username, nextProxy, key);
- const resp = await apiClient.broadcastWitnessProxy(signedTx, username);
- if (!resp.success) throw new Error(resp.error || tCommon('error'));
- userActionRecord('account_witness_proxy', { username, proxy: nextProxy });
+ const done = await doSetProxy(nextProxy);
+ if (!done) return;
setProxyInput('');
toast.success(nextProxy ? t('proxySetSuccess') : t('proxyClearedSuccess'));
await refetchAccount();
@@ -228,20 +297,17 @@ export function WitnessVoteForm() {
};
useEffect(() => {
- if (!pendingAction || !isAuthenticated || !username || !signingKeyRef.current) return;
+ if (!pendingAction || !isAuthenticated || !username) return;
// Close login dialog after auth is available, but do it async to avoid
// cascading renders flagged by react-hooks/set-state-in-effect.
queueMicrotask(() => setLoginOpen(false));
const run = async () => {
- if (!signingKeyRef.current) {
- setPendingAction(null);
- return;
- }
try {
setActionLoading(true);
if (pendingAction.type === 'vote') {
- await doVote(pendingAction.witnessName, pendingAction.approve);
+ const done = await doVote(pendingAction.witnessName, pendingAction.approve);
+ if (!done) return;
setLocalVotes((prev) => {
const set = new Set(prev);
if (pendingAction.approve) set.add(pendingAction.witnessName);
@@ -251,12 +317,8 @@ export function WitnessVoteForm() {
});
toast.success(pendingAction.approve ? t('voteSuccess') : t('unvoteSuccess'));
} else {
- const key = signingKeyRef.current;
- if (!key) throw new Error(tCommon('error'));
- const signedTx = await SteemSigner.signWitnessProxy(username, pendingAction.proxy, key);
- const resp = await apiClient.broadcastWitnessProxy(signedTx, username);
- if (!resp.success) throw new Error(resp.error || tCommon('error'));
- userActionRecord('account_witness_proxy', { username, proxy: pendingAction.proxy });
+ const done = await doSetProxy(pendingAction.proxy);
+ if (!done) return;
toast.success(pendingAction.proxy ? t('proxySetSuccess') : t('proxyClearedSuccess'));
}
await refetchAccount();
@@ -269,7 +331,7 @@ export function WitnessVoteForm() {
};
void run();
- }, [doVote, isAuthenticated, pendingAction, refetchAccount, t, tCommon, username]);
+ }, [doVote, doSetProxy, isAuthenticated, pendingAction, refetchAccount, t, tCommon, username]);
// Format vote count for display
const formatVotes = (votes: string): string => {
@@ -305,16 +367,45 @@ export function WitnessVoteForm() {
{tAuth('login')}
+ {tAuth('login')}}>
+ {/* Unauthenticated visitors may log in as any account; the
+ active-authority requirement keeps a privateKey login fit
+ for witness voting the first time (both witness ops are
+ active-class). No fixedUsername: the dialog only opens for
+ visitors without a session — this retires the pre-A6
+ conditional pin that could surface the Vault Mode
+ "unsupported" notice; in Vault Mode this dialog offers
+ identity selection and the per-action password dialog
+ enforces the floor after login. */}
setLoginOpen(false)}
/>
+
+
+
+
+ {tWallet('reauthTitle')}
+ {tWallet('reauthDescription')}
+
+ }>
+ setReauthOpen(false)}
+ />
+
+
+
+
+ {signing.dialog}
{/* Vote stats + quick vote (outside top 100) */}
diff --git a/tests/e2e/vault-session-signing.spec.ts b/tests/e2e/vault-session-signing.spec.ts
index 579be5bd..f3eaa4f6 100644
--- a/tests/e2e/vault-session-signing.spec.ts
+++ b/tests/e2e/vault-session-signing.spec.ts
@@ -2,8 +2,9 @@ import { test, expect, type Locator, type Page } from '@playwright/test';
import vectors from '../fixtures/vault-development-test-vectors.json';
/**
- * Vault identity session SIGNING (A6-T2 pilot, A6-T3a wallet-ops batch) —
- * real-browser coverage for the per-key password path.
+ * Vault identity session SIGNING (A6-T2 pilot, A6-T3a wallet-ops batch,
+ * A6-T4 proposals vote) — real-browser coverage for the per-key password
+ * path.
*
* Setup mirrors vault-per-key.spec.ts (real IndexedDB + real Web Crypto;
* chain-dependent branches made deterministic by intercepting
@@ -32,6 +33,12 @@ import vectors from '../fixtures/vault-development-test-vectors.json';
* "a vault session never reads the Legacy remembered posting key"
* invariant is NOT exercised here — it is pinned by the unit suite's
* Storage-prototype spy in tests/unit/claim-rewards-banner.test.tsx.);
+ * - proposals vote (A6-T4): a vault identity session votes on /proposals
+ * directly — the pre-A6 gap (identity-selection login dialog reopening on
+ * every vote because no Redux key exists) is gone — signs through the
+ * password dialog at the ACTIVE floor (update_proposal_votes is
+ * active-class on Steem) and broadcasts the byte-identical
+ * update_proposal_votes tuple;
* - no /api/auth/* traffic at any point (identity + signing are local).
*
* Fixture discipline: WIF/public keys/password come from the shared
@@ -172,6 +179,69 @@ async function interceptClaimBroadcast(page: Page) {
return bodies;
}
+/** Intercept the proposals-vote broadcast route, returning the captured bodies. */
+async function interceptProposalVoteBroadcast(page: Page) {
+ const bodies: Array> = [];
+ await page.route('**/api/broadcast/proposal-vote', (route) => {
+ bodies.push(route.request().postDataJSON() as Record);
+ return route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify({ success: true, result: { id: 'e2e-tx' } }),
+ });
+ });
+ return bodies;
+}
+
+/**
+ * SPA-navigate to the proposals page through the app's own side-panel link
+ * (a vault identity session lives only in Redux — a full page.goto would
+ * wipe it, and a synthetic pushState/popstate does not drive the App Router
+ * across paths, only the same-route query change the wallet modal uses).
+ */
+async function openProposalsViaAppNavigation(page: Page) {
+ await page.getByRole('button', { name: 'Menu' }).click();
+ await page.getByRole('link', { name: 'Steem Proposals' }).click();
+}
+
+/** Serve one votable proposal row on the proposals query routes. */
+const E2E_PROPOSAL = {
+ id: 77,
+ proposal_id: 77,
+ creator: 'alice',
+ receiver: 'alice',
+ start_date: '2026-01-01T00:00:00',
+ end_date: '2027-01-01T00:00:00',
+ daily_pay: '10.000 SBD',
+ subject: 'E2E vault vote proposal',
+ permlink: 'e2e-vault-vote-proposal',
+ total_votes: '1000000000',
+ upVoted: false,
+};
+
+async function fulfillProposalsRoutes(page: Page) {
+ await page.route('**/api/query/proposals?**', (route) =>
+ route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify({ success: true, proposals: [{ ...E2E_PROPOSAL }] }),
+ }),
+ );
+ await page.route('**/api/query/proposals/dao-stats', (route) =>
+ route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify({
+ success: true,
+ daoTreasury: '1000.000 SBD',
+ dailyBudget: '500.000 SBD',
+ paidProposalIds: [],
+ treasuryFeeSbd: '10.000',
+ }),
+ }),
+ );
+}
+
/**
* Global props for the delegate form's SP -> VESTS math. 200M VESTS over
* 100M STEEM makes 1 SP convert to exactly 2.000000 VESTS.
@@ -645,4 +715,74 @@ test.describe('Vault identity session signing (A6-T2/T3a)', () => {
// The whole flow — identity login + signing — never touched auth endpoints.
expect(authEndpoints).toEqual([]);
});
+
+ test('proposals vote (A6-T4): vault session votes directly, signs through the password dialog and broadcasts', async ({
+ page,
+ }) => {
+ const activeKey = fixtureKey('active');
+ const postingKey = fixtureKey('posting');
+ await abortOtherQueries(page);
+ await fulfillTransactionHeader(page);
+ await fulfillGlobalProps(page);
+ await fulfillProposalsRoutes(page);
+ const broadcastBodies = await interceptProposalVoteBroadcast(page);
+ const authEndpoints = trackAuthEndpoints(page);
+
+ const chain = {
+ alice: chainAccount('alice', {
+ active: [[activeKey.publicKey, 1]],
+ posting: [[postingKey.publicKey, 1]],
+ }),
+ };
+ await fulfillAccountsRoute(page, chain);
+ await establishVaultIdentity(page);
+
+ // The proposals page opens for a vault session with the Vote action
+ // AVAILABLE (canVote no longer requires a Redux active key) — the pre-A6
+ // gap had every vote reopen the identity-selection login dialog.
+ await openProposalsViaAppNavigation(page);
+ const voteButton = page.getByRole('button', { name: 'Vote', exact: true });
+ await expect(voteButton).toBeVisible({ timeout: 15_000 });
+ await expect(voteButton).toBeEnabled();
+ // No sign-in prompt banner for the authenticated vault session.
+ await expect(page.getByText('Sign in with your active key to vote')).toHaveCount(0);
+
+ await voteButton.click();
+
+ // update_proposal_votes floors at ACTIVE, so only the active-stored key
+ // is offered (the posting key stays below the floor) and auto-selects.
+ const signDialog = page.getByTestId('vault-signing-dialog');
+ await expect(signDialog).toBeVisible({ timeout: 15_000 });
+ await expect(signDialog.getByText('trezor active key')).toBeVisible();
+ await expect(signDialog.getByText('posting only key')).toHaveCount(0);
+
+ await signDialog.getByLabel('Vault password').fill(VAULT_PASSWORD);
+ await signDialog.getByTestId('vault-signing-submit').click();
+ await expect(signDialog).toBeHidden({ timeout: 30_000 });
+
+ // Byte-identical update_proposal_votes tuple for the clicked proposal.
+ await expect(broadcastBodies).toHaveLength(1);
+ const body = broadcastBodies[0] as {
+ username?: string;
+ signedTx?: {
+ ref_block_num?: number;
+ ref_block_prefix?: number;
+ operations?: unknown[];
+ signatures?: string[];
+ };
+ };
+ expect(body.username).toBe('alice');
+ expect(body.signedTx?.ref_block_num).toBe(12345);
+ expect(body.signedTx?.ref_block_prefix).toBe(6789012);
+ expect(body.signedTx?.operations).toEqual([
+ [
+ 'update_proposal_votes',
+ { voter: 'alice', proposal_ids: [E2E_PROPOSAL.proposal_id], approve: true },
+ ],
+ ]);
+ expect(body.signedTx?.signatures?.length).toBe(1);
+
+ // The whole flow — identity login + voting — never touched auth endpoints.
+ expect(authEndpoints).toEqual([]);
+ });
});
diff --git a/tests/unit/login-form-dispatch.test.tsx b/tests/unit/login-form-dispatch.test.tsx
index dc2071a1..edbe5fae 100644
--- a/tests/unit/login-form-dispatch.test.tsx
+++ b/tests/unit/login-form-dispatch.test.tsx
@@ -1,14 +1,19 @@
/**
- * LoginForm mode dispatcher (R3).
+ * LoginForm mode dispatcher (R3; A6-T4 narrowing).
*
* `LoginForm` reads the persisted signing mode (through the REAL
* useSigningMode hook over a mocked facade) and renders:
* - 'privateKey' (and every not-yet-'vault' state: loading, failed read,
* unavailable runtime) -> the classic form, as-is;
* - 'vault' -> VaultLoginForm;
- * - 'vault' + embedded re-auth (fixedUsername / requiredAuthTypes)
+ * - 'vault' + embedded ACCOUNT-PINNED re-auth (fixedUsername)
* -> the explicit
* "not available in Vault Mode yet" notice + Work Mode shortcut.
+ * Since A6-T4 `requiredAuthTypes` ALONE no longer triggers the notice:
+ * the market / proposals / witnesses "sign in to trade / vote" dialogs
+ * declare an authority floor for the PRIVATEKEY branch while Vault Mode
+ * keeps identity selection — the per-action password dialog (via
+ * useSessionSigning) enforces the floor after login.
*
* The PrivateKey branch's own behavior is pinned by the UNCHANGED
* login-form-reauth.test.tsx (rendered without any VaultProvider — the
@@ -174,12 +179,15 @@ describe('LoginForm mode dispatch (R3)', () => {
window.removeEventListener(VAULT_WORK_MODE_OPEN_EVENT, onOpen);
});
- it("'vault' mode + embedded re-auth with requiredAuthTypes shows the notice too", async () => {
+ it("'vault' mode + embedded with requiredAuthTypes ALONE gets identity selection (A6-T4 gap closure)", async () => {
mockRuntime = readyRuntime('vault');
renderLogin({ embedded: true, requiredAuthTypes: ['active'] });
- expect(await screen.findByTestId('vault-mode-unsupported')).toBeInTheDocument();
- expect(screen.queryByTestId('vault-login-form-stub')).not.toBeInTheDocument();
+ // The market / proposals / witnesses sign-in dialogs: the declared
+ // authority floor applies to the privateKey branch; in Vault Mode the
+ // per-action password dialog enforces it after identity selection.
+ expect(await screen.findByTestId('vault-login-form-stub')).toBeInTheDocument();
+ expect(screen.queryByTestId('vault-mode-unsupported')).not.toBeInTheDocument();
expect(privateKeyInput()).not.toBeInTheDocument();
});
diff --git a/tests/unit/market-page-client.test.tsx b/tests/unit/market-page-client.test.tsx
index 13c1f33d..4c5dc043 100644
--- a/tests/unit/market-page-client.test.tsx
+++ b/tests/unit/market-page-client.test.tsx
@@ -6,6 +6,11 @@
* way every other broadcast flow does, and the orderid handed to the chain
* must be a per-session unique uint32 (G-14) instead of a seconds timestamp
* whose same-second repeat silently REPLACED the previous order.
+ *
+ * Since A6-T4 signing goes through useSessionSigning (mocked here at its
+ * module boundary): a typed `{status:'error'}` outcome or a broadcast
+ * transport throw must reach the same toasts, and the unique orderid now
+ * lives in the operation tuple handed to the unified entry.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
@@ -14,8 +19,7 @@ import { MarketPageClient } from '@/components/market/market-page-client';
const mocks = vi.hoisted(() => ({
refresh: vi.fn().mockResolvedValue(undefined),
- signCreate: vi.fn(),
- signCancel: vi.fn(),
+ sign: vi.fn(),
broadcastCreate: vi.fn(),
broadcastCancel: vi.fn(),
invalidate: vi.fn(),
@@ -43,8 +47,10 @@ vi.mock('@/hooks/use-auth', () => ({
username: mocks.auth.username,
isAuthenticated: mocks.auth.isAuthenticated,
}),
- useActiveSigningKey: () =>
- mocks.auth.isAuthenticated ? '5J-test-active' : null,
+}));
+
+vi.mock('@/hooks/use-session-signing', () => ({
+ useSessionSigning: () => ({ sign: mocks.sign, dialog: null }),
}));
vi.mock('@/hooks/use-steem-account', () => ({
@@ -75,10 +81,6 @@ vi.mock('@/hooks/use-market-data', () => ({
}));
vi.mock('@/lib/steem/client', () => ({
- SteemSigner: {
- signLimitOrderCreate: (...args: unknown[]) => mocks.signCreate(...args),
- signLimitOrderCancel: (...args: unknown[]) => mocks.signCancel(...args),
- },
apiClient: {
broadcastLimitOrderCreate: (...args: unknown[]) => mocks.broadcastCreate(...args),
broadcastLimitOrderCancel: (...args: unknown[]) => mocks.broadcastCancel(...args),
@@ -106,6 +108,25 @@ const mockToast = toast as unknown as {
const UINT32_MAX = 4_294_967_295;
+function signedOutcome() {
+ return {
+ status: 'signed' as const,
+ result: { signedTx: { id: 'tx' } },
+ };
+}
+
+/** The orderid of the i-th signing request's limit_order_create payload. */
+function placedOrderId(callIndex: number): number {
+ const request = mocks.sign.mock.calls[callIndex]?.[0] as {
+ operations: Array<[string, { orderid?: number }]>;
+ };
+ const payload = request.operations[0]?.[1];
+ if (!payload || typeof payload.orderid !== 'number') {
+ throw new Error('expected a limit_order_create payload with a numeric orderid');
+ }
+ return payload.orderid;
+}
+
/** Fill the buy form (price auto-seeds from the ticker) and submit. */
async function placeBuyOrder() {
fireEvent.change(screen.getAllByLabelText('amount')[0]!, {
@@ -117,6 +138,7 @@ async function placeBuyOrder() {
describe('MarketPageClient — order error capture (G-7) + orderid (G-14)', () => {
beforeEach(() => {
vi.clearAllMocks();
+ mocks.sign.mockResolvedValue(signedOutcome());
vi.spyOn(window, 'confirm').mockReturnValue(true);
});
@@ -124,8 +146,8 @@ describe('MarketPageClient — order error capture (G-7) + orderid (G-14)', () =
vi.restoreAllMocks();
});
- it('surfaces a signing failure as a toast instead of an unhandled rejection', async () => {
- mocks.signCreate.mockRejectedValueOnce(new Error('signing boom'));
+ it('surfaces a typed signing-error outcome as a toast (no broadcast attempt)', async () => {
+ mocks.sign.mockResolvedValueOnce({ status: 'error', code: 'unexpected' });
render();
await placeBuyOrder();
@@ -133,12 +155,22 @@ describe('MarketPageClient — order error capture (G-7) + orderid (G-14)', () =
await waitFor(() => {
expect(mockToast.error).toHaveBeenCalledWith('orderFailed');
});
- // The broadcast was never attempted and the signing key was not consumed.
+ // The broadcast was never attempted.
expect(mocks.broadcastCreate).not.toHaveBeenCalled();
});
+ it('surfaces a broadcast transport throw as a toast instead of an unhandled rejection', async () => {
+ mocks.broadcastCreate.mockRejectedValueOnce(new Error('relay unreachable'));
+ render();
+
+ await placeBuyOrder();
+
+ await waitFor(() => {
+ expect(mockToast.error).toHaveBeenCalledWith('orderFailed');
+ });
+ });
+
it('surfaces a relay failure ({success:false}) as a toast', async () => {
- mocks.signCreate.mockResolvedValueOnce({ id: 'tx' });
mocks.broadcastCreate.mockResolvedValueOnce({ success: false, error: 'relay rejected' });
render();
@@ -151,7 +183,6 @@ describe('MarketPageClient — order error capture (G-7) + orderid (G-14)', () =
});
it('success path: unique uint32 orderids, cache invalidation, refresh', async () => {
- mocks.signCreate.mockResolvedValue({ id: 'tx' });
mocks.broadcastCreate.mockResolvedValue({ success: true });
render();
@@ -161,9 +192,8 @@ describe('MarketPageClient — order error capture (G-7) + orderid (G-14)', () =
await placeBuyOrder();
await waitFor(() => expect(mockToast.success).toHaveBeenCalledTimes(2));
- const firstId = mocks.signCreate.mock.calls[0]?.[3] as number;
- const secondId = mocks.signCreate.mock.calls[1]?.[3] as number;
- // signLimitOrderCreate(owner, amountToSell, minToReceive, orderid, ...)
+ const firstId = placedOrderId(0);
+ const secondId = placedOrderId(1);
expect(firstId).not.toBe(secondId);
for (const id of [firstId, secondId]) {
expect(id).toBeGreaterThanOrEqual(0);
@@ -173,8 +203,8 @@ describe('MarketPageClient — order error capture (G-7) + orderid (G-14)', () =
expect(mocks.refresh).toHaveBeenCalled();
});
- it('cancel: signing failure surfaces a toast and releases the spinner', async () => {
- mocks.signCancel.mockRejectedValueOnce(new Error('cancel signing boom'));
+ it('cancel: typed signing-error outcome surfaces a toast and releases the spinner', async () => {
+ mocks.sign.mockResolvedValueOnce({ status: 'error', code: 'unexpected' });
render();
fireEvent.click(screen.getByRole('button', { name: 'cancelOrder' }));
@@ -190,7 +220,6 @@ describe('MarketPageClient — order error capture (G-7) + orderid (G-14)', () =
});
it('cancel: relay failure surfaces the relay error', async () => {
- mocks.signCancel.mockResolvedValueOnce({ id: 'tx' });
mocks.broadcastCancel.mockResolvedValueOnce({ success: false, error: 'rate limited' });
render();
@@ -203,7 +232,6 @@ describe('MarketPageClient — order error capture (G-7) + orderid (G-14)', () =
});
it('cancel: success path still works (toast + invalidation + refresh)', async () => {
- mocks.signCancel.mockResolvedValueOnce({ id: 'tx' });
mocks.broadcastCancel.mockResolvedValueOnce({ success: true });
render();
@@ -217,7 +245,6 @@ describe('MarketPageClient — order error capture (G-7) + orderid (G-14)', () =
});
it('sell orders take the price-warning branch and succeed with a unique orderid', async () => {
- mocks.signCreate.mockResolvedValue({ id: 'tx' });
mocks.broadcastCreate.mockResolvedValue({ success: true });
render();
@@ -229,8 +256,7 @@ describe('MarketPageClient — order error capture (G-7) + orderid (G-14)', () =
await waitFor(() => {
expect(mockToast.success).toHaveBeenCalledWith('orderPlaced');
});
- const sellOrderid = mocks.signCreate.mock.calls.at(-1)?.[3] as number;
- expect(sellOrderid).toBeLessThanOrEqual(UINT32_MAX);
+ expect(placedOrderId(mocks.sign.mock.calls.length - 1)).toBeLessThanOrEqual(UINT32_MAX);
expect(mockToast.error).not.toHaveBeenCalled();
});
@@ -241,8 +267,7 @@ describe('MarketPageClient — order error capture (G-7) + orderid (G-14)', () =
await placeBuyOrder();
fireEvent.click(screen.getByRole('button', { name: 'cancelOrder' }));
- expect(mocks.signCreate).not.toHaveBeenCalled();
- expect(mocks.signCancel).not.toHaveBeenCalled();
+ expect(mocks.sign).not.toHaveBeenCalled();
});
it('anonymous users get the sign-in prompt, login dialog, and no order attempt', async () => {
@@ -258,7 +283,7 @@ describe('MarketPageClient — order error capture (G-7) + orderid (G-14)', () =
// The order form is disabled for anonymous users.
expect(screen.getByRole('button', { name: 'buySteem' })).toBeDisabled();
- expect(mocks.signCreate).not.toHaveBeenCalled();
+ expect(mocks.sign).not.toHaveBeenCalled();
} finally {
mocks.auth.username = 'alice';
mocks.auth.isAuthenticated = true;
diff --git a/tests/unit/proposal-creator-dialog.test.tsx b/tests/unit/proposal-creator-dialog.test.tsx
index 74d58f2c..3ff2afd2 100644
--- a/tests/unit/proposal-creator-dialog.test.tsx
+++ b/tests/unit/proposal-creator-dialog.test.tsx
@@ -7,9 +7,16 @@
* lowercase account names — the signed create_proposal op must therefore
* carry normalized creator/receiver names, or the user gets a relay/chain
* rejection instead of the previous early validation toast.
+ *
+ * Since A6-T4 signing goes through useSessionSigning (mocked at its module
+ * boundary); the normalization assertions read the create_proposal tuple
+ * handed to the unified entry.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
+import { Provider } from 'react-redux';
+import { configureStore } from '@reduxjs/toolkit';
+import authReducer from '@/lib/store/slices/auth';
import { ProposalCreatorDialog } from '@/components/proposals/proposal-creator-dialog';
// jsdom lacks ResizeObserver, required by radix-ui primitives.
@@ -28,21 +35,53 @@ vi.mock('sonner', () => ({
toast: { error: vi.fn(), success: vi.fn() },
}));
-vi.mock('@/hooks/use-auth', () => ({
- useActiveSigningKey: () => '5J-test-active-key',
+const mocks = vi.hoisted(() => ({
+ sign: vi.fn().mockResolvedValue({ status: 'signed', result: { signedTx: { signed: true } } }),
+ broadcastCreate: vi.fn().mockResolvedValue({ success: true }),
+}));
+
+vi.mock('@/hooks/use-session-signing', () => ({
+ useSessionSigning: () => ({ sign: mocks.sign, dialog: null }),
+}));
+
+vi.mock('@/components/auth/login-form', () => ({
+ LoginForm: () => ,
}));
-const mockSignCreateProposal = vi.fn().mockResolvedValue({ signed: true });
-const mockBroadcastCreate = vi.fn().mockResolvedValue({ success: true });
vi.mock('@/lib/steem/client', () => ({
- SteemSigner: {
- signCreateProposal: (...args: unknown[]) => mockSignCreateProposal(...args),
- },
apiClient: {
- broadcastProposalCreate: (...args: unknown[]) => mockBroadcastCreate(...args),
+ broadcastProposalCreate: (...args: unknown[]) => mocks.broadcastCreate(...args),
},
}));
+function renderDialog() {
+ const onSuccess = vi.fn();
+ const store = configureStore({ reducer: { auth: authReducer } });
+ render(
+
+
+
+ );
+ return { onSuccess };
+}
+
+/** The create_proposal payload of the (only) signing request. */
+function signedCreatePayload(): { creator?: string; receiver?: string } {
+ const request = mocks.sign.mock.calls[0]?.[0] as {
+ operations: Array<[string, Record]>;
+ };
+ const payload = request.operations[0]?.[1];
+ if (!payload) throw new Error('expected a create_proposal payload');
+ return payload as { creator?: string; receiver?: string };
+}
+
function fillForm(overrides: { creator?: string; receiver?: string; permlink?: string } = {}) {
fireEvent.change(screen.getByLabelText('createTitle'), { target: { value: 'Dev fund' } });
fireEvent.change(screen.getByLabelText('createDailyAmount'), { target: { value: '100' } });
@@ -63,21 +102,6 @@ function fillForm(overrides: { creator?: string; receiver?: string; permlink?: s
});
}
-function renderDialog() {
- const onSuccess = vi.fn();
- render(
-
- );
- return { onSuccess };
-}
-
describe('ProposalCreatorDialog — normalized names in the signed op', () => {
beforeEach(() => {
vi.clearAllMocks();
@@ -90,11 +114,11 @@ describe('ProposalCreatorDialog — normalized names in the signed op', () => {
fireEvent.click(screen.getByRole('button', { name: 'createSubmit' }));
await waitFor(() => expect(onSuccess).toHaveBeenCalledTimes(1));
- expect(mockSignCreateProposal).toHaveBeenCalledTimes(1);
- const [creator, receiver] = mockSignCreateProposal.mock.calls[0] as [string, string];
- expect(creator).toBe('alice');
- expect(receiver).toBe('alice');
- expect(mockBroadcastCreate).toHaveBeenCalledTimes(1);
+ expect(mocks.sign).toHaveBeenCalledTimes(1);
+ const payload = signedCreatePayload();
+ expect(payload.creator).toBe('alice');
+ expect(payload.receiver).toBe('alice');
+ expect(mocks.broadcastCreate).toHaveBeenCalledTimes(1);
});
it('normalizes the creator parsed from a mixed-case permlink when fields fall back', async () => {
@@ -108,9 +132,9 @@ describe('ProposalCreatorDialog — normalized names in the signed op', () => {
fireEvent.click(screen.getByRole('button', { name: 'createSubmit' }));
await waitFor(() => expect(onSuccess).toHaveBeenCalledTimes(1));
- const [creator, receiver] = mockSignCreateProposal.mock.calls[0] as [string, string];
- expect(creator).toBe('alice');
- expect(receiver).toBe('alice');
+ const payload = signedCreatePayload();
+ expect(payload.creator).toBe('alice');
+ expect(payload.receiver).toBe('alice');
});
it('still blocks a creator that is a different account', async () => {
@@ -123,7 +147,7 @@ describe('ProposalCreatorDialog — normalized names in the signed op', () => {
await waitFor(() =>
expect(vi.mocked(toast.error)).toHaveBeenCalledWith('createMustSignAsCreator')
);
- expect(mockSignCreateProposal).not.toHaveBeenCalled();
- expect(mockBroadcastCreate).not.toHaveBeenCalled();
+ expect(mocks.sign).not.toHaveBeenCalled();
+ expect(mocks.broadcastCreate).not.toHaveBeenCalled();
});
});
diff --git a/tests/unit/proposal-remove-dialog.test.tsx b/tests/unit/proposal-remove-dialog.test.tsx
index da221e67..d3f9ad42 100644
--- a/tests/unit/proposal-remove-dialog.test.tsx
+++ b/tests/unit/proposal-remove-dialog.test.tsx
@@ -7,9 +7,16 @@
* remove_proposal op must carry the canonical lowercase account name
* (mirrors proposal-creator-dialog.tsx, see its test for the create side),
* or a mixed-case session value would ship an op the chain rejects.
+ *
+ * Since A6-T4 signing goes through useSessionSigning (mocked at its module
+ * boundary); the normalization assertions read the remove_proposal tuple
+ * handed to the unified entry.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
+import { Provider } from 'react-redux';
+import { configureStore } from '@reduxjs/toolkit';
+import authReducer from '@/lib/store/slices/auth';
import { ProposalRemoveDialog } from '@/components/proposals/proposal-remove-dialog';
// jsdom lacks ResizeObserver, required by radix-ui primitives.
@@ -28,36 +35,53 @@ vi.mock('sonner', () => ({
toast: { error: vi.fn(), success: vi.fn() },
}));
-vi.mock('@/hooks/use-auth', () => ({
- useActiveSigningKey: () => '5J-test-active-key',
+const mocks = vi.hoisted(() => ({
+ sign: vi.fn().mockResolvedValue({ status: 'signed', result: { signedTx: { signed: true } } }),
+ broadcastRemove: vi.fn().mockResolvedValue({ success: true }),
+}));
+
+vi.mock('@/hooks/use-session-signing', () => ({
+ useSessionSigning: () => ({ sign: mocks.sign, dialog: null }),
+}));
+
+vi.mock('@/components/auth/login-form', () => ({
+ LoginForm: () => ,
}));
-const mockSignRemoveProposal = vi.fn().mockResolvedValue({ signed: true });
-const mockBroadcastRemove = vi.fn().mockResolvedValue({ success: true });
vi.mock('@/lib/steem/client', () => ({
- SteemSigner: {
- signRemoveProposal: (...args: unknown[]) => mockSignRemoveProposal(...args),
- },
apiClient: {
- broadcastProposalRemove: (...args: unknown[]) => mockBroadcastRemove(...args),
+ broadcastProposalRemove: (...args: unknown[]) => mocks.broadcastRemove(...args),
},
}));
function renderDialog(username: string) {
const onSuccess = vi.fn();
+ const store = configureStore({ reducer: { auth: authReducer } });
render(
-
+
+
+
);
return { onSuccess };
}
+/** The remove_proposal payload of the (only) signing request. */
+function signedRemovePayload(): { proposal_owner?: string; proposal_ids?: number[] } {
+ const request = mocks.sign.mock.calls[0]?.[0] as {
+ operations: Array<[string, Record]>;
+ };
+ const payload = request.operations[0]?.[1];
+ if (!payload) throw new Error('expected a remove_proposal payload');
+ return payload as { proposal_owner?: string; proposal_ids?: number[] };
+}
+
function confirmAndSubmit() {
fireEvent.change(screen.getByLabelText('removeConfirmId'), { target: { value: '7' } });
fireEvent.click(screen.getByRole('button', { name: 'removeButton' }));
@@ -74,9 +98,11 @@ describe('ProposalRemoveDialog — normalized name in the signed op', () => {
confirmAndSubmit();
await waitFor(() => expect(onSuccess).toHaveBeenCalledTimes(1));
- expect(mockSignRemoveProposal).toHaveBeenCalledTimes(1);
- expect(mockSignRemoveProposal).toHaveBeenCalledWith('alice', [7], '5J-test-active-key');
- expect(mockBroadcastRemove).toHaveBeenCalledTimes(1);
+ expect(mocks.sign).toHaveBeenCalledTimes(1);
+ const payload = signedRemovePayload();
+ expect(payload.proposal_owner).toBe('alice');
+ expect(payload.proposal_ids).toEqual([7]);
+ expect(mocks.broadcastRemove).toHaveBeenCalledTimes(1);
});
it('keeps an already-canonical session username unchanged', async () => {
@@ -84,7 +110,7 @@ describe('ProposalRemoveDialog — normalized name in the signed op', () => {
confirmAndSubmit();
await waitFor(() => expect(onSuccess).toHaveBeenCalledTimes(1));
- expect(mockSignRemoveProposal).toHaveBeenCalledWith('alice', [7], '5J-test-active-key');
+ expect(signedRemovePayload().proposal_owner).toBe('alice');
});
it('does not sign when the confirmation id does not match', async () => {
@@ -100,7 +126,7 @@ describe('ProposalRemoveDialog — normalized name in the signed op', () => {
await waitFor(() =>
expect(vi.mocked(toast.error)).toHaveBeenCalledWith('removeIdMismatch')
);
- expect(mockSignRemoveProposal).not.toHaveBeenCalled();
- expect(mockBroadcastRemove).not.toHaveBeenCalled();
+ expect(mocks.sign).not.toHaveBeenCalled();
+ expect(mocks.broadcastRemove).not.toHaveBeenCalled();
});
});
diff --git a/tests/unit/proposals-page-vote.test.tsx b/tests/unit/proposals-page-vote.test.tsx
index 81f08940..4e2ab2e8 100644
--- a/tests/unit/proposals-page-vote.test.tsx
+++ b/tests/unit/proposals-page-vote.test.tsx
@@ -14,6 +14,10 @@ import { ProposalsPageClient } from '@/components/proposals-page-client';
const mocks = vi.hoisted(() => ({
broadcast: vi.fn(),
refreshMeta: vi.fn(),
+ sign: vi.fn().mockResolvedValue({
+ status: 'signed',
+ result: { signedTx: { signed: 'tx' } },
+ }),
}));
vi.mock('next-intl', () => ({
@@ -26,13 +30,16 @@ vi.mock('sonner', () => ({
vi.mock('@/hooks/use-auth', () => ({
useAuth: () => ({ username: 'alice', isAuthenticated: true }),
- useActiveSigningKey: () => '5Jactivekey',
+}));
+
+vi.mock('@/hooks/use-session-signing', () => ({
+ useSessionSigning: () => ({
+ sign: mocks.sign,
+ dialog: null,
+ }),
}));
vi.mock('@/lib/steem/client', () => ({
- SteemSigner: {
- signUpdateProposalVotes: vi.fn().mockResolvedValue({ signed: 'tx' }),
- },
apiClient: {
broadcastProposalVote: mocks.broadcast,
getGlobalProps: vi.fn().mockResolvedValue({ props: { total_vesting_shares: '1 VESTS' } }),
diff --git a/tests/unit/vault-signer.test.ts b/tests/unit/vault-signer.test.ts
index 78c33822..9f473499 100644
--- a/tests/unit/vault-signer.test.ts
+++ b/tests/unit/vault-signer.test.ts
@@ -383,6 +383,49 @@ describe('vault signer (per-key hierarchy)', () => {
).toBe('owner');
});
+ it('classifies the A6-T4 market / proposals / witnesses operation shapes as active (vault path cannot fail closed on them)', () => {
+ // The five T4 callers all sign at role floor 'active'. NOTE:
+ // update_proposal_votes is ACTIVE on Steem — the legacy postingOps
+ // whitelist never listed it and the pre-T4 caller signed it with the
+ // active-or-owner key — so the floor and the classifier agree. An
+ // unclassified op would make the vault path fail closed with
+ // VAULT_OPERATION_UNSUPPORTED; all seven call-site shapes were ALREADY
+ // in the table — this pins that none regresses.
+ const activeFloorOps: Array<[string, Record]> = [
+ [
+ 'limit_order_create',
+ {
+ owner: 'alice',
+ amount_to_sell: '5.000 SBD',
+ min_to_receive: '5.000 STEEM',
+ fill_or_kill: false,
+ expiration: '2026-12-18T00:00:00',
+ orderid: 42,
+ },
+ ],
+ ['limit_order_cancel', { owner: 'alice', orderid: 42 }],
+ ['update_proposal_votes', { voter: 'alice', proposal_ids: [1], approve: true }],
+ [
+ 'create_proposal',
+ {
+ creator: 'alice',
+ receiver: 'alice',
+ start_date: '2026-10-01T00:00:00',
+ end_date: '2026-10-15T00:00:00',
+ daily_pay: '100.000 SBD',
+ subject: 'Dev fund',
+ permlink: 'dev-fund-post',
+ },
+ ],
+ ['remove_proposal', { proposal_owner: 'alice', proposal_ids: [7] }],
+ ['account_witness_vote', { account: 'alice', witness: 'witness1', approve: true }],
+ ['account_witness_proxy', { account: 'alice', proxy: 'bob' }],
+ ];
+ for (const [type, payload] of activeFloorOps) {
+ expect(resolveRequiredAuthorityClass([[type, payload]])).toBe('active');
+ }
+ });
+
it('mixed operations require the most privileged class; garbage fails closed', () => {
expect(resolveRequiredAuthorityClass([postingOp('alice'), activeOp('alice')])).toBe('active');
const expectClassifierRejection = (operations: unknown[]): void => {
diff --git a/tests/unit/wallet-t4-session-signing.test.tsx b/tests/unit/wallet-t4-session-signing.test.tsx
new file mode 100644
index 00000000..03803d1f
--- /dev/null
+++ b/tests/unit/wallet-t4-session-signing.test.tsx
@@ -0,0 +1,751 @@
+/**
+ * The five A6-T4 callers × useSessionSigning integration — market
+ * (limit_order_create / limit_order_cancel), proposals vote
+ * (update_proposal_votes), proposal create (create_proposal), proposal
+ * remove (remove_proposal) and witness voting (account_witness_vote /
+ * account_witness_proxy) — in all three session shapes. The hook is mocked
+ * at its module boundary (its own matrix lives in
+ * use-session-signing.test.tsx); these tests pin what each CALLER does with
+ * each outcome:
+ * - privateKey session: the action is NOT key-gated up front, the
+ * byte-identical operation tuple (exactly what the retired
+ * SteemSigner.* builder built, including field order and the
+ * limit_order_create ISO expiration conversion) reaches the unified entry
+ * at the ACTIVE floor, and the broadcast follows on `signed`;
+ * - vault identity session (no Redux keys): the action is AVAILABLE and
+ * completes through the unified entry — NO login dialog is ever opened
+ * for an authenticated vault session (the pre-A6 re-login loop /
+ * vaultUnsupported notice reachability is retired);
+ * - privateKey session missing an active/owner key: `needsClassicReauth`
+ * routes to the caller's classic re-auth dialog (fixedUsername locked
+ * to the session account + requiredAuthTypes ['active']).
+ *
+ * Login-dialog contract pins (the documented pre-A6 gap closure): the
+ * market / proposals / witnesses sign-in dialogs pass requiredAuthTypes
+ * ['active'] with NO fixedUsername (session-account pages: unauthenticated
+ * visitors may log in as any account; a privateKey login is fit for
+ * purpose the first time because every action on these pages is
+ * active-class).
+ */
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { render, screen, fireEvent, waitFor } from '@testing-library/react';
+import { Provider } from 'react-redux';
+import { configureStore } from '@reduxjs/toolkit';
+import authReducer, { setVaultIdentity, type AuthState } from '@/lib/store/slices/auth';
+import { MarketPageClient } from '@/components/market/market-page-client';
+import { ProposalsPageClient } from '@/components/proposals-page-client';
+import { ProposalCreatorDialog } from '@/components/proposals/proposal-creator-dialog';
+import { ProposalRemoveDialog } from '@/components/proposals/proposal-remove-dialog';
+import { WitnessVoteForm } from '@/components/wallet/witness-vote-form';
+
+class ResizeObserverStub {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+}
+vi.stubGlobal('ResizeObserver', ResizeObserverStub);
+
+// STABLE echo function: witness-vote-form's mount effect lists the returned
+// translator in its deps — a fresh identity per render would loop it.
+vi.mock('next-intl', () => {
+ const echo = (key: string) => key;
+ return { useTranslations: () => echo };
+});
+
+vi.mock('next/navigation', () => ({
+ useRouter: () => ({ push: vi.fn(), back: vi.fn() }),
+ useSearchParams: () => new URLSearchParams(),
+}));
+
+const mocks = vi.hoisted(() => ({
+ sign: vi.fn(),
+ /** Every props object the embedded LoginForm probe received. */
+ loginFormCalls: [] as Array<{
+ fixedUsername?: string | undefined;
+ requiredAuthTypes?: string[] | undefined;
+ }>,
+ broadcastLimitOrderCreate: vi.fn().mockResolvedValue({ success: true }),
+ broadcastLimitOrderCancel: vi.fn().mockResolvedValue({ success: true }),
+ broadcastProposalVote: vi.fn().mockResolvedValue({ success: true }),
+ broadcastProposalCreate: vi.fn().mockResolvedValue({ success: true }),
+ broadcastProposalRemove: vi.fn().mockResolvedValue({ success: true }),
+ broadcastWitnessVote: vi.fn().mockResolvedValue({ success: true }),
+ broadcastWitnessProxy: vi.fn().mockResolvedValue({ success: true }),
+ getWitnesses: vi.fn(),
+ getGlobalProps: vi.fn(),
+ refetchAccount: vi.fn().mockResolvedValue(undefined),
+ refreshMarket: vi.fn().mockResolvedValue(undefined),
+ refreshMeta: vi.fn().mockResolvedValue(undefined),
+ invalidate: vi.fn(),
+}));
+
+vi.mock('@/hooks/use-session-signing', () => ({
+ useSessionSigning: () => ({ sign: mocks.sign, dialog: null }),
+}));
+
+vi.mock('@/components/auth/login-form', () => ({
+ // Probe: records the props each embedded dialog passes (the propagation
+ // pins) and renders a marker so dialog-open assertions work.
+ LoginForm: (props: { fixedUsername?: string; requiredAuthTypes?: string[] }) => {
+ mocks.loginFormCalls.push({
+ fixedUsername: props.fixedUsername,
+ requiredAuthTypes: props.requiredAuthTypes,
+ });
+ return ;
+ },
+}));
+
+vi.mock('@/lib/steem/client', () => ({
+ apiClient: {
+ broadcastLimitOrderCreate: (...args: unknown[]) => mocks.broadcastLimitOrderCreate(...args),
+ broadcastLimitOrderCancel: (...args: unknown[]) => mocks.broadcastLimitOrderCancel(...args),
+ broadcastProposalVote: (...args: unknown[]) => mocks.broadcastProposalVote(...args),
+ broadcastProposalCreate: (...args: unknown[]) => mocks.broadcastProposalCreate(...args),
+ broadcastProposalRemove: (...args: unknown[]) => mocks.broadcastProposalRemove(...args),
+ broadcastWitnessVote: (...args: unknown[]) => mocks.broadcastWitnessVote(...args),
+ broadcastWitnessProxy: (...args: unknown[]) => mocks.broadcastWitnessProxy(...args),
+ getWitnesses: (...args: unknown[]) => mocks.getWitnesses(...args),
+ getGlobalProps: (...args: unknown[]) => mocks.getGlobalProps(...args),
+ },
+}));
+
+vi.mock('@/hooks/use-market-data', () => ({
+ useMarketData: () => ({
+ orderbook: { bids: [], asks: [] },
+ ticker: {
+ latest: 1,
+ lowest_ask: 1,
+ highest_bid: 1,
+ percent_change: 0,
+ steem_volume: 0,
+ sbd_volume: 0,
+ },
+ history: [],
+ openOrders: [
+ { orderid: 42, created: '2026-01-01T00:00:00', type: 'bid', steem: 1, sbd: 1, price: 1 },
+ ],
+ loading: false,
+ error: null,
+ refresh: mocks.refreshMarket,
+ }),
+}));
+
+vi.mock('@/hooks/use-steem-account', () => ({
+ useSteemAccount: () => ({
+ data: { balance: '100.000 STEEM', sbd_balance: '100.000 SBD' },
+ }),
+}));
+
+vi.mock('@/lib/cache/client-invalidate', () => ({
+ invalidateWalletCache: mocks.invalidate,
+}));
+
+vi.mock('@/hooks/use-proposals-meta', () => ({
+ useProposalsMeta: () => ({
+ daoTreasury: null,
+ dailyBudget: null,
+ paidProposalIds: [],
+ treasuryFeeSbd: null,
+ loading: false,
+ refreshMeta: mocks.refreshMeta,
+ }),
+}));
+
+vi.mock('@/components/proposals/proposal-voters-dialog', () => ({
+ ProposalVotersDialog: () => null,
+}));
+
+vi.mock('@/hooks/use-account-data', () => ({
+ useAccountData: () => ({
+ data: { name: 'alice', proxy: '', witness_votes: [] as string[] },
+ refetch: mocks.refetchAccount,
+ loading: false,
+ error: null,
+ }),
+}));
+
+vi.mock('@/lib/analytics/overseer', () => ({
+ userActionRecord: vi.fn(),
+}));
+
+import { userActionRecord } from '@/lib/analytics/overseer';
+
+const BASE_AUTH: AuthState = {
+ username: null,
+ ownerKey: null,
+ activeKey: null,
+ postingKey: null,
+ memoKey: null,
+ privateKey: null,
+ publicKey: null,
+ isAuthenticated: false,
+ sessionKind: 'privateKey',
+};
+
+type TestStore = ReturnType;
+
+function privateKeyStore(username: string, withActiveKey: boolean) {
+ return configureStore({
+ reducer: { auth: authReducer },
+ preloadedState: {
+ auth: {
+ ...BASE_AUTH,
+ username,
+ // A posting-only privateKey session: enough to be "logged in", no
+ // key at-or-above the active floor.
+ postingKey: '5J-test-posting-key',
+ activeKey: withActiveKey ? '5J-test-active-key' : null,
+ privateKey: withActiveKey ? '5J-test-active-key' : '5J-test-posting-key',
+ isAuthenticated: true,
+ } satisfies AuthState,
+ },
+ });
+}
+
+function vaultStore(username = 'alice') {
+ const store = configureStore({ reducer: { auth: authReducer }, preloadedState: { auth: BASE_AUTH } });
+ store.dispatch(setVaultIdentity({ username }));
+ return store;
+}
+
+function signedOutcome() {
+ return {
+ status: 'signed' as const,
+ result: { signedTx: { signatures: ['SIG'], operations: [] } },
+ };
+}
+
+/** The i-th signing request's single operation tuple. */
+function signedOperation(callIndex = 0): [string, Record] {
+ const request = mocks.sign.mock.calls[callIndex]?.[0] as {
+ operations: Array<[string, Record]>;
+ };
+ const op = request?.operations?.[0];
+ if (!op) throw new Error('expected one signing request with an operation tuple');
+ return op;
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ // The hook mock cannot see the store: session-shape routing is the REAL
+ // hook's own matrix; here each caller test pins its reaction to the
+ // outcome, so the keyless tests inject the outcome explicitly.
+ mocks.sign.mockResolvedValue(signedOutcome());
+ mocks.loginFormCalls.length = 0;
+ mocks.getWitnesses.mockResolvedValue({
+ witnesses: [
+ {
+ owner: 'witness1',
+ votes: '1000',
+ total_missed: 0,
+ running_version: '0.23.0',
+ signing_key: 'STM8ActiveAuthorityKeyNotInFixtures000000000000',
+ last_confirmed_block_num: 100,
+ },
+ ],
+ });
+ mocks.getGlobalProps.mockResolvedValue({
+ props: {
+ head_block_number: 100,
+ total_vesting_shares: '1 VESTS',
+ total_vesting_fund_steem: '1 STEEM',
+ },
+ });
+});
+
+/* ───────── MarketPageClient ───────── */
+
+function renderMarket(store: TestStore) {
+ return render(
+
+
+
+ );
+}
+
+/** Fill the buy form (price auto-seeds 1 from the ticker) and submit. */
+async function placeBuyOrder() {
+ fireEvent.change(screen.getAllByLabelText('amount')[0]!, { target: { value: '5' } });
+ fireEvent.click(screen.getByRole('button', { name: 'buySteem' }));
+}
+
+async function cancelOpenOrder() {
+ fireEvent.click(screen.getByRole('button', { name: 'cancelOrder' }));
+}
+
+describe('MarketPageClient × session signing (A6-T4)', () => {
+ beforeEach(() => {
+ vi.spyOn(window, 'confirm').mockReturnValue(true);
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('privateKey with key: byte-identical limit_order_create tuple at the active floor', async () => {
+ renderMarket(privateKeyStore('alice', true));
+ await placeBuyOrder();
+
+ await waitFor(() => expect(mocks.broadcastLimitOrderCreate).toHaveBeenCalledTimes(1));
+ expect(mocks.sign).toHaveBeenCalledTimes(1);
+ const request = mocks.sign.mock.calls[0]![0];
+ expect(request.accountName).toBe('alice');
+ expect(request.role).toBe('active');
+ const [type, payload] = signedOperation();
+ // Exactly what SteemSigner.signLimitOrderCreate built: field order,
+ // fill_or_kill default, ISO expiration (not unix seconds).
+ expect(type).toBe('limit_order_create');
+ expect(payload).toEqual({
+ owner: 'alice',
+ amount_to_sell: '5.000 SBD',
+ min_to_receive: '5.000 STEEM',
+ fill_or_kill: false,
+ expiration: expect.stringMatching(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$/),
+ orderid: expect.any(Number),
+ });
+ // Object key order pinned byte-for-byte (serialization order matters).
+ expect(Object.keys(payload)).toEqual([
+ 'owner',
+ 'amount_to_sell',
+ 'min_to_receive',
+ 'fill_or_kill',
+ 'expiration',
+ 'orderid',
+ ]);
+ const orderid = payload.orderid as number;
+ expect(orderid).toBeGreaterThanOrEqual(0);
+ expect(orderid).toBeLessThanOrEqual(4_294_967_295);
+ expect(mocks.broadcastLimitOrderCreate).toHaveBeenCalledWith(
+ signedOutcome().result.signedTx,
+ 'alice'
+ );
+ });
+
+ it('vault identity session trades without any Redux key and NO login dialog', async () => {
+ renderMarket(vaultStore());
+ await placeBuyOrder();
+
+ await waitFor(() => expect(mocks.broadcastLimitOrderCreate).toHaveBeenCalledTimes(1));
+ // The pre-A6 gap: an authenticated vault session reopened the login
+ // dialog (identity selection loop). Now no LoginForm is ever rendered.
+ expect(mocks.loginFormCalls).toHaveLength(0);
+ });
+
+ it('keyless privateKey: needsClassicReauth opens the account-locked re-auth dialog', async () => {
+ mocks.sign.mockResolvedValueOnce({ status: 'needsClassicReauth' });
+ renderMarket(privateKeyStore('alice', false));
+ await placeBuyOrder();
+
+ await waitFor(() => expect(screen.getByTestId('login-form-probe')).toBeInTheDocument());
+ expect(mocks.sign).toHaveBeenCalledTimes(1);
+ expect(mocks.broadcastLimitOrderCreate).not.toHaveBeenCalled();
+ expect(mocks.loginFormCalls.at(-1)).toEqual({
+ fixedUsername: 'alice',
+ requiredAuthTypes: ['active'],
+ });
+ });
+
+ it('cancel: byte-identical limit_order_cancel tuple; vault session completes', async () => {
+ renderMarket(vaultStore());
+ await cancelOpenOrder();
+
+ await waitFor(() => expect(mocks.broadcastLimitOrderCancel).toHaveBeenCalledTimes(1));
+ expect(mocks.sign).toHaveBeenCalledTimes(1);
+ const request = mocks.sign.mock.calls[0]![0];
+ expect(request.accountName).toBe('alice');
+ expect(request.role).toBe('active');
+ expect(signedOperation()).toEqual([
+ 'limit_order_cancel',
+ { owner: 'alice', orderid: 42 },
+ ]);
+ expect(mocks.loginFormCalls).toHaveLength(0);
+ });
+
+ it('anonymous visitor: the sign-in dialog asks for the active authority, no fixed username', async () => {
+ const anonStore = configureStore({
+ reducer: { auth: authReducer },
+ preloadedState: { auth: BASE_AUTH },
+ });
+ renderMarket(anonStore);
+
+ fireEvent.click(screen.getByRole('button', { name: 'login' }));
+
+ await waitFor(() => expect(screen.getByTestId('login-form-probe')).toBeInTheDocument());
+ expect(mocks.loginFormCalls.at(-1)).toEqual({
+ fixedUsername: undefined,
+ requiredAuthTypes: ['active'],
+ });
+ });
+});
+
+/* ───────── ProposalsPageClient (update_proposal_votes) ───────── */
+
+const PROPOSAL = {
+ id: 1,
+ proposal_id: 1,
+ creator: 'creator',
+ receiver: 'receiver',
+ start_date: '2026-01-01T00:00:00',
+ end_date: '2027-01-01T00:00:00',
+ daily_pay: '10.000 SBD',
+ subject: 'Test proposal',
+ permlink: 'permlink',
+ total_votes: 0,
+ upVoted: false,
+};
+
+function okJson(body: unknown) {
+ return {
+ ok: true,
+ json: async () => body,
+ headers: new Headers(),
+ } as unknown as Response;
+}
+
+const mockFetch = vi.fn();
+
+function renderProposals(store: TestStore) {
+ mockFetch.mockImplementation((input: RequestInfo | URL) => {
+ const url = typeof input === 'string' ? input : input.toString();
+ if (url.includes('/api/query/proposals')) {
+ return Promise.resolve(okJson({ success: true, proposals: [{ ...PROPOSAL }] }));
+ }
+ return Promise.resolve(okJson({ success: true }));
+ });
+ vi.stubGlobal('fetch', mockFetch);
+ return render(
+
+
+
+ );
+}
+
+async function voteOnProposal() {
+ fireEvent.click(await screen.findByRole('button', { name: 'vote' }));
+}
+
+describe('ProposalsPageClient × session signing (A6-T4)', () => {
+ it('privateKey with key: byte-identical update_proposal_votes tuple at the ACTIVE floor', async () => {
+ renderProposals(privateKeyStore('alice', true));
+ await voteOnProposal();
+
+ await waitFor(() => expect(mocks.broadcastProposalVote).toHaveBeenCalledTimes(1));
+ expect(mocks.sign).toHaveBeenCalledTimes(1);
+ const request = mocks.sign.mock.calls[0]![0];
+ expect(request.accountName).toBe('alice');
+ // update_proposal_votes is an ACTIVE-class Steem operation (the legacy
+ // postingOps whitelist never listed it; the previous caller signed it
+ // with the active-or-owner key) — the floor preserves that resolution.
+ expect(request.role).toBe('active');
+ expect(signedOperation()).toEqual([
+ 'update_proposal_votes',
+ { voter: 'alice', proposal_ids: [1], approve: true },
+ ]);
+ });
+
+ it('vault identity session votes without any Redux key and NO login dialog', async () => {
+ renderProposals(vaultStore());
+ await voteOnProposal();
+
+ await waitFor(() => expect(mocks.broadcastProposalVote).toHaveBeenCalledTimes(1));
+ expect(mocks.loginFormCalls).toHaveLength(0);
+ });
+
+ it('keyless privateKey: needsClassicReauth rolls the optimistic vote back and opens re-auth', async () => {
+ mocks.sign.mockResolvedValueOnce({ status: 'needsClassicReauth' });
+ renderProposals(privateKeyStore('alice', false));
+ await voteOnProposal();
+
+ await waitFor(() => expect(screen.getByTestId('login-form-probe')).toBeInTheDocument());
+ expect(mocks.broadcastProposalVote).not.toHaveBeenCalled();
+ expect(mocks.loginFormCalls.at(-1)).toEqual({
+ fixedUsername: 'alice',
+ requiredAuthTypes: ['active'],
+ });
+ // Optimistic flip rolled back — the button still offers "vote". (The
+ // open re-auth dialog aria-hides the page tree, so query with hidden.)
+ await waitFor(() =>
+ expect(screen.getByRole('button', { name: 'vote', hidden: true })).toBeInTheDocument()
+ );
+ });
+
+ it('anonymous visitor: the sign-in dialog asks for the active authority, no fixed username', async () => {
+ const anonStore = configureStore({
+ reducer: { auth: authReducer },
+ preloadedState: { auth: BASE_AUTH },
+ });
+ renderProposals(anonStore);
+
+ fireEvent.click(await screen.findByRole('button', { name: 'login' }));
+
+ await waitFor(() => expect(screen.getByTestId('login-form-probe')).toBeInTheDocument());
+ expect(mocks.loginFormCalls.at(-1)).toEqual({
+ fixedUsername: undefined,
+ requiredAuthTypes: ['active'],
+ });
+ });
+});
+
+/* ───────── ProposalCreatorDialog (create_proposal) ───────── */
+
+function renderCreator(store: TestStore) {
+ const onSuccess = vi.fn();
+ render(
+
+
+
+ );
+ return { onSuccess };
+}
+
+function fillCreatorForm() {
+ fireEvent.change(screen.getByLabelText('createTitle'), { target: { value: 'Dev fund' } });
+ fireEvent.change(screen.getByLabelText('createDailyAmount'), { target: { value: '100' } });
+ fireEvent.change(screen.getByLabelText('createStartDate'), {
+ target: { value: '2026-10-01T00:00' },
+ });
+ fireEvent.change(screen.getByLabelText('createEndDate'), {
+ target: { value: '2026-10-15T00:00' },
+ });
+ fireEvent.change(screen.getByLabelText('createPermlink'), { target: { value: 'dev-fund-post' } });
+ fireEvent.change(screen.getByLabelText('createCreator'), { target: { value: 'Alice' } });
+ fireEvent.change(screen.getByLabelText('createReceiver'), { target: { value: '@Alice' } });
+}
+
+describe('ProposalCreatorDialog × session signing (A6-T4)', () => {
+ it('privateKey with key: byte-identical create_proposal tuple at the active floor', async () => {
+ const { onSuccess } = renderCreator(privateKeyStore('alice', true));
+ fillCreatorForm();
+ fireEvent.click(screen.getByRole('button', { name: 'createSubmit' }));
+
+ await waitFor(() => expect(onSuccess).toHaveBeenCalledTimes(1));
+ expect(mocks.broadcastProposalCreate).toHaveBeenCalledTimes(1);
+ const request = mocks.sign.mock.calls[0]![0];
+ expect(request.accountName).toBe('alice');
+ expect(request.role).toBe('active');
+ expect(signedOperation()).toEqual([
+ 'create_proposal',
+ {
+ creator: 'alice',
+ receiver: 'alice',
+ start_date: '2026-10-01T00:00:00',
+ end_date: '2026-10-15T00:00:00',
+ daily_pay: '100.000 SBD',
+ subject: 'Dev fund',
+ permlink: 'dev-fund-post',
+ },
+ ]);
+ });
+
+ it('vault identity session creates a proposal without any Redux key', async () => {
+ const { onSuccess } = renderCreator(vaultStore());
+ fillCreatorForm();
+ fireEvent.click(screen.getByRole('button', { name: 'createSubmit' }));
+
+ await waitFor(() => expect(onSuccess).toHaveBeenCalledTimes(1));
+ expect(mocks.broadcastProposalCreate).toHaveBeenCalledTimes(1);
+ expect(mocks.loginFormCalls).toHaveLength(0);
+ });
+
+ it('keyless privateKey: needsClassicReauth opens the account-locked re-auth dialog', async () => {
+ mocks.sign.mockResolvedValueOnce({ status: 'needsClassicReauth' });
+ const { onSuccess } = renderCreator(privateKeyStore('alice', false));
+ fillCreatorForm();
+ fireEvent.click(screen.getByRole('button', { name: 'createSubmit' }));
+
+ await waitFor(() => expect(screen.getByTestId('login-form-probe')).toBeInTheDocument());
+ expect(onSuccess).not.toHaveBeenCalled();
+ expect(mocks.broadcastProposalCreate).not.toHaveBeenCalled();
+ expect(mocks.loginFormCalls.at(-1)).toEqual({
+ fixedUsername: 'alice',
+ requiredAuthTypes: ['active'],
+ });
+ });
+});
+
+/* ───────── ProposalRemoveDialog (remove_proposal) ───────── */
+
+function renderRemove(store: TestStore) {
+ const onSuccess = vi.fn();
+ render(
+
+
+
+ );
+ return { onSuccess };
+}
+
+function confirmRemove() {
+ fireEvent.change(screen.getByLabelText('removeConfirmId'), { target: { value: '7' } });
+ fireEvent.click(screen.getByRole('button', { name: 'removeButton' }));
+}
+
+describe('ProposalRemoveDialog × session signing (A6-T4)', () => {
+ it('privateKey with key: byte-identical remove_proposal tuple at the active floor', async () => {
+ const { onSuccess } = renderRemove(privateKeyStore('alice', true));
+ confirmRemove();
+
+ await waitFor(() => expect(onSuccess).toHaveBeenCalledTimes(1));
+ expect(mocks.broadcastProposalRemove).toHaveBeenCalledTimes(1);
+ const request = mocks.sign.mock.calls[0]![0];
+ expect(request.accountName).toBe('alice');
+ expect(request.role).toBe('active');
+ expect(signedOperation()).toEqual([
+ 'remove_proposal',
+ { proposal_owner: 'alice', proposal_ids: [7] },
+ ]);
+ });
+
+ it('vault identity session removes a proposal without any Redux key', async () => {
+ const { onSuccess } = renderRemove(vaultStore());
+ confirmRemove();
+
+ await waitFor(() => expect(onSuccess).toHaveBeenCalledTimes(1));
+ expect(mocks.broadcastProposalRemove).toHaveBeenCalledTimes(1);
+ });
+
+ it('keyless privateKey: needsClassicReauth opens the account-locked re-auth dialog', async () => {
+ mocks.sign.mockResolvedValueOnce({ status: 'needsClassicReauth' });
+ const { onSuccess } = renderRemove(privateKeyStore('alice', false));
+ confirmRemove();
+
+ await waitFor(() => expect(screen.getByTestId('login-form-probe')).toBeInTheDocument());
+ expect(onSuccess).not.toHaveBeenCalled();
+ expect(mocks.broadcastProposalRemove).not.toHaveBeenCalled();
+ expect(mocks.loginFormCalls.at(-1)).toEqual({
+ fixedUsername: 'alice',
+ requiredAuthTypes: ['active'],
+ });
+ });
+});
+
+/* ───────── WitnessVoteForm (account_witness_vote / account_witness_proxy) ───────── */
+
+function renderWitness(store: TestStore) {
+ return render(
+
+
+
+ );
+}
+
+async function voteOnWitnessRow() {
+ // One table witness -> the enabled "vote" button is the row action (the
+ // quick-vote button renders immediately but stays disabled with an empty
+ // custom witness input, so wait for an ENABLED match).
+ const rowButton = await waitFor(() => {
+ const voteButtons = screen.getAllByRole('button', { name: 'vote' });
+ const enabled = voteButtons.find((button) => !button.hasAttribute('disabled'));
+ if (!enabled) throw new Error('witness row has not rendered an enabled vote button yet');
+ return enabled;
+ });
+ fireEvent.click(rowButton);
+}
+
+async function setProxy(proxy: string) {
+ // The label's text is the echoed i18n key of proxyTitle (htmlFor="proxy").
+ fireEvent.change(await screen.findByLabelText('proxyTitle'), { target: { value: proxy } });
+ fireEvent.click(screen.getByRole('button', { name: 'proxySet' }));
+}
+
+describe('WitnessVoteForm × session signing (A6-T4)', () => {
+ it('privateKey with key: byte-identical account_witness_vote tuple at the active floor', async () => {
+ renderWitness(privateKeyStore('alice', true));
+ await voteOnWitnessRow();
+
+ await waitFor(() => expect(mocks.broadcastWitnessVote).toHaveBeenCalledTimes(1));
+ expect(mocks.sign).toHaveBeenCalledTimes(1);
+ const request = mocks.sign.mock.calls[0]![0];
+ expect(request.accountName).toBe('alice');
+ expect(request.role).toBe('active');
+ expect(signedOperation()).toEqual([
+ 'account_witness_vote',
+ { account: 'alice', witness: 'witness1', approve: true },
+ ]);
+ expect(userActionRecord).toHaveBeenCalledWith('account_witness_vote', {
+ username: 'alice',
+ witness: 'witness1',
+ });
+ });
+
+ it('vault identity session votes through the password path — NO login dialog, NO notice (retirement pin)', async () => {
+ renderWitness(vaultStore());
+ await voteOnWitnessRow();
+
+ await waitFor(() => expect(mocks.broadcastWitnessVote).toHaveBeenCalledTimes(1));
+ // The pre-A6 signingKey gate re-opened the login dialog for a keyless
+ // vault session (which, with the old conditional fixedUsername pin,
+ // reached the Vault Mode "unsupported" notice). Neither renders now.
+ expect(mocks.loginFormCalls).toHaveLength(0);
+ expect(screen.queryByTestId('vault-mode-unsupported')).not.toBeInTheDocument();
+ });
+
+ it('keyless privateKey: needsClassicReauth opens re-auth and does NOT update the local votes', async () => {
+ mocks.sign.mockResolvedValueOnce({ status: 'needsClassicReauth' });
+ renderWitness(privateKeyStore('alice', false));
+ await voteOnWitnessRow();
+
+ await waitFor(() => expect(screen.getByTestId('login-form-probe')).toBeInTheDocument());
+ expect(mocks.broadcastWitnessVote).not.toHaveBeenCalled();
+ expect(mocks.loginFormCalls.at(-1)).toEqual({
+ fixedUsername: 'alice',
+ requiredAuthTypes: ['active'],
+ });
+ // No optimistic vote was recorded: the row still offers "vote". (The
+ // open re-auth dialog aria-hides the page tree, so query with hidden.)
+ await waitFor(() => {
+ const voteButtons = screen.getAllByRole('button', { name: 'vote', hidden: true });
+ expect(voteButtons.some((button) => !button.hasAttribute('disabled'))).toBe(true);
+ });
+ });
+
+ it('proxy: byte-identical account_witness_proxy tuple; vault session completes', async () => {
+ renderWitness(vaultStore());
+ await setProxy('bob');
+
+ await waitFor(() => expect(mocks.broadcastWitnessProxy).toHaveBeenCalledTimes(1));
+ expect(mocks.sign).toHaveBeenCalledTimes(1);
+ const request = mocks.sign.mock.calls[0]![0];
+ expect(request.accountName).toBe('alice');
+ expect(request.role).toBe('active');
+ expect(signedOperation()).toEqual([
+ 'account_witness_proxy',
+ { account: 'alice', proxy: 'bob' },
+ ]);
+ expect(userActionRecord).toHaveBeenCalledWith('account_witness_proxy', {
+ username: 'alice',
+ proxy: 'bob',
+ });
+ });
+
+ it('anonymous visitor: the sign-in dialog asks for the active authority, no fixed username', async () => {
+ const anonStore = configureStore({
+ reducer: { auth: authReducer },
+ preloadedState: { auth: BASE_AUTH },
+ });
+ renderWitness(anonStore);
+ // Any vote attempt from an anonymous visitor opens the login dialog.
+ await voteOnWitnessRow();
+
+ await waitFor(() => expect(screen.getByTestId('login-form-probe')).toBeInTheDocument());
+ expect(mocks.loginFormCalls.at(-1)).toEqual({
+ fixedUsername: undefined,
+ requiredAuthTypes: ['active'],
+ });
+ expect(mocks.sign).not.toHaveBeenCalled();
+ });
+});