Skip to content

feat: improved notifications + session key renewal + fix vrf example#92

Merged
jonasXchen merged 5 commits into
mainfrom
feat/improved-notifications
Jun 4, 2026
Merged

feat: improved notifications + session key renewal + fix vrf example#92
jonasXchen merged 5 commits into
mainfrom
feat/improved-notifications

Conversation

@jonasXchen
Copy link
Copy Markdown
Collaborator

@jonasXchen jonasXchen commented Jun 2, 2026

Summary by CodeRabbit

  • New Features

    • Alerts can include clickable Solana Explorer links and stay visible longer for interaction
    • Transaction feedback now includes structured messages with optional explorer URLs across examples
    • Session-keys: session expiry tracking, "Renew Session" CTA, and session-aware transaction flows
    • Roll-dice: bundled IDLs, roll count display, and event-driven VRF callbacks
  • Documentation

    • README reorganized with expanded, categorized examples
  • Chores

    • Example package/name updates and test script adjustments

@vercel
Copy link
Copy Markdown

vercel Bot commented Jun 2, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
counter-session-keys Ready Ready Preview, Comment Jun 4, 2026 7:10am
er-rolldice Canceled Canceled Jun 4, 2026 7:10am
magicblock-counter-example Ready Ready Preview, Comment Jun 4, 2026 7:10am
magicblock-engine-examples Ready Ready Preview, Comment Jun 4, 2026 7:10am
magicblock-rewards-dashboard Ready Ready Preview, Comment Jun 4, 2026 7:10am
spl-tokens Ready Ready Preview, Comment Jun 4, 2026 7:10am

Request Review

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jun 2, 2026

Review Change Stack

Walkthrough

The PR converts transaction feedback to structured objects with optional explorer URLs and extends Alert to render clickable external links. Session-keys gains session expiry tracking, temp keypair rotation, and sessionTokenV2 flows. A new pinocchio-private-counter program is added (with state, processor, entrypoint), roll-dice IDLs/programs/tests are updated to bundled IDLs and client_seed callbacks, and README/tests/scripts/package metadata are adjusted.

Changes

Transaction Feedback & Session Management

Layer / File(s) Summary
Alert component with href link support
00-LEGACY_EXAMPLES/*/components/Alert.tsx, anchor-counter/app/src/components/Alert.tsx, private-counter/app/src/components/Alert.tsx, session-keys/app/src/components/Alert.tsx
AlertProps adds optional href; Alert conditionally renders an external <a target="_blank"> (longer visibleMs) or a <div>; styling consolidated into containerStyle; timers depend on href.
Transaction state restructuring to objects
00-LEGACY_EXAMPLES/*/App.tsx, anchor-counter/app/src/App.tsx, private-counter/app/src/App.tsx, session-keys/app/src/App.tsx
transactionError and transactionSuccess changed from `string
Explorer URL generation in submitTransaction
00-LEGACY_EXAMPLES/*/App.tsx, anchor-counter/app/src/App.tsx, private-counter/app/src/App.tsx
submitTransaction/tx helpers initialize signature, construct Solana Explorer URLs for success/failure, and build ER custom URLs when submitting to ephemeral endpoints (including auth token fetching for TEE flows).
Legacy anchor-counter wiring
00-LEGACY_EXAMPLES/anchor-counter/app/src/App.tsx
Switch ephemeral counter WS subscription from confirmed to processed, guard uninitialized client in increase flow, compute confirmation commitment based on isDelegated, and pass watchAccount into submitTransaction for inline refresh.
private-counter error wiring
00-LEGACY_EXAMPLES/private-counter/app/src/App.tsx, private-counter/app/src/App.tsx
ER-not-ready and wallet-declined paths now set structured transactionError objects; submitTransaction builds explorerUrl on failure and stores it with the message.
Session expiry state and endpoint management
session-keys/app/src/App.tsx
Adds nowEpoch, sessionExpiresAt, isSessionExpired, centralized explorer helpers, and PUBLIC_ER_ENDPOINT; transaction reporting moved to structured objects.
Temp keypair nonce rotation and sessionTokenV2 migration
00-LEGACY_EXAMPLES/session-keys/app/src/App.tsx, session-keys/app/src/App.tsx
Per-wallet session nonce stored in localStorage with deriveTempKeypair for fresh temp keypair per session; session token seed updated to session_token_v2; revoke uses revokeSessionV2.
Counter increment and delegation flows with session checks
session-keys/app/src/App.tsx
Counter increment, delegate, undelegate, and revoke flows add session-expired guards, branch signing by temp keypair vs wallet, measure timing/signature, confirm on-chain errors, and set structured success/error messages (ER vs base explorer URLs).
Session creation transaction execution
session-keys/app/src/App.tsx
Rotate nonce, sign with temp keypair then wallet adapter, send/confirm transaction, verify session token PDA exists, set sessionTokenExists/sessionExpiresAt, and report structured success/error with explorer link.
Pinocchio private-counter program
pinocchio-private-counter/src/{entrypoint.rs,processor.rs,state.rs}, pinocchio-private-counter/*
Add new private-counter program: entrypoint discriminator handling for permission ops, processor implementing counter init/increment/delegate/permission lifecycle/commit hooks and callbacks, Counter state struct with loaders, README, package.json, and tests updated to new keypair and validator addresses.
Pinocchio secret-counter removal
pinocchio-secret-counter/src/{processor.rs,state.rs}
Remove legacy secret-counter processor and state files and associated public process_* functions.
roll-dice: bundled IDLs, helpers, programs, tests
roll-dice/app/lib/idl/*, roll-dice/app/lib/solana-utils.ts, roll-dice/app/app/*, roll-dice/programs/*, roll-dice/tests/*
Add loadIdl helper and bundled IDLs; update pages to use local-first IDL loading; add rollnum to Player state and pass client_seed through VRF request/callback; loosen oracle_queue constraints; update tests to subscribe to logs and wait for callback signatures.
Docs, scripts, package tweaks
README.md, test-locally.sh, roll-dice/Anchor.toml, package.json files
Rewrite Examples section in README; update local test script commands and rust deploy step; adjust Anchor test script; update package names and test scripts for pinocchio-private-counter; small dependency version pin in session-keys package.json.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Suggested reviewers

  • GabrielePicco
  • taco-paco
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 26.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The PR title accurately summarizes the primary changes: improved notifications (structured explorer-link messages across multiple examples), session key renewal (session expiry tracking and "Renew Session" UI), and VRF example fixes (updated oracle queue constraints, program IDs, client_seed handling).

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/improved-notifications

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@00-LEGACY_EXAMPLES/anchor-counter/app/src/components/Alert.tsx`:
- Around line 58-64: The anchor rendered in the Alert component when href is
present should include an aria-label to inform screen reader users that the link
opens in a new tab; update the <a> element in the Alert component (the block
handling href) to add an aria-label that combines the visible message and a
clear hint like "(opens in a new tab)" (e.g., use aria-label={`${message} (opens
in a new tab)`}) so the link text and behavior are announced together.

In `@00-LEGACY_EXAMPLES/private-counter/app/src/App.tsx`:
- Around line 394-410: The code that builds explorerUrl inside the error handler
can mask the original transaction error if ensureAuthToken() throws; wrap the
call to ensureAuthToken() in a try-catch inside the block that checks ephemeral
and signature (the same place where explorerUrl is assigned), so any error from
ensureAuthToken() is caught and does not overwrite or change the original
transaction error; if token retrieval fails, proceed without the token (i.e.,
leave explorerUrl undefined or build the URL without the token) and optionally
log the token retrieval error, then call setTransactionError({ message:
`Transaction failed: ${error}`, explorerUrl }) as before.

In `@00-LEGACY_EXAMPLES/session-keys/app/src/App.tsx`:
- Around line 150-159: The deriveTempKeypair implementation uses insecure
XOR-based seed construction; replace it with a proper KDF (e.g., HKDF via Web
Crypto subtle APIs) so the 32-byte seed is derived cryptographically from the
public key and nonce, make deriveTempKeypair async and update call sites to
await it, and keep returning Keypair.fromSeed(seed) (where seed is the 32-byte
output of the HKDF) so callers using deriveTempKeypair and Keypair.fromSeed
continue to work correctly.

In `@00-LEGACY_EXAMPLES/session-keys/app/src/components/Alert.tsx`:
- Around line 58-64: The anchor returned when href is present lacks an
aria-label to announce that the link opens in a new tab; update the JSX in the
Alert component (the branch that returns <a href={href} ...
style={containerStyle}>) to include a descriptive aria-label that mentions the
link target and that it opens in a new tab (e.g., use the message or a default
text plus "opens in a new tab") so screen readers are informed; ensure you still
keep target="_blank" and rel="noopener noreferrer".

In `@session-keys/app/src/App.tsx`:
- Around line 539-552: The two branches of the if (sessionTokenPDA.current)
duplicate the success handling; keep only the branch-specific action
setSessionTokenExists(true) in the else, then move the shared logic
(setSessionExpiresAt(validUntilBN.toNumber()), compute totalMs from
performance.now() - txStart, and setTransactionSuccess({ message: `[Base]
Session created in ${totalMs}ms`, explorerUrl: baseExplorerUrl(signature) })) to
execute once after the conditional. Update references to validUntilBN, txStart,
signature, baseExplorerUrl, setSessionExpiresAt, and setTransactionSuccess
accordingly so behavior is unchanged.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 7055c5b5-187c-4b0c-9eb2-93df8cb8f515

📥 Commits

Reviewing files that changed from the base of the PR and between b62e133 and 66955a1.

📒 Files selected for processing (10)
  • 00-LEGACY_EXAMPLES/anchor-counter/app/src/App.tsx
  • 00-LEGACY_EXAMPLES/anchor-counter/app/src/components/Alert.tsx
  • 00-LEGACY_EXAMPLES/private-counter/app/src/App.tsx
  • 00-LEGACY_EXAMPLES/session-keys/app/src/App.tsx
  • 00-LEGACY_EXAMPLES/session-keys/app/src/components/Alert.tsx
  • anchor-counter/app/src/App.tsx
  • anchor-counter/app/src/components/Alert.tsx
  • private-counter/app/src/App.tsx
  • session-keys/app/src/App.tsx
  • session-keys/app/src/components/Alert.tsx

Comment on lines +58 to +64
if (href) {
return (
<a href={href} target="_blank" rel="noopener noreferrer" style={containerStyle}>
{message} <span style={{ marginLeft: 4 }}>↗</span>
</a>
);
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick | 🔵 Trivial | 💤 Low value

Consider adding aria-label for screen reader users.

The external link opens in a new tab but doesn't announce this to screen readers. Adding an aria-label would improve accessibility.

♿ Optional accessibility enhancement
 if (href) {
     return (
-        <a href={href} target="_blank" rel="noopener noreferrer" style={containerStyle}>
+        <a 
+            href={href} 
+            target="_blank" 
+            rel="noopener noreferrer" 
+            aria-label={`${message} (opens in new tab)`}
+            style={containerStyle}
+        >
             {message} <span style={{ marginLeft: 4 }}>↗</span>
         </a>
     );
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (href) {
return (
<a href={href} target="_blank" rel="noopener noreferrer" style={containerStyle}>
{message} <span style={{ marginLeft: 4 }}></span>
</a>
);
}
if (href) {
return (
<a
href={href}
target="_blank"
rel="noopener noreferrer"
aria-label={`${message} (opens in new tab)`}
style={containerStyle}
>
{message} <span style={{ marginLeft: 4 }}></span>
</a>
);
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@00-LEGACY_EXAMPLES/anchor-counter/app/src/components/Alert.tsx` around lines
58 - 64, The anchor rendered in the Alert component when href is present should
include an aria-label to inform screen reader users that the link opens in a new
tab; update the <a> element in the Alert component (the block handling href) to
add an aria-label that combines the visible message and a clear hint like
"(opens in a new tab)" (e.g., use aria-label={`${message} (opens in a new
tab)`}) so the link text and behavior are announced together.

Comment on lines +394 to +410
// If the tx made it on-chain (signature was returned by sendRawTransaction),
// attach an explorer link so the user can inspect the failure logs.
let explorerUrl: string | undefined;
if (signature) {
if (ephemeral) {
const token = await ensureAuthToken();
if (token) {
explorerUrl = `https://explorer.solana.com/tx/${signature}?cluster=custom&customUrl=${encodeURIComponent(PRIVATE_ER_ENDPOINT + '?token=' + token)}`;
}
} else {
explorerUrl = `https://explorer.solana.com/tx/${signature}?cluster=devnet`;
}
}
setTransactionError({
message: `Transaction failed: ${error}`,
explorerUrl,
});
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Wrap ensureAuthToken() in try-catch to prevent masking the original error.

If ensureAuthToken() throws in the catch block, the original transaction error will be masked and the user won't see the failure message.

🛡️ Proposed fix to handle potential ensureAuthToken failure
         let explorerUrl: string | undefined;
         if (signature) {
             if (ephemeral) {
-                const token = await ensureAuthToken();
-                if (token) {
-                    explorerUrl = `https://explorer.solana.com/tx/${signature}?cluster=custom&customUrl=${encodeURIComponent(PRIVATE_ER_ENDPOINT + '?token=' + token)}`;
+                try {
+                    const token = await ensureAuthToken();
+                    if (token) {
+                        explorerUrl = `https://explorer.solana.com/tx/${signature}?cluster=custom&customUrl=${encodeURIComponent(PRIVATE_ER_ENDPOINT + '?token=' + token)}`;
+                    }
+                } catch (tokenErr) {
+                    console.error("Failed to get auth token for explorer URL:", tokenErr);
                 }
             } else {
                 explorerUrl = `https://explorer.solana.com/tx/${signature}?cluster=devnet`;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// If the tx made it on-chain (signature was returned by sendRawTransaction),
// attach an explorer link so the user can inspect the failure logs.
let explorerUrl: string | undefined;
if (signature) {
if (ephemeral) {
const token = await ensureAuthToken();
if (token) {
explorerUrl = `https://explorer.solana.com/tx/${signature}?cluster=custom&customUrl=${encodeURIComponent(PRIVATE_ER_ENDPOINT + '?token=' + token)}`;
}
} else {
explorerUrl = `https://explorer.solana.com/tx/${signature}?cluster=devnet`;
}
}
setTransactionError({
message: `Transaction failed: ${error}`,
explorerUrl,
});
// If the tx made it on-chain (signature was returned by sendRawTransaction),
// attach an explorer link so the user can inspect the failure logs.
let explorerUrl: string | undefined;
if (signature) {
if (ephemeral) {
try {
const token = await ensureAuthToken();
if (token) {
explorerUrl = `https://explorer.solana.com/tx/${signature}?cluster=custom&customUrl=${encodeURIComponent(PRIVATE_ER_ENDPOINT + '?token=' + token)}`;
}
} catch (tokenErr) {
console.error("Failed to get auth token for explorer URL:", tokenErr);
}
} else {
explorerUrl = `https://explorer.solana.com/tx/${signature}?cluster=devnet`;
}
}
setTransactionError({
message: `Transaction failed: ${error}`,
explorerUrl,
});
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@00-LEGACY_EXAMPLES/private-counter/app/src/App.tsx` around lines 394 - 410,
The code that builds explorerUrl inside the error handler can mask the original
transaction error if ensureAuthToken() throws; wrap the call to
ensureAuthToken() in a try-catch inside the block that checks ephemeral and
signature (the same place where explorerUrl is assigned), so any error from
ensureAuthToken() is caught and does not overwrite or change the original
transaction error; if token retrieval fails, proceed without the token (i.e.,
leave explorerUrl undefined or build the URL without the token) and optionally
log the token retrieval error, then call setTransactionError({ message:
`Transaction failed: ${error}`, explorerUrl }) as before.

Comment on lines +150 to +159
const deriveTempKeypair = useCallback((pk: PublicKey, nonce: string) => {
// 32-byte seed from sha256(publicKey || nonce). Use Web Crypto for portability.
const seedBytes = new Uint8Array(32);
const src = new TextEncoder().encode(pk.toBase58() + ":" + nonce);
// Synchronous-ish: borrow first 32 bytes by hashing manually via subtle isn't sync.
// Simpler: pad/truncate the raw bytes ourselves since they don't need to be uniform.
const raw = new Uint8Array(pk.toBytes());
for (let i = 0; i < 32; i++) seedBytes[i] = raw[i] ^ (src[i % src.length] ?? 0);
return Keypair.fromSeed(seedBytes);
}, []);
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Use a proper KDF instead of XOR for key derivation.

The XOR-based seed derivation is not cryptographically sound. Even for demo purposes, this weakens the security model and could lead to predictable session keys. Use a proper key derivation function like HKDF via Web Crypto API.

🔐 Proposed fix using Web Crypto subtle.deriveBits
-const deriveTempKeypair = useCallback((pk: PublicKey, nonce: string) => {
-    // 32-byte seed from sha256(publicKey || nonce). Use Web Crypto for portability.
-    const seedBytes = new Uint8Array(32);
-    const src = new TextEncoder().encode(pk.toBase58() + ":" + nonce);
-    // Synchronous-ish: borrow first 32 bytes by hashing manually via subtle isn't sync.
-    // Simpler: pad/truncate the raw bytes ourselves since they don't need to be uniform.
-    const raw = new Uint8Array(pk.toBytes());
-    for (let i = 0; i < 32; i++) seedBytes[i] = raw[i] ^ (src[i % src.length] ?? 0);
-    return Keypair.fromSeed(seedBytes);
-}, []);
+const deriveTempKeypair = useCallback(async (pk: PublicKey, nonce: string) => {
+    // Proper KDF using Web Crypto API
+    const encoder = new TextEncoder();
+    const keyMaterial = encoder.encode(pk.toBase58() + ":" + nonce);
+    const hashBuffer = await crypto.subtle.digest('SHA-256', keyMaterial);
+    const seedBytes = new Uint8Array(hashBuffer);
+    return Keypair.fromSeed(seedBytes);
+}, []);

Note: This makes deriveTempKeypair async. You'll need to await it at the call sites (lines 165, 468).

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@00-LEGACY_EXAMPLES/session-keys/app/src/App.tsx` around lines 150 - 159, The
deriveTempKeypair implementation uses insecure XOR-based seed construction;
replace it with a proper KDF (e.g., HKDF via Web Crypto subtle APIs) so the
32-byte seed is derived cryptographically from the public key and nonce, make
deriveTempKeypair async and update call sites to await it, and keep returning
Keypair.fromSeed(seed) (where seed is the 32-byte output of the HKDF) so callers
using deriveTempKeypair and Keypair.fromSeed continue to work correctly.

Comment on lines +58 to +64
if (href) {
return (
<a href={href} target="_blank" rel="noopener noreferrer" style={containerStyle}>
{message} <span style={{ marginLeft: 4 }}>↗</span>
</a>
);
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick | 🔵 Trivial | 💤 Low value

Consider adding aria-label for screen reader users.

The external link opens in a new tab but doesn't announce this to screen readers. Adding an aria-label would improve accessibility.

♿ Optional accessibility enhancement
 if (href) {
     return (
-        <a href={href} target="_blank" rel="noopener noreferrer" style={containerStyle}>
+        <a 
+            href={href} 
+            target="_blank" 
+            rel="noopener noreferrer" 
+            aria-label={`${message} (opens in new tab)`}
+            style={containerStyle}
+        >
             {message} <span style={{ marginLeft: 4 }}>↗</span>
         </a>
     );
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (href) {
return (
<a href={href} target="_blank" rel="noopener noreferrer" style={containerStyle}>
{message} <span style={{ marginLeft: 4 }}></span>
</a>
);
}
if (href) {
return (
<a
href={href}
target="_blank"
rel="noopener noreferrer"
aria-label={`${message} (opens in new tab)`}
style={containerStyle}
>
{message} <span style={{ marginLeft: 4 }}></span>
</a>
);
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@00-LEGACY_EXAMPLES/session-keys/app/src/components/Alert.tsx` around lines 58
- 64, The anchor returned when href is present lacks an aria-label to announce
that the link opens in a new tab; update the JSX in the Alert component (the
branch that returns <a href={href} ... style={containerStyle}>) to include a
descriptive aria-label that mentions the link target and that it opens in a new
tab (e.g., use the message or a default text plus "opens in a new tab") so
screen readers are informed; ensure you still keep target="_blank" and
rel="noopener noreferrer".

Comment on lines +539 to +552
setSessionExpiresAt(validUntilBN.toNumber());
const totalMs = Math.round(performance.now() - txStart);
setTransactionSuccess({
message: `[Base] Session created in ${totalMs}ms`,
explorerUrl: baseExplorerUrl(signature),
});
} else {
setSessionTokenExists(true);
setTransactionSuccess(`Session created successfully`);
setSessionExpiresAt(validUntilBN.toNumber());
const totalMs = Math.round(performance.now() - txStart);
setTransactionSuccess({
message: `[Base] Session created in ${totalMs}ms`,
explorerUrl: baseExplorerUrl(signature),
});
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick | 🔵 Trivial | ⚡ Quick win

Refactor to eliminate duplicated success-message block.

The success-message logic is duplicated in both branches of the if (sessionTokenPDA.current) conditional. Extract it to run once after the conditional completes.

♻️ Consolidate success handling
             }
             setSessionTokenExists(true);
             setSessionExpiresAt(validUntilBN.toNumber());
-            const totalMs = Math.round(performance.now() - txStart);
-            setTransactionSuccess({
-                message: `[Base] Session created in ${totalMs}ms`,
-                explorerUrl: baseExplorerUrl(signature),
-            });
         } else {
             setSessionTokenExists(true);
             setSessionExpiresAt(validUntilBN.toNumber());
-            const totalMs = Math.round(performance.now() - txStart);
-            setTransactionSuccess({
-                message: `[Base] Session created in ${totalMs}ms`,
-                explorerUrl: baseExplorerUrl(signature),
-            });
         }
+        const totalMs = Math.round(performance.now() - txStart);
+        setTransactionSuccess({
+            message: `[Base] Session created in ${totalMs}ms`,
+            explorerUrl: baseExplorerUrl(signature),
+        });
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@session-keys/app/src/App.tsx` around lines 539 - 552, The two branches of the
if (sessionTokenPDA.current) duplicate the success handling; keep only the
branch-specific action setSessionTokenExists(true) in the else, then move the
shared logic (setSessionExpiresAt(validUntilBN.toNumber()), compute totalMs from
performance.now() - txStart, and setTransactionSuccess({ message: `[Base]
Session created in ${totalMs}ms`, explorerUrl: baseExplorerUrl(signature) })) to
execute once after the conditional. Update references to validUntilBN, txStart,
signature, baseExplorerUrl, setSessionExpiresAt, and setTransactionSuccess
accordingly so behavior is unchanged.

@jonasXchen jonasXchen merged commit ccf32f1 into main Jun 4, 2026
8 of 10 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant