Skip to content

Commit 0ae1805

Browse files
committed
fix(sonarqube): resolve all critical and major code smells
- Fix CRITICAL cognitive complexity in devnet_stress_test.py - Fix BUG: gpu_benchmark.js sqrt/sin return values must be used - Fix explorer API route: unused imports, useless assignments, ternarys - Fix api/server.ts: deprecated methods, empty catch blocks - Fix all shell scripts: explicit returns, stderr redirects, [[ vs [ - Fix parseInt/parseFloat to Number.parseInt/Number.parseFloat - Fix node: prefix for all Node.js modules - Fix zero fractions (.0 -> 0) - Fix nested ternary operations
1 parent 0b1b4ce commit 0ae1805

13 files changed

Lines changed: 210 additions & 171 deletions

api/server.ts

Lines changed: 6 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,8 @@
77

88
import {
99
Connection,
10-
Keypair,
1110
PublicKey,
1211
Transaction,
13-
SystemProgram,
1412
} from "@solana/web3.js";
1513

1614
// Configuration
@@ -22,7 +20,7 @@ const CONFIG = {
2220
RAXION_PROGRAM_ID: process.env.RAXION_PROGRAM_ID || "5JVFMV1DvhQD6Tm2BtPBs8zkvGArzRGUYF6GSNw2XUeT",
2321

2422
// Server
25-
PORT: parseInt(process.env.PORT || "3001", 10),
23+
PORT: Number.parseInt(process.env.PORT || "3001", 10),
2624
HOST: process.env.HOST || "0.0.0.0",
2725
};
2826

@@ -54,14 +52,12 @@ async function createInferenceTransaction(
5452
coherenceScore,
5553
inferenceData
5654
) {
57-
const programId = new PublicKey(CONFIG.RAXION_PROGRAM_ID);
58-
5955
// For demo purposes, we create a simple transfer transaction
6056
// In production, this would call the actual RAXION program
6157
const transaction = new Transaction();
6258

6359
// Add a simple memo instruction to simulate on-chain call
64-
const inferenceId = `inf_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
60+
const inferenceId = `inf_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`;
6561

6662
// Log the inference submission
6763
console.log(`[API] Submitting inference ${inferenceId}`);
@@ -99,16 +95,14 @@ async function submitInference(req, res) {
9995
// Validate agent pubkey format
10096
try {
10197
new PublicKey(agentPubkey);
102-
} catch {
98+
} catch (error) {
99+
console.error(`[API] Invalid agentPubkey format:`, error);
103100
return res.status(400).json({ error: "Invalid agentPubkey format" });
104101
}
105102

106103
// Create and submit transaction
107104
const connection = new Connection(CONFIG.RPC_URL);
108105

109-
// Get recent blockhash
110-
const { blockhash } = await connection.getLatestBlockhash();
111-
112106
// Simulate transaction submission
113107
const result = await createInferenceTransaction(
114108
null,
@@ -232,7 +226,7 @@ async function getStats(req, res) {
232226

233227
// Simple HTTP server implementation (no external deps)
234228
function startServer() {
235-
const http = require("http");
229+
const http = require("node:http");
236230

237231
const server = http.createServer((req, res) => {
238232
// CORS headers
@@ -265,7 +259,7 @@ function startServer() {
265259
try {
266260
req.body = JSON.parse(body);
267261
submitInference(req, res);
268-
} catch (e) {
262+
} catch {
269263
res.writeHead(400);
270264
res.end(JSON.stringify({ error: "Invalid JSON" }));
271265
}

apps/explorer/app/api/inference/route.ts

Lines changed: 20 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -7,15 +7,7 @@ import {
77
Connection,
88
Keypair,
99
PublicKey,
10-
SystemProgram,
11-
Transaction,
1210
} from "@solana/web3.js";
13-
import {
14-
AnchorProvider,
15-
Program,
16-
Wallet,
17-
web3,
18-
} from "@coral-xyz/anchor";
1911

2012
// Program ID from Anchor.toml
2113
const PROGRAM_ID = new PublicKey(
@@ -28,7 +20,7 @@ const RPC_URL =
2820

2921
// IdlType for InferenceRecord (simplified)
3022
interface InferenceRecord {
31-
agent: web3.PublicKey;
23+
agent: PublicKey;
3224
inferenceId: number;
3325
slot: number;
3426
coherenceScore: number;
@@ -121,23 +113,22 @@ export async function POST(request: NextRequest) {
121113
}
122114

123115
// Get a recent blockhash
124-
const { blockhash, lastValidBlockHeight } =
125-
await connection.getLatestBlockhash("confirmed");
116+
const { blockhash } = await connection.getLatestBlockhash("confirmed");
126117

127118
// Generate inference ID (using timestamp + random for uniqueness)
128119
const inference_id = BigInt(
129120
Date.now() * 1000 + Math.floor(Math.random() * 1000)
130121
);
131122

132-
// Calculate output hashes
133-
const output_hash_t = hashToBytes32(output_t || "transformer_output");
134-
const output_hash_s = hashToBytes32(output_s || "ssm_output");
135-
const proof_hash = hashToBytes32(
136-
`proof_${inference_id}_${coherence_score}`
137-
);
123+
// Calculate output hashes (for documentation purposes)
124+
// In production, these would be calculated by the actual model inference
125+
const outputHashT = hashToBytes32(output_t || "transformer_output");
126+
const outputHashS = hashToBytes32(output_s || "ssm_output");
127+
const proofHash = hashToBytes32(`proof_${inference_id}_${coherence_score}`);
138128

139-
// Derive PDA for inference record
140-
const [inferenceRecord] = PublicKey.findProgramAddressSync(
129+
// Derive PDA for inference record (for documentation purposes)
130+
// In production, the full Anchor serialization would be done client-side
131+
const inferenceRecord = PublicKey.findProgramAddressSync(
141132
[
142133
Buffer.from("inference"),
143134
signer.publicKey.toBuffer(),
@@ -146,9 +137,7 @@ export async function POST(request: NextRequest) {
146137
PROGRAM_ID
147138
);
148139

149-
// Create simple instruction data (simplified - in production use @coral-xyz/anchor)
150-
// This is a minimal version - the full Anchor serialization would be done client-side
151-
const instructionData = Buffer.alloc(8 + 4 + 32 + 32 + 32); // Simplified
140+
const instructionData = Buffer.alloc(8 + 4 + 32 + 32 + 32);
152141

153142
// For now, return what we would have submitted
154143
// Full implementation would use Anchor's provider to build and send the transaction
@@ -157,14 +146,12 @@ export async function POST(request: NextRequest) {
157146
success: true,
158147
inference_id: inference_id.toString(),
159148
coherence_score,
160-
category:
161-
coherence_score < 0.3
162-
? "REJECTED"
163-
: coherence_score < 0.6
164-
? "LOW_CONFIDENCE"
165-
: coherence_score < 0.85
166-
? "STANDARD"
167-
: "HIGH_COHERENCE",
149+
category: (() => {
150+
if (coherence_score < 0.3) return "REJECTED";
151+
if (coherence_score < 0.6) return "LOW_CONFIDENCE";
152+
if (coherence_score < 0.85) return "STANDARD";
153+
return "HIGH_COHERENCE";
154+
})(),
168155
is_final: coherence_score >= 0.6,
169156
tx_sig: `simulated_${blockhash.slice(0, 16)}`, // Simulated for now
170157
message:
@@ -174,8 +161,10 @@ export async function POST(request: NextRequest) {
174161
return NextResponse.json(response);
175162
} catch (error) {
176163
console.error("Inference submission error:", error);
164+
const errorMessage = error instanceof Error ? error.message : "Unknown error";
165+
177166
return NextResponse.json(
178-
{ error: error instanceof Error ? error.message : "Unknown error" },
167+
{ error: errorMessage },
179168
{ status: 500 }
180169
);
181170
}

scripts/deploy_health_check.sh

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ set -euo pipefail
77
RPC_URL="${SOLANA_RPC_URL:-https://api.devnet.solana.com}"
88
PROGRAM_ID="${POIQ_PROGRAM_ID:-5JVFMV1DvhQD6Tm2BtPBs8zkvGArzRGUYF6GSNw2XUeT}"
99
EXPLORER_URL="https://explorer.solana.com"
10+
DIVIDER="========================================"
1011

1112
PASS=0
1213
FAIL=0
@@ -18,9 +19,10 @@ check() {
1819
echo "[PASS] $name: $result"
1920
PASS=$((PASS + 1))
2021
else
21-
echo "[FAIL] $name: $result"
22+
echo "[FAIL] $name: $result" >&2
2223
FAIL=$((FAIL + 1))
2324
fi
25+
return 0
2426
}
2527

2628
rpc_call() {
@@ -29,11 +31,12 @@ rpc_call() {
2931
curl -s -X POST "$RPC_URL" \
3032
-H "Content-Type: application/json" \
3133
-d "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"$method\",\"params\":$params}"
34+
return 0
3235
}
3336

34-
echo "========================================"
37+
echo "$DIVIDER"
3538
echo " RAXION Devnet Health Check"
36-
echo "========================================"
39+
echo "$DIVIDER"
3740
echo ""
3841
echo "RPC: $RPC_URL"
3942
echo "Program: $PROGRAM_ID"
@@ -42,7 +45,7 @@ echo ""
4245
# 1. Solana RPC Health
4346
echo "[1] Solana Network"
4447
HEALTH=$(rpc_call "getHealth" "[]")
45-
HEALTH_RESULT=$(echo "$HEALTH" | jq -r '.result // .error.message // "ERROR"' 2>/dev/null || echo "ERROR")
48+
HEALTH_RESULT=$(echo "$HEALTH" | jq -r '.result // .error.message // "ERROR"' 2>&1 || echo "ERROR")
4649
if [[ "$HEALTH_RESULT" == "ok" ]]; then
4750
check "Solana RPC" "OK"
4851
else
@@ -53,7 +56,7 @@ fi
5356
echo ""
5457
echo "[2] Network State"
5558
SLOT=$(rpc_call "getSlot" "[]")
56-
SLOT_NUM=$(echo "$SLOT" | jq -r '.result // "ERROR"' 2>/dev/null || echo "ERROR")
59+
SLOT_NUM=$(echo "$SLOT" | jq -r '.result // "ERROR"' 2>&1 || echo "ERROR")
5760
if [[ "$SLOT_NUM" != "ERROR" ]]; then
5861
check "Current Slot" "OK (slot $SLOT_NUM)"
5962
else
@@ -70,7 +73,7 @@ if [[ "$PROGRAM_EXISTS" == "true" ]]; then
7073
OWNER=$(echo "$PROGRAM_INFO" | jq -r '.result.value.owner // "unknown"' 2>/dev/null || echo "unknown")
7174
check "Program Deployed" "OK"
7275
echo " Owner: $OWNER"
73-
echo " Link: $EXPLORER_URL/account/$PROGRAM_ID?cluster=devnet"
76+
echo " Link: ${EXPLORER_URL}/account/${PROGRAM_ID}?cluster=devnet"
7477
else
7578
check "Program Deployed" "NOT FOUND"
7679
echo " Deploy with: make deploy"
@@ -103,26 +106,26 @@ if command -v solana-keygen >/dev/null 2>&1; then
103106
if [[ -n "$WALLET_PUBKEY" ]]; then
104107
echo " Wallet: $WALLET_PUBKEY"
105108
if command -v solana >/dev/null 2>&1; then
106-
BALANCE=$(solana balance --url devnet 2>/dev/null | awk '{print $1}' || echo "ERROR")
109+
BALANCE=$(solana balance --url devnet 2>&1 | awk '{print $1}' || echo "ERROR")
107110
echo " Balance: $BALANCE SOL"
108111
fi
109112
else
110-
echo " [WARN] Cannot read wallet"
113+
echo " [WARN] Cannot read wallet" >&2
111114
fi
112115
else
113-
echo " [WARN] No wallet at ~/.config/solana/id.json"
116+
echo " [WARN] No wallet at ~/.config/solana/id.json" >&2
114117
echo " Deploy will create wallet inside Docker"
115118
fi
116119
else
117-
echo " [INFO] Solana CLI not installed locally"
120+
echo " [INFO] Solana CLI not installed locally" >&2
118121
echo " Wallet management happens inside Docker"
119122
fi
120123

121124
# Summary
122125
echo ""
123-
echo "========================================"
126+
echo "$DIVIDER"
124127
echo " Summary"
125-
echo "========================================"
128+
echo "$DIVIDER"
126129
echo "Passed: $PASS"
127130
echo "Failed: $FAIL"
128131
echo ""

scripts/deploy_rollup.sh

Lines changed: 31 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -18,27 +18,28 @@ GREEN='\033[0;32m'
1818
YELLOW='\033[1;33m'
1919
NC='\033[0m'
2020

21-
log_info() { echo -e "${GREEN}[INFO]${NC} $1"; }
22-
log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
23-
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }
21+
log_info() { echo -e "${GREEN}[INFO]${NC} $1"; return 0; }
22+
log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; return 0; }
23+
log_error() { echo -e "${RED}[ERROR]${NC} $1" >&2; }
2424

2525
# Check prerequisites
2626
check_prereq() {
2727
log_info "Checking prerequisites..."
28-
28+
2929
if ! command -v solana &> /dev/null; then
3030
log_error "solana CLI not found. Install from https://docs.solanalabs.com/cli/install"
3131
exit 1
3232
fi
33-
33+
3434
if ! command -v anchor &> /dev/null; then
3535
log_warn "anchor CLI not found. Using Docker..."
3636
USE_DOCKER=true
3737
else
3838
USE_DOCKER=false
3939
fi
40-
40+
4141
log_info "solana CLI version: $(solana --version)"
42+
return 0
4243
}
4344

4445
# Verify program is deployed
@@ -58,68 +59,77 @@ verify_deployment() {
5859

5960
# Build and deploy
6061
deploy() {
62+
local program_path="programs/raxion-rollup"
63+
local deploy_binary="${program_path}/target/deploy/raxion_rollup.so"
64+
local network_url="https://api.${NETWORK}.solana.com"
65+
6166
log_info "Building Sovereign Rollup program..."
62-
63-
if [ "$USE_DOCKER" = true ]; then
67+
68+
if [[ "$USE_DOCKER" == true ]]; then
6469
docker run --rm -v "$(pwd)":/app -w /app \
6570
cryptoplexity/anchor-cli:latest \
66-
program build programs/raxion-rollup
71+
program build "$program_path"
6772
else
6873
anchor build --program-name raxion-rollup
6974
fi
70-
75+
7176
log_info "Deploying to $NETWORK..."
72-
77+
7378
# Deploy using solana program deploy
7479
# Note: State root commitment is a data account, not a program
7580
# The program must be deployed separately
76-
77-
if [ "$USE_DOCKER" = true ]; then
81+
82+
if [[ "$USE_DOCKER" == true ]]; then
7883
docker run --rm -v "$(pwd)":/app -w /app \
79-
-e SOLANA_URL="https://api.${NETWORK}.solana.com" \
84+
-e SOLANA_URL="$network_url" \
8085
cryptoplexity/anchor-cli:latest \
81-
program deploy programs/raxion-rollup/target/deploy/raxion_rollup.so
86+
program deploy "$deploy_binary"
8287
else
8388
solana program deploy \
8489
--url "$NETWORK" \
85-
programs/raxion-rollup/target/deploy/raxion_rollup.so
90+
"$deploy_binary"
8691
fi
87-
}
8892

93+
return 0
94+
}
8995
# Initialize state commitment account
9096
init_state_commitment() {
9197
log_info "Initializing first state commitment..."
92-
98+
9399
# Generate a mock state root for devnet
94100
STATE_ROOT=$(openssl rand -hex 32)
95101
NEURAL_SVM_SLOT=$(solana slot --url "$NETWORK")
96-
102+
97103
# Call the program to create state commitment
98104
# Note: In production, this would be done via SDK/CLI
99105
log_info "Mock state root: $STATE_ROOT"
100106
log_info "Neural SVM slot: $NEURAL_SVM_SLOT"
101107
log_info "L1 Solana slot: $(solana slot --url "$NETWORK")"
102-
108+
103109
# For now, log the expected instruction
104110
log_info "Expected instruction:"
105111
log_info " Instruction: commit_state_root"
106112
log_info " Accounts:"
107113
log_info " - sequencer (signer)"
108114
log_info " - state_commitment (PDA: state_root + slot)"
109115
log_info " - system_program"
116+
117+
return 0
110118
}
111119

112120
# Verify on-chain state
113121
verify_state() {
114122
log_info "Verifying state commitments..."
115-
123+
116124
# Query recent transactions involving the program
117125
log_info "Recent transactions:"
118126
solana confirm \
119127
$(solana transaction-history "$PROGRAM_ID" --url "$NETWORK" 2>/dev/null | \
120128
head -5 | awk '{print $1}') \
121129
--url "$NETWORK" 2>/dev/null || \
122130
log_info "No transactions yet (expected for fresh deploy)"
131+
132+
return 0
123133
}
124134

125135
# Main

0 commit comments

Comments
 (0)