Skip to content

YNU-268: update manual rpc.Client test according to NitroRPCv0.4#380

Merged
philanton merged 2 commits intomainfrom
feat/nitro-rpc-0-4-test
Oct 7, 2025
Merged

YNU-268: update manual rpc.Client test according to NitroRPCv0.4#380
philanton merged 2 commits intomainfrom
feat/nitro-rpc-0-4-test

Conversation

@philanton
Copy link
Contributor

@philanton philanton commented Oct 7, 2025

Summary by CodeRabbit

  • Tests
    • Expanded coverage for Nitro RPC v0.2 and v0.4 workflows, including app session create/submit/close scenarios.
    • Added deposit, withdraw, and operate cases with detailed pre/post balance tracking and assertions across multi-step flows.
    • Introduced payload hashing and signature validation steps in key flows.
    • Updated test configuration to use a canary/UAT endpoint and a dedicated test asset.
    • Reorganized into a clearer, table-driven multi-scenario suite with descriptive case names.

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @philanton, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly updates the manual RPC client test suite to align with the latest NitroRPCv0.4 specification. It involves migrating the test environment to a new UAT WebSocket RPC endpoint, refining existing v0.2 test cases, and introducing a suite of new tests to thoroughly validate the v0.4 protocol's session lifecycle, including various state submission intents (operate, deposit, withdraw) and their corresponding impact on asset allocations and balances.

Highlights

  • RPC Endpoint Update: The WebSocket RPC URL has been updated from sandboxWsRpcUrl to uatWsRpcUrl (wss://canarynet.yellow.com/ws) across the manual client test.
  • Test Function Renaming: The main test function TestManualClient has been renamed to TestManualClientNitroRPCv0_2 to explicitly indicate its compatibility with NitroRPCv0.2.
  • Asset Symbol Change: The default asset symbol used in the tests has been changed from usdc to ytest.usd.
  • NitroRPCv0.4 Test Cases: Comprehensive new test cases have been introduced for NitroRPCv0.4, covering CreateAppSession, SubmitAppState with Operate, Deposit, and Withdraw intents, and CloseAppSession.
  • Integrated Balance Assertions: Balance tracking and assertions have been refactored and integrated directly within individual test cases for more precise verification of asset movements during session operations.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 7, 2025

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Walkthrough

Reworks the manual client test to cover Nitro RPC v0.2 and v0.4 flows: updates WS endpoint and asset symbol, adds per-test allocation variants, expands table-driven cases (create/submit/close), and adds explicit payload hashing/signing plus per-step balance assertions.

Changes

Cohort / File(s) Summary
Manual RPC client tests
clearnode/pkg/rpc/client_manual_test.go
Rewrote manual test into a table-driven suite. Switched websocket endpoint (sandbox → canary/uat) and asset symbol (usdcytest.usd). Added allocation sets (appAllocationsV0_2, appAllocationsV0_4_Original, appAllocationsV0_4_Deposited). Added many cases covering CreateAppSession, SubmitAppState (operate/deposit/withdraw), and CloseAppSession across VersionNitroRPCv0_2 and VersionNitroRPCv0_4. Introduced explicit payload hashing and signing, per-step balance retrievals and delta assertions, and per-case descriptors/labels.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant T as Test Suite
  participant C as RPC Client
  participant R as Nitro RPC Server
  participant B as Balance/Acct Service

  rect rgba(220,235,255,0.35)
  note over T,C: CreateAppSession (v0_2 / v0_4)
  T->>T: build create payload, hash, sign
  T->>C: CreateAppSession(request, versionFlag)
  C->>R: RPC CreateAppSession
  R-->>C: CreateAck (sessionID)
  C-->>T: sessionID
  T->>B: getBalances(pre / post-create)
  end

  rect rgba(220,255,220,0.35)
  note over T,C: SubmitAppState (operate / deposit / withdraw)
  T->>T: build state payload, hash, sign
  T->>C: SubmitAppState(sessionID, state, allocations)
  C->>R: RPC SubmitAppState
  R-->>C: SubmitAck
  C-->>T: ack
  T->>B: getBalances(check deltas per action)
  end

  rect rgba(255,240,220,0.35)
  note over T,C: CloseAppSession
  T->>T: build close payload, hash, sign
  T->>C: CloseAppSession(sessionID)
  C->>R: RPC CloseAppSession
  R-->>C: CloseAck
  C-->>T: ack
  T->>B: getBalances(final assertion)
  end

  note over T,B: Assertions per scenario: no-op / decrease / increase as expected
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

I am a rabbit, test-snout twitching bright,
I hop through v0_2 and v0_4 by night.
I nibble hashes, stamp each signed bite,
Count balances changing left and right.
A canary endpoint, ytest coin in sight—cheerful burrow, tests alright.

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 succinctly describes the main change of updating the manual rpc.Client test to align with NitroRPC v0.4, which matches the core modifications made in the pull request.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/nitro-rpc-0-4-test

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.

@codecov
Copy link

codecov bot commented Oct 7, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request updates the manual RPC client test to support NitroRPC v0.4. It correctly renames existing tests to specify v0.2 and adds new sub-tests for v0.4 features like deposit, withdraw, and operate intents. The balance assertions have also been improved by moving them inside each sub-test. The changes are logical and well-structured. I've added a few suggestions to improve naming and code clarity.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
clearnode/pkg/rpc/client_manual_test.go (2)

44-47: Avoid blocking the client's error path: make handleError non‑blocking or just log

Current code can deadlock if multiple errors occur; the buffered chan (size 1) is never drained.

Apply one of these minimal fixes:

Option A — log directly (simplest):

- errCh := make(chan error, 1)
- handleError := func(err error) {
-   errCh <- err
- }
+ handleError := func(err error) {
+   t.Logf("client error: %v", err)
+}

Option B — keep the chan but prevent blocking:

- errCh := make(chan error, 1)
- handleError := func(err error) {
-   errCh <- err
- }
+ errCh := make(chan error, 16)
+ handleError := func(err error) {
+   select {
+   case errCh <- err:
+   default:
+     t.Logf("client error (dropped, buffer full): %v", err)
+   }
+ }
+ go func() {
+   for err := range errCh {
+     t.Logf("client error: %v", err)
+   }
+ }()

169-181: Compile-time bug: uuid.New().ID() does not exist; generate Nonce from UUID bytes

github.com/google/uuid exposes no ID() method. Use the first 8 bytes of a v4 UUID.

Apply the following diffs:

CreateAppSession v0_2:

-       Nonce:     uint64(uuid.New().ID()),
+       Nonce:     binary.BigEndian.Uint64(uuid.New()[:8]),

CreateAppSession v0_4:

-       Nonce:     uint64(uuid.New().ID()),
+       Nonce:     binary.BigEndian.Uint64(uuid.New()[:8]),

Also add the import:

// add to the import block
import (
  // ...
  "encoding/binary"
  // ...
)

Also applies to: 293-306

🧹 Nitpick comments (2)
clearnode/pkg/rpc/client_manual_test.go (2)

94-96: Wait for first balance update to avoid flaky reads

Reads of currentBalance can occur before any event arrives after reconnect.

Apply this after Start:

 err = client.Start(ctx, uatWsRpcUrl, handleError)
 require.NoError(t, err)
+
+ // Wait until we get the first balance update for the tracked asset
+ require.Eventually(t, func() bool {
+   currentBalanceMu.RLock()
+   ok := currentBalance.Cmp(decimal.Zero) >= 0
+   currentBalanceMu.RUnlock()
+   return ok
+ }, 10*time.Second, 200*time.Millisecond, "no balance update received for %s", assetSymbol)

Add import:

import (
  // ...
  "time"
)

20-22: Optional: make WS URL and asset configurable via env for different envs

Hardcoded values limit reuse across environments.

Example:

-const (
-  uatWsRpcUrl = "wss://canarynet.yellow.com/ws"
-)
+var uatWsRpcUrl = getenvDefault("TEST_WS_URL", "wss://canarynet.yellow.com/ws")
+
+func getenvDefault(k, def string) string {
+  if v := os.Getenv(k); v != "" {
+    return v
+  }
+  return def
+}

Similarly, allow overriding:

- assetSymbol := "ytest.usd"
+ if v := os.Getenv("TEST_ASSET_SYMBOL"); v != "" {
+   assetSymbol = v
+ } else {
+   assetSymbol = "ytest.usd"
+ }

Also applies to: 78-78

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 82fa08a and ba6a06e.

📒 Files selected for processing (1)
  • clearnode/pkg/rpc/client_manual_test.go (9 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
clearnode/pkg/rpc/client_manual_test.go (4)
clearnode/pkg/rpc/api.go (13)
  • AppAllocation (582-589)
  • SubmitAppStateRequest (388-401)
  • CloseAppSessionRequest (407-414)
  • CreateAppSessionRequest (375-382)
  • AppDefinition (538-551)
  • VersionNitroRPCv0_4 (33-33)
  • CreateAppSessionMethod (102-102)
  • AppSessionIntentOperate (596-596)
  • Version (27-27)
  • SubmitAppStateMethod (104-104)
  • AppSessionIntentDeposit (598-598)
  • AppSessionIntentWithdraw (600-600)
  • CloseAppSessionMethod (106-106)
clearnode/pkg/sign/eth_signer.go (1)
  • NewEthereumAddress (24-26)
clearnode/nitrolite/signature.go (1)
  • Sign (57-78)
clearnode/pkg/rpc/message.go (1)
  • NewRequest (42-47)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: Build and Publish (Clearnode)
  • GitHub Check: Test (Integration) / Test Integration
  • GitHub Check: Analyze (go)

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

🧹 Nitpick comments (1)
clearnode/pkg/rpc/client_manual_test.go (1)

98-118: Consider consolidating identical allocation sets.

appAllocationsV0_2 and appAllocationsV0_4_Original are identical, which may cause confusion. Consider one of these approaches:

  1. Use a single shared allocation variable if the protocol version doesn't affect initial allocation structure
  2. Add comments explaining why separate variables are needed for different protocol versions

Example consolidation:

-	appAllocationsV0_2 := []rpc.AppAllocation{
-		{
-			ParticipantWallet: walletSigner.PublicKey().Address().String(),
-			AssetSymbol:       assetSymbol,
-			Amount:            decimal.NewFromInt(1),
-		},
-	}
-	appAllocationsV0_4_Original := []rpc.AppAllocation{
+	// Initial allocation for both v0.2 and v0.4 session creation
+	appAllocationsInitial := []rpc.AppAllocation{
 		{
 			ParticipantWallet: walletSigner.PublicKey().Address().String(),
 			AssetSymbol:       assetSymbol,
 			Amount:            decimal.NewFromInt(1),
 		},
 	}
+	// Increased allocation for v0.4 deposit testing
 	appAllocationsV0_4_Deposited := []rpc.AppAllocation{
 		{
 			ParticipantWallet: walletSigner.PublicKey().Address().String(),
 			AssetSymbol:       assetSymbol,
 			Amount:            decimal.NewFromInt(2),
 		},
 	}
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ba6a06e and 925fbb3.

📒 Files selected for processing (1)
  • clearnode/pkg/rpc/client_manual_test.go (9 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
clearnode/pkg/rpc/client_manual_test.go (5)
clearnode/pkg/rpc/api.go (13)
  • AppAllocation (582-589)
  • SubmitAppStateRequest (388-401)
  • CloseAppSessionRequest (407-414)
  • CreateAppSessionRequest (375-382)
  • AppDefinition (538-551)
  • VersionNitroRPCv0_4 (33-33)
  • CreateAppSessionMethod (102-102)
  • AppSessionIntentOperate (596-596)
  • Version (27-27)
  • SubmitAppStateMethod (104-104)
  • AppSessionIntentDeposit (598-598)
  • AppSessionIntentWithdraw (600-600)
  • CloseAppSessionMethod (106-106)
clearnode/pkg/sign/sign.go (2)
  • PublicKey (22-25)
  • Address (28-33)
clearnode/pkg/sign/eth_signer.go (1)
  • NewEthereumAddress (24-26)
clearnode/nitrolite/signature.go (1)
  • Sign (57-78)
clearnode/pkg/rpc/message.go (1)
  • NewRequest (42-47)
🔇 Additional comments (7)
clearnode/pkg/rpc/client_manual_test.go (7)

21-21: LGTM! Environment and test asset updates are appropriate.

The WebSocket URL change to canary and the test asset symbol update are correct for UAT testing.

Also applies to: 78-78


163-284: Verify balance update timing in tests.

The balance assertions rely on currentBalance being updated via the async event handler (lines 82-92) before the assertion runs. If the balance update event is delayed, tests could produce false positives or negatives.

Consider adding explicit synchronization or polling with timeout:

// Helper function to wait for balance update
func waitForBalanceChange(t *testing.T, mu *sync.RWMutex, current *decimal.Decimal, expected int64, timeout time.Duration) {
	deadline := time.Now().Add(timeout)
	for time.Now().Before(deadline) {
		mu.RLock()
		actual := current.IntPart()
		mu.RUnlock()
		if actual == expected {
			return
		}
		time.Sleep(10 * time.Millisecond)
	}
	t.Fatalf("balance did not update to expected value %d within timeout", expected)
}

Then use it in tests:

 createAppRes, _, err := client.CreateAppSession(ctx, &createAppFullReq)
 require.NoError(t, err)
 fmt.Printf("App Session Created: %+v\n", createAppRes.AppSessionID)
 appSessionID = createAppRes.AppSessionID
 
-currentBalanceMu.RLock()
-balanceAfter := currentBalance.IntPart()
-currentBalanceMu.RUnlock()
-
-balanceDiff := balanceBefore - balanceAfter
-assert.Equal(t, int64(1), balanceDiff, "balance should decrease by 1 unit")
+expectedBalance := balanceBefore - 1
+waitForBalanceChange(t, &currentBalanceMu, &currentBalance, expectedBalance, 5*time.Second)

287-332: LGTM! v0.4 session creation is correctly implemented.

The test properly uses VersionNitroRPCv0_4 protocol and the balance tracking logic is consistent with the expected behavior (1 unit locked in the session).


335-373: LGTM! v0.4 operate intent is correctly implemented.

The test properly includes the required v0.4 fields (Intent, Version) and correctly expects no balance change for an operate action.


376-412: LGTM! v0.4 deposit flow is correctly implemented.

The test properly demonstrates deposit behavior: allocation increases from 1 to 2 units, and the ledger balance decreases by 1 unit accordingly.


415-451: LGTM! v0.4 withdraw flow is correctly implemented.

The test properly demonstrates withdraw behavior: allocation decreases from 2 to 1 units, and the ledger balance increases by 1 unit accordingly.


454-488: LGTM! Test case naming issue resolved.

The test case name is now correct (CloseAppSession_v0_4), addressing the previous review feedback. The implementation properly closes the v0.4 session with the expected balance increase.

@philanton philanton merged commit 9047e71 into main Oct 7, 2025
12 checks passed
@philanton philanton deleted the feat/nitro-rpc-0-4-test branch October 7, 2025 15:04
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.

3 participants