Skip to content

Commit 55125ea

Browse files
vvillait88claude
andauthored
feat: add usd_to_atomic helper (#23)
## Summary - Convert a USD amount to atomic units for a token with `decimals` places, exported from `agentscore_commerce.payment.usd_to_atomic`. - Decimal-based with `ROUND_HALF_UP` so values at exactly half a base unit round away from zero. - Accepts `str`, `float`, `int`, and `Decimal`. Whitespace-padded strings are trimmed. - Rejects negative, NaN, infinite, and unparseable inputs. ## Tests - 22-fixture corpus with hardcoded atomic values locked as the cross-language contract with `@agent-score/commerce`'s `usdToAtomic`. - Parametrized via `pytest.mark.parametrize` so multiple drifts surface independently. ## Test plan - [x] `uv run pytest tests/test_amounts.py` — 38 tests pass - [x] `uv run pytest` — full suite 929 pass / 3 skip, coverage 95.04% - [x] `uv run ruff check`, `uv run ruff format --check`, `uv run ty check` — green 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
1 parent 7a2e4ce commit 55125ea

3 files changed

Lines changed: 206 additions & 0 deletions

File tree

agentscore_commerce/payment/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
"""Payment helpers — networks/usdc/rails registries, paymentauth.org directive builders, dispatch, headers."""
22

3+
from agentscore_commerce.payment.amounts import usd_to_atomic
34
from agentscore_commerce.payment.directive import (
45
BuildPaymentDirectiveInput,
56
PaymentDirectiveInput,
@@ -137,6 +138,7 @@
137138
"register_x402_schemes_v1_v2",
138139
"settle_result_to_json_bytes",
139140
"settlement_override_header",
141+
"usd_to_atomic",
140142
"validate_x402_network_config",
141143
"verify_x402_request",
142144
"www_authenticate_header",
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
"""USD ↔ atomic-unit conversion for token amounts.
2+
3+
`usd_to_atomic(usd, decimals=6)` returns the integer atomic value of a USD
4+
amount for a token with `decimals` places of precision (USDC is 6). Uses
5+
``Decimal`` + ``ROUND_HALF_UP`` so a USD value at exactly half a base unit
6+
rounds away from zero, matching the cross-language Node sibling.
7+
8+
Rejects negative, NaN, and infinite inputs. Scientific-notation strings
9+
(``"1e6"``) are accepted on the Python side via ``Decimal``; the Node sibling
10+
rejects them and requires fixed notation, so cross-language byte-parity tests
11+
fix on fixed-notation fixtures.
12+
"""
13+
14+
from __future__ import annotations
15+
16+
from decimal import ROUND_HALF_UP, Decimal, InvalidOperation
17+
18+
19+
def usd_to_atomic(usd: str | float | int | Decimal, *, decimals: int) -> int:
20+
"""Convert a USD amount to atomic units for a token with ``decimals`` places.
21+
22+
Args:
23+
usd: USD amount. Strings (``"1.23"``), ``float`` (``1.23``), ``int``,
24+
and ``Decimal`` instances are accepted. The value is converted via
25+
``str()`` before parsing with ``Decimal``.
26+
decimals: Number of decimal places in the atomic unit (6 for USDC,
27+
18 for ETH, etc.). Must be a non-negative ``int``.
28+
29+
Returns:
30+
Integer atomic units. ``1.23`` with ``decimals=6`` returns ``1_230_000``.
31+
32+
Raises:
33+
ValueError: if ``usd`` is negative, NaN, infinite, or unparseable, or
34+
if ``decimals`` is not a non-negative ``int``.
35+
"""
36+
if not isinstance(decimals, int) or isinstance(decimals, bool) or decimals < 0:
37+
msg = f"decimals must be a non-negative int, got {decimals!r}"
38+
raise ValueError(msg)
39+
40+
# Strip whitespace on string input so Python matches Node's `.trim()` behavior
41+
# (Decimal itself rejects whitespace-padded strings with InvalidOperation).
42+
raw = usd.strip() if isinstance(usd, str) else usd
43+
try:
44+
amount = Decimal(str(raw))
45+
except (InvalidOperation, ValueError) as exc:
46+
msg = f"invalid usd value: {usd!r}"
47+
raise ValueError(msg) from exc
48+
49+
if not amount.is_finite():
50+
msg = f"usd must be finite, got {usd!r}"
51+
raise ValueError(msg)
52+
if amount < 0:
53+
msg = f"usd must be non-negative, got {amount}"
54+
raise ValueError(msg)
55+
56+
scaled = (amount * (Decimal(10) ** decimals)).to_integral_value(rounding=ROUND_HALF_UP)
57+
return int(scaled)

tests/test_amounts.py

Lines changed: 147 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,147 @@
1+
"""Tests for ``agentscore_commerce.payment.amounts.usd_to_atomic``.
2+
3+
The fixture corpus below is locked as the cross-language contract with the
4+
Node sibling at ``node-commerce/tests/payment/amounts.test.ts``. Both files
5+
reference identical fixed-notation inputs + decimals + expected atomic values.
6+
A drift in either language (rounding mode, encoding, edge-case handling) fails
7+
that language's test against the locked value.
8+
"""
9+
10+
from __future__ import annotations
11+
12+
from decimal import Decimal
13+
14+
import pytest
15+
16+
from agentscore_commerce.payment import usd_to_atomic
17+
18+
# Cross-language fixtures: (input_string, decimals, expected_atomic).
19+
# Inputs are fixed-notation strings so Python's Decimal and the Node sibling's
20+
# regex-based parser produce identical results.
21+
_FIXTURES = [
22+
# Plain whole + simple decimals
23+
("0", 6, 0),
24+
("1", 6, 1_000_000),
25+
("1.0", 6, 1_000_000),
26+
("1.00", 6, 1_000_000),
27+
("0.5", 6, 500_000),
28+
("10.00", 6, 10_000_000),
29+
("270.00", 6, 270_000_000),
30+
# Exact decimal precision
31+
("1.234567", 6, 1_234_567),
32+
# Round-half-up at the boundary (USDC tail of 5)
33+
("1.2345675", 6, 1_234_568),
34+
("1.2345674", 6, 1_234_567),
35+
("1.2345679", 6, 1_234_568),
36+
# Sub-precision rounding
37+
("0.0000005", 6, 1),
38+
("0.0000004", 6, 0),
39+
# Different decimals tail
40+
("1.23", 2, 123),
41+
("1.5", 0, 2),
42+
("1.4", 0, 1),
43+
("0.5", 0, 1),
44+
("0.4999999999", 0, 0),
45+
("0.5000000001", 0, 1),
46+
# Leading-zero and trailing-dot forms
47+
(".5", 6, 500_000),
48+
("5.", 6, 5_000_000),
49+
("001", 6, 1_000_000),
50+
]
51+
52+
53+
@pytest.mark.parametrize(
54+
("usd", "decimals", "expected"),
55+
_FIXTURES,
56+
ids=[f"{u!r}@{d}" for u, d, _ in _FIXTURES],
57+
)
58+
def test_locked_cross_language_fixture(usd: str, decimals: int, expected: int) -> None:
59+
"""Each fixture input maps to the locked cross-language atomic value."""
60+
assert usd_to_atomic(usd, decimals=decimals) == expected
61+
62+
63+
def test_accepts_float_input() -> None:
64+
"""Float input is converted via ``str()`` then parsed by Decimal."""
65+
assert usd_to_atomic(1.23, decimals=6) == 1_230_000
66+
67+
68+
def test_accepts_decimal_input() -> None:
69+
"""``Decimal`` input is passed through (matches the float path's precision)."""
70+
assert usd_to_atomic(Decimal("1.234567"), decimals=6) == 1_234_567
71+
72+
73+
def test_accepts_int_input() -> None:
74+
"""Plain ``int`` is treated as a whole-USD amount."""
75+
assert usd_to_atomic(5, decimals=6) == 5_000_000
76+
77+
78+
def test_zero_input_returns_zero() -> None:
79+
assert usd_to_atomic("0", decimals=6) == 0
80+
assert usd_to_atomic(0, decimals=6) == 0
81+
assert usd_to_atomic(0.0, decimals=6) == 0
82+
83+
84+
def test_decimals_zero_returns_whole_dollars() -> None:
85+
"""``decimals=0`` returns the (rounded) whole-USD value."""
86+
assert usd_to_atomic("123.4", decimals=0) == 123
87+
assert usd_to_atomic("123.5", decimals=0) == 124
88+
89+
90+
def test_negative_string_rejected() -> None:
91+
with pytest.raises(ValueError, match="non-negative"):
92+
usd_to_atomic("-1.00", decimals=6)
93+
94+
95+
def test_negative_float_rejected() -> None:
96+
with pytest.raises(ValueError, match="non-negative"):
97+
usd_to_atomic(-1.0, decimals=6)
98+
99+
100+
def test_nan_rejected() -> None:
101+
with pytest.raises(ValueError, match="finite"):
102+
usd_to_atomic(float("nan"), decimals=6)
103+
104+
105+
def test_positive_infinity_rejected() -> None:
106+
with pytest.raises(ValueError, match="finite"):
107+
usd_to_atomic(float("inf"), decimals=6)
108+
109+
110+
def test_negative_infinity_rejected() -> None:
111+
# Negative-infinity fails the finite check before the non-negative check; either error is OK.
112+
with pytest.raises(ValueError):
113+
usd_to_atomic(float("-inf"), decimals=6)
114+
115+
116+
def test_empty_string_rejected() -> None:
117+
with pytest.raises(ValueError, match="invalid usd value"):
118+
usd_to_atomic("", decimals=6)
119+
120+
121+
def test_garbage_string_rejected() -> None:
122+
with pytest.raises(ValueError, match="invalid usd value"):
123+
usd_to_atomic("abc", decimals=6)
124+
with pytest.raises(ValueError, match="invalid usd value"):
125+
usd_to_atomic("1.2.3", decimals=6)
126+
127+
128+
def test_whitespace_padded_string_accepted() -> None:
129+
"""String input is trimmed so a leading/trailing space matches the Node sibling."""
130+
assert usd_to_atomic(" 1.00 ", decimals=6) == 1_000_000
131+
assert usd_to_atomic("\t0.50\n", decimals=6) == 500_000
132+
133+
134+
def test_negative_decimals_rejected() -> None:
135+
with pytest.raises(ValueError, match="non-negative int"):
136+
usd_to_atomic("1.00", decimals=-1)
137+
138+
139+
def test_non_int_decimals_rejected() -> None:
140+
with pytest.raises(ValueError, match="non-negative int"):
141+
usd_to_atomic("1.00", decimals=6.0) # type: ignore[arg-type]
142+
143+
144+
def test_bool_decimals_rejected() -> None:
145+
"""``bool`` is a subclass of ``int`` in Python; reject explicitly to avoid surprise."""
146+
with pytest.raises(ValueError, match="non-negative int"):
147+
usd_to_atomic("1.00", decimals=True) # type: ignore[arg-type]

0 commit comments

Comments
 (0)