Skip to content

Added TonCenter API key support#81

Open
SergeyG-Solicy wants to merge 1 commit intomainfrom
feature/add-ton-network
Open

Added TonCenter API key support#81
SergeyG-Solicy wants to merge 1 commit intomainfrom
feature/add-ton-network

Conversation

@SergeyG-Solicy
Copy link
Copy Markdown
Contributor

@SergeyG-Solicy SergeyG-Solicy commented Mar 13, 2026

Summary by CodeRabbit

  • New Features
    • Added support for configuring an API key for TON network connections, which is automatically applied during network initialization.

@SergeyG-Solicy SergeyG-Solicy requested a review from cwilvx March 13, 2026 11:32
@qodo-code-review
Copy link
Copy Markdown
Contributor

Review Summary by Qodo

Add TonCenter API key support to TON chain

✨ Enhancement

Grey Divider

Walkthroughs

Description
• Add TonCenter API key support to TON chain class
• Introduce setApiKey() method for configuring API authentication
• Store API key in private field and apply to provider initialization
• Recreate provider when API key is set to ensure proper configuration
Diagram
flowchart LR
  A["TON Class"] -->|"setApiKey()"| B["Store API Key"]
  B -->|"Recreate Provider"| C["TonClient with apiKey"]
  D["setRpc()"] -->|"Apply API Key"| C
Loading

Grey Divider

File Changes

1. src/multichain/core/ton.ts ✨ Enhancement +11/-0

Add API key support to TON provider

• Added private _apiKey field to store TonCenter API key
• Modified setRpc() to conditionally include API key in TonClient configuration
• Implemented new setApiKey() method to set and apply API key
• Provider is recreated when API key is set to ensure proper initialization

src/multichain/core/ton.ts


Grey Divider

Qodo Logo

@qodo-code-review
Copy link
Copy Markdown
Contributor

qodo-code-review bot commented Mar 13, 2026

Code Review by Qodo

🐞 Bugs (2) 📘 Rule violations (1) 📎 Requirement gaps (0)

Grey Divider


Action required

1. Bad apiKey spread operand 🐞 Bug ✓ Correctness
Description
TON.setRpc conditionally spreads this._apiKey && { apiKey: this._apiKey }, but if setApiKey("")
is used (allowed by the current signature), the && expression evaluates to a string and is spread
into the options object, producing an invalid configuration and omitting apiKey. This makes
API-key configuration fail in a hard-to-debug way when the key is empty/missing (e.g., env var
defaulting to "").
Code

src/multichain/core/ton.ts[R34-37]

        this.provider = new TonClient({
            endpoint: this.rpc_url,
+            ...(this._apiKey && { apiKey: this._apiKey }),
        })
Evidence
setApiKey accepts any string (including "") and stores it in _apiKey, and setRpc uses `_apiKey &&
{ ... } inside an object spread; in JavaScript, &&` returns the original falsy operand (""), so
the spread operand is not guaranteed to be an object, meaning the TonClient options object can be
malformed and will not contain apiKey.

src/multichain/core/ton.ts[29-37]
src/multichain/core/ton.ts[40-46]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
`TON.setRpc()` uses `...(this._apiKey && { apiKey: this._apiKey })` inside an object literal. Because `setApiKey()` accepts any string (including `""`), the `&&` expression can evaluate to a non-object value and be spread into the TonClient options.

### Issue Context
- `setApiKey(apiKey: string)` stores the raw string.
- `setRpc()` reconstructs `TonClient` with an object spread based on `_apiKey`.

### Fix Focus Areas
- src/multichain/core/ton.ts[31-46]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. setApiKey doesn’t reconnect 🐞 Bug ⛯ Reliability
Description
TON.setApiKey rebuilds the TonClient provider but never re-runs connect() or resets connected, so
the instance can report an outdated connection state after changing auth configuration. This is
especially problematic with DefaultChain.create() which immediately calls connect() after setRpc(),
giving no opportunity to set the API key before the initial connection attempt.
Code

src/multichain/core/ton.ts[R40-46]

+    setApiKey(apiKey: string): void {
+        this._apiKey = apiKey
+        // Recreate provider with the API key
+        if (this.rpc_url) {
+            this.setRpc(this.rpc_url)
+        }
+    }
Evidence
DefaultChain.create() eagerly calls instance.setRpc(rpc_url) and then await instance.connect()
when rpc_url is provided. TON.setApiKey only calls setRpc (recreating the provider) and does not
call connect() or adjust connected, so the connection state can remain stale across API key
changes and the initial create/connect attempt cannot include the key.

src/multichain/core/types/defaultChain.ts[43-54]
src/multichain/core/ton.ts[40-46]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
`TON.setApiKey()` recreates the provider but does not reconnect or reset `connected`, leaving stale connection state after auth config changes. This also conflicts with `DefaultChain.create()` which immediately calls `connect()` after `setRpc()`.

### Issue Context
- `DefaultChain.create()` eagerly connects when `rpc_url` is passed.
- `TON.setApiKey()` currently only calls `setRpc()`.

### Fix Focus Areas
- src/multichain/core/ton.ts[40-57]
- src/multichain/core/types/defaultChain.ts[43-54]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended

3. .beads/issues.jsonl not updated 📘 Rule violation ✧ Quality
Description
This PR introduces code changes but does not include a corresponding update to
.beads/issues.jsonl, risking desynchronization between the issue state file and the codebase.
Ensure the beads issue state is updated/committed in the same change set.
Code

src/multichain/core/ton.ts[R29-46]

+    private _apiKey?: string
+
    override setRpc(rpc_url: string): void {
        this.rpc_url = rpc_url

        this.provider = new TonClient({
            endpoint: this.rpc_url,
+            ...(this._apiKey && { apiKey: this._apiKey }),
        })
    }

+    setApiKey(apiKey: string): void {
+        this._apiKey = apiKey
+        // Recreate provider with the API key
+        if (this.rpc_url) {
+            this.setRpc(this.rpc_url)
+        }
+    }
Evidence
PR Compliance ID 3 requires .beads/issues.jsonl to be updated alongside code changes. The diff
shows new TON API key support code changes, while the provided PR diff does not show any
accompanying .beads/issues.jsonl update.

AGENTS.md
src/multichain/core/ton.ts[29-46]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The PR includes code changes but does not include an accompanying update to `.beads/issues.jsonl`, which is required to keep issue state in sync.

## Issue Context
Rule requires that whenever code changes are introduced, `.beads/issues.jsonl` is also updated/committed in the same change set.

## Fix Focus Areas
- src/multichain/core/ton.ts[29-46]
- .beads/issues.jsonl[1-1]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

ⓘ The new review experience is currently in Beta. Learn more

Grey Divider

Qodo Logo

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Mar 13, 2026

Walkthrough

Adds API key management to the TON provider class with a private _apiKey field, a new setApiKey() public method for setting and applying the key, and updates setRpc() to pass the API key to TonClient initialization when available.

Changes

Cohort / File(s) Summary
API Key Management
src/multichain/core/ton.ts
Introduces private _apiKey field to store optional API key. Adds public setApiKey() method to set the key and reinitialize the provider. Updates setRpc() to conditionally pass API key to TonClient initialization via spread syntax.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Poem

🐰 A key for TON, now tucked away,
Private and safe, it's here to stay,
When RPC initializes with care,
The API key floats through the air! 🔑

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately and concisely describes the main change: adding API key support for TonCenter to the TON class.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

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

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feature/add-ton-network
📝 Coding Plan
  • Generate coding plan for human review comments

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.

@sonarqubecloud
Copy link
Copy Markdown

Comment on lines 34 to 37
this.provider = new TonClient({
endpoint: this.rpc_url,
...(this._apiKey && { apiKey: this._apiKey }),
})
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.

Action required

1. Bad apikey spread operand 🐞 Bug ✓ Correctness

TON.setRpc conditionally spreads this._apiKey && { apiKey: this._apiKey }, but if setApiKey("")
is used (allowed by the current signature), the && expression evaluates to a string and is spread
into the options object, producing an invalid configuration and omitting apiKey. This makes
API-key configuration fail in a hard-to-debug way when the key is empty/missing (e.g., env var
defaulting to "").
Agent Prompt
### Issue description
`TON.setRpc()` uses `...(this._apiKey && { apiKey: this._apiKey })` inside an object literal. Because `setApiKey()` accepts any string (including `""`), the `&&` expression can evaluate to a non-object value and be spread into the TonClient options.

### Issue Context
- `setApiKey(apiKey: string)` stores the raw string.
- `setRpc()` reconstructs `TonClient` with an object spread based on `_apiKey`.

### Fix Focus Areas
- src/multichain/core/ton.ts[31-46]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Comment on lines +40 to +46
setApiKey(apiKey: string): void {
this._apiKey = apiKey
// Recreate provider with the API key
if (this.rpc_url) {
this.setRpc(this.rpc_url)
}
}
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.

Action required

2. Setapikey doesn’t reconnect 🐞 Bug ⛯ Reliability

TON.setApiKey rebuilds the TonClient provider but never re-runs connect() or resets connected, so
the instance can report an outdated connection state after changing auth configuration. This is
especially problematic with DefaultChain.create() which immediately calls connect() after setRpc(),
giving no opportunity to set the API key before the initial connection attempt.
Agent Prompt
### Issue description
`TON.setApiKey()` recreates the provider but does not reconnect or reset `connected`, leaving stale connection state after auth config changes. This also conflicts with `DefaultChain.create()` which immediately calls `connect()` after `setRpc()`.

### Issue Context
- `DefaultChain.create()` eagerly connects when `rpc_url` is passed.
- `TON.setApiKey()` currently only calls `setRpc()`.

### Fix Focus Areas
- src/multichain/core/ton.ts[40-57]
- src/multichain/core/types/defaultChain.ts[43-54]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

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

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/multichain/core/ton.ts`:
- Around line 40-46: Add a JSDoc block for the new public method setApiKey
describing its purpose, parameters, and side effects: document that
setApiKey(apiKey: string): void sets the internal _apiKey, and that if rpc_url
is present it will recreate the provider by calling setRpc(this.rpc_url);
include `@param` {string} apiKey and `@returns` {void} (or omit returns if style
prefers), and mention any thrown errors or behaviors if applicable; attach the
JSDoc immediately above the setApiKey method.
- Around line 40-46: In setApiKey, validate the incoming apiKey (reject
null/empty/whitespace by throwing a descriptive error) and then update
this._apiKey; before calling setRpc(this.rpc_url) ensure you invalidate any
existing connection state (set this.connected = false and clear any cached
client/socket state) so the old connected flag can't remain true after
recreating the provider; call setRpc only if rpc_url is present to recreate
provider with the new key.
🪄 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: CHILL

Plan: Pro

Run ID: ccb043a8-0d08-447f-b657-8803b83e3a2f

📥 Commits

Reviewing files that changed from the base of the PR and between 81811d7 and 6d96742.

📒 Files selected for processing (1)
  • src/multichain/core/ton.ts

Comment on lines +40 to +46
setApiKey(apiKey: string): void {
this._apiKey = apiKey
// Recreate provider with the API key
if (this.rpc_url) {
this.setRpc(this.rpc_url)
}
}
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

Add JSDoc for the new public setApiKey method.

The method introduced at Line 40 is public API and should include JSDoc in this repository.

Proposed fix
+    /**
+     * Set TonCenter API key and recreate the RPC provider when an endpoint is already configured.
+     * `@param` apiKey TonCenter API key.
+     */
     setApiKey(apiKey: string): void {

As per coding guidelines, "Use JSDoc format for all new methods and functions".

📝 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
setApiKey(apiKey: string): void {
this._apiKey = apiKey
// Recreate provider with the API key
if (this.rpc_url) {
this.setRpc(this.rpc_url)
}
}
/**
* Set TonCenter API key and recreate the RPC provider when an endpoint is already configured.
* `@param` apiKey TonCenter API key.
*/
setApiKey(apiKey: string): void {
this._apiKey = apiKey
// Recreate provider with the API key
if (this.rpc_url) {
this.setRpc(this.rpc_url)
}
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/multichain/core/ton.ts` around lines 40 - 46, Add a JSDoc block for the
new public method setApiKey describing its purpose, parameters, and side
effects: document that setApiKey(apiKey: string): void sets the internal
_apiKey, and that if rpc_url is present it will recreate the provider by calling
setRpc(this.rpc_url); include `@param` {string} apiKey and `@returns` {void} (or
omit returns if style prefers), and mention any thrown errors or behaviors if
applicable; attach the JSDoc immediately above the setApiKey method.

⚠️ Potential issue | 🟠 Major

setApiKey should invalidate stale connection state and reject empty keys.

On Line 40-45, recreating the provider can leave this.connected stale (true from old client). Also, empty/whitespace API keys are silently accepted and degrade into unauthenticated calls.

Proposed fix
-    setApiKey(apiKey: string): void {
-        this._apiKey = apiKey
-        // Recreate provider with the API key
-        if (this.rpc_url) {
-            this.setRpc(this.rpc_url)
-        }
-    }
+    setApiKey(apiKey: string): void {
+        const normalizedApiKey = apiKey.trim()
+        if (!normalizedApiKey) {
+            throw new Error("TON API key must be a non-empty string")
+        }
+
+        this._apiKey = normalizedApiKey
+
+        if (this.rpc_url) {
+            this.setRpc(this.rpc_url)
+            this.connected = false
+        }
+    }

As per coding guidelines, "Provide clear, actionable error messages".

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/multichain/core/ton.ts` around lines 40 - 46, In setApiKey, validate the
incoming apiKey (reject null/empty/whitespace by throwing a descriptive error)
and then update this._apiKey; before calling setRpc(this.rpc_url) ensure you
invalidate any existing connection state (set this.connected = false and clear
any cached client/socket state) so the old connected flag can't remain true
after recreating the provider; call setRpc only if rpc_url is present to
recreate provider with the new key.

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