# What Is the Purpose of the broadcast_race_test in CloddsBot's fast-broadcast Module?

> Discover the purpose of broadcast_race_test in CloddsBot's fast-broadcast module. Learn how it validates transaction racing across RPC endpoints and handles failures.

- Repository: [AL/CloddsBot](https://github.com/alsk1992/CloddsBot)
- Tags: how-to-guide
- Published: 2026-09-13

---

**The `broadcast_race_test` validates that the Fast EVM Broadcast module correctly races transactions across multiple RPC endpoints, returns structured `BroadcastRaceResult` objects, and handles failures gracefully.**

The `broadcast_race_test` is a critical unit test in the [alsk1992/CloddsBot](https://github.com/alsk1992/CloddsBot) repository that ensures the high-performance transaction broadcasting logic functions reliably. Located in [`tests/unit/fast-broadcast.test.ts`](https://github.com/alsk1992/CloddsBot/blob/main/tests/unit/fast-broadcast.test.ts), this test verifies the integration between the TypeScript wrapper and the Rust-based racing engine to guarantee low-latency on-chain operations.

## Core Functionality Validated by broadcast_race_test

### RPC Endpoint Racing Logic

The test confirms that **`broadcastRace`** submits signed raw transactions to multiple RPC URLs simultaneously and correctly identifies the first successful responder. It asserts that the `wonBy` field in the result corresponds to the fastest endpoint and that `latencyMs` reflects the actual round-trip time measured by the Rust worker.

### BroadcastRaceResult Structure Verification

According to the test assertions in [`tests/unit/fast-broadcast.test.ts`](https://github.com/alsk1992/CloddsBot/blob/main/tests/unit/fast-broadcast.test.ts), the function must return a valid `BroadcastRaceResult` object containing the transaction `hash`, the winning endpoint URL (`wonBy`), the measured latency in milliseconds (`latencyMs`), and the total `endpointCount` queried during the race.

### Error Handling and Failure Scenarios

The `broadcast_race_test` simulates conditions where all RPC endpoints reject the transaction or return errors. It validates that the Promise is rejected with an appropriate error when no endpoints succeed, ensuring the module does not resolve with partial or invalid data during network outages or RPC downtime.

### TypeScript-to-Rust Bridge Integrity

Because the heavy computation runs in a compiled Rust binary spawned from [`src/evm/fast-broadcast.ts`](https://github.com/alsk1992/CloddsBot/blob/main/src/evm/fast-broadcast.ts), the test verifies correct JSON marshaling between Node.js and the Rust process. This includes handling `stderr` output and malformed JSON responses without crashing the TypeScript wrapper.

## Code Examples: Using the Fast-Broadcast Module

### Broadcasting a Transaction with signAndBroadcastRace

```typescript
import { Wallet } from 'ethers';
import { signAndBroadcastRace } from '../src/evm/fast-broadcast';

const wallet = new Wallet(process.env.PRIVATE_KEY);
const tx = {
  to: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb',
  value: ethers.utils.parseEther('0.01'),
  gasLimit: 100000,
};

const rpcUrls = [
  'https://rpc1.example.com',
  'https://rpc2.example.com',
  'https://rpc3.example.com'
];

async function submit() {
  const result = await signAndBroadcastRace(wallet, tx, rpcUrls);
  console.log('Tx hash:', result.hash);
  console.log('Won by:', result.wonBy);
  console.log('Latency:', result.latencyMs, 'ms');
}
submit();

```

### Testing the Race Logic (Mock Scenario)

```typescript
// Conceptual representation of broadcast_race_test assertions
const fastRpc = mockEndpoint({ latency: 10, success: true });
const slowRpc = mockEndpoint({ latency: 200, success: true });

const result = await broadcastRace(signedTx, [fastRpc.url, slowRpc.url]);

// Assert the fastest endpoint wins
expect(result.wonBy).toBe(fastRpc.url);
expect(result.latencyMs).toBeLessThan(50);
expect(result.endpointCount).toBe(2);
expect(result.hash).toMatch(/^0x[a-fA-F0-9]{64}$/);

```

## Key Source Files in CloddsBot

- **[`src/evm/fast-broadcast.ts`](https://github.com/alsk1992/CloddsBot/blob/main/src/evm/fast-broadcast.ts)**: Implements `broadcastRace` and `signAndBroadcastRace`, spawning the Rust worker and managing JSON I/O streams.
- **[`tests/unit/fast-broadcast.test.ts`](https://github.com/alsk1992/CloddsBot/blob/main/tests/unit/fast-broadcast.test.ts)**: Contains the `broadcast_race_test` suite that exercises race conditions, result validation, and error paths.
- **[`rust/fast-broadcast/src/main.rs`](https://github.com/alsk1992/CloddsBot/blob/main/rust/fast-broadcast/src/main.rs)**: The high-performance Rust binary that executes the actual RPC racing logic and returns results to the TypeScript host.
- **[`src/utils/logger.ts`](https://github.com/alsk1992/CloddsBot/blob/main/src/utils/logger.ts)**: Provides debug logging utilities used by the fast-broadcast module to trace which endpoint won the race.

## Summary

- The **`broadcast_race_test`** ensures the fast-broadcast module correctly races transactions across multiple RPC endpoints and identifies the fastest successful response.
- It validates the **`BroadcastRaceResult`** structure, confirming the presence of `hash`, `wonBy`, `latencyMs`, and `endpointCount` fields.
- The test verifies robust **error handling** when all RPC endpoints fail, ensuring the Promise rejects appropriately rather than resolving with invalid data.
- It confirms the integrity of the **TypeScript-Rust boundary**, ensuring JSON communication between the Node.js wrapper and the compiled binary works reliably.

## Frequently Asked Questions

### What does the broadcast_race_test validate in CloddsBot?

The `broadcast_race_test` validates that the `broadcastRace` function correctly implements a racing mechanism across multiple RPC endpoints, returns properly structured `BroadcastRaceResult` objects, and handles complete failure scenarios without hanging or returning corrupted data.

### How does the fast-broadcast module handle RPC failures?

According to the source code in [`src/evm/fast-broadcast.ts`](https://github.com/alsk1992/CloddsBot/blob/main/src/evm/fast-broadcast.ts), when all configured RPC endpoints fail to return a successful response, the module rejects the Promise with an aggregate error, ensuring that the caller knows the transaction was not broadcast rather than receiving a falsified success message.

### What fields are included in the BroadcastRaceResult object?

As verified by [`tests/unit/fast-broadcast.test.ts`](https://github.com/alsk1992/CloddsBot/blob/main/tests/unit/fast-broadcast.test.ts), the `BroadcastRaceResult` object includes the transaction `hash` as a hex string, the winning endpoint URL (`wonBy`), the measured round-trip latency in milliseconds (`latencyMs`), and the total number of endpoints queried (`endpointCount`).

### Where is the broadcast_race_test file located?

The test file is located at [`tests/unit/fast-broadcast.test.ts`](https://github.com/alsk1992/CloddsBot/blob/main/tests/unit/fast-broadcast.test.ts) in the [alsk1992/CloddsBot](https://github.com/alsk1992/CloddsBot) repository, alongside other unit tests for the EVM interaction layer.