-
Notifications
You must be signed in to change notification settings - Fork 21
Add Starknet JS agent example with balance fetching' or 'Introduce Starknet example agent kit #32
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
base: master
Are you sure you want to change the base?
Conversation
WalkthroughAdds 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
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)
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes
Possibly related PRs
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this 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-USEDis 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 including0xprefix 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
axClientis 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. IfPAYMENTS_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: UseoptionalEnvfor consistency.Lines 36-37 use the
optionalEnvhelper for optional environment variables, but line 39 directly accessesprocess.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, multipleRpcProviderinstances 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
⛔ Files ignored due to path filters (1)
packages/agent-kit/examples/starknet-js-example/bun.lockis 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.examplepackages/agent-kit/examples/starknet-js-example/src/agent.tspackages/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
BalanceResulttype is well-defined with all necessary fields for balance information.
71-82: LGTM!The
formatUnitsfunction 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: 18on 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, );
Summary by CodeRabbit
New Features
Documentation