Skip to content

Add integration tests for vault client functionality - #22

Open
BigJohn-dev wants to merge 1 commit into
clevercon-protocol:mainfrom
BigJohn-dev:Write-integration-tests-for-the-CleverVault-orchestrator
Open

Add integration tests for vault client functionality#22
BigJohn-dev wants to merge 1 commit into
clevercon-protocol:mainfrom
BigJohn-dev:Write-integration-tests-for-the-CleverVault-orchestrator

Conversation

@BigJohn-dev

@BigJohn-dev BigJohn-dev commented Jun 21, 2026

Copy link
Copy Markdown

Closes #6

Orchestrator Vault Client and Integration Testing

This document describes the CleverVault integration point used by the orchestrator and the new live integration tests covering the full vault lifecycle on Stellar testnet.

Overview

The orchestrator interacts with the CleverVault Soroban contract via packages/orchestrator/src/agent-vault-client.ts.

That client provides two modes of operation:

  • User-signed XDR builders for Freighter-style flows:

    • buildRegisterOrchestratorXdr — register a user/orchestrator mapping
    • buildDepositXdr — deposit USDC into the vault
    • buildWithdrawXdr — withdraw available USDC from the vault
    • buildCancelTaskXdr — cancel an active task and refund unused budget
  • Server-side orchestrator operations signed by the orchestrator keypair:

    • createTask — lock a task budget from user available balance
    • releasePayment — release payment from the vault to the orchestrator
    • completeTask / forceCompleteTask — complete the task and unlock remaining balance

The client also exposes read-only views:

  • getAvailable — available (unlocked) vault balance
  • getBalance — total vault balance
  • getAccount — full vault account summary for the user

Configuration

The client uses these environment variables:

  • AGENT_VAULT_CONTRACT_ID — address of the deployed CleverVault contract
  • STELLAR_RPC_URL — Soroban RPC endpoint (defaults to https://soroban-testnet.stellar.org)
  • ORCHESTRATOR_SECRET_KEY — orchestrator wallet secret used in test setup and funding helpers

If AGENT_VAULT_CONTRACT_ID is missing or invalid, the client disables live vault features and returns safe defaults for read-only calls.

Live Vault Lifecycle

The orchestrator vault lifecycle tested in packages/orchestrator/src/__tests__/vault-client.integration.test.ts covers:

  1. Friendbot-funded testnet wallets for user and orchestrator
  2. USDC trustline creation for both wallets
  3. Orchestrator registration with the CleverVault contract
  4. Depositing USDC into the vault
  5. Creating a task and locking budget on-chain
  6. Releasing payment from the vault to the orchestrator
  7. Completing the task and withdrawing remaining available balance
  8. Error cases such as duplicate release and insufficient balance

Integration Tests

The new integration suite lives in:

  • packages/orchestrator/src/__tests__/vault-client.integration.test.ts

Each test is tagged with @integration and uses it.concurrent(..., { tags: ['integration'] }, ...) so Vitest can filter them separately.

Running integration tests

From the repository root:

npm run test:integration

From the orchestrator package:

npm --workspace packages/orchestrator run test:integration

Excluding integration tests from default CI runs

The root package.json is configured so npm test excludes integration-tagged tests:

npm test

This runs only unit tests and leaves live Soroban testnet coverage to the dedicated integration command.

Notes

  • The integration tests depend on a live Stellar testnet environment and the deployed AGENT_VAULT_CONTRACT_ID.
  • The orchestrator package also has a package-scoped test:integration script for convenience.
  • The vault client is intentionally separated into user-signed XDR builders and orchestrator-signed execution helpers to mirror on-chain authorization boundaries.

Summary by CodeRabbit

  • Other
    • Updated application branding and interface name
    • Refreshed application build with latest dependencies

- Implement tests for deposit, task creation, payment release, and withdrawal.
- Include checks for available balance adjustments and task state validation.
- Utilize Vitest for concurrent test execution and setup.
- Ensure proper handling of edge cases, such as double release on completed tasks and insufficient balance for task creation.
@coderabbitai

coderabbitai Bot commented Jun 21, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Adds a Vitest integration test suite (vault-client.integration.test.ts) that exercises the full vault lifecycle against the Stellar testnet, including deposit, task creation, payment release, withdrawal, double-release failure, and insufficient-funds failure. Splits the root and orchestrator package.json test scripts into separate unit and integration commands. Updates the orchestrator HTML title and bundle URL.

Changes

Vault Client Integration Tests

Layer / File(s) Summary
Test script split and HTML update
package.json, packages/orchestrator/package.json, packages/orchestrator/public/index.html
Root package.json adds --excludeTags integration to test and a new test:integration script. Orchestrator package.json adds a test:integration script targeting *.integration.test.ts with the integration tag. HTML title changed to "CleverCon" and module bundle URL updated.
Integration test module setup and Soroban helpers
packages/orchestrator/src/__tests__/vault-client.integration.test.ts (lines 1–180)
Introduces the test module with dotenv, Stellar/Soroban SDK, vault-client XDR imports, network constants, and conditional suite enabling. Adds RPC server factories, a Soroban transaction polling loop, friendbot funding, USDC trustline setup, USDC funding helpers, Horizon balance reading, on-chain get_task simulation, and a fixture builder that provisions fresh random participants.
Vault operation wrappers and integration test cases
packages/orchestrator/src/__tests__/vault-client.integration.test.ts (lines 182–351)
Adds wrappers for register, deposit, and withdraw using imported XDR builders. Adds releasePaymentDirect for full Soroban call/simulate/assemble/sign/send flow. Defines USDC stroop constants. Adds six concurrent integration tests: deposit balance increase, task creation and field assertions, payment release and balance increase, complete-and-withdraw to zero, double-release error match, and insufficient-funds task creation failure.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related issues

  • #6 — Write integration tests for the CleverVault orchestrator client: This PR directly implements all six acceptance criteria from that issue, including the test file location, all six test scenarios, it.concurrent and integration tagging, the test:integration script, exclusion from default npm test, and testnet-appropriate timeouts.
  • #10 — Unit tests for CleverVault contract internals: The PR adds the client-side integration layer that complements the contract-level unit tests requested in that issue, covering overlapping vault behaviors (deposit, task creation, release, withdraw) from the Soroban client perspective.

Poem

🐇 Hop, hop, the testnet awaits,
Fresh keypairs funded at friendbot's gates.
Deposit, create, release, withdraw—
Six scenarios tested without a flaw.
Double release? Contract says nay!
The vault client hops another day. 🌟

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Out of Scope Changes check ❓ Inconclusive Changes are within scope, except for the HTML title change in index.html from 'AgentForge' to 'CleverCon' which appears unrelated to integration testing requirements. Clarify whether the HTML title change in packages/orchestrator/public/index.html is intentional or should be reverted to stay focused on vault client integration tests.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title directly and clearly summarizes the main change: adding integration tests for vault client functionality.
Linked Issues check ✅ Passed All six test scenarios from issue #6 are covered: deposit, task creation, payment release, withdrawal, double release error, and insufficient balance handling. Configuration requirements (test:integration script, default npm test exclusion, timeouts, fresh keypairs) are met.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/orchestrator/src/__tests__/vault-client.integration.test.ts`:
- Around line 109-133: The sendUsdcFromFundedOrchestrator function shares a
single source account across concurrent tests, causing sequence number race
conditions on Stellar. Replace all instances of it.concurrent with it to
serialize the tests that call this function. This includes the test definitions
around the sendUsdcFromFundedOrchestrator function itself and any other test
blocks that invoke USDC funding operations (affecting the areas mentioned at
lines 169-177 and 255-350), ensuring tests execute sequentially rather than in
parallel.
🪄 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: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 8b8282e4-df41-4d69-b0f7-0b77914679f6

📥 Commits

Reviewing files that changed from the base of the PR and between 66c5d4c and e9c2ca8.

📒 Files selected for processing (5)
  • package.json
  • packages/orchestrator/package.json
  • packages/orchestrator/public/assets/index-90giOIxm.js
  • packages/orchestrator/public/index.html
  • packages/orchestrator/src/__tests__/vault-client.integration.test.ts

Comment on lines +109 to +133
async function sendUsdcFromFundedOrchestrator(destination: string, amount: string): Promise<void> {
if (!ORCHESTRATOR_SECRET_KEY) {
throw new Error('Missing ORCHESTRATOR_SECRET_KEY for USDC funding');
}

const source = Keypair.fromSecret(ORCHESTRATOR_SECRET_KEY);
const server = horizonServer();
const account = await server.loadAccount(source.publicKey());
const tx = new TransactionBuilder(account, {
fee: '100',
networkPassphrase: NETWORK_PASSPHRASE,
})
.addOperation(
Operation.payment({
destination,
asset: USDC,
amount,
}),
)
.setTimeout(30)
.build();

tx.sign(source);
await server.submitTransaction(tx);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Shared funding account + it.concurrent can cause intermittent tx_bad_seq failures.

sendUsdcFromFundedOrchestrator signs from one source account (ORCHESTRATOR_SECRET_KEY) while all scenarios run concurrently. On Stellar, that creates sequence-number races and flaky integration runs.

Suggested low-effort fix (serialize the live-network tests)
-  it.concurrent('`@integration` Deposit increases available by 1 USDC', { tags: ['integration'] }, async () => {
+  it('`@integration` Deposit increases available by 1 USDC', { tags: ['integration'] }, async () => {
@@
-  it.concurrent('`@integration` Create task decreases available and get_task returns the task', { tags: ['integration'] }, async () => {
+  it('`@integration` Create task decreases available and get_task returns the task', { tags: ['integration'] }, async () => {
@@
-  it.concurrent('`@integration` Release payment increases orchestrator USDC balance', { tags: ['integration'] }, async () => {
+  it('`@integration` Release payment increases orchestrator USDC balance', { tags: ['integration'] }, async () => {
@@
-  it.concurrent('`@integration` Withdraw remaining balance leaves available at 0', { tags: ['integration'] }, async () => {
+  it('`@integration` Withdraw remaining balance leaves available at 0', { tags: ['integration'] }, async () => {
@@
-  it.concurrent('`@integration` Double release on completed task fails', { tags: ['integration'] }, async () => {
+  it('`@integration` Double release on completed task fails', { tags: ['integration'] }, async () => {
@@
-  it.concurrent('`@integration` Creating a task with insufficient available balance fails', { tags: ['integration'] }, async () => {
+  it('`@integration` Creating a task with insufficient available balance fails', { tags: ['integration'] }, async () => {

Also applies to: 169-177, 255-350

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/orchestrator/src/__tests__/vault-client.integration.test.ts` around
lines 109 - 133, The sendUsdcFromFundedOrchestrator function shares a single
source account across concurrent tests, causing sequence number race conditions
on Stellar. Replace all instances of it.concurrent with it to serialize the
tests that call this function. This includes the test definitions around the
sendUsdcFromFundedOrchestrator function itself and any other test blocks that
invoke USDC funding operations (affecting the areas mentioned at lines 169-177
and 255-350), ensuring tests execute sequentially rather than in parallel.

@Bosun-Josh121

Copy link
Copy Markdown
Collaborator

LGTM! Just fix the CI fail @BigJohn-dev

@Bosun-Josh121

Copy link
Copy Markdown
Collaborator

You've been unresponsive so far regarding the PR after reaching out privately. The CI fail is a small fix or are you experiencing some difficulties? If no response from you i'll have to assign the task to someone else

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.

[Task]: Write integration tests for the CleverVault orchestrator client

2 participants