Skip to content

Stylus CLI updates #7502

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 19 commits into from
Jul 4, 2025
Merged

Stylus CLI updates #7502

merged 19 commits into from
Jul 4, 2025

Conversation

kumaryash90
Copy link
Member

@kumaryash90 kumaryash90 commented Jul 2, 2025


PR-Codex overview

This PR introduces new functionalities and enhancements related to the Stylus extension in the thirdweb package, including new contract methods, event handling, and improvements in project creation and deployment processes.

Detailed summary

  • Added stylus_constructor function to IStylusConstructor.json.
  • Enhanced IStylusDeployer.json with deploy function and ContractDeployed event.
  • Updated IArbWasm.json to include codehashVersion function.
  • Changed ARB_WASM_ADDRESS to be exported in activateStylusContract.ts.
  • Added deployment methods and event handling in deploy-with-abi.ts.
  • Introduced isStylus_constructorSupported and stylus_constructor functions in stylus_constructor.ts.
  • Enhanced checkPrerequisites function for better error handling.
  • Improved project creation with additional templates in create.ts.
  • Added codehashVersion function with encoding and decoding capabilities in codehashVersion.ts.
  • Added deploy function with parameter encoding in IStylusDeployer/write/deploy.ts.

✨ Ask PR-Codex anything about this PR by commenting with /codex {your question}

Summary by CodeRabbit

  • New Features

    • Added new project templates: "ERC721", "ERC1155", "Airdrop ERC20", "Airdrop ERC721", and "Airdrop ERC1155".
    • Introduced Stylus contract deployment with constructor parameter support.
    • Added detection and integration of Stylus constructor signatures during contract build.
    • Included new contract interfaces for Stylus deployment and constructor handling.
    • Added a mechanism to verify if a Stylus contract is activated on-chain before deployment.
  • Improvements

    • Unified error handling for project creation.
    • Enhanced contract deployment flow to support Stylus-specific deployment events.
    • Added prerequisite checks for Rust and Solidity tooling before build and deploy commands.
    • Exported key constants for broader usage across modules.

@kumaryash90 kumaryash90 requested review from a team as code owners July 2, 2025 10:29
Copy link

vercel bot commented Jul 2, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
docs-v2 ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jul 4, 2025 3:35pm
nebula ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jul 4, 2025 3:35pm
thirdweb_playground ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jul 4, 2025 3:35pm
thirdweb-www ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jul 4, 2025 3:35pm
wallet-ui ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jul 4, 2025 3:35pm

Copy link

changeset-bot bot commented Jul 2, 2025

⚠️ No Changeset found

Latest commit: 16fdd1e

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

Copy link
Contributor

coderabbitai bot commented Jul 2, 2025

"""

Walkthrough

The CLI project creation flow is extended with new Stylus project templates including ERC721, ERC1155, and various airdrop types. Project creation logic is unified into a single variable with consolidated error handling after all template cloning attempts. Additionally, new ABI files, deployment logic for Stylus contracts with constructors, constructor signature parsing, and prerequisite tool checks are introduced.

Changes

File(s) Change Summary
packages/thirdweb/src/cli/commands/stylus/create.ts Added multiple new Stylus project templates (ERC721, ERC1155, Airdrop ERC20/ERC721/ERC1155), unified project creation and error handling, added prerequisite checks.
packages/thirdweb/scripts/generate/abis/stylus/IStylusConstructor.json Added new ABI file defining stylus_constructor() function signature.
packages/thirdweb/scripts/generate/abis/stylus/IStylusDeployer.json Added new ABI file for IStylusDeployer interface with deploy function and ContractDeployed event.
packages/thirdweb/scripts/generate/abis/stylus/IArbWasm.json Added new function codehashVersion(bytes32) to existing ABI JSON file.
packages/thirdweb/src/cli/commands/stylus/builder.ts Added detection and parsing of Stylus constructor signature, converting it to ABI and prepending it to the ABI array; added prerequisite checks.
packages/thirdweb/src/cli/commands/stylus/check-prerequisites.ts Added helper function to check presence and versions of required CLI tools with spinner feedback and error handling.
packages/thirdweb/src/contract/deployment/deploy-with-abi.ts Extended deployContract to support Stylus contract deployment using deployWithStylusConstructor and event-based address extraction.
packages/thirdweb/src/extensions/stylus/write/deployWithStylusConstructor.ts Added deployWithStylusConstructor function to deploy Stylus contracts with constructor parameters, encoding calldata accordingly.
packages/thirdweb/src/extensions/stylus/write/isContractActivated.ts Added isContractActivated function to verify contract activation status by extracting runtime bytecode and querying on-chain precompile.
packages/thirdweb/src/extensions/stylus/write/activateStylusContract.ts Exported ARB_WASM_ADDRESS constant for external use.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant CLI
    participant GitRepo

    User->>CLI: Select Stylus project type (ERC20, ERC721, ERC1155, Airdrop variants)
    CLI->>CLI: Check prerequisites (cargo, rustc, solc)
    CLI->>CLI: Assign newProject via spawnSync based on selected template
    CLI->>GitRepo: Clone corresponding template repository
    CLI->>CLI: Check newProject exit status
    alt Success
        CLI->>User: Confirm project creation
    else Failure
        CLI->>User: Show error and exit
    end
Loading
sequenceDiagram
    participant Builder
    participant StylusCLI

    Builder->>StylusCLI: Run `cargo stylus constructor` to get constructor signature
    StylusCLI->>Builder: Return constructor signature string
    Builder->>Builder: Parse signature string to ABI constructor object
    Builder->>Builder: Prepend constructor ABI to ABI array if missing
Loading
sequenceDiagram
    participant DeployFunction
    participant StylusDeployerContract
    participant Blockchain

    DeployFunction->>StylusDeployerContract: Prepare deploy transaction with bytecode, encoded constructor calldata, zero value, zero salt
    DeployFunction->>Blockchain: Send and confirm transaction
    Blockchain->>DeployFunction: Emit ContractDeployed event with deployed contract address
    DeployFunction->>DeployFunction: Parse event logs and extract deployed address
Loading

Possibly related PRs

  • Stylus ERC20 template for CLI #7192: Adds an ERC20 template and enhances ABI contract name extraction and selection in the Stylus CLI builder, related to project creation and ABI handling.

Suggested reviewers

  • joaquim-verges
    """

Warning

Review ran into problems

🔥 Problems

Errors were encountered while retrieving linked issues.

Errors (1)
  • TEAM-0000: Entity not found: Issue - Could not find referenced Issue.
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@kumaryash90 kumaryash90 marked this pull request as draft July 2, 2025 10:29
Copy link
Contributor

graphite-app bot commented Jul 2, 2025

How to use the Graphite Merge Queue

Add either label to this PR to merge it via the merge queue:

  • merge-queue - adds this PR to the back of the merge queue
  • hotfix - for urgent hot fixes, skip the queue and merge this PR next

You must have a Graphite account in order to use the merge queue. Sign up using this link.

An organization admin has enabled the Graphite Merge Queue in this repository.

Please do not merge from GitHub as this will restart CI on PRs being processed by the merge queue.

@github-actions github-actions bot added packages SDK Involves changes to the thirdweb SDK labels Jul 2, 2025
@kumaryash90 kumaryash90 added the DO NOT MERGE This pull request is still in progress and is not ready to be merged. label Jul 2, 2025
Copy link
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: 2

🧹 Nitpick comments (1)
packages/thirdweb/src/cli/commands/stylus/create.ts (1)

66-72: Consider refactoring to reduce code duplication.

The ERC721 branch is nearly identical to the ERC20 branch, differing only in the repository URL and spinner message. Consider extracting the common logic into a helper function.

+  const cloneTemplate = (templateType: string, repoUrl: string, projectName: string) => {
+    spinner.start(`Creating new ${templateType} Stylus project: ${projectName}...`);
+    return spawnSync("git", ["clone", repoUrl, projectName], {
+      stdio: "inherit",
+    });
+  };
+
   } else if (projectType === "erc20") {
-    const repoUrl = "[email protected]:thirdweb-example/stylus-erc20-template.git";
-    spinner.start(`Creating new ERC20 Stylus project: ${projectName}...`);
-    newProject = spawnSync("git", ["clone", repoUrl, projectName], {
-      stdio: "inherit",
-    });
+    newProject = cloneTemplate("ERC20", "[email protected]:thirdweb-example/stylus-erc20-template.git", projectName);
   } else if (projectType === "erc721") {
-    const repoUrl = "[email protected]:thirdweb-example/stylus-erc721-template.git";
-    spinner.start(`Creating new ERC721 Stylus project: ${projectName}...`);
-    newProject = spawnSync("git", ["clone", repoUrl, projectName], {
-      stdio: "inherit",
-    });
+    newProject = cloneTemplate("ERC721", "[email protected]:thirdweb-example/stylus-erc721-template.git", projectName);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 85c4ef1 and c01e0a8.

📒 Files selected for processing (1)
  • packages/thirdweb/src/cli/commands/stylus/create.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.{ts,tsx}`: Write idiomatic TypeScript with explicit function declarations ...

**/*.{ts,tsx}: Write idiomatic TypeScript with explicit function declarations and return types
Limit each file to one stateless, single-responsibility function for clarity
Re-use shared types from @/types or local types.ts barrels
Prefer type aliases over interface except for nominal shapes
Avoid any and unknown unless unavoidable; narrow generics when possible
Choose composition over inheritance; leverage utility types (Partial, Pick, etc.)
Comment only ambiguous logic; avoid restating TypeScript in prose
Load heavy dependencies inside async paths to keep initial bundle lean (lazy loading)

📄 Source: CodeRabbit Inference Engine (CLAUDE.md)

List of files the instruction was applied to:

  • packages/thirdweb/src/cli/commands/stylus/create.ts
🧠 Learnings (2)
📓 Common learnings
Learnt from: CR
PR: thirdweb-dev/js#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-30T10:25:29.488Z
Learning: Surface breaking changes prominently in PR descriptions
Learnt from: MananTank
PR: thirdweb-dev/js#7315
File: apps/dashboard/src/app/(app)/team/[team_slug]/[project_slug]/(sidebar)/assets/create/nft/form.ts:25-42
Timestamp: 2025-06-10T00:46:00.514Z
Learning: In NFT creation functions, the setClaimConditions function signatures are intentionally different between ERC721 and ERC1155. ERC721 setClaimConditions accepts the full CreateNFTFormValues, while ERC1155 setClaimConditions accepts a custom object with nftCollectionInfo and nftBatch parameters because it processes batches differently than the entire form data.
packages/thirdweb/src/cli/commands/stylus/create.ts (1)
Learnt from: MananTank
PR: thirdweb-dev/js#7434
File: apps/dashboard/src/app/(app)/team/~/~/contract/[chain]/[contractAddress]/components/project-selector.tsx:62-76
Timestamp: 2025-06-24T21:38:03.155Z
Learning: In the project-selector.tsx component for contract imports, the addToProject.mutate() call is intentionally not awaited (fire-and-forget pattern) to allow immediate navigation to the contract page while the import happens in the background. This is a deliberate design choice to prioritize user experience.
⏰ Context from checks skipped due to timeout of 90000ms (8)
  • GitHub Check: Unit Tests
  • GitHub Check: E2E Tests (pnpm, vite)
  • GitHub Check: Size
  • GitHub Check: Build Packages
  • GitHub Check: E2E Tests (pnpm, esbuild)
  • GitHub Check: E2E Tests (pnpm, webpack)
  • GitHub Check: Lint Packages
  • GitHub Check: Analyze (javascript)
🔇 Additional comments (1)
packages/thirdweb/src/cli/commands/stylus/create.ts (1)

46-46: LGTM: ERC721 template option added correctly.

The new ERC721 template option follows the existing pattern and integrates well with the project type selection.

],
message: "Select a template:",
name: "projectType",
type: "select",
});

// Step 5: Create the project
let newProject;
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add explicit type annotation to comply with coding guidelines.

The variable declaration violates the coding guidelines which require explicit types and avoiding any. The implicit any type should be replaced with the proper return type.

-  let newProject;
+  let newProject: ReturnType<typeof spawnSync>;
📝 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
let newProject;
let newProject: ReturnType<typeof spawnSync>;
🤖 Prompt for AI Agents
In packages/thirdweb/src/cli/commands/stylus/create.ts at line 54, the variable
newProject is declared without an explicit type, causing an implicit any type
violation. Add an explicit type annotation to newProject that matches the
expected return type of the value it will hold, ensuring compliance with coding
guidelines that forbid implicit any types.

Comment on lines 74 to 77
if (!newProject?.status || newProject.status !== 0) {
spinner.fail("Failed to create Stylus project.");
process.exit(1);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add explicit handling for unexpected project types.

The unified error handling is good, but if projectType doesn't match any known values, newProject remains undefined and triggers the error condition. Consider adding an explicit else clause or validation.

+  } else {
+    spinner.fail(`Unknown project type: ${projectType}`);
+    process.exit(1);
+  }
+
-  if (!newProject?.status || newProject.status !== 0) {
+  if (!newProject || newProject.status !== 0) {

This makes the error handling more explicit and removes the need for optional chaining since newProject will always be defined at this point.

🤖 Prompt for AI Agents
In packages/thirdweb/src/cli/commands/stylus/create.ts around lines 74 to 77,
add explicit validation for the projectType before creating newProject to ensure
it matches known values. Include an else clause that handles unexpected
projectType values by setting newProject to a defined error state or throwing an
error. This will guarantee newProject is always defined, allowing you to remove
optional chaining and make error handling more explicit and clear.

Copy link
Contributor

github-actions bot commented Jul 2, 2025

size-limit report 📦

Path Size Loading time (3g) Running time (snapdragon) Total time
thirdweb (esm) 63.2 KB (0%) 1.3 s (0%) 369 ms (+87.82% 🔺) 1.7 s
thirdweb (cjs) 352.68 KB (0%) 7.1 s (0%) 1.5 s (-3.76% 🔽) 8.6 s
thirdweb (minimal + tree-shaking) 5.69 KB (0%) 114 ms (0%) 112 ms (+719.69% 🔺) 226 ms
thirdweb/chains (tree-shaking) 526 B (0%) 11 ms (0%) 21 ms (+462.62% 🔺) 31 ms
thirdweb/react (minimal + tree-shaking) 19.57 KB (0%) 392 ms (0%) 81 ms (+222.93% 🔺) 472 ms

Copy link

codecov bot commented Jul 2, 2025

Codecov Report

Attention: Patch coverage is 10.82803% with 140 lines in your changes missing coverage. Please review.

Project coverage is 51.86%. Comparing base (7500d87) to head (4962bbc).

Files with missing lines Patch % Lines
...src/extensions/stylus/write/isContractActivated.ts 5.19% 73 Missing ⚠️
...hirdweb/src/contract/deployment/deploy-with-abi.ts 8.88% 40 Missing and 1 partial ⚠️
...nsions/stylus/write/deployWithStylusConstructor.ts 23.52% 26 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #7502      +/-   ##
==========================================
- Coverage   51.96%   51.86%   -0.11%     
==========================================
  Files         952      954       +2     
  Lines       64220    64375     +155     
  Branches     4237     4240       +3     
==========================================
+ Hits        33375    33391      +16     
- Misses      30738    30876     +138     
- Partials      107      108       +1     
Flag Coverage Δ
packages 51.86% <10.82%> (-0.11%) ⬇️
Files with missing lines Coverage Δ
.../extensions/stylus/write/activateStylusContract.ts 12.28% <100.00%> (ø)
...nsions/stylus/write/deployWithStylusConstructor.ts 23.52% <23.52%> (ø)
...hirdweb/src/contract/deployment/deploy-with-abi.ts 52.90% <8.88%> (-17.37%) ⬇️
...src/extensions/stylus/write/isContractActivated.ts 5.19% <5.19%> (ø)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Copy link
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: 1

🧹 Nitpick comments (2)
packages/thirdweb/src/extensions/stylus/write/isContractActivated.ts (2)

14-33: Consider logging errors for debugging purposes.

While the boolean return pattern is appropriate for an activation check, swallowing all errors silently might make debugging difficult. Consider adding optional error logging or returning a result object with error details.

 export async function isContractActivated(
   options: IsContractActivatedOptions,
 ): Promise<boolean> {
   const { chain, client, bytecode } = options;
   const arbWasmPrecompile = getContract({
     address: ARB_WASM_ADDRESS,
     chain,
     client,
   });
 
   try {
     await codehashVersion({
       codehash: keccak256(extractRuntimeBytecode(bytecode)),
       contract: arbWasmPrecompile,
     });
     return true;
-  } catch {
+  } catch (error) {
+    // Optionally log for debugging while maintaining the simple boolean API
+    if (process.env.NODE_ENV === 'development') {
+      console.debug('Contract activation check failed:', error);
+    }
     return false;
   }
 }

35-90: Consider extracting magic numbers as named constants.

The function implementation is thorough, but the magic numbers and expected pattern could be more maintainable as named constants.

+// Constants for Stylus deployment bytecode structure
+const PUSH32_OPCODE = 0x7f;
+const PRELUDE_LENGTH = 42;
+const VERSION_BYTE_LENGTH = 1;
+const TOTAL_FIXED_LENGTH = PRELUDE_LENGTH + VERSION_BYTE_LENGTH;
+const EXPECTED_PRELUDE_PATTERN = [
+  0x80, // DUP1
+  0x60, 0x2b, // PUSH1 0x2b (42 + 1)
+  0x60, 0x00, // PUSH1 0
+  0x39, // CODECOPY
+  0x60, 0x00, // PUSH1 0
+  0xf3, // RETURN
+  0x00, // version
+] as const;

 function extractRuntimeBytecode(deployInput: string | Uint8Array): Uint8Array {
   // normalise input
   const deploy: Uint8Array =
     typeof deployInput === "string" ? hexToBytes(deployInput) : deployInput;
 
-  // the contract_deployment_calldata helper emits 42-byte prelude + 1-byte version  =>  43 bytes total
-  // ref: https://github.com/OffchainLabs/cargo-stylus/blob/main/main/src/deploy/mod.rs#L305
-  const PRELUDE_LEN = 42;
-  const TOTAL_FIXED = PRELUDE_LEN + 1; // +1 version byte
-
-  if (deploy.length < TOTAL_FIXED) {
+  if (deploy.length < TOTAL_FIXED_LENGTH) {
     throw new Error("Deployment bytecode too short");
   }
-  if (deploy[0] !== 0x7f) {
+  if (deploy[0] !== PUSH32_OPCODE) {
     throw new Error(
       "Missing 0x7f PUSH32 - not produced by contract_deployment_calldata",
     );
   }
 
   // read length
   const codeLenBytes = deploy.slice(1, 33);
   let codeLen = 0n;
   for (const b of codeLenBytes) codeLen = (codeLen << 8n) | BigInt(b);
 
   if (codeLen > BigInt(Number.MAX_SAFE_INTEGER)) {
     throw new Error("Runtime code length exceeds JS safe integer range");
   }
 
   // pattern sanity-check
-  const EXPECTED = [
-    0x80, // DUP1
-    0x60,
-    0x2b, // PUSH1 0x2b (42 + 1)
-    0x60,
-    0x00, // PUSH1 0
-    0x39, // CODECOPY
-    0x60,
-    0x00, // PUSH1 0
-    0xf3, // RETURN
-    0x00, // version
-  ] as const;
-  for (let i = 0; i < EXPECTED.length; i++) {
-    if (deploy[33 + i] !== EXPECTED[i]) {
+  for (let i = 0; i < EXPECTED_PRELUDE_PATTERN.length; i++) {
+    if (deploy[33 + i] !== EXPECTED_PRELUDE_PATTERN[i]) {
       throw new Error("Prelude bytes do not match expected pattern");
     }
   }
 
   // slice out runtime code
-  const start = TOTAL_FIXED;
+  const start = TOTAL_FIXED_LENGTH;
   const end = start + Number(codeLen);
   if (deploy.length < end) {
     throw new Error("Deployment bytecode truncated - runtime code incomplete");
   }
 
   return deploy.slice(start, end);
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 16cabef and 4962bbc.

⛔ Files ignored due to path filters (1)
  • packages/thirdweb/src/extensions/stylus/__generated__/IArbWasm/read/codehashVersion.ts is excluded by !**/__generated__/**
📒 Files selected for processing (4)
  • packages/thirdweb/scripts/generate/abis/stylus/IArbWasm.json (1 hunks)
  • packages/thirdweb/src/contract/deployment/deploy-with-abi.ts (3 hunks)
  • packages/thirdweb/src/extensions/stylus/write/activateStylusContract.ts (1 hunks)
  • packages/thirdweb/src/extensions/stylus/write/isContractActivated.ts (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • packages/thirdweb/src/extensions/stylus/write/activateStylusContract.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/thirdweb/src/contract/deployment/deploy-with-abi.ts
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.{ts,tsx}`: Write idiomatic TypeScript with explicit function declarations ...

**/*.{ts,tsx}: Write idiomatic TypeScript with explicit function declarations and return types
Limit each file to one stateless, single-responsibility function for clarity
Re-use shared types from @/types or local types.ts barrels
Prefer type aliases over interface except for nominal shapes
Avoid any and unknown unless unavoidable; narrow generics when possible
Choose composition over inheritance; leverage utility types (Partial, Pick, etc.)
Comment only ambiguous logic; avoid restating TypeScript in prose
Load heavy dependencies inside async paths to keep initial bundle lean (lazy loading)

📄 Source: CodeRabbit Inference Engine (CLAUDE.md)

List of files the instruction was applied to:

  • packages/thirdweb/src/extensions/stylus/write/isContractActivated.ts
🧠 Learnings (3)
📓 Common learnings
Learnt from: CR
PR: thirdweb-dev/js#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-30T10:25:29.488Z
Learning: Surface breaking changes prominently in PR descriptions
Learnt from: CR
PR: thirdweb-dev/js#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-30T10:25:29.489Z
Learning: Applies to src/extensions/**/*.{ts,tsx} : Auto-generated contracts from ABI definitions in extensions
Learnt from: CR
PR: thirdweb-dev/js#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-30T10:25:29.489Z
Learning: Applies to src/wallets/**/*.{ts,tsx} : Support EIP-1193, EIP-5792, EIP-7702 standards in wallet architecture
packages/thirdweb/scripts/generate/abis/stylus/IArbWasm.json (1)
Learnt from: CR
PR: thirdweb-dev/js#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-30T10:25:29.489Z
Learning: Applies to src/extensions/**/*.{ts,tsx} : Auto-generated contracts from ABI definitions in extensions
packages/thirdweb/src/extensions/stylus/write/isContractActivated.ts (3)
Learnt from: CR
PR: thirdweb-dev/js#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-30T10:25:29.489Z
Learning: Applies to src/extensions/**/*.{ts,tsx} : Auto-generated contracts from ABI definitions in extensions
Learnt from: CR
PR: thirdweb-dev/js#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-30T10:25:29.489Z
Learning: Applies to src/wallets/**/*.{ts,tsx} : Support EIP-1193, EIP-5792, EIP-7702 standards in wallet architecture
Learnt from: MananTank
PR: thirdweb-dev/js#7332
File: apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/public-pages/nft/overview/nft-drop-claim.tsx:82-90
Timestamp: 2025-06-13T13:03:41.732Z
Learning: The thirdweb `contract` object is serializable and can safely be used in contexts (e.g., React-Query keys) that require serializable values.
🧬 Code Graph Analysis (1)
packages/thirdweb/src/extensions/stylus/write/isContractActivated.ts (3)
packages/thirdweb/src/extensions/stylus/write/activateStylusContract.ts (1)
  • ARB_WASM_ADDRESS (15-15)
packages/thirdweb/src/extensions/stylus/__generated__/IArbWasm/read/codehashVersion.ts (1)
  • codehashVersion (118-126)
packages/thirdweb/src/extensions/stylus/__generated__/IStylusDeployer/write/deploy.ts (1)
  • deploy (141-178)
⏰ Context from checks skipped due to timeout of 90000ms (8)
  • GitHub Check: E2E Tests (pnpm, esbuild)
  • GitHub Check: Size
  • GitHub Check: E2E Tests (pnpm, vite)
  • GitHub Check: E2E Tests (pnpm, webpack)
  • GitHub Check: Unit Tests
  • GitHub Check: Build Packages
  • GitHub Check: Lint Packages
  • GitHub Check: Analyze (javascript)
🔇 Additional comments (3)
packages/thirdweb/scripts/generate/abis/stylus/IArbWasm.json (1)

1-4: LGTM!

The new codehashVersion function signature is correctly added to the ABI. The function signature follows proper Solidity conventions with appropriate modifiers (external view) for a read-only function.

packages/thirdweb/src/extensions/stylus/write/isContractActivated.ts (2)

1-6: Imports are well-organized and necessary.

All imports are relevant to the module's functionality and follow the project's conventions.


8-12: Type definition follows best practices.

The type alias is well-structured with appropriate property types, including the hex string template literal type for bytecode validation.

Comment on lines +92 to +102
function hexToBytes(hex: string): Uint8Array {
const normalized = hex.startsWith("0x") ? hex.slice(2) : hex;
if (normalized.length % 2 !== 0) {
throw new Error("Hex string must have an even length");
}
const bytes = new Uint8Array(normalized.length / 2);
for (let i = 0; i < bytes.length; i++) {
bytes[i] = parseInt(normalized.slice(i * 2, i * 2 + 2), 16);
}
return bytes;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add validation for hex characters to prevent silent data corruption.

The parseInt function returns NaN for invalid hex characters, which gets coerced to 0 in Uint8Array. This could lead to silent data corruption if invalid hex strings are passed.

 function hexToBytes(hex: string): Uint8Array {
   const normalized = hex.startsWith("0x") ? hex.slice(2) : hex;
   if (normalized.length % 2 !== 0) {
     throw new Error("Hex string must have an even length");
   }
+  if (!/^[0-9a-fA-F]*$/.test(normalized)) {
+    throw new Error("Invalid hex characters in string");
+  }
   const bytes = new Uint8Array(normalized.length / 2);
   for (let i = 0; i < bytes.length; i++) {
-    bytes[i] = parseInt(normalized.slice(i * 2, i * 2 + 2), 16);
+    const byte = parseInt(normalized.slice(i * 2, i * 2 + 2), 16);
+    if (isNaN(byte)) {
+      throw new Error(`Invalid hex byte at position ${i}`);
+    }
+    bytes[i] = byte;
   }
   return bytes;
 }
📝 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
function hexToBytes(hex: string): Uint8Array {
const normalized = hex.startsWith("0x") ? hex.slice(2) : hex;
if (normalized.length % 2 !== 0) {
throw new Error("Hex string must have an even length");
}
const bytes = new Uint8Array(normalized.length / 2);
for (let i = 0; i < bytes.length; i++) {
bytes[i] = parseInt(normalized.slice(i * 2, i * 2 + 2), 16);
}
return bytes;
}
function hexToBytes(hex: string): Uint8Array {
const normalized = hex.startsWith("0x") ? hex.slice(2) : hex;
if (normalized.length % 2 !== 0) {
throw new Error("Hex string must have an even length");
}
if (!/^[0-9a-fA-F]*$/.test(normalized)) {
throw new Error("Invalid hex characters in string");
}
const bytes = new Uint8Array(normalized.length / 2);
for (let i = 0; i < bytes.length; i++) {
const byte = parseInt(normalized.slice(i * 2, i * 2 + 2), 16);
if (isNaN(byte)) {
throw new Error(`Invalid hex byte at position ${i}`);
}
bytes[i] = byte;
}
return bytes;
}
🤖 Prompt for AI Agents
In packages/thirdweb/src/extensions/stylus/write/isContractActivated.ts around
lines 92 to 102, the hexToBytes function lacks validation for hex characters,
causing parseInt to return NaN for invalid input, which coerces to 0 and
silently corrupts data. Add a check after parsing each byte to verify that the
result is a valid number and throw an error if invalid hex characters are
detected to prevent silent data corruption.

Copy link
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: 2

🧹 Nitpick comments (1)
packages/thirdweb/src/exports/extensions/stylus.ts (1)

1-16: Consider adding file-level documentation.

While the exports are well-structured, consider adding a file-level TSDoc comment to explain the purpose of this Stylus extensions module in the public API.

+/**
+ * Stylus contract extensions for the thirdweb SDK.
+ * 
+ * Provides functionality for deploying and managing Stylus contracts on Arbitrum chains.
+ * 
+ * @example
+ * ```typescript
+ * import { deployWithStylusConstructor, isContractActivated } from "thirdweb/extensions/stylus";
+ * ```
+ */
 /**
  * Write
  */
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 764e808 and 16fdd1e.

📒 Files selected for processing (1)
  • packages/thirdweb/src/exports/extensions/stylus.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
`**/*.{ts,tsx}`: Write idiomatic TypeScript with explicit function declarations ...

**/*.{ts,tsx}: Write idiomatic TypeScript with explicit function declarations and return types
Limit each file to one stateless, single-responsibility function for clarity
Re-use shared types from @/types or local types.ts barrels
Prefer type aliases over interface except for nominal shapes
Avoid any and unknown unless unavoidable; narrow generics when possible
Choose composition over inheritance; leverage utility types (Partial, Pick, etc.)
Comment only ambiguous logic; avoid restating TypeScript in prose
Load heavy dependencies inside async paths to keep initial bundle lean (lazy loading)

📄 Source: CodeRabbit Inference Engine (CLAUDE.md)

List of files the instruction was applied to:

  • packages/thirdweb/src/exports/extensions/stylus.ts
`packages/thirdweb/src/exports/**/*.{ts,tsx}`: Export everything via `exports/` ...

packages/thirdweb/src/exports/**/*.{ts,tsx}: Export everything via exports/ directory, grouped by feature in the public API of the SDK
Every public symbol must have comprehensive TSDoc with at least one @example block that compiles and custom annotation tags (@beta, @internal, @experimental)

📄 Source: CodeRabbit Inference Engine (CLAUDE.md)

List of files the instruction was applied to:

  • packages/thirdweb/src/exports/extensions/stylus.ts
🧠 Learnings (2)
📓 Common learnings
Learnt from: CR
PR: thirdweb-dev/js#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-30T10:25:29.488Z
Learning: Surface breaking changes prominently in PR descriptions
Learnt from: CR
PR: thirdweb-dev/js#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-30T10:25:29.489Z
Learning: Applies to src/extensions/**/*.{ts,tsx} : Auto-generated contracts from ABI definitions in extensions
Learnt from: CR
PR: thirdweb-dev/js#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-30T10:25:29.489Z
Learning: Applies to src/wallets/**/*.{ts,tsx} : Support EIP-1193, EIP-5792, EIP-7702 standards in wallet architecture
packages/thirdweb/src/exports/extensions/stylus.ts (10)
Learnt from: CR
PR: thirdweb-dev/js#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-30T10:25:29.488Z
Learning: Applies to packages/thirdweb/src/exports/**/*.{ts,tsx} : Export everything via `exports/` directory, grouped by feature in the public API of the SDK
Learnt from: CR
PR: thirdweb-dev/js#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-30T10:25:29.489Z
Learning: Applies to src/extensions/**/*.{ts,tsx} : Auto-generated contracts from ABI definitions in extensions
Learnt from: CR
PR: thirdweb-dev/js#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-30T10:25:29.488Z
Learning: Applies to packages/thirdweb/src/exports/**/*.{ts,tsx} : Every public symbol must have comprehensive TSDoc with at least one `@example` block that compiles and custom annotation tags (`@beta`, `@internal`, `@experimental`)
Learnt from: CR
PR: thirdweb-dev/js#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-30T10:25:29.489Z
Learning: Applies to src/exports/react.native.ts : React Native specific exports are in `src/exports/react.native.ts`
Learnt from: CR
PR: thirdweb-dev/js#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-30T10:25:29.489Z
Learning: Applies to src/extensions/**/*.{ts,tsx} : Extensions follow modular pattern in `src/extensions/`
Learnt from: CR
PR: thirdweb-dev/js#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-30T10:25:29.489Z
Learning: Applies to src/extensions/**/*.{ts,tsx} : Support for read/write operations in extensions
Learnt from: CR
PR: thirdweb-dev/js#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-30T10:25:29.488Z
Learning: Applies to **/*.{ts,tsx} : Write idiomatic TypeScript with explicit function declarations and return types
Learnt from: CR
PR: thirdweb-dev/js#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-30T10:25:29.489Z
Learning: Applies to src/extensions/**/*.{ts,tsx} : Composable functions with TypeScript safety in extensions
Learnt from: CR
PR: thirdweb-dev/js#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-30T10:25:29.488Z
Learning: Applies to apps/{dashboard,playground-web}/**/*.{tsx,ts} : Use Tailwind CSS only – no inline styles or CSS modules
Learnt from: CR
PR: thirdweb-dev/js#0
File: .cursor/rules/dashboard.mdc:0-0
Timestamp: 2025-06-30T10:26:04.389Z
Learning: Applies to dashboard/**/api/**/*.{ts,tsx} : Export default async functions without `'use client';` – they run on the Node edge.
⏰ Context from checks skipped due to timeout of 90000ms (8)
  • GitHub Check: Size
  • GitHub Check: E2E Tests (pnpm, esbuild)
  • GitHub Check: Unit Tests
  • GitHub Check: Build Packages
  • GitHub Check: Lint Packages
  • GitHub Check: E2E Tests (pnpm, webpack)
  • GitHub Check: E2E Tests (pnpm, vite)
  • GitHub Check: Analyze (javascript)

Comment on lines +12 to +15
export {
type IsContractActivatedOptions,
isContractActivated,
} from "../../extensions/stylus/write/isContractActivated.js";
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Verify TSDoc compliance for the new export.

The export structure is consistent with the existing pattern. Ensure the source function has proper TSDoc documentation as required.


🏁 Script executed:

#!/bin/bash
# Description: Check if isContractActivated has proper TSDoc documentation
# Expected: TSDoc comments with @example block and annotation tags

rg -A 20 "export.*isContractActivated" --type ts

Length of output: 1947


Add comprehensive TSDoc for isContractActivated export

The isContractActivated function in
packages/thirdweb/src/extensions/stylus/write/isContractActivated.ts
is currently missing a TSDoc comment with an @example block and the required custom annotation tags (@beta, @internal, @experimental, as applicable). Please add a documentation block immediately above the function declaration, for example:

/**
 * Checks whether a given contract’s bytecode has been activated.
 *
 * @remarks
 * This uses the ArbWasm precompile contract to verify the runtime bytecode version.
 *
 * @param options - Configuration options for the activation check.
 * @param options.chain - The target blockchain.
 * @param options.client - The RPC client instance.
 * @param options.bytecode - The contract’s runtime bytecode.
 *
 * @returns A promise that resolves to `true` if activated, otherwise `false`.
 *
 * @example
 * ```ts
 * const activated = await isContractActivated({
 *   chain: "arbitrum",
 *   client: myRpcClient,
 *   bytecode: myContractBytecode,
 * });
 * console.log(activated); // true
 * ```
 *
 * @beta
 */
export async function isContractActivated(
  options: IsContractActivatedOptions,
): Promise<boolean> {  }
  • Ensure the TSDoc compiles without errors.
  • Include at least one valid @example block.
  • Add the appropriate custom annotation tag.
🤖 Prompt for AI Agents
In packages/thirdweb/src/extensions/stylus/write/isContractActivated.ts around
lines 12 to 15, the isContractActivated function lacks a comprehensive TSDoc
comment. Add a detailed TSDoc block immediately above the function declaration
that describes its purpose, parameters, and return value. Include an @example
block demonstrating usage and add the appropriate custom annotation tag such as
@beta. Ensure the TSDoc is well-formed and compiles without errors.

Comment on lines +8 to +11
export {
type DeployWithStylusConstructorOptions,
deployWithStylusConstructor,
} from "../../extensions/stylus/write/deployWithStylusConstructor.js";
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Verify TSDoc compliance for the new export.

The export structure follows the established pattern correctly. However, per the coding guidelines, every public symbol must have comprehensive TSDoc with at least one @example block and custom annotation tags.


🏁 Script executed:

#!/bin/bash
# Description: Check if deployWithStylusConstructor has proper TSDoc documentation
# Expected: TSDoc comments with @example block and annotation tags

rg -A 20 "export.*deployWithStylusConstructor" --type ts

Length of output: 2307


🏁 Script executed:

#!/bin/bash
# Check for existing TSDoc above the deployWithStylusConstructor function
rg -B5 -n "export function deployWithStylusConstructor" packages/thirdweb/src/extensions/stylus/write/deployWithStylusConstructor.ts

Length of output: 275


🏁 Script executed:

#!/bin/bash
# Display TSDoc for deployWithStylusConstructor function
echo "===== deployWithStylusConstructor.ts (first 50 lines) ====="
head -n 50 packages/thirdweb/src/extensions/stylus/write/deployWithStylusConstructor.ts

# Display exports file to check for file-level TSDoc
echo "===== stylus.ts exports file (first 20 lines) ====="
head -n 20 packages/thirdweb/src/exports/extensions/stylus.ts

Length of output: 2570


Add missing custom annotation tag to deployWithStylusConstructor TSDoc

The deployWithStylusConstructor function already has a description, @param, @returns and a working @example, but per our SDK docs guidelines every public symbol also needs a custom annotation tag (e.g. @beta or @experimental).

• In packages/thirdweb/src/extensions/stylus/write/deployWithStylusConstructor.ts, add an appropriate annotation to the existing TSDoc block above export function deployWithStylusConstructor(...).

/**
 * Deploy stylus contract with constructor params
 * @beta               ← add one of: @beta | @experimental | @internal
 * @param options – The options for deploying a contract with constructor
 * @returns Prepared transaction to call stylus deployer
 * @example
 * …
 */
export function deployWithStylusConstructor()

• (Optional) Enhance the file-level TSDoc in packages/thirdweb/src/exports/extensions/stylus.ts to describe the module’s purpose more thoroughly.

🤖 Prompt for AI Agents
In packages/thirdweb/src/extensions/stylus/write/deployWithStylusConstructor.ts
around the export function deployWithStylusConstructor, add a custom annotation
tag such as @beta, @experimental, or @internal to the existing TSDoc block above
the function to comply with SDK docs guidelines. Optionally, in
packages/thirdweb/src/exports/extensions/stylus.ts, enhance the file-level TSDoc
comment to provide a more detailed description of the module's purpose.

@kumaryash90 kumaryash90 removed the DO NOT MERGE This pull request is still in progress and is not ready to be merged. label Jul 4, 2025
@joaquim-verges joaquim-verges merged commit 8def4f3 into main Jul 4, 2025
27 of 29 checks passed
@joaquim-verges joaquim-verges deleted the yash/stylus-cli-update branch July 4, 2025 19:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
packages SDK Involves changes to the thirdweb SDK
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants