Skip to content

Conversation

@Cheelax
Copy link

@Cheelax Cheelax commented Nov 10, 2025

Summary by CodeRabbit

  • New Features

    • Added a Starknet JS example agent with endpoints to query ETH and token balances and an echo endpoint.
    • Includes token registry, on-chain balance utilities, and optional payments support.
  • Documentation

    • Added README, environment example, and template schema for configuring and running the example.
    • Project scaffolding and TypeScript/Bun config included.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 10, 2025

Walkthrough

Adds a new Starknet JS example Bun agent demonstrating agent-kit usage with three entrypoints (echo, starknet-balance, starknet-token-balances), Starknet integration utilities, token registry, config/schema, example env, and a Bun server entrypoint.

Changes

Cohort / File(s) Summary
Project metadata & config files
packages/agent-kit/examples/starknet-js-example/package.json, packages/agent-kit/examples/starknet-js-example/tsconfig.json, packages/agent-kit/examples/starknet-js-example/.env.example, packages/agent-kit/examples/starknet-js-example/template.schema.json
New Bun project metadata, TypeScript config, example environment variables, and JSON schema for agent template and config.
Documentation
packages/agent-kit/examples/starknet-js-example/README.md
New README with setup, usage, entrypoints, development workflow, and extension notes.
Agent entry & server
packages/agent-kit/examples/starknet-js-example/src/agent.ts, packages/agent-kit/examples/starknet-js-example/src/index.ts
New agent implementation registering three entrypoints and a Bun server entry that mounts the agent fetch handler.
Starknet integration & utilities
packages/agent-kit/examples/starknet-js-example/src/starknet.ts, packages/agent-kit/examples/starknet-js-example/src/config.ts
Provider/account initialization, ETH/token balance fetch functions, uint256 helpers, config reading (required/optional envs), and exported types/constants.
Token registry & data
packages/agent-kit/examples/starknet-js-example/src/tokenRegistry.ts, packages/agent-kit/examples/starknet-js-example/src/token_list.json
Zod-validated token metadata schema and a static token list exported as AVAILABLE_TOKENS.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant Agent as Agent (agent-kit)
  participant Stark as StarkNet Utils
  participant Provider as Provider/Contract

  Client->>Agent: POST /invoke (entrypoint, input)
  Agent->>Agent: validate input & resolve address (input || env)
  Agent->>Stark: fetch balances / ETH balance
  Stark->>Provider: call contract / provider RPC
  Provider-->>Stark: balance data / errors
  Stark-->>Agent: serialized balances + errors
  Agent-->>Client: JSON response (resolved_address, balances, summary, errors)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

  • Pay extra attention to:
    • src/starknet.ts — uint256 extraction, ABI retrieval, and error handling branches.
    • src/agent.ts — input validation, address resolution fallbacks, and response serialization.
    • src/config.ts & src/tokenRegistry.ts — env handling and Zod schema correctness.

Possibly related PRs

  • Refactor Template System #10 — Related to refactored template/runtime env var and payments conventions (AGENT_NAME, PAYMENTS_RECEIVABLE_ADDRESS, useConfigPayments) used by this example.

Poem

🐰 I hopped into code with a spark so bright,
Fetching balances by day and token by night.
Echoes and sums, an agent that learns,
Configs and tokens in neat little urns—
Hooray for Starknet, the rabbit takes flight! ✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately reflects the main change: adding a new Starknet JS example agent with balance fetching capabilities.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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
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

🧹 Nitpick comments (8)
packages/agent-kit/examples/starknet-js-example/template.schema.json (1)

3-4: Update schema title and description to match Starknet example.

The title and description reference "AxLLM Flow Agent Template" but this schema is for the Starknet JS example specifically. Update to accurately reflect the purpose.

Apply this diff:

-  "title": "AxLLM Flow Agent Template Schema",
-  "description": "Configuration schema for the AxLLM Flow-powered Bun agent template with multi-step workflows",
+  "title": "Starknet JS Agent Example Schema",
+  "description": "Configuration schema for the Starknet.js Bun agent example",
packages/agent-kit/examples/starknet-js-example/.env.example (1)

39-40: Clarify OPENAI_API_KEY requirement or remove the misleading comment.

The comment "Required for AXLLM - but can be ignored" with a dummy value THIS-WILL-NOT-BE-USED is confusing. If it's truly not used in this example, either remove the variable or clarify why it's present.

Consider either removing this variable entirely or updating the comment to explain:

-# Required for AXLLM - but can be ignored
-OPENAI_API_KEY=THIS-WILL-NOT-BE-USED
+# Not used by the Starknet example entrypoints, but may be required by the agent-kit framework
+# OPENAI_API_KEY=
packages/agent-kit/examples/starknet-js-example/src/tokenRegistry.ts (1)

7-10: Consider validating Starknet address length.

The regex pattern allows any length of hex after 0x, but Starknet addresses have a specific format (typically 66 characters including 0x prefix for felt252). Consider adding length validation to catch malformed addresses early.

Apply this diff to enforce proper Starknet address length:

   address: z
     .string()
-    .regex(/^0x[0-9a-fA-F]+$/, "Token address must be 0x-prefixed hex"),
+    .regex(/^0x[0-9a-fA-F]{1,64}$/, "Token address must be 0x-prefixed hex (max 64 hex chars for Starknet felt252)"),

Or for stricter validation matching typical Starknet addresses:

   address: z
     .string()
-    .regex(/^0x[0-9a-fA-F]+$/, "Token address must be 0x-prefixed hex"),
+    .length(66, "Starknet address must be 66 characters (0x + 64 hex)")
+    .regex(/^0x[0-9a-fA-F]{64}$/, "Token address must be 0x-prefixed hex"),
packages/agent-kit/examples/starknet-js-example/src/agent.ts (3)

15-25: Remove unused axClient or document its purpose.

The axClient is created but never used in this file. Either remove it or add a comment explaining its purpose if it's intended for future extensions.

If unused, apply this diff:

-const axClient = createAxLLMClient({
-  logger: {
-    warn(message, error) {
-      if (error) {
-        console.warn(`[examples] ${message}`, error);
-      } else {
-        console.warn(`[examples] ${message}`);
-      }
-    },
-  },
-});
-

27-34: Type assertions bypass validation for payment configuration.

The payment configuration uses type assertions (as any, as \0x${string}`) without validating the environment variable values. If PAYMENTS_DEFAULT_PRICE` is set but other payment variables are missing or malformed, this could cause runtime errors.

Consider validating the payment configuration or adding a helper function:

+function readPaymentsConfig(): AgentKitConfig['payments'] {
+  const facilitatorUrl = process.env.PAYMENTS_FACILITATOR_URL;
+  const receivableAddress = process.env.PAYMENTS_RECEIVABLE_ADDRESS;
+  const network = process.env.PAYMENTS_NETWORK;
+  const defaultPrice = process.env.PAYMENTS_DEFAULT_PRICE;
+
+  if (!facilitatorUrl || !receivableAddress || !network) {
+    throw new Error('Payment configuration incomplete. Set PAYMENTS_FACILITATOR_URL, PAYMENTS_RECEIVABLE_ADDRESS, and PAYMENTS_NETWORK');
+  }
+
+  return {
+    facilitatorUrl: facilitatorUrl as any,
+    payTo: receivableAddress as `0x${string}`,
+    network: network as any,
+    defaultPrice,
+  };
+}
+
-const configOverrides: AgentKitConfig = {
-  payments: {
-    facilitatorUrl: process.env.PAYMENTS_FACILITATOR_URL as any,
-    payTo: process.env.PAYMENTS_RECEIVABLE_ADDRESS as `0x${string}`,
-    network: process.env.PAYMENTS_NETWORK as any,
-    defaultPrice: process.env.PAYMENTS_DEFAULT_PRICE,
-  },
-};
+const configOverrides: AgentKitConfig = {
+  payments: readPaymentsConfig(),
+};

89-89: Use English for summary text or make it configurable.

The summary uses French text ("Adresse ... détient ... ETH ...") which is inconsistent with the rest of the English codebase. Consider using English or making the language configurable.

Apply this diff:

-    const summary = `Adresse ${balance.address} détient ${balance.formatted} ETH (18 décimales).`;
+    const summary = `Address ${balance.address} holds ${balance.formatted} ETH (18 decimals).`;
packages/agent-kit/examples/starknet-js-example/src/config.ts (1)

38-39: Use optionalEnv for consistency.

Lines 36-37 use the optionalEnv helper for optional environment variables, but line 39 directly accesses process.env.STARKNET_ETH_CONTRACT. For consistency and maintainability, consider using the same pattern.

Apply this diff:

     ethContractAddress:
-      process.env.STARKNET_ETH_CONTRACT?.trim() || DEFAULT_ETH_CONTRACT,
+      optionalEnv("STARKNET_ETH_CONTRACT") || DEFAULT_ETH_CONTRACT,
packages/agent-kit/examples/starknet-js-example/src/starknet.ts (1)

17-25: Consider the concurrency edge case.

If getProvider() is called concurrently before the first call completes, multiple RpcProvider instances could be created. For production code, consider using a promise-based lock or initialization flag. However, for this example, the current implementation is acceptable.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1c6b7c1 and 96d2a0c.

⛔ Files ignored due to path filters (1)
  • packages/agent-kit/examples/starknet-js-example/bun.lock is excluded by !**/*.lock
📒 Files selected for processing (11)
  • packages/agent-kit/examples/starknet-js-example/.env.example (1 hunks)
  • packages/agent-kit/examples/starknet-js-example/README.md (1 hunks)
  • packages/agent-kit/examples/starknet-js-example/package.json (1 hunks)
  • packages/agent-kit/examples/starknet-js-example/src/agent.ts (1 hunks)
  • packages/agent-kit/examples/starknet-js-example/src/config.ts (1 hunks)
  • packages/agent-kit/examples/starknet-js-example/src/index.ts (1 hunks)
  • packages/agent-kit/examples/starknet-js-example/src/starknet.ts (1 hunks)
  • packages/agent-kit/examples/starknet-js-example/src/tokenRegistry.ts (1 hunks)
  • packages/agent-kit/examples/starknet-js-example/src/token_list.json (1 hunks)
  • packages/agent-kit/examples/starknet-js-example/template.schema.json (1 hunks)
  • packages/agent-kit/examples/starknet-js-example/tsconfig.json (1 hunks)
🧰 Additional context used
🧠 Learnings (2)
📚 Learning: 2025-11-08T02:57:45.823Z
Learnt from: beauwilliams
Repo: daydreamsai/lucid-agents PR: 10
File: packages/create-agent-kit/templates/axllm-flow/src/agent.ts:32-34
Timestamp: 2025-11-08T02:57:45.823Z
Learning: In the lucid-agents codebase, as an architectural invariant, do not provide default fallbacks for required environment variables (AGENT_NAME, AGENT_VERSION, AGENT_DESCRIPTION, PAYMENTS_RECEIVABLE_ADDRESS, etc.). The system uses explicit validation via validateAgentMetadata and validatePaymentsConfig to throw clear errors when configuration is not set, rather than silently falling back to defaults.

Applied to files:

  • packages/agent-kit/examples/starknet-js-example/.env.example
📚 Learning: 2025-11-08T03:00:11.330Z
Learnt from: beauwilliams
Repo: daydreamsai/lucid-agents PR: 10
File: packages/create-agent-kit/templates/axllm-flow/template.json:6-49
Timestamp: 2025-11-08T03:00:11.330Z
Learning: In the lucid-agents codebase, AGENT_NAME is derived from the project directory name during scaffolding, not collected via wizard prompts in template.json. Only AGENT_VERSION, AGENT_DESCRIPTION, and payment-related configuration should be defined in the wizard prompts.

Applied to files:

  • packages/agent-kit/examples/starknet-js-example/.env.example
  • packages/agent-kit/examples/starknet-js-example/src/agent.ts
  • packages/agent-kit/examples/starknet-js-example/template.schema.json
🧬 Code graph analysis (2)
packages/agent-kit/examples/starknet-js-example/src/agent.ts (3)
packages/agent-core/src/agent.ts (1)
  • addEntrypoint (30-35)
packages/agent-kit/examples/starknet-js-example/src/config.ts (1)
  • readStarknetConfig (29-43)
packages/agent-kit/examples/starknet-js-example/src/starknet.ts (4)
  • fetchEthBalance (327-362)
  • fetchAllTokenBalances (281-325)
  • TokenBalanceResult (242-244)
  • TokenBalanceFetchError (276-279)
packages/agent-kit/examples/starknet-js-example/src/starknet.ts (2)
packages/agent-kit/examples/starknet-js-example/src/config.ts (1)
  • readStarknetConfig (29-43)
packages/agent-kit/examples/starknet-js-example/src/tokenRegistry.ts (2)
  • TokenMetadata (19-19)
  • AVAILABLE_TOKENS (21-21)
🪛 dotenv-linter (4.0.0)
packages/agent-kit/examples/starknet-js-example/.env.example

[warning] 7-7: [UnorderedKey] The API_BASE_URL key should go before the PORT key

(UnorderedKey)


[warning] 13-13: [UnorderedKey] The REGISTER_IDENTITY key should go before the RPC_URL key

(UnorderedKey)


[warning] 15-15: [UnorderedKey] The NETWORK key should go before the REGISTER_IDENTITY key

(UnorderedKey)


[warning] 17-17: [UnorderedKey] The FACILITATOR_URL key should go before the NETWORK key

(UnorderedKey)


[warning] 23-23: [UnorderedKey] The DEFAULT_PRICE key should go before the PAYMENTS_RECEIVABLE_ADDRESS key

(UnorderedKey)


[warning] 33-33: [UnorderedKey] The STARKNET_ACCOUNT_ADDRESS key should go before the STARKNET_RPC_URL key

(UnorderedKey)


[warning] 35-35: [UnorderedKey] The STARKNET_PRIVATE_KEY key should go before the STARKNET_RPC_URL key

(UnorderedKey)


[warning] 37-37: [UnorderedKey] The STARKNET_ETH_CONTRACT key should go before the STARKNET_PRIVATE_KEY key

(UnorderedKey)

🪛 LanguageTool
packages/agent-kit/examples/starknet-js-example/README.md

[misspelling] ~80-~80: This word is normally spelled as one.
Context: ...YMENTS_DEFAULT_PRICE` is set, the agent auto-loads the config and enforces pricing for eve...

(EN_COMPOUNDS_AUTO_LOADS)

🔇 Additional comments (14)
packages/agent-kit/examples/starknet-js-example/package.json (2)

1-14: Configuration structure looks good.

The metadata, engine constraint, and scripts are well-structured for a Bun-based example project. The dev, start, and agent commands provide appropriate entry points, and the typecheck script ensures TypeScript correctness.


20-24: DevDependencies are properly pinned.

All development dependencies use appropriate caret version ranges for predictable updates while allowing patch fixes.

packages/agent-kit/examples/starknet-js-example/src/index.ts (1)

1-12: LGTM!

Clean server bootstrap implementation. Port handling and server setup are correct.

packages/agent-kit/examples/starknet-js-example/src/agent.ts (1)

151-176: LGTM!

The serialization helpers cleanly transform the internal balance and error types into response-friendly formats.

packages/agent-kit/examples/starknet-js-example/src/config.ts (2)

1-9: LGTM!

The configuration structure is clear and well-defined. The comment on line 2 helpfully documents that the ETH contract is for Sepolia testnet.


11-25: LGTM!

Both helper functions properly validate and normalize environment variables with appropriate trimming and empty-string handling.

packages/agent-kit/examples/starknet-js-example/src/starknet.ts (8)

1-11: LGTM!

Imports are appropriate and the BalanceResult type is well-defined with all necessary fields for balance information.


71-82: LGTM!

The formatUnits function properly handles edge cases including zero decimals, negative values, and trailing zeros in the fractional part.


84-105: LGTM!

The uint256 handling logic correctly splits large integers into low and high 128-bit components with proper validation for negative values.


107-240: LGTM!

Excellent defensive programming with comprehensive handling of various response formats from the StarkNet RPC. The functions robustly handle arrays, objects, primitives, and nested structures with clear error messages.


242-274: LGTM!

The token balance fetching logic is clean and properly structures the response with all necessary balance information including wei and formatted values.


281-325: LGTM!

Excellent error handling strategy that fetches all token balances in parallel, gracefully handles individual failures, and provides comprehensive results with both successful balances and errors.


327-362: LGTM!

The fallback pattern for fetching ETH balance is robust, providing resilience against contract helper failures. The hardcoded decimals: 18 on line 359 is correct for ETH. The console warnings are helpful for debugging without disrupting the flow.


39-43: Change Account constructor initialization to use positional parameters.

Starknet.js Account constructor uses positional parameters: new Account(provider, address, privateKey). Line 39-42 uses object-based initialization, which differs from all documented examples. Update to:

account = new Account(
  getProvider(),
  config.accountAddress,
  config.privateKey,
);

@Cheelax Cheelax changed the title Starknet example Add Starknet JS agent example with balance fetching' or 'Introduce Starknet example agent kit Nov 10, 2025
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