stablecoin-games-renpy 0.1.4 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. package/package.json +1 -1
  2. package/plugin/game/python-packages/scfg_core/__init__.py +1 -1
  3. package/plugin/game/python-packages/scfg_core/amounts.py +57 -4
  4. package/plugin/game/python-packages/scfg_core/backends/base.py +3 -2
  5. package/plugin/game/python-packages/scfg_core/backends/evm.py +2 -2
  6. package/plugin/game/python-packages/scfg_core/backends/solana.py +15 -12
  7. package/plugin/game/python-packages/scfg_core/checkout.py +1 -0
  8. package/plugin/game/python-packages/scfg_core/coio.py +4 -3
  9. package/plugin/game/python-packages/scfg_core/config.py +86 -58
  10. package/plugin/game/python-packages/scfg_core/engine.py +15 -8
  11. package/plugin/game/python-packages/scfg_core/errors.py +19 -2
  12. package/plugin/game/python-packages/scfg_core/evm.py +10 -5
  13. package/plugin/game/python-packages/scfg_core/ints.py +50 -0
  14. package/plugin/game/python-packages/scfg_core/local_server.py +10 -4
  15. package/plugin/game/python-packages/scfg_core/overlay.py +13 -2
  16. package/plugin/game/python-packages/scfg_core/payments.py +10 -7
  17. package/plugin/game/python-packages/scfg_core/receipts.py +8 -8
  18. package/plugin/game/python-packages/scfg_core/restore.py +26 -5
  19. package/plugin/game/python-packages/scfg_core/reverify.py +72 -23
  20. package/plugin/game/python-packages/scfg_core/rpc.py +8 -6
  21. package/plugin/game/python-packages/scfg_core/sessions.py +2 -2
  22. package/plugin/game/python-packages/scfg_core/solana/base58.py +18 -0
  23. package/plugin/game/python-packages/scfg_core/solana/rpc.py +11 -8
  24. package/plugin/game/python-packages/scfg_core/watcher.py +2 -2
  25. package/plugin/game/scfg/scfg_api.rpy +38 -7
  26. package/plugin/game/scfg/web/app.js +35 -3
  27. package/plugin/game/scfg/web/bridge.js +70 -10
  28. package/plugin/game/scfg/web/evm.js +52 -14
  29. package/plugin/game/scfg/web/solana.js +60 -19
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "stablecoin-games-renpy",
3
- "version": "0.1.4",
3
+ "version": "0.2.0",
4
4
  "description": "Stablecoin for Games (SCFG): USDC/USDT tips and unlocks for Ren'Py games, paid straight to your wallet. No server, no tokens, no NFTs. Installs the plugin into your project.",
5
5
  "keywords": [
6
6
  "stablecoin-for-games",
@@ -4,4 +4,4 @@ Nothing in this package may import ``renpy``. Ren'Py-specific glue lives in
4
4
  ``game/scfg/*.rpy``. Code must remain compatible with Python 3.9.
5
5
  """
6
6
 
7
- __version__ = "0.1.4"
7
+ __version__ = "0.2.0"
@@ -14,13 +14,46 @@ from decimal import Decimal, InvalidOperation
14
14
  TOKEN_DECIMALS = 6
15
15
  MAX_AMOUNT = Decimal("1000000")
16
16
  _CENT = Decimal("0.01")
17
+ # The magnitude bound of every amount the core reads: a nonzero amount's adjusted exponent (the
18
+ # power of ten of its leading digit, Decimal.adjusted()) must lie in [-40, 40]. That is far
19
+ # beyond any token amount (the smallest unit is 1E-6; a uint256 of base units read through
20
+ # Arc's 18-decimal emitter is floored to 6 decimals and never stored past 10**32 units), and it
21
+ # keeps near-Emax values (1E+999999) from overflowing or building million-digit integers.
22
+ AMOUNT_EXPONENT_LIMIT = 40
23
+ # The longest amount text the core parses (parse_amount, stored_amount): far beyond any amount
24
+ # (a stored one is at most about 40 characters), and it keeps digit parsing cheap in every core.
25
+ AMOUNT_TEXT_LIMIT = 100
26
+
27
+
28
+ def _in_range(d: Decimal) -> bool:
29
+ return d.is_finite() and (d.is_zero() or -AMOUNT_EXPONENT_LIMIT <= d.adjusted()
30
+ <= AMOUNT_EXPONENT_LIMIT)
31
+
32
+
33
+ def stored_amount(value) -> Decimal:
34
+ """An amount read back from storage (a receipt's amount, a session's price): Decimal(value)
35
+ when it is a finite number within the amount range (AMOUNT_EXPONENT_LIMIT) and, as text, at
36
+ most AMOUNT_TEXT_LIMIT characters, else a ValueError (a TypeError for a list or tuple, or a
37
+ value Decimal() does not take)."""
38
+ if isinstance(value, (list, tuple)): # Decimal() reads a (sign, digits, exponent) tuple
39
+ raise TypeError(f"a stored amount is a number, not a {type(value).__name__}")
40
+ if isinstance(value, str) and len(value) > AMOUNT_TEXT_LIMIT:
41
+ raise ValueError(f"amount text longer than {AMOUNT_TEXT_LIMIT} characters")
42
+ try:
43
+ d = Decimal(value)
44
+ except InvalidOperation:
45
+ raise ValueError(f"not a number: {value!r}") from None
46
+ if not _in_range(d):
47
+ raise ValueError(f"amount out of range: {value!r}")
48
+ return d
17
49
 
18
50
 
19
51
  def parse_amount(value) -> Decimal:
20
52
  """Validate a price/tip amount and return it quantized to cents.
21
53
 
22
54
  Accepts str, int or Decimal. Floats are refused: binary floating point and
23
- money do not mix.
55
+ money do not mix. A str is a plain decimal number: Decimal's digit-group underscores
56
+ ("1_000") are refused like any other malformed amount.
24
57
  """
25
58
  if isinstance(value, (bool, float)):
26
59
  raise TypeError("amounts must be str, int or Decimal (never float)")
@@ -29,6 +62,10 @@ def parse_amount(value) -> Decimal:
29
62
  elif isinstance(value, Decimal):
30
63
  d = value
31
64
  elif isinstance(value, str):
65
+ if len(value) > AMOUNT_TEXT_LIMIT:
66
+ raise ValueError(f"amount text longer than {AMOUNT_TEXT_LIMIT} characters")
67
+ if "_" in value:
68
+ raise ValueError(f"not a number: {value!r}")
32
69
  try:
33
70
  d = Decimal(value.strip())
34
71
  except InvalidOperation:
@@ -37,6 +74,8 @@ def parse_amount(value) -> Decimal:
37
74
  raise TypeError(f"unsupported amount type: {type(value).__name__}")
38
75
  if not d.is_finite():
39
76
  raise ValueError("amount must be finite")
77
+ if not _in_range(d):
78
+ raise ValueError("amount out of range")
40
79
  if d <= 0:
41
80
  raise ValueError("amount must be positive")
42
81
  if d > MAX_AMOUNT:
@@ -61,7 +100,11 @@ def encode(price, code: int, nonce: int) -> int:
61
100
 
62
101
 
63
102
  def decode(units: int) -> tuple[Decimal, int, int]:
64
- """Inverse of encode: base units -> (price, code, nonce)."""
103
+ """Inverse of encode: base units -> (price, code, nonce).
104
+
105
+ From 10**32 units the price needs more than Decimal's 28 digits and this raises
106
+ decimal.InvalidOperation; callers that read transfers off the chain skip such a value.
107
+ """
65
108
  if units < 0:
66
109
  raise ValueError("units must be >= 0")
67
110
  price = (Decimal(units // 10_000) / 100).quantize(_CENT)
@@ -69,11 +112,21 @@ def decode(units: int) -> tuple[Decimal, int, int]:
69
112
 
70
113
 
71
114
  def units_to_decimal(units: int) -> Decimal:
72
- return Decimal(units).scaleb(-TOKEN_DECIMALS)
115
+ """Base units -> token amount, exactly (4993742 -> 4.993742), however many digits: the
116
+ value is built from its digits instead of through Decimal's 28-digit arithmetic."""
117
+ sign, digits, exponent = Decimal(units).as_tuple()
118
+ return Decimal((sign, digits, exponent - TOKEN_DECIMALS))
73
119
 
74
120
 
75
121
  def decimal_to_units(amount: Decimal) -> int:
76
- q = Decimal(amount).scaleb(TOKEN_DECIMALS)
122
+ """Token amount -> base units, exactly (no rounding to Decimal's 28 digits). ValueError for
123
+ more than 6 decimals, or for an amount that is not finite or out of range
124
+ (AMOUNT_EXPONENT_LIMIT)."""
125
+ amount = Decimal(amount)
126
+ if not _in_range(amount):
127
+ raise ValueError(f"amount out of range: {amount}")
128
+ sign, digits, exponent = amount.as_tuple()
129
+ q = Decimal((sign, digits, exponent + TOKEN_DECIMALS))
77
130
  if q != q.to_integral_value():
78
131
  raise ValueError("more than 6 decimals")
79
132
  return int(q)
@@ -28,9 +28,10 @@ class Backend(Protocol):
28
28
  def reverify(self, receipt: dict, *, rpc, chain, wallets: Sequence[str]) -> str:
29
29
  """"keep" or "drop". Network trouble must answer "keep"."""
30
30
 
31
- def lookup(self, tx: str, *, config, chain, rpc, receipts: MutableMapping):
31
+ def lookup(self, tx: str, *, config, chain, rpc, receipts: MutableMapping, on_error=None):
32
32
  """Restore candidates for tx on this chain, or None if the chain doesn't know it.
33
- Raises restore.RestoreError("tx_reverted" | "tx_not_a_payment")."""
33
+ Raises restore.RestoreError("tx_reverted" | "tx_not_a_payment"). A transfer that
34
+ cannot be classified is skipped and reported to on_error (restore.classify_or_skip)."""
34
35
 
35
36
  def check_ready(self, *, rpc, chain, wallet: str) -> dict[str, bool]:
36
37
  """token name -> can the developer receive it on this chain."""
@@ -31,9 +31,9 @@ class EvmBackend:
31
31
  return (yield from reverify.check_evm_receipt(receipt, rpc=rpc, chain=chain,
32
32
  wallets=wallets))
33
33
 
34
- def lookup(self, tx, *, config, chain, rpc, receipts):
34
+ def lookup(self, tx, *, config, chain, rpc, receipts, on_error=None):
35
35
  return (yield from restore.lookup_evm(tx, config=config, chain=chain, rpc=rpc,
36
- receipts=receipts))
36
+ receipts=receipts, on_error=on_error))
37
37
 
38
38
  def check_ready(self, *, rpc, chain, wallet):
39
39
  return {name: True for name in chain.tokens}
@@ -10,9 +10,9 @@ from __future__ import annotations
10
10
 
11
11
  import base64
12
12
  import secrets
13
- from decimal import Decimal
14
13
 
15
- from ..amounts import decimal_to_units, units_to_decimal
14
+ from ..amounts import decimal_to_units, stored_amount, units_to_decimal
15
+ from ..ints import int_from
16
16
  from ..receipts import add_receipt, make_receipt, receipt_key
17
17
  from ..rpc import RpcClient, RpcError, RpcUnavailable
18
18
  from ..sessions import clear_hint, is_past_horizon, remove_session
@@ -60,7 +60,7 @@ def transfer_to(tx: dict, *, sig: str, mint: str, owner: str) -> Transfer | None
60
60
  rows = {}
61
61
  for b in meta.get(name) or []:
62
62
  if b.get("mint") == mint:
63
- rows[b["accountIndex"]] = (b.get("owner"), int(b["uiTokenAmount"]["amount"]))
63
+ rows[b["accountIndex"]] = (b.get("owner"), int_from(b["uiTokenAmount"]["amount"]))
64
64
  return rows
65
65
 
66
66
  pre, post = table("preTokenBalances"), table("postTokenBalances")
@@ -78,7 +78,7 @@ def transfer_to(tx: dict, *, sig: str, mint: str, owner: str) -> Transfer | None
78
78
  return None
79
79
  payer = min(drops, key=drops.get) if drops else _fee_payer(tx)
80
80
  return Transfer(token=mint, sender=payer, recipient=owner, value=gained, tx_hash=sig,
81
- log_index=index, block_number=int(tx["slot"]))
81
+ log_index=index, block_number=int_from(tx["slot"]))
82
82
 
83
83
 
84
84
  def _match_dict(t: Transfer) -> dict:
@@ -174,7 +174,7 @@ class SolanaBackend:
174
174
  out.status = "reorged"
175
175
  return out
176
176
  if status.get("confirmationStatus") != "finalized":
177
- out.confirmations = int(status.get("confirmations") or 0)
177
+ out.confirmations = int_from(status.get("confirmations") or 0)
178
178
  return out
179
179
  out.confirmations = FINAL_CONFIRMATIONS
180
180
  transfer = Transfer(mint, m["payer"], m["recipient"], m["value"], m["tx_hash"],
@@ -252,7 +252,7 @@ class SolanaBackend:
252
252
  page = yield from rpc.get_signatures_for_address(address, until=until, before=before,
253
253
  limit=SIG_PAGE)
254
254
  for n, info in enumerate(page):
255
- if info.get("slot") is not None and int(info["slot"]) < min_slot:
255
+ if info.get("slot") is not None and int_from(info["slot"]) < min_slot:
256
256
  found.extend(page[:n])
257
257
  return found, True
258
258
  found.extend(page)
@@ -303,7 +303,7 @@ class SolanaBackend:
303
303
  def reverify(self, receipt, *, rpc, chain, wallets):
304
304
  from ..reverify import FUTURE_TOLERANCE_BLOCKS
305
305
 
306
- slot = int(receipt["block"])
306
+ slot = int_from(receipt["block"])
307
307
  owner = receipt.get("recipient")
308
308
  if owner not in wallets:
309
309
  return "drop"
@@ -323,12 +323,12 @@ class SolanaBackend:
323
323
  except (KeyError, TypeError, ValueError, AttributeError):
324
324
  return "keep" # a payload this build can't read: can't judge the receipt
325
325
  genuine = (t is not None and t.block_number == slot
326
- and t.log_index == int(receipt["log_index"])
327
- and t.value == decimal_to_units(Decimal(receipt["amount"])))
326
+ and t.log_index == int_from(receipt["log_index"])
327
+ and t.value == decimal_to_units(stored_amount(receipt["amount"])))
328
328
  return "keep" if genuine else "drop"
329
329
 
330
- def lookup(self, tx, *, config, chain, rpc, receipts):
331
- from ..restore import RestoreCandidate, RestoreError, classify
330
+ def lookup(self, tx, *, config, chain, rpc, receipts, on_error=None):
331
+ from ..restore import RestoreCandidate, RestoreError, classify_or_skip
332
332
 
333
333
  found, _ = yield from rpc.get_transaction_any(tx)
334
334
  if found is None:
@@ -341,7 +341,10 @@ class SolanaBackend:
341
341
  t = transfer_to(found, sig=tx, mint=token.address, owner=owner)
342
342
  if t is None:
343
343
  continue
344
- kind, item, choices = classify(config, t.value)
344
+ classified = classify_or_skip(config, t.value, on_error)
345
+ if classified is None:
346
+ continue
347
+ kind, item, choices = classified
345
348
  out.append(RestoreCandidate(
346
349
  chain=chain.key, token=name, transfer=t, kind=kind, item=item,
347
350
  choices=choices,
@@ -263,6 +263,7 @@ class CheckoutController:
263
263
  def mark_sent(self) -> None:
264
264
  """The player says they sent the payment from the QR or manual page."""
265
265
  if self.step in ("qr", "manual"):
266
+ self.error = None
266
267
  self._go("waiting", 1)
267
268
 
268
269
  def open_browser(self) -> str | None:
@@ -18,9 +18,10 @@ from __future__ import annotations
18
18
 
19
19
  import functools
20
20
  import inspect
21
- import json
22
21
  from dataclasses import dataclass
23
22
 
23
+ from .ints import int_from, json_loads
24
+
24
25
 
25
26
  class TransportError(Exception):
26
27
  """Network or HTTP failure talking to one endpoint."""
@@ -104,9 +105,9 @@ def response_from_envelope(envelope: dict):
104
105
  TransportError."""
105
106
  if "error" in envelope:
106
107
  raise TransportError(str(envelope["error"]))
107
- status = int(envelope.get("status") or 0)
108
+ status = int_from(envelope.get("status") or 0)
108
109
  try:
109
- body = json.loads(envelope.get("body") or "")
110
+ body = json_loads(envelope.get("body") or "")
110
111
  except ValueError:
111
112
  body = _UNREADABLE
112
113
  if not 200 <= status < 300:
@@ -25,11 +25,12 @@ DEFAULT_METHODS = {
25
25
  "qr": {"enabled": True, "wallet_button": True, "chains": None},
26
26
  "manual": {"enabled": True, "allow_tx_paste": True},
27
27
  }
28
- _ITEM_ID = re.compile(r"^[a-z0-9_-]{1,64}$")
29
- _CHAIN_KEY = re.compile(r"^[a-z0-9_-]{1,32}$")
30
- _NATIVE_SYMBOL = re.compile(r"^[A-Za-z0-9]{1,11}$")
28
+ # Used with fullmatch: the whole string (`$` would also match before a trailing newline).
29
+ _ITEM_ID = re.compile(r"[a-z0-9_-]{1,64}")
30
+ _CHAIN_KEY = re.compile(r"[a-z0-9_-]{1,32}")
31
+ _NATIVE_SYMBOL = re.compile(r"[A-Za-z0-9]{1,11}")
31
32
  # Plain http is only accepted for a node on this computer (e.g. a local Anvil test chain).
32
- _LOCAL_HTTP = re.compile(r"^http://(127\.0\.0\.1|localhost)(:\d{1,5})?(/|$)")
33
+ _LOCAL_HTTP = re.compile(r"^http://(127\.0\.0\.1|localhost)(:\d{1,5})?(/|\Z)") # \Z: no "\n"
33
34
  FEE_HINTS = ("lowest", "low", "high")
34
35
 
35
36
  DEFAULT_ACCENT = "#0e7c74"
@@ -37,7 +38,7 @@ INK = "#17202e"
37
38
  # Raster formats only: an SVG served from the checkout page's origin could run script.
38
39
  LOGO_TYPES = {".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg",
39
40
  ".webp": "image/webp"}
40
- _HEX_COLOR = re.compile(r"^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$")
41
+ _HEX_COLOR = re.compile(r"#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})") # fullmatch
41
42
 
42
43
 
43
44
  @dataclass
@@ -87,17 +88,18 @@ def _address(value, what: str) -> str:
87
88
  try:
88
89
  return normalize_address(value)
89
90
  except ValueError as e:
90
- raise ConfigError(f"{what}: {e}") from None
91
+ raise ConfigError(f"{what}: {e}", code="address.invalid") from None
91
92
 
92
93
 
93
94
  def _solana_address(value, what: str) -> str:
94
95
  try:
95
96
  address = normalize_pubkey(value)
96
97
  except ValueError:
97
- raise ConfigError(f"{what}: not a Solana address: {value!r}") from None
98
+ raise ConfigError(f"{what}: not a Solana address: {value!r}",
99
+ code="solana_address.invalid") from None
98
100
  if not is_on_curve(b58decode(address)):
99
101
  raise ConfigError(f"{what}: {address} looks like a token account or program address; "
100
- "use your wallet address")
102
+ "use your wallet address", code="solana_address.not_on_curve")
101
103
  return address
102
104
 
103
105
 
@@ -111,16 +113,16 @@ def _any_wallet(value, what: str) -> tuple[str, str]:
111
113
  def _rpc_urls(value, what: str) -> tuple[str, ...]:
112
114
  urls = [value] if isinstance(value, str) else value
113
115
  if not isinstance(urls, (list, tuple)) or not urls:
114
- raise ConfigError(f"{what} must be a URL or a non-empty list of URLs")
116
+ raise ConfigError(f"{what} must be a URL or a non-empty list of URLs", code="rpc.bad_list")
115
117
  for u in urls:
116
118
  if not isinstance(u, str) or not (u.startswith("https://") or _LOCAL_HTTP.match(u)):
117
- raise ConfigError(f"rpc url must start with https://: {u!r}")
119
+ raise ConfigError(f"rpc url must start with https://: {u!r}", code="rpc.not_https")
118
120
  return tuple(urls)
119
121
 
120
122
 
121
123
  def _positive_int(value, what: str, minimum: int = 1) -> int:
122
124
  if isinstance(value, bool) or not isinstance(value, int) or value < minimum:
123
- raise ConfigError(f"{what} must be an int >= {minimum}")
125
+ raise ConfigError(f"{what} must be an int >= {minimum}", code="int.below_minimum")
124
126
  return value
125
127
 
126
128
 
@@ -134,33 +136,41 @@ def build_chain(key, *, name, chain_id, rpc, tokens, confirmations, explorer_tx,
134
136
  Ethereum JSON-RPC. The tokens must have 6 decimals, because the item code and
135
137
  nonce live in the last four decimals of the amount.
136
138
  """
137
- if not isinstance(key, str) or not _CHAIN_KEY.match(key):
138
- raise ConfigError(f"invalid chain key {key!r} (use a-z, 0-9, _ and -)")
139
+ if not isinstance(key, str) or not _CHAIN_KEY.fullmatch(key):
140
+ raise ConfigError(f"invalid chain key {key!r} (use a-z, 0-9, _ and -)",
141
+ code="chain.invalid_key")
139
142
  what = f"chain {key!r}"
140
143
  if not isinstance(name, str) or not name.strip() or len(name) > 32:
141
- raise ConfigError(f"{what}: name must be a non-empty string of at most 32 characters")
144
+ raise ConfigError(f"{what}: name must be a non-empty string of at most 32 characters",
145
+ code="chain.invalid_name")
142
146
  chain_id = _positive_int(chain_id, f"{what}: chain_id")
143
147
  rpc = _rpc_urls(rpc, f"{what}: rpc")
144
148
  if not isinstance(tokens, dict) or not tokens:
145
- raise ConfigError(f"{what}: tokens must be a dict like {{'USDC': '0x...'}}")
149
+ raise ConfigError(f"{what}: tokens must be a dict like {{'USDC': '0x...'}}",
150
+ code="chain.tokens_invalid")
146
151
  parsed: dict[str, Token] = {}
147
152
  for symbol, address in tokens.items():
148
153
  if symbol not in TOKENS:
149
- raise ConfigError(f"{what}: unknown token {symbol!r} (supported: USDC, USDT)")
154
+ raise ConfigError(f"{what}: unknown token {symbol!r} (supported: USDC, USDT)",
155
+ code="chain.unknown_token")
150
156
  parsed[symbol] = Token(_address(address, f"{what}: {symbol} address"))
151
157
  confirmations = _positive_int(confirmations, f"{what}: confirmations")
152
158
  if (not isinstance(explorer_tx, str) or not explorer_tx.startswith("https://")
153
159
  or explorer_tx.count("{}") != 1):
154
160
  raise ConfigError(f"{what}: explorer_tx must be an https:// URL with {{}} where the "
155
- f"transaction hash goes, like 'https://snowtrace.io/tx/{{}}'")
161
+ f"transaction hash goes, like 'https://snowtrace.io/tx/{{}}'",
162
+ code="chain.bad_explorer_tx")
156
163
  try:
157
164
  explorer_tx.format("0x")
158
165
  except (IndexError, KeyError, ValueError):
159
- raise ConfigError(f"{what}: explorer_tx may contain no braces besides {{}}") from None
160
- if not isinstance(native_symbol, str) or not _NATIVE_SYMBOL.match(native_symbol):
161
- raise ConfigError(f"{what}: native_symbol must be letters/digits, like 'AVAX'")
166
+ raise ConfigError(f"{what}: explorer_tx may contain no braces besides {{}}",
167
+ code="chain.bad_explorer_tx_braces") from None
168
+ if not isinstance(native_symbol, str) or not _NATIVE_SYMBOL.fullmatch(native_symbol):
169
+ raise ConfigError(f"{what}: native_symbol must be letters/digits, like 'AVAX'",
170
+ code="chain.bad_native_symbol")
162
171
  if fee_hint not in FEE_HINTS:
163
- raise ConfigError(f"{what}: fee_hint must be one of {', '.join(FEE_HINTS)}")
172
+ raise ConfigError(f"{what}: fee_hint must be one of {', '.join(FEE_HINTS)}",
173
+ code="chain.bad_fee_hint")
164
174
  max_log_range = _positive_int(max_log_range, f"{what}: max_log_range", MIN_LOG_RANGE)
165
175
  return Chain(key=key, chain_id=chain_id, name=name.strip(), rpc=rpc,
166
176
  confirmations=confirmations, max_log_range=max_log_range,
@@ -175,19 +185,21 @@ def _custom_chains(custom, testnet: bool) -> tuple[dict[str, Chain], set[str]]:
175
185
  other: set[str] = set()
176
186
  for chain in custom or ():
177
187
  if not isinstance(chain, Chain):
178
- raise ConfigError("custom chains must be created with scfg.add_chain()")
188
+ raise ConfigError("custom chains must be created with scfg.add_chain()",
189
+ code="chain.not_from_add_chain")
179
190
  if chain.key in get_chains(False) or chain.key in get_chains(True):
180
191
  raise ConfigError(f"chain {chain.key!r} is built in; use rpc_urls/confirmations "
181
- "to change it, or pick another key")
192
+ "to change it, or pick another key", code="chain.is_builtin")
182
193
  if chain.testnet != testnet:
183
194
  other.add(chain.key)
184
195
  continue
185
196
  if chain.key in mine:
186
- raise ConfigError(f"chain {chain.key!r} added twice")
197
+ raise ConfigError(f"chain {chain.key!r} added twice", code="chain.duplicate")
187
198
  for c in list(builtin.values()) + list(mine.values()):
188
199
  if c.chain_id == chain.chain_id:
189
200
  raise ConfigError(f"chain {chain.key!r} has the same chain_id "
190
- f"({chain.chain_id}) as {c.key!r}")
201
+ f"({chain.chain_id}) as {c.key!r}",
202
+ code="chain.duplicate_chain_id")
191
203
  mine[chain.key] = chain
192
204
  return mine, other - set(mine)
193
205
 
@@ -198,7 +210,7 @@ def _logo(value) -> str | None:
198
210
  if (not isinstance(value, str) or not value or "\\" in value or ":" in value
199
211
  or value.startswith("/") or ".." in value.split("/")):
200
212
  raise ConfigError("logo must be a path inside the game folder, "
201
- f"like 'images/logo.png': {value!r}")
213
+ f"like 'images/logo.png': {value!r}", code="logo.bad_path")
202
214
  logo_content_type(value)
203
215
  return value
204
216
 
@@ -206,15 +218,17 @@ def _logo(value) -> str | None:
206
218
  def logo_content_type(path: str) -> str:
207
219
  ext = path[path.rfind("."):].lower() if "." in path else ""
208
220
  if ext not in LOGO_TYPES:
209
- raise ConfigError(f"logo must be a .png, .jpg or .webp image: {path!r}")
221
+ raise ConfigError(f"logo must be a .png, .jpg or .webp image: {path!r}",
222
+ code="logo.bad_type")
210
223
  return LOGO_TYPES[ext]
211
224
 
212
225
 
213
226
  def _accent(value) -> str:
214
227
  if value is None:
215
228
  return DEFAULT_ACCENT
216
- if not isinstance(value, str) or not _HEX_COLOR.match(value):
217
- raise ConfigError(f"accent must be a color like '#0e7c74': {value!r}")
229
+ if not isinstance(value, str) or not _HEX_COLOR.fullmatch(value):
230
+ raise ConfigError(f"accent must be a color like '#0e7c74': {value!r}",
231
+ code="accent.invalid")
218
232
  digits = value[1:]
219
233
  if len(digits) == 3:
220
234
  digits = "".join(c * 2 for c in digits)
@@ -241,24 +255,29 @@ def _merge_methods(methods: dict | None, chains: tuple[str, ...]) -> dict[str, d
241
255
  merged = copy.deepcopy(DEFAULT_METHODS)
242
256
  for name, opts in (methods or {}).items():
243
257
  if name not in merged:
244
- raise ConfigError(f"unknown method: {name!r}")
258
+ raise ConfigError(f"unknown method: {name!r}", code="methods.unknown_method")
245
259
  for key, value in opts.items():
246
260
  if key not in merged[name]:
247
- raise ConfigError(f"unknown option {key!r} for method {name!r}")
261
+ raise ConfigError(f"unknown option {key!r} for method {name!r}",
262
+ code="methods.unknown_option")
248
263
  merged[name][key] = value
249
264
  for name, opts in merged.items():
250
265
  if not isinstance(opts["enabled"], bool):
251
- raise ConfigError(f"methods.{name}.enabled must be True or False")
266
+ raise ConfigError(f"methods.{name}.enabled must be True or False",
267
+ code="methods.enabled_not_bool")
252
268
  timeout = merged["browser"]["timeout_min"]
253
269
  if isinstance(timeout, bool) or not isinstance(timeout, (int, float)) or not timeout > 0:
254
- raise ConfigError("methods.browser.timeout_min must be a number of minutes above 0")
270
+ raise ConfigError("methods.browser.timeout_min must be a number of minutes above 0",
271
+ code="methods.bad_timeout")
255
272
  if not any(o["enabled"] for o in merged.values()):
256
- raise ConfigError("at least one payment method must be enabled")
273
+ raise ConfigError("at least one payment method must be enabled",
274
+ code="methods.none_enabled")
257
275
  qr_chains = merged["qr"]["chains"]
258
276
  if qr_chains is not None:
259
277
  for c in qr_chains:
260
278
  if c not in chains:
261
- raise ConfigError(f"methods.qr.chains contains disabled chain {c!r}")
279
+ raise ConfigError(f"methods.qr.chains contains disabled chain {c!r}",
280
+ code="methods.qr_disabled_chain")
262
281
  return merged
263
282
 
264
283
 
@@ -270,7 +289,8 @@ def build_config(wallet=None, *, testnet=False, chains=None, tokens=None, method
270
289
  custom, other_network = _custom_chains(custom_chains, testnet)
271
290
  registry = {**get_chains(testnet), **custom}
272
291
  if wallet is None and solana_wallet is None:
273
- raise ConfigError("configure() needs wallet= (an EVM 0x address) and/or solana_wallet=")
292
+ raise ConfigError("configure() needs wallet= (an EVM 0x address) and/or solana_wallet=",
293
+ code="wallet.missing")
274
294
  wallet = _address(wallet, "wallet") if wallet is not None else None
275
295
  sol = _solana_address(solana_wallet, "solana_wallet") if solana_wallet is not None else None
276
296
  prev: list[str] = []
@@ -285,46 +305,50 @@ def build_config(wallet=None, *, testnet=False, chains=None, tokens=None, method
285
305
  chains = ((DISPLAY_ORDER + tuple(custom) if wallet else ()) + (solana_keys if sol else ())
286
306
  if chains is None else tuple(chains))
287
307
  if not chains:
288
- raise ConfigError("chains must not be empty")
308
+ raise ConfigError("chains must not be empty", code="chains.empty")
289
309
  for c in chains:
290
310
  if c in other_network:
291
311
  net = "mainnet" if testnet else "testnet"
292
312
  raise ConfigError(f"chain {c!r} was only added for {net}; add it again with "
293
- f"testnet={testnet} to use it here")
313
+ f"testnet={testnet} to use it here", code="chains.wrong_network")
294
314
  if c not in registry:
295
- raise ConfigError(f"unknown chain: {c!r}")
315
+ raise ConfigError(f"unknown chain: {c!r}", code="chains.unknown")
296
316
  family = registry[c].family
297
317
  if family == "solana" and sol is None:
298
- raise ConfigError(f"chain {c!r} needs solana_wallet=")
318
+ raise ConfigError(f"chain {c!r} needs solana_wallet=", code="chain.needs_solana_wallet")
299
319
  if family == "evm" and wallet is None:
300
- raise ConfigError(f"chain {c!r} needs wallet= (an EVM 0x address)")
320
+ raise ConfigError(f"chain {c!r} needs wallet= (an EVM 0x address)",
321
+ code="chain.needs_evm_wallet")
301
322
  if len(set(chains)) != len(chains):
302
- raise ConfigError("duplicate chain in chains")
323
+ raise ConfigError("duplicate chain in chains", code="chains.duplicate")
303
324
 
304
325
  tokens = tuple(TOKENS if tokens is None else tokens)
305
326
  if not tokens:
306
- raise ConfigError("tokens must not be empty")
327
+ raise ConfigError("tokens must not be empty", code="tokens.empty")
307
328
  for t in tokens:
308
329
  if t not in TOKENS:
309
- raise ConfigError(f"unknown token: {t!r}")
330
+ raise ConfigError(f"unknown token: {t!r}", code="tokens.unknown")
310
331
 
311
332
  merged = _merge_methods(methods, chains)
312
333
 
313
334
  urls: dict[str, tuple[str, ...]] = {}
314
335
  for c, lst in (rpc_urls or {}).items():
315
336
  if c not in chains:
316
- raise ConfigError(f"rpc_urls for unknown or disabled chain {c!r}")
337
+ raise ConfigError(f"rpc_urls for unknown or disabled chain {c!r}",
338
+ code="rpc_urls.unknown_chain")
317
339
  urls[c] = _rpc_urls(lst, f"rpc_urls[{c!r}]")
318
340
 
319
341
  confs: dict[str, int] = {}
320
342
  for c, n in (confirmations or {}).items():
321
343
  if c not in chains:
322
- raise ConfigError(f"confirmations for unknown or disabled chain {c!r}")
344
+ raise ConfigError(f"confirmations for unknown or disabled chain {c!r}",
345
+ code="confirmations.unknown_chain")
323
346
  if registry[c].family == "solana":
324
347
  raise ConfigError("Solana payments wait for finalization; "
325
- f"confirmations can't be set for {c!r}")
348
+ f"confirmations can't be set for {c!r}",
349
+ code="confirmations.solana_fixed")
326
350
  if isinstance(n, bool) or not isinstance(n, int) or n < 1:
327
- raise ConfigError("confirmations must be an int >= 1")
351
+ raise ConfigError("confirmations must be an int >= 1", code="confirmations.invalid")
328
352
  confs[c] = n
329
353
 
330
354
  cfg = Config(wallet=wallet, testnet=testnet, chains=chains, tokens=tokens,
@@ -332,7 +356,8 @@ def build_config(wallet=None, *, testnet=False, chains=None, tokens=None, method
332
356
  solana_wallet=sol, previous_solana_wallets=tuple(prev_sol),
333
357
  logo=_logo(logo), accent=_accent(accent), custom_chains=custom)
334
358
  if not enabled_chains(cfg):
335
- raise ConfigError("no enabled chain supports any enabled token")
359
+ raise ConfigError("no enabled chain supports any enabled token",
360
+ code="config.no_usable_token")
336
361
  return cfg
337
362
 
338
363
 
@@ -360,25 +385,28 @@ def chains_for_token(config: Config, token: str) -> list[str]:
360
385
 
361
386
 
362
387
  def add_item(config: Config, item_id, *, code, price, token, title, min_price=None) -> Item:
363
- if not isinstance(item_id, str) or not _ITEM_ID.match(item_id):
364
- raise ConfigError(f"invalid item id {item_id!r} (use a-z, 0-9, _ and -)")
388
+ if not isinstance(item_id, str) or not _ITEM_ID.fullmatch(item_id):
389
+ raise ConfigError(f"invalid item id {item_id!r} (use a-z, 0-9, _ and -)",
390
+ code="item.invalid_id")
365
391
  if item_id in config.items:
366
- raise ConfigError(f"duplicate item id {item_id!r}")
392
+ raise ConfigError(f"duplicate item id {item_id!r}", code="item.duplicate_id")
367
393
  if isinstance(code, bool) or not isinstance(code, int) or not 1 <= code <= 99:
368
- raise ConfigError("item code must be an int in 1..99")
394
+ raise ConfigError("item code must be an int in 1..99", code="item.invalid_code")
369
395
  if config.item_by_code(code) is not None:
370
- raise ConfigError(f"duplicate item code {code}")
396
+ raise ConfigError(f"duplicate item code {code}", code="item.duplicate_code")
371
397
  try:
372
398
  p = parse_amount(price)
373
399
  mp = p if min_price is None else parse_amount(min_price)
374
400
  except (TypeError, ValueError) as e:
375
- raise ConfigError(f"item {item_id!r}: {e}") from None
401
+ raise ConfigError(f"item {item_id!r}: {e}", code="item.invalid_price") from None
376
402
  if mp > p:
377
- raise ConfigError("min_price must not exceed price")
403
+ raise ConfigError("min_price must not exceed price", code="item.min_price_above_price")
378
404
  if token not in config.tokens or not chains_for_token(config, token):
379
- raise ConfigError(f"token {token!r} is not available on any enabled chain")
405
+ raise ConfigError(f"token {token!r} is not available on any enabled chain",
406
+ code="token.unavailable")
380
407
  if not isinstance(title, str) or not title.strip() or len(title) > 80:
381
- raise ConfigError("title must be a non-empty string of at most 80 characters")
408
+ raise ConfigError("title must be a non-empty string of at most 80 characters",
409
+ code="item.invalid_title")
382
410
  item = Item(item_id=item_id, code=code, price=p, token=token, title=title, min_price=mp)
383
411
  config.items[item_id] = item
384
412
  return item