walletcap 0.2.0__py3-none-any.whl
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.
- walletcap/__init__.py +74 -0
- walletcap/__main__.py +284 -0
- walletcap/budget.py +537 -0
- walletcap/errors.py +52 -0
- walletcap/ledger.py +762 -0
- walletcap/money.py +236 -0
- walletcap/py.typed +0 -0
- walletcap-0.2.0.dist-info/METADATA +312 -0
- walletcap-0.2.0.dist-info/RECORD +13 -0
- walletcap-0.2.0.dist-info/WHEEL +4 -0
- walletcap-0.2.0.dist-info/entry_points.txt +2 -0
- walletcap-0.2.0.dist-info/licenses/LICENSE +201 -0
- walletcap-0.2.0.dist-info/licenses/NOTICE +11 -0
walletcap/budget.py
ADDED
|
@@ -0,0 +1,537 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
"""One spend budget per wallet, counted across every process, key, permission and rail.
|
|
3
|
+
|
|
4
|
+
Agent payment kits count "spent so far" per process, per key, per permission or
|
|
5
|
+
per period, so a restart, a second replica, one more key or the next period
|
|
6
|
+
starts the count again. This budget is counted per wallet, in a file every
|
|
7
|
+
process shares, over a rolling window. Changing a limit never resets what has
|
|
8
|
+
been spent, a restart can lower a limit but never raise one, and if the count
|
|
9
|
+
cannot be read, nothing is paid::
|
|
10
|
+
|
|
11
|
+
from walletcap import open_budget
|
|
12
|
+
|
|
13
|
+
budget = open_budget(agent_address, per_payment="$50", per_day="$150")
|
|
14
|
+
with budget.pay("$12.50", to=payee) as payment:
|
|
15
|
+
payment.tx = send_usdc(payee, "12.50")
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import json
|
|
21
|
+
import shlex
|
|
22
|
+
import time
|
|
23
|
+
import warnings
|
|
24
|
+
from collections.abc import Callable
|
|
25
|
+
from dataclasses import dataclass
|
|
26
|
+
from datetime import UTC, datetime
|
|
27
|
+
from pathlib import Path
|
|
28
|
+
from types import TracebackType
|
|
29
|
+
from typing import Any
|
|
30
|
+
|
|
31
|
+
from walletcap.errors import BudgetError, BudgetWarning, NotSent
|
|
32
|
+
from walletcap.ledger import UNSET, BudgetLimits, Ledger
|
|
33
|
+
from walletcap.money import (
|
|
34
|
+
DAY_MS,
|
|
35
|
+
HOUR_MS,
|
|
36
|
+
WEEK_MS,
|
|
37
|
+
default_budget_path,
|
|
38
|
+
describe_limits,
|
|
39
|
+
expand_home,
|
|
40
|
+
format_usd,
|
|
41
|
+
format_window,
|
|
42
|
+
limit_flags,
|
|
43
|
+
normalize_wallet,
|
|
44
|
+
short_wallet,
|
|
45
|
+
to_micros,
|
|
46
|
+
to_window_ms,
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
__all__ = ["Budget", "Check", "Payment", "Paying", "Reservation", "Status", "open_budget"]
|
|
50
|
+
|
|
51
|
+
_TO_LIMIT = 256
|
|
52
|
+
_NOTE_LIMIT = 1024
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@dataclass(frozen=True)
|
|
56
|
+
class Check:
|
|
57
|
+
"""Whether an amount would be paid right now. Amounts are micro-dollars."""
|
|
58
|
+
|
|
59
|
+
ok: bool
|
|
60
|
+
remaining: int
|
|
61
|
+
reason: str | None = None
|
|
62
|
+
message: str | None = None
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@dataclass(frozen=True)
|
|
66
|
+
class Status:
|
|
67
|
+
"""What a wallet has spent, has in flight and has left. Amounts are micro-dollars."""
|
|
68
|
+
|
|
69
|
+
wallet: str
|
|
70
|
+
path: Path
|
|
71
|
+
cap: int
|
|
72
|
+
window_ms: int
|
|
73
|
+
per_payment: int | None
|
|
74
|
+
max_payments: int | None
|
|
75
|
+
spent: int
|
|
76
|
+
in_flight: int
|
|
77
|
+
remaining: int
|
|
78
|
+
payments: int
|
|
79
|
+
frozen: bool
|
|
80
|
+
|
|
81
|
+
@property
|
|
82
|
+
def summary(self) -> str:
|
|
83
|
+
window = format_window(self.window_ms)
|
|
84
|
+
parts = [
|
|
85
|
+
f"{short_wallet(self.wallet)}: {format_usd(self.spent)} spent of "
|
|
86
|
+
f"{format_usd(self.cap)} per {window}, {format_usd(self.remaining)} left"
|
|
87
|
+
]
|
|
88
|
+
if self.in_flight > 0:
|
|
89
|
+
parts.append(f"{format_usd(self.in_flight)} in flight")
|
|
90
|
+
if self.per_payment is not None:
|
|
91
|
+
parts.append(f"at most {format_usd(self.per_payment)} a payment")
|
|
92
|
+
if self.max_payments is not None:
|
|
93
|
+
parts.append(f"at most {self.max_payments} payments per {window}")
|
|
94
|
+
if self.frozen:
|
|
95
|
+
parts.append("FROZEN")
|
|
96
|
+
return " · ".join(parts)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
@dataclass(frozen=True)
|
|
100
|
+
class Payment:
|
|
101
|
+
"""One entry of a wallet's history. ``amount`` is micro-dollars."""
|
|
102
|
+
|
|
103
|
+
id: str
|
|
104
|
+
amount: int
|
|
105
|
+
status: str
|
|
106
|
+
counting: bool
|
|
107
|
+
at: datetime
|
|
108
|
+
rail: str
|
|
109
|
+
to: str | None
|
|
110
|
+
note: str | None
|
|
111
|
+
tx: str | None
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _limits(
|
|
115
|
+
*,
|
|
116
|
+
per_payment: object,
|
|
117
|
+
per_hour: object,
|
|
118
|
+
per_day: object,
|
|
119
|
+
per_week: object,
|
|
120
|
+
cap: object,
|
|
121
|
+
window: object,
|
|
122
|
+
max_payments: object,
|
|
123
|
+
) -> dict[str, Any]:
|
|
124
|
+
"""The limits named, in budget units: absent keys have no opinion."""
|
|
125
|
+
|
|
126
|
+
limits: dict[str, Any] = {}
|
|
127
|
+
named = {
|
|
128
|
+
key: value
|
|
129
|
+
for key, value in (("per_hour", per_hour), ("per_day", per_day), ("per_week", per_week))
|
|
130
|
+
if value is not None
|
|
131
|
+
}
|
|
132
|
+
explicit = cap is not None or window is not None
|
|
133
|
+
if len(named) + (1 if explicit else 0) > 1:
|
|
134
|
+
raise BudgetError("give one rolling limit: per_hour, per_day, per_week, or cap with window")
|
|
135
|
+
if named:
|
|
136
|
+
((key, value),) = named.items()
|
|
137
|
+
limits["cap"] = to_micros(value, key)
|
|
138
|
+
limits["window_ms"] = {"per_hour": HOUR_MS, "per_day": DAY_MS, "per_week": WEEK_MS}[key]
|
|
139
|
+
elif explicit:
|
|
140
|
+
if cap is None or window is None:
|
|
141
|
+
raise BudgetError("cap and window go together, like cap='$150', window='24h'")
|
|
142
|
+
limits["cap"] = to_micros(cap, "cap")
|
|
143
|
+
limits["window_ms"] = to_window_ms(window)
|
|
144
|
+
if per_payment is not UNSET:
|
|
145
|
+
limits["per_payment"] = (
|
|
146
|
+
None if per_payment is None else to_micros(per_payment, "per_payment")
|
|
147
|
+
)
|
|
148
|
+
if limits["per_payment"] == 0:
|
|
149
|
+
raise BudgetError("per_payment must be more than $0; to stop every payment, freeze")
|
|
150
|
+
if max_payments is not UNSET:
|
|
151
|
+
if max_payments is None:
|
|
152
|
+
limits["max_uses"] = None
|
|
153
|
+
elif type(max_payments) is int and max_payments >= 0:
|
|
154
|
+
limits["max_uses"] = max_payments
|
|
155
|
+
else:
|
|
156
|
+
raise BudgetError("max_payments must be a whole number of payments")
|
|
157
|
+
return limits
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _describe(to: str | None, note: str | None, details: dict[str, Any] | None) -> dict[str, Any]:
|
|
161
|
+
if to is not None and (not isinstance(to, str) or len(to) > _TO_LIMIT):
|
|
162
|
+
raise BudgetError(f"to must be a string of at most {_TO_LIMIT} characters")
|
|
163
|
+
if note is not None and (not isinstance(note, str) or len(note) > _NOTE_LIMIT):
|
|
164
|
+
raise BudgetError(f"note must be a string of at most {_NOTE_LIMIT} characters")
|
|
165
|
+
if details is not None and not isinstance(details, dict):
|
|
166
|
+
raise BudgetError("details must be a dict")
|
|
167
|
+
info = {**(details or {}), "to": to, "note": note}
|
|
168
|
+
return {key: value for key, value in info.items() if value is not None}
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _positive(micros: int) -> int:
|
|
172
|
+
if micros == 0:
|
|
173
|
+
raise BudgetError("the amount must be more than $0")
|
|
174
|
+
return micros
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _info(reference: str | None) -> dict[str, Any]:
|
|
178
|
+
try:
|
|
179
|
+
info = json.loads(reference) if reference else {}
|
|
180
|
+
except ValueError:
|
|
181
|
+
return {}
|
|
182
|
+
return info if isinstance(info, dict) else {}
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
class Reservation:
|
|
186
|
+
"""An amount taken from the budget for one payment, until committed or released."""
|
|
187
|
+
|
|
188
|
+
def __init__(self, ledger: Ledger, spend_id: str, amount: int, info: dict[str, Any]) -> None:
|
|
189
|
+
self._ledger = ledger
|
|
190
|
+
self._id = spend_id
|
|
191
|
+
self._amount = amount
|
|
192
|
+
self._info = info
|
|
193
|
+
self._state = "open"
|
|
194
|
+
self.tx: str | None = None
|
|
195
|
+
"""Set it inside ``with budget.pay(...)`` to keep the transaction hash in the history."""
|
|
196
|
+
|
|
197
|
+
@property
|
|
198
|
+
def id(self) -> str:
|
|
199
|
+
"""Unique per payment: a good idempotency key for the rail you pay through."""
|
|
200
|
+
|
|
201
|
+
return self._id
|
|
202
|
+
|
|
203
|
+
@property
|
|
204
|
+
def amount(self) -> int:
|
|
205
|
+
"""In micro-dollars."""
|
|
206
|
+
|
|
207
|
+
return self._amount
|
|
208
|
+
|
|
209
|
+
@property
|
|
210
|
+
def open(self) -> bool:
|
|
211
|
+
return self._state == "open"
|
|
212
|
+
|
|
213
|
+
def commit(
|
|
214
|
+
self, *, tx: str | None = None, outcome: str | None = None, error: str | None = None
|
|
215
|
+
) -> None:
|
|
216
|
+
"""The payment settled. It counts for one rolling window from now."""
|
|
217
|
+
|
|
218
|
+
if not self.open:
|
|
219
|
+
raise BudgetError(f"reservation {self._id} is already {self._state}")
|
|
220
|
+
tx = tx or self.tx
|
|
221
|
+
info = {
|
|
222
|
+
**self._info,
|
|
223
|
+
**({"tx": tx} if tx else {}),
|
|
224
|
+
**({"outcome": outcome} if outcome else {}),
|
|
225
|
+
**({"error": error} if error else {}),
|
|
226
|
+
}
|
|
227
|
+
self._ledger.commit(self._id, reference=json.dumps(info) if info else None)
|
|
228
|
+
self._state = "committed"
|
|
229
|
+
|
|
230
|
+
def release(self) -> None:
|
|
231
|
+
"""The payment never left the wallet: give its amount back."""
|
|
232
|
+
|
|
233
|
+
if not self.open:
|
|
234
|
+
raise BudgetError(f"reservation {self._id} is already {self._state}")
|
|
235
|
+
self._ledger.release(self._id)
|
|
236
|
+
self._state = "released"
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
class Paying:
|
|
240
|
+
"""``with budget.pay(amount):`` reserves on entry and records the payment on exit.
|
|
241
|
+
|
|
242
|
+
A clean exit commits it. An exception commits it as an unknown outcome (it
|
|
243
|
+
may have left the wallet), unless the exception is ``NotSent``, which gives
|
|
244
|
+
the amount back. Works with ``async with`` too.
|
|
245
|
+
"""
|
|
246
|
+
|
|
247
|
+
def __init__(self, budget: Budget, amount: object, info: dict[str, Any], rail: str) -> None:
|
|
248
|
+
self._budget = budget
|
|
249
|
+
self._amount = amount
|
|
250
|
+
self._info = info
|
|
251
|
+
self._rail = rail
|
|
252
|
+
self._reservation: Reservation | None = None
|
|
253
|
+
|
|
254
|
+
def __enter__(self) -> Reservation:
|
|
255
|
+
self._reservation = self._budget._reserve(self._amount, self._info, self._rail, None)
|
|
256
|
+
return self._reservation
|
|
257
|
+
|
|
258
|
+
def __exit__(
|
|
259
|
+
self,
|
|
260
|
+
exc_type: type[BaseException] | None,
|
|
261
|
+
exc: BaseException | None,
|
|
262
|
+
traceback: TracebackType | None,
|
|
263
|
+
) -> None:
|
|
264
|
+
reservation = self._reservation
|
|
265
|
+
if reservation is None or not reservation.open:
|
|
266
|
+
return
|
|
267
|
+
if exc is None:
|
|
268
|
+
try:
|
|
269
|
+
reservation.commit()
|
|
270
|
+
except BudgetError as error:
|
|
271
|
+
raise BudgetError(
|
|
272
|
+
"the payment went through but could not be recorded as settled; "
|
|
273
|
+
f"it still counts as in flight ({reservation.id})"
|
|
274
|
+
) from error
|
|
275
|
+
return
|
|
276
|
+
try:
|
|
277
|
+
if isinstance(exc, NotSent) or getattr(exc, "not_sent", False) is True:
|
|
278
|
+
reservation.release()
|
|
279
|
+
else:
|
|
280
|
+
reservation.commit(outcome="unknown", error=str(exc)[:200])
|
|
281
|
+
except BudgetError:
|
|
282
|
+
pass # recording failed; the reservation stays open, and keeps counting
|
|
283
|
+
|
|
284
|
+
async def __aenter__(self) -> Reservation:
|
|
285
|
+
return self.__enter__()
|
|
286
|
+
|
|
287
|
+
async def __aexit__(
|
|
288
|
+
self,
|
|
289
|
+
exc_type: type[BaseException] | None,
|
|
290
|
+
exc: BaseException | None,
|
|
291
|
+
traceback: TracebackType | None,
|
|
292
|
+
) -> None:
|
|
293
|
+
self.__exit__(exc_type, exc, traceback)
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
class Budget:
|
|
297
|
+
"""A wallet's budget in the shared file. Open it with ``open_budget``."""
|
|
298
|
+
|
|
299
|
+
def __init__(
|
|
300
|
+
self,
|
|
301
|
+
wallet: str,
|
|
302
|
+
*,
|
|
303
|
+
path: str | Path | None = None,
|
|
304
|
+
create: bool = True,
|
|
305
|
+
per_payment: object = UNSET,
|
|
306
|
+
per_hour: object = None,
|
|
307
|
+
per_day: object = None,
|
|
308
|
+
per_week: object = None,
|
|
309
|
+
cap: object = None,
|
|
310
|
+
window: object = None,
|
|
311
|
+
max_payments: object = UNSET,
|
|
312
|
+
clock: Callable[[], float] = time.time,
|
|
313
|
+
busy_timeout_seconds: float = 30.0,
|
|
314
|
+
on_warning: Callable[[str], None] | None = None,
|
|
315
|
+
) -> None:
|
|
316
|
+
self._wallet = normalize_wallet(wallet)
|
|
317
|
+
self._path = expand_home(path if path is not None else default_budget_path()).absolute()
|
|
318
|
+
limits = _limits(
|
|
319
|
+
per_payment=per_payment,
|
|
320
|
+
per_hour=per_hour,
|
|
321
|
+
per_day=per_day,
|
|
322
|
+
per_week=per_week,
|
|
323
|
+
cap=cap,
|
|
324
|
+
window=window,
|
|
325
|
+
max_payments=max_payments,
|
|
326
|
+
)
|
|
327
|
+
if not create and not self._path.exists():
|
|
328
|
+
raise BudgetError(
|
|
329
|
+
f"no budget file at {self._path}; its owner creates one with: "
|
|
330
|
+
f"walletcap set --wallet {self._wallet}{self._path_flag()} "
|
|
331
|
+
"--per-day <dollars>"
|
|
332
|
+
)
|
|
333
|
+
if create:
|
|
334
|
+
self._path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
335
|
+
self._ledger = Ledger(self._path, clock=clock, busy_timeout_seconds=busy_timeout_seconds)
|
|
336
|
+
ensured = self._ledger.ensure(self._wallet, unit="usd", create=create, **limits)
|
|
337
|
+
if ensured.looser:
|
|
338
|
+
self._warn_kept(on_warning, ensured.budget, limits)
|
|
339
|
+
|
|
340
|
+
@property
|
|
341
|
+
def wallet(self) -> str:
|
|
342
|
+
"""The name the budget is kept under: an EVM address, lowercased."""
|
|
343
|
+
|
|
344
|
+
return self._wallet
|
|
345
|
+
|
|
346
|
+
@property
|
|
347
|
+
def path(self) -> Path:
|
|
348
|
+
return self._path
|
|
349
|
+
|
|
350
|
+
def _path_flag(self) -> str:
|
|
351
|
+
default = expand_home(default_budget_path()).absolute()
|
|
352
|
+
return "" if self._path == default else f" --path {shlex.quote(str(self._path))}"
|
|
353
|
+
|
|
354
|
+
def _warn_kept(
|
|
355
|
+
self, on_warning: Callable[[str], None] | None, stored: BudgetLimits, asked: dict[str, Any]
|
|
356
|
+
) -> None:
|
|
357
|
+
kept = describe_limits(
|
|
358
|
+
cap=stored.cap,
|
|
359
|
+
window_ms=stored.window_ms,
|
|
360
|
+
per_payment=stored.per_payment,
|
|
361
|
+
max_uses=stored.max_uses,
|
|
362
|
+
)
|
|
363
|
+
wanted = {
|
|
364
|
+
"cap": asked.get("cap"),
|
|
365
|
+
"window_ms": asked.get("window_ms", stored.window_ms),
|
|
366
|
+
"per_payment": asked.get("per_payment"),
|
|
367
|
+
"max_uses": asked.get("max_uses"),
|
|
368
|
+
}
|
|
369
|
+
wanted_text = describe_limits(**wanted) or "no limit"
|
|
370
|
+
message = (
|
|
371
|
+
f"walletcap: {short_wallet(self._wallet)} keeps its stored limits ({kept}); "
|
|
372
|
+
f"your code asks for {wanted_text}. A restart can lower a limit but never raise one. "
|
|
373
|
+
f"To raise it, its owner runs: walletcap set --wallet {self._wallet}"
|
|
374
|
+
f"{self._path_flag()} {limit_flags(**wanted)}"
|
|
375
|
+
).rstrip()
|
|
376
|
+
if on_warning is not None:
|
|
377
|
+
on_warning(message)
|
|
378
|
+
else:
|
|
379
|
+
warnings.warn(message, BudgetWarning, stacklevel=4)
|
|
380
|
+
|
|
381
|
+
def check(self, amount: object) -> Check:
|
|
382
|
+
"""Whether ``amount`` would be paid right now, without taking it."""
|
|
383
|
+
|
|
384
|
+
checked = self._ledger.check(self._wallet, _positive(to_micros(amount)))
|
|
385
|
+
if checked.refusal is None:
|
|
386
|
+
return Check(True, checked.remaining)
|
|
387
|
+
return Check(False, checked.remaining, checked.refusal.reason, str(checked.refusal))
|
|
388
|
+
|
|
389
|
+
def reserve(
|
|
390
|
+
self,
|
|
391
|
+
amount: object,
|
|
392
|
+
*,
|
|
393
|
+
to: str | None = None,
|
|
394
|
+
note: str | None = None,
|
|
395
|
+
details: dict[str, Any] | None = None,
|
|
396
|
+
rail: str = "python",
|
|
397
|
+
settles_by: datetime | None = None,
|
|
398
|
+
) -> Reservation:
|
|
399
|
+
"""Take ``amount`` before paying, or raise ``BudgetRefused``.
|
|
400
|
+
|
|
401
|
+
Commit the reservation when the payment settles; release it only if the
|
|
402
|
+
payment never left the wallet.
|
|
403
|
+
"""
|
|
404
|
+
|
|
405
|
+
return self._reserve(amount, _describe(to, note, details), rail, settles_by)
|
|
406
|
+
|
|
407
|
+
def _reserve(
|
|
408
|
+
self, amount: object, info: dict[str, Any], rail: str, settles_by: datetime | None
|
|
409
|
+
) -> Reservation:
|
|
410
|
+
micros = _positive(to_micros(amount))
|
|
411
|
+
settles_by_ms = None if settles_by is None else int(settles_by.timestamp() * 1000)
|
|
412
|
+
spend_id = self._ledger.reserve(
|
|
413
|
+
self._wallet,
|
|
414
|
+
micros,
|
|
415
|
+
rail=rail,
|
|
416
|
+
reference=json.dumps(info) if info else None,
|
|
417
|
+
settles_by_ms=settles_by_ms,
|
|
418
|
+
)
|
|
419
|
+
return Reservation(self._ledger, spend_id, micros, info)
|
|
420
|
+
|
|
421
|
+
def pay(
|
|
422
|
+
self,
|
|
423
|
+
amount: object,
|
|
424
|
+
*,
|
|
425
|
+
to: str | None = None,
|
|
426
|
+
note: str | None = None,
|
|
427
|
+
details: dict[str, Any] | None = None,
|
|
428
|
+
rail: str = "python",
|
|
429
|
+
) -> Paying:
|
|
430
|
+
"""``with budget.pay("$12.50"):`` reserve, pay inside the block, and record it.
|
|
431
|
+
|
|
432
|
+
Raises ``BudgetRefused`` on entry if the budget would be passed. If the
|
|
433
|
+
block raises, the payment still counts, unless it raised ``NotSent``.
|
|
434
|
+
"""
|
|
435
|
+
|
|
436
|
+
return Paying(self, amount, _describe(to, note, details), rail)
|
|
437
|
+
|
|
438
|
+
def status(self) -> Status:
|
|
439
|
+
status = self._ledger.status(self._wallet)
|
|
440
|
+
return Status(
|
|
441
|
+
self._wallet,
|
|
442
|
+
self._path,
|
|
443
|
+
status.cap,
|
|
444
|
+
status.window_ms,
|
|
445
|
+
status.per_payment,
|
|
446
|
+
status.max_uses,
|
|
447
|
+
status.spent,
|
|
448
|
+
status.reserved,
|
|
449
|
+
status.remaining,
|
|
450
|
+
status.uses,
|
|
451
|
+
status.revoked,
|
|
452
|
+
)
|
|
453
|
+
|
|
454
|
+
def set_limits(
|
|
455
|
+
self,
|
|
456
|
+
*,
|
|
457
|
+
per_payment: object = UNSET,
|
|
458
|
+
per_hour: object = None,
|
|
459
|
+
per_day: object = None,
|
|
460
|
+
per_week: object = None,
|
|
461
|
+
cap: object = None,
|
|
462
|
+
window: object = None,
|
|
463
|
+
max_payments: object = UNSET,
|
|
464
|
+
) -> Status:
|
|
465
|
+
"""Change the limits, up or down. What was spent keeps counting: nothing resets."""
|
|
466
|
+
|
|
467
|
+
limits = _limits(
|
|
468
|
+
per_payment=per_payment,
|
|
469
|
+
per_hour=per_hour,
|
|
470
|
+
per_day=per_day,
|
|
471
|
+
per_week=per_week,
|
|
472
|
+
cap=cap,
|
|
473
|
+
window=window,
|
|
474
|
+
max_payments=max_payments,
|
|
475
|
+
)
|
|
476
|
+
if not limits:
|
|
477
|
+
raise BudgetError("set_limits needs a limit, like per_day='$150'")
|
|
478
|
+
self._ledger.set_limits(self._wallet, unit="usd", **limits)
|
|
479
|
+
return self.status()
|
|
480
|
+
|
|
481
|
+
def freeze(self) -> None:
|
|
482
|
+
"""Refuse every payment from this wallet, on every rail and in every process."""
|
|
483
|
+
|
|
484
|
+
self._ledger.revoke(self._wallet)
|
|
485
|
+
|
|
486
|
+
def unfreeze(self) -> None:
|
|
487
|
+
self._ledger.unrevoke(self._wallet)
|
|
488
|
+
|
|
489
|
+
def history(self, limit: int = 20) -> list[Payment]:
|
|
490
|
+
"""The newest payments first."""
|
|
491
|
+
|
|
492
|
+
payments = []
|
|
493
|
+
for spend in self._ledger.history(self._wallet, limit=limit):
|
|
494
|
+
info = _info(spend.reference)
|
|
495
|
+
if spend.status == "committed":
|
|
496
|
+
label = "unknown" if info.get("outcome") == "unknown" else "settled"
|
|
497
|
+
elif not spend.counting:
|
|
498
|
+
label = "expired"
|
|
499
|
+
elif info.get("outcome") in ("refused", "unknown"):
|
|
500
|
+
label = str(info["outcome"])
|
|
501
|
+
else:
|
|
502
|
+
label = "in flight"
|
|
503
|
+
payments.append(
|
|
504
|
+
Payment(
|
|
505
|
+
spend.spend_id,
|
|
506
|
+
spend.amount,
|
|
507
|
+
label,
|
|
508
|
+
spend.counting,
|
|
509
|
+
datetime.fromtimestamp(spend.at_ms / 1000, tz=UTC),
|
|
510
|
+
spend.rail,
|
|
511
|
+
info.get("to") or info.get("payTo"),
|
|
512
|
+
info.get("note") or info.get("network"),
|
|
513
|
+
info.get("tx"),
|
|
514
|
+
)
|
|
515
|
+
)
|
|
516
|
+
return payments
|
|
517
|
+
|
|
518
|
+
def close(self) -> None:
|
|
519
|
+
"""Nothing to close: the ledger opens a connection per operation."""
|
|
520
|
+
|
|
521
|
+
def __enter__(self) -> Budget:
|
|
522
|
+
return self
|
|
523
|
+
|
|
524
|
+
def __exit__(self, *_: object) -> None:
|
|
525
|
+
self.close()
|
|
526
|
+
|
|
527
|
+
|
|
528
|
+
def open_budget(wallet: str, **options: Any) -> Budget:
|
|
529
|
+
"""Open the wallet's budget, creating it on first use.
|
|
530
|
+
|
|
531
|
+
Limits are dollars: strings (``"$150"``, ``"12.50 USDC"``), ints, floats or
|
|
532
|
+
Decimals. Give one rolling limit (``per_hour``, ``per_day``, ``per_week``,
|
|
533
|
+
or ``cap`` with ``window``) and optionally ``per_payment`` and ``max_payments``.
|
|
534
|
+
"""
|
|
535
|
+
|
|
536
|
+
return Budget(wallet, **options)
|
|
537
|
+
|
walletcap/errors.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
"""What the budget raises, and the exception that says a payment never left."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
from typing import ClassVar
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class BudgetError(ValueError):
|
|
10
|
+
"""A request is malformed, or the ledger file cannot be trusted."""
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class BudgetRefused(BudgetError):
|
|
14
|
+
"""Granting the reservation would break the budget."""
|
|
15
|
+
|
|
16
|
+
reason: ClassVar[str] = "budget"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class OverBudget(BudgetRefused):
|
|
20
|
+
"""The rolling window's spend plus this amount would pass the cap."""
|
|
21
|
+
|
|
22
|
+
reason: ClassVar[str] = "budget"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class OverPerPayment(BudgetRefused):
|
|
26
|
+
"""This one payment is larger than the per-payment max."""
|
|
27
|
+
|
|
28
|
+
reason: ClassVar[str] = "per_payment"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class OverUses(BudgetRefused):
|
|
32
|
+
"""The rolling window already holds the most payments allowed."""
|
|
33
|
+
|
|
34
|
+
reason: ClassVar[str] = "uses"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class BudgetRevoked(BudgetRefused):
|
|
38
|
+
"""The instrument's budget was revoked (frozen); nothing more may be reserved."""
|
|
39
|
+
|
|
40
|
+
reason: ClassVar[str] = "revoked"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class BudgetWarning(UserWarning):
|
|
44
|
+
"""The budget file kept a limit tighter than the code asked for."""
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class NotSent(Exception):
|
|
48
|
+
"""Raise inside ``with budget.pay(...)`` to say the payment never left the wallet.
|
|
49
|
+
|
|
50
|
+
Its amount is given back. Any other exception keeps counting, because a
|
|
51
|
+
payment that failed halfway may still have moved money.
|
|
52
|
+
"""
|