Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 36 additions & 2 deletions frontend/lib/sort.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,17 @@
import { sortServices, sortAgents, sortServicesWithTieBreaker, sortAgentsWithTieBreaker } from './sort';
import { sortServices, sortAgents, sortServicesWithTieBreaker, sortAgentsWithTieBreaker, parsePriceMicroUsdc } from './sort';
import type { ServiceEntry, AgentEntry, SortOption, AgentSortOption } from './types';

function makeAgent(overrides: Partial<AgentEntry> = {}): AgentEntry {
return {
address: 'GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWFL',
score: 0,
total_payments: '0',
registered_at: '100',
active: true,
...overrides,
};
}
Comment on lines +4 to +13

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.

🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the factory and its declared return contract.
ast-grep outline frontend/lib/sort.test.ts --items all --match makeAgent
sed -n '4,14p' frontend/lib/sort.test.ts
sed -n '87,102p' frontend/lib/types.ts

Repository: Stellar-Ecosystem/lodestar

Length of output: 951


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Package version and tsconfig(s):"
if [ -f package.json ]; then
  jq -r '.devDependencies.typescript // .dependencies.typescript // empty' package.json
fi
fd -a 'tsconfig\.json$' . | sed 's#^\./##' | sort

echo
echo "TS availability:"
if command -v npx >/dev/null 2>&1; then
  npx tsc --version 2>/dev/null || true
fi
if command -v tsc >/dev/null 2>&1; then
  tsc --version 2>/dev/null || true
fi

echo
echo "Check TS diagnostic for sort.test.ts (read-only):"
if command -v tsc >/dev/null 2>&1; then
  tsc --noEmit --strict frontend/lib/sort.test.ts frontend/lib/types.ts 2>&1 || true
fi

Repository: Stellar-Ecosystem/lodestar

Length of output: 7318


Make the fixture satisfy AgentEntry.

makeAgent returns AgentEntry, but the object omits required fields: name, description, owner, successful_payments, failed_payments, total_volume_stroops, last_active, flagged, and flag_reason. Add defaults so overrides: Partial<AgentEntry> = {} can still produce a complete AgentEntry.

🤖 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 `@frontend/lib/sort.test.ts` around lines 4 - 13, Update the makeAgent fixture
to include defaults for the required AgentEntry fields name, description, owner,
successful_payments, failed_payments, total_volume_stroops, last_active,
flagged, and flag_reason, while preserving the existing overrides spread so
callers can replace any default.


function makeService(overrides: Partial<ServiceEntry> = {}): ServiceEntry {
return {
id: 1,
Expand Down Expand Up @@ -66,6 +77,29 @@ function makeAgent(overrides: Partial<AgentEntry> = {}): AgentEntry {
expect(result.map((s) => s.id)).toEqual([2, 3, 1]);
});

it('does not disturb ordering of valid entries when a malformed price exists', () => {
const services = [
makeService({ id: 1, price_usdc: '1.50' }),
makeService({ id: 2, price_usdc: 'not-a-price' }),
makeService({ id: 3, price_usdc: '0.25' }),
makeService({ id: 4, price_usdc: '0.75' }),
];
const result = sortServices(services, 'price');
// Valid entries [3, 4, 1] come first in price order; malformed entry (id: 2) sorts last
expect(result.map((s) => s.id)).toEqual([3, 4, 1, 2]);
});

it('places unparseable prices at the end', () => {
const services = [
makeService({ id: 1, price_usdc: '0.50' }),
makeService({ id: 2, price_usdc: 'bad' }),
makeService({ id: 3, price_usdc: '0.10' }),
];
const result = sortServices(services, 'price');
// id 3 (0.10) < id 1 (0.50) < id 2 (unparseable)
expect(result.map((s) => s.id)).toEqual([3, 1, 2]);
});

it('does not mutate the original array', () => {
const services = [
makeService({ id: 1, registered_at: 100 }),
Expand Down Expand Up @@ -126,7 +160,7 @@ describe('sortServicesWithTieBreaker', () => {
makeService({ id: 2, reputation: 10, price_usdc: '0.50' }),
];
const result = sortServicesWithTieBreaker(services, 'reputation', (a, b) =>
parseFloat(a.price_usdc) - parseFloat(b.price_usdc)
parsePriceMicroUsdc(a.price_usdc)! - parsePriceMicroUsdc(b.price_usdc)!
);
expect(result.map((s) => s.id)).toEqual([2, 1]);
});
Expand Down
46 changes: 43 additions & 3 deletions frontend/lib/sort.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,45 @@
import type { ServiceEntry, AgentEntry, SortOption, AgentSortOption } from './types';

/**
* Parse a USDC price string to a fixed-point integer (micro-USDC, 7 decimals).
* Stellar USDC has 7 decimal places, so "1.50" → 15_000_000 micro-USDC.
* Returns null for unparseable values (e.g. "abc", "0.001abc").
* Exported for testing.
*/
export function parsePriceMicroUsdc(price: string): number | null {
if (typeof price !== 'string') return null;
const trimmed = price.trim();
const match = trimmed.match(/^(\d+)(?:\.(\d+))?$/);
if (!match) return null;

const intPart = match[1];
const fracPart = (match[2] ?? '').padEnd(7, '0').slice(0, 7);
const combined = `${intPart}${fracPart}`;
const normalized = combined.replace(/^0+/, '') || '0';
const result = Number(normalized);

return Number.isSafeInteger(result) && result >= 0 ? result : null;
Comment on lines +15 to +21

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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Reject prices with more than seven fractional digits.

Line 16 silently truncates excess precision. For example, "1.00000009" becomes the valid value "1.0000000" instead of sorting as an invalid price. Reject fractions longer than seven digits before fixed-point conversion.

Proposed fix
   const intPart = match[1];
-  const fracPart = (match[2] ?? '').padEnd(7, '0').slice(0, 7);
+  const fraction = match[2] ?? '';
+  if (fraction.length > 7) return null;
+  const fracPart = fraction.padEnd(7, '0');
📝 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
const intPart = match[1];
const fracPart = (match[2] ?? '').padEnd(7, '0').slice(0, 7);
const combined = `${intPart}${fracPart}`;
const normalized = combined.replace(/^0+/, '') || '0';
const result = Number(normalized);
return Number.isSafeInteger(result) && result >= 0 ? result : null;
const intPart = match[1];
const fraction = match[2] ?? '';
if (fraction.length > 7) return null;
const fracPart = fraction.padEnd(7, '0');
const combined = `${intPart}${fracPart}`;
const normalized = combined.replace(/^0+/, '') || '0';
const result = Number(normalized);
return Number.isSafeInteger(result) && result >= 0 ? result : null;
🤖 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 `@frontend/lib/sort.ts` around lines 15 - 21, Update the price parsing logic
around match[2] and the fixed-point conversion so fractional parts longer than
seven digits return null instead of being truncated by slice(0, 7). Preserve
zero-padding for fractions with seven or fewer digits and keep the existing
safe-integer validation.

}

/**
* Compare two price strings as fixed-point integers.
* Unparseable prices sort last; never returns NaN.
*/
function comparePrice(a: string, b: string): number {
const pa = parsePriceMicroUsdc(a);
const pb = parsePriceMicroUsdc(b);

if (pa !== null && pb !== null) {
if (pa < pb) return -1;
if (pa > pb) return 1;
return 0;
}
// Unparseable sorts after parseable
if (pa !== null) return -1;
if (pb !== null) return 1;
return 0; // both unparseable — preserve original order
}

/**
* Sort services by the given option.
*
Expand All @@ -16,7 +56,7 @@ export function sortServices(
return b.reputation - a.reputation;
}
if (sort === 'price') {
return parseFloat(a.price_usdc) - parseFloat(b.price_usdc);
return comparePrice(a.price_usdc, b.price_usdc);
}
// 'newest' - highest registered_at first
return b.registered_at - a.registered_at;
Expand Down Expand Up @@ -65,7 +105,7 @@ export function sortServicesWithTieBreaker(
if (sort === 'reputation') {
result = b.reputation - a.reputation;
} else if (sort === 'price') {
result = parseFloat(a.price_usdc) - parseFloat(b.price_usdc);
result = comparePrice(a.price_usdc, b.price_usdc);
} else {
result = b.registered_at - a.registered_at;
}
Expand Down Expand Up @@ -103,4 +143,4 @@ export function sortAgentsWithTieBreaker(
}
return result;
});
}
}
Loading