fair-meter 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.
fair_meter/__init__.py ADDED
@@ -0,0 +1,30 @@
1
+ # Copyright 2026 Kamkar Foundation, LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """The fair meter kit: what an x402 seller needs to keep the Fair Offer Standard 0.4.
16
+
17
+ - `declare`: the fair-offer block for the 402 (every rule it names, FO-2 to FO-10).
18
+ - `meter`: FO-9, the charge under the buyer's ceiling with x402's `upto`.
19
+ - `receipt`: FO-3, a signed receipt bound to the hash of what was delivered.
20
+ - `guard`: FO-6, a check that a response carries no instructions aimed at the buying agent.
21
+ - `ledger`: FO-10, a receipts ledger that only grows, with monthly Merkle roots and a proof per receipt.
22
+ - `pledge`: FO-7, a public share paid monthly: the pledge ledger page from the receipts ledger, and the carry-1 rule
23
+ for small sums.
24
+ - `jcs`: RFC 8785, the canonical form the delivery hash is taken over.
25
+
26
+ No dependencies beyond the standard library; signing receipts uses `eth-account`.
27
+ """
28
+
29
+ __version__ = "0.2.0"
30
+ STANDARD_VERSION = "0.4"
fair_meter/declare.py ADDED
@@ -0,0 +1,99 @@
1
+ # Copyright 2026 Kamkar Foundation, LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """The Fair Offer 0.4 block: what a route declares in its x402 402, under the extension key `fair-offer`.
16
+
17
+ Declare only what the server really does. Each field names a rule a buyer can check:
18
+ FO-2 settlement, FO-3 receipts, FO-4 sample, FO-5 listing price, FO-6 data not instructions, FO-7 pledge,
19
+ FO-8 one offer, FO-9 metered, FO-10 book. The block must be the same in the unpaid 402 and on the paid retry, so it
20
+ holds no counts or timestamps.
21
+ """
22
+
23
+ import re
24
+ from typing import Any, Dict, Optional
25
+
26
+ VERSION = "0.4"
27
+ EXTENSION_KEY = "fair-offer"
28
+ STANDARD = "https://agoranome.com/standard"
29
+ SCHEMA = "https://agoranome.com/standard/fair-offer-0.4.schema.json"
30
+ METERED_SCHEME = "upto"
31
+
32
+ _UNIT = re.compile(r"^[a-z][a-z_]{0,31}$")
33
+ _PRICE = re.compile(r"^(0|[1-9][0-9]{0,8})(\.[0-9]{1,9})?$")
34
+ _ADDRESS = re.compile(r"^0x[0-9a-fA-F]{40}$")
35
+ _BASES = ("settled_revenue", "gross_revenue", "profit")
36
+
37
+
38
+ def _url(value: str, name: str) -> str:
39
+ text = str(value or "").strip()
40
+ if not text or len(text) > 2048 or not (text.startswith("https://") or text.startswith("/")):
41
+ raise ValueError(f"{name} must be an https URL or a path relative to the resource URL")
42
+ return text
43
+
44
+
45
+ def metered(unit: str, unit_price_usd: str) -> Dict[str, str]:
46
+ """FO-9: one public unit price, the same at every size and for every buyer, charged under x402's `upto`."""
47
+ if not _UNIT.match(unit or ""):
48
+ raise ValueError("the unit is a lower-case word, such as row, page or token")
49
+ if not _PRICE.match(unit_price_usd or ""):
50
+ raise ValueError("the unit price is a decimal string in dollars, such as \"0.0002\"")
51
+ return {"unit": unit, "unit_price_usd": unit_price_usd, "scheme": METERED_SCHEME}
52
+
53
+
54
+ def block(*, failed_calls_enforced_by: str = "seller", signer: Optional[str] = None,
55
+ receipts_verify: Optional[str] = None, sample: Optional[str] = None,
56
+ listing_price_matches_offer: bool = True, data_not_instructions: bool = True, one_offer: bool = True,
57
+ meter: Optional[Dict[str, str]] = None, pledge_share: Optional[float] = None,
58
+ pledge_basis: str = "settled_revenue", pledge_ledger: Optional[str] = None,
59
+ ledger: Optional[str] = None, reports: Optional[str] = None,
60
+ standard: str = STANDARD) -> Dict[str, Any]:
61
+ """The block's info. `signer` is the address that signs receipts (FO-3); `meter` comes from `metered()` and is
62
+ given only on a route that offers `upto` (FO-9); `ledger` and `reports` are the public receipts ledger and the
63
+ buyers' report listing (FO-10)."""
64
+ if failed_calls_enforced_by not in ("seller", "rail"):
65
+ raise ValueError("failed calls are enforced by the seller or by the rail")
66
+ settlement: Dict[str, Any] = {"failed_calls": "not_charged", "enforced_by": failed_calls_enforced_by}
67
+ if failed_calls_enforced_by == "rail":
68
+ settlement["capture_on"] = "2xx"
69
+ receipts: Dict[str, Any] = {"signed": True, "delivery_hash": "sha256-jcs"}
70
+ if signer is not None:
71
+ if not _ADDRESS.match(signer):
72
+ raise ValueError("the signer is a 0x address")
73
+ receipts["signer"] = signer
74
+ if receipts_verify:
75
+ receipts["verify"] = _url(receipts_verify, "receipts_verify")
76
+ info: Dict[str, Any] = {"version": VERSION, "standard": standard, "settlement": settlement,
77
+ "receipts": receipts, "listing_price_matches_offer": bool(listing_price_matches_offer),
78
+ "data_not_instructions": bool(data_not_instructions), "one_offer": bool(one_offer)}
79
+ if sample:
80
+ info["sample"] = {"url": _url(sample, "sample")}
81
+ if meter is not None:
82
+ info["metered"] = metered(meter["unit"], meter["unit_price_usd"])
83
+ if pledge_share is not None:
84
+ if not 0 < float(pledge_share) <= 1 or pledge_basis not in _BASES or not pledge_ledger:
85
+ raise ValueError("a pledge names a share in (0, 1], a basis and its public ledger (FO-7)")
86
+ info["pledge"] = {"share": pledge_share, "basis": pledge_basis,
87
+ "ledger": _url(pledge_ledger, "pledge_ledger")}
88
+ if ledger:
89
+ info["book"] = {"ledger": _url(ledger, "ledger")}
90
+ if reports:
91
+ info["book"]["reports"] = _url(reports, "reports")
92
+ elif reports:
93
+ raise ValueError("the book names its receipts ledger before its reports (FO-10)")
94
+ return info
95
+
96
+
97
+ def extension(info: Dict[str, Any]) -> Dict[str, Any]:
98
+ """The entry for a route's x402 `extensions`: the info, and the schema by reference."""
99
+ return {EXTENSION_KEY: {"info": info, "schema": {"$ref": SCHEMA}}}
fair_meter/guard.py ADDED
@@ -0,0 +1,100 @@
1
+ # Copyright 2026 Kamkar Foundation, LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """FO-6, data, never instructions: a seller's own check on what it is about to send.
16
+
17
+ A response carries data for the buying agent, never instructions aimed at it. Data from elsewhere (a scraped page,
18
+ a third party's text) can carry them without the seller meaning it. `scan` finds text that reads as an instruction
19
+ to an agent in every string of a response, matched as a model reads it: character references decoded,
20
+ compatibility forms folded, invisible characters dropped and look-alike letters made Latin. It is a set of fixed
21
+ patterns, not a model: it misses what they don't cover and is meant as a guard, not a proof.
22
+
23
+ The patterns are Agoranome's, from its listing checks and the red-team of its own defences (November 2026).
24
+ """
25
+
26
+ import html
27
+ import re
28
+ import unicodedata
29
+ from typing import Any, List, Tuple
30
+
31
+ PATTERNS = [
32
+ r"\bignore (all|any|the|your|previous|prior|other)\b",
33
+ r"\bdisregard\b",
34
+ r"\b(always|must|should|you should) (choose|pick|select|prefer|call|use) (this|us|me|our)\b",
35
+ r"\b(choose|pick|select|prefer) (this|us|me|our \w+) (over|instead|first|before)\b",
36
+ r"\bdo not (choose|pick|select|use|call) (any|other|another|competing)\b",
37
+ r"\bsystem prompt\b",
38
+ r"\byou are (an?|the) (ai|assistant|agent|model|llm)\b",
39
+ r"\b(attention|note to|dear) (ai|llm|agents?|assistants?|models?)\b",
40
+ r"<\s*/?\s*(system|instructions?|prompt)\s*>",
41
+ r"\[\s*/?\s*(system|inst)\s*\]",
42
+ r"\bforget (all |any |the |your )?(previous|prior|earlier|above|preceding|other) "
43
+ r"(instructions?|prompts?|rules?|messages?)\b",
44
+ r"\boverride (all |any |your )(previous |prior |other )?(instructions?|rules?|system prompt)\b",
45
+ r"\bnew instructions?\s*:",
46
+ r"<\|\s*(im_start|im_end|system|assistant|endoftext)\s*\|>",
47
+ r"\bthe only (tool|service|api|option|seller) (you|agents?|models?) (should|must|may) (call|use|pick|choose|"
48
+ r"select)\b",
49
+ ]
50
+ _RE = re.compile("|".join(PATTERNS), re.IGNORECASE)
51
+ _CONFUSABLES = str.maketrans({
52
+ "а": "a", "е": "e", "о": "o", "р": "p", "с": "c", "у": "y", "х": "x",
53
+ "і": "i", "ј": "j", "ѕ": "s", "ԁ": "d", "һ": "h", "А": "A", "В": "B",
54
+ "Е": "E", "К": "K", "М": "M", "Н": "H", "О": "O", "Р": "P", "С": "C",
55
+ "Т": "T", "Х": "X", "І": "I", "Ј": "J", "Ѕ": "S", "ο": "o", "Ο": "O",
56
+ "α": "a", "ι": "i", "Ι": "I", "ν": "v", "ρ": "p", "Α": "A", "Β": "B",
57
+ "Ε": "E", "Η": "H", "Κ": "K", "Μ": "M", "Ν": "N", "Τ": "T", "Χ": "X",
58
+ "Υ": "Y", "Ζ": "Z",
59
+ })
60
+ _SPACES = re.compile(r"\s+")
61
+
62
+
63
+ class InstructionFound(ValueError):
64
+ """A response holds text that reads as an instruction to the buying agent (FO-6)."""
65
+
66
+ def __init__(self, found: List[Tuple[str, str]]):
67
+ self.found = found
68
+ super().__init__("text that reads as an instruction to an agent at " + ", ".join(p for p, _ in found[:5]))
69
+
70
+
71
+ def normalized(text: str) -> str:
72
+ text = unicodedata.normalize("NFKC", html.unescape(text or ""))
73
+ text = "".join(ch for ch in text if unicodedata.category(ch) != "Cf")
74
+ return _SPACES.sub(" ", text.translate(_CONFUSABLES))
75
+
76
+
77
+ def _strings(value: Any, path: str):
78
+ if isinstance(value, str):
79
+ yield path, value
80
+ elif isinstance(value, dict):
81
+ for key, item in value.items():
82
+ yield from _strings(str(key), f"{path}.{key}#key")
83
+ yield from _strings(item, f"{path}.{key}")
84
+ elif isinstance(value, (list, tuple)):
85
+ for i, item in enumerate(value):
86
+ yield from _strings(item, f"{path}[{i}]")
87
+
88
+
89
+ def scan(value: Any) -> List[Tuple[str, str]]:
90
+ """(where, phrase) for each instruction-like phrase in the strings of a JSON value, keys included."""
91
+ return [(where, m.group(0)) for where, text in _strings(value, "$") for m in _RE.finditer(normalized(text))]
92
+
93
+
94
+ def guard(value: Any) -> Any:
95
+ """The value unchanged when it holds no instruction-like text, else InstructionFound. Call it on a result before
96
+ it is sent and settled: FO-2 says a call that fails is not charged."""
97
+ found = scan(value)
98
+ if found:
99
+ raise InstructionFound(found)
100
+ return value
fair_meter/jcs.py ADDED
@@ -0,0 +1,81 @@
1
+ # Copyright 2026 Kamkar Foundation, LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """RFC 8785 (JCS): the one canonical form of a JSON value, and the delivery hash FO-3 (0.4) names.
16
+
17
+ A receipt bound to what was delivered names `sha256(jcs(result))`. Any JCS library in any language gives the same
18
+ bytes for the JSON the buyer received, so a buyer can show what it was sold and anyone can recompute the hash.
19
+ """
20
+
21
+ import hashlib
22
+ import json
23
+ import math
24
+ from decimal import Decimal
25
+ from typing import Any, Dict
26
+
27
+ DELIVERY_HASH = "sha256-jcs"
28
+ DELIVERY_OF = "the RFC 8785 (JCS) form of result"
29
+
30
+
31
+ def _number(value: Any) -> str:
32
+ """An ECMAScript Number's text (RFC 8785 section 3.2.2.3)."""
33
+ if isinstance(value, int) and abs(value) < 2 ** 53:
34
+ return str(value)
35
+ x = float(value)
36
+ if math.isnan(x) or math.isinf(x):
37
+ raise ValueError("JSON has no NaN or Infinity")
38
+ if x == 0:
39
+ return "0"
40
+ if x < 0:
41
+ return "-" + _number(-x)
42
+ _, digits, exp = Decimal(repr(x)).as_tuple()
43
+ digits = list(digits)
44
+ while len(digits) > 1 and digits[-1] == 0:
45
+ digits.pop()
46
+ exp += 1
47
+ d = "".join(map(str, digits))
48
+ k, n = len(d), exp + len(d)
49
+ if k <= n <= 21:
50
+ return d + "0" * (n - k)
51
+ if 0 < n <= 21:
52
+ return d[:n] + "." + d[n:]
53
+ if -6 < n <= 0:
54
+ return "0." + "0" * (-n) + d
55
+ e = n - 1
56
+ return (d if k == 1 else d[0] + "." + d[1:]) + "e" + ("+" if e >= 0 else "-") + str(abs(e))
57
+
58
+
59
+ def _jcs(value: Any) -> str:
60
+ if value is None or isinstance(value, bool):
61
+ return json.dumps(value)
62
+ if isinstance(value, (int, float)):
63
+ return _number(value)
64
+ if isinstance(value, str):
65
+ return json.dumps(value, ensure_ascii=False)
66
+ if isinstance(value, (list, tuple)):
67
+ return "[" + ",".join(_jcs(v) for v in value) + "]"
68
+ if isinstance(value, dict):
69
+ keys = sorted((str(k) for k in value), key=lambda k: k.encode("utf-16-be"))
70
+ return "{" + ",".join(json.dumps(k, ensure_ascii=False) + ":" + _jcs(value[k]) for k in keys) + "}"
71
+ raise TypeError(f"not JSON: {type(value).__name__}")
72
+
73
+
74
+ def canonical(value: Any) -> bytes:
75
+ """The RFC 8785 bytes of a JSON value (dicts, lists, strings, numbers, booleans and None)."""
76
+ return _jcs(value).encode("utf-8")
77
+
78
+
79
+ def delivery(result: Any) -> Dict[str, str]:
80
+ """The receipt's `delivery` block for the result it comes with."""
81
+ return {"sha256": "0x" + hashlib.sha256(canonical(result)).hexdigest(), "of": DELIVERY_OF}
fair_meter/ledger.py ADDED
@@ -0,0 +1,174 @@
1
+ # Copyright 2026 Kamkar Foundation, LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """FO-10, the book is open: a receipts ledger that only grows, with one Merkle root a month and a proof per receipt.
16
+
17
+ Only settled receipts go in (a payment with a transaction on the chain); a metered call that charged nothing has
18
+ no transaction and no entry. Nothing is ever edited or removed. Each month's root is published, and each receipt's
19
+ proof folds into it, so a buyer can match its own payments against the book, and an outside inspector that copies
20
+ the roots (Agoranome's inspector: `anchor-lab`, then `verify-receipt`) can show a past month was never changed.
21
+
22
+ The construction is Agoranome's lab ledger's, so the same tools check both:
23
+ leaf = sha256(0x00 || canonical_json({receipt_id, payer, amount_atomic, tx_hash}))
24
+ node = sha256(0x01 || min(a, b) || max(a, b)) (sorted pairs, no positions)
25
+ Leaves are sorted; an odd node is promoted unchanged to the next level.
26
+ `canonical_json` is JSON with sorted keys and no spaces; `amount_atomic` is an integer; EVM addresses lower case.
27
+ """
28
+
29
+ import hashlib
30
+ import json
31
+ import sqlite3
32
+ import threading
33
+ from datetime import datetime, timezone
34
+ from typing import Any, Dict, List, Optional
35
+
36
+ LEAF = "sha256(0x00 || canonical_json({receipt_id, payer, amount_atomic, tx_hash}))"
37
+ NODE = "sha256(0x01 || min(a, b) || max(a, b)); leaves sorted; an odd node is promoted"
38
+ FIELDS = ("receipt_id", "payer", "amount_atomic", "tx_hash")
39
+
40
+ _SCHEMA = """
41
+ CREATE TABLE IF NOT EXISTS receipts (
42
+ receipt_id TEXT PRIMARY KEY,
43
+ payer TEXT NOT NULL,
44
+ amount_atomic INTEGER NOT NULL,
45
+ tx_hash TEXT NOT NULL,
46
+ period TEXT NOT NULL,
47
+ settled_at TEXT NOT NULL,
48
+ resource TEXT,
49
+ delivery_sha256 TEXT
50
+ );
51
+ CREATE TRIGGER IF NOT EXISTS receipts_never_change BEFORE UPDATE ON receipts
52
+ BEGIN SELECT RAISE(ABORT, 'the book only grows'); END;
53
+ CREATE TRIGGER IF NOT EXISTS receipts_never_leave BEFORE DELETE ON receipts
54
+ BEGIN SELECT RAISE(ABORT, 'the book only grows'); END;
55
+ """
56
+
57
+
58
+ def _h(data: bytes) -> bytes:
59
+ return hashlib.sha256(data).digest()
60
+
61
+
62
+ def _address(text: str) -> str:
63
+ text = (text or "").strip()
64
+ return text.lower() if text.lower().startswith("0x") else text
65
+
66
+
67
+ def leaf_hash(entry: Dict[str, Any]) -> str:
68
+ fields = {k: entry[k] for k in FIELDS}
69
+ return "0x" + _h(b"\x00" + json.dumps(fields, sort_keys=True, separators=(",", ":")).encode()).hex()
70
+
71
+
72
+ def _node(a: bytes, b: bytes) -> bytes:
73
+ lo, hi = sorted((a, b))
74
+ return _h(b"\x01" + lo + hi)
75
+
76
+
77
+ def _levels(leaves: List[str]) -> List[List[bytes]]:
78
+ level = sorted(bytes.fromhex(x[2:]) for x in leaves)
79
+ levels = [level]
80
+ while len(level) > 1:
81
+ nxt = [_node(level[i], level[i + 1]) for i in range(0, len(level) - 1, 2)]
82
+ if len(level) % 2:
83
+ nxt.append(level[-1])
84
+ levels.append(nxt)
85
+ level = nxt
86
+ return levels
87
+
88
+
89
+ def merkle_root(leaves: List[str]) -> Optional[str]:
90
+ return "0x" + _levels(leaves)[-1][0].hex() if leaves else None
91
+
92
+
93
+ def merkle_proof(leaves: List[str], leaf: str) -> List[str]:
94
+ levels = _levels(leaves)
95
+ index = levels[0].index(bytes.fromhex(leaf[2:]))
96
+ proof = []
97
+ for level in levels[:-1]:
98
+ if index ^ 1 < len(level):
99
+ proof.append("0x" + level[index ^ 1].hex())
100
+ index //= 2
101
+ return proof
102
+
103
+
104
+ def verify_proof(leaf: str, proof: List[str], root: str) -> bool:
105
+ node = bytes.fromhex(leaf[2:])
106
+ for sibling in proof:
107
+ node = _node(node, bytes.fromhex(sibling[2:]))
108
+ return "0x" + node.hex() == (root or "").lower()
109
+
110
+
111
+ class Ledger:
112
+ """A seller's receipts ledger in one SQLite file (":memory:" for tests)."""
113
+
114
+ def __init__(self, path: str = "receipts.db"):
115
+ self._lock = threading.Lock()
116
+ self._db = sqlite3.connect(path, check_same_thread=False)
117
+ self._db.row_factory = sqlite3.Row
118
+ self._db.executescript(_SCHEMA)
119
+
120
+ def record(self, receipt_id: str, *, payer: str, amount_atomic: int, tx_hash: str,
121
+ settled_at: Optional[datetime] = None, resource: Optional[str] = None,
122
+ delivery_sha256: Optional[str] = None) -> bool:
123
+ """Add a settled receipt. True when added; False when the same receipt is already in (a retried call).
124
+ A different receipt under the same id is refused: the book never changes an entry."""
125
+ if not tx_hash or int(amount_atomic) <= 0:
126
+ raise ValueError("only a settled payment, with its transaction, goes in the book")
127
+ moment = (settled_at or datetime.now(timezone.utc)).astimezone(timezone.utc)
128
+ row = (receipt_id, _address(payer), int(amount_atomic), tx_hash.lower(), moment.strftime("%Y-%m"),
129
+ moment.isoformat(), resource, delivery_sha256)
130
+ with self._lock:
131
+ held = self._db.execute("SELECT * FROM receipts WHERE receipt_id = ?", (receipt_id,)).fetchone()
132
+ if held is not None:
133
+ if (held["payer"], held["amount_atomic"], held["tx_hash"]) != row[1:4]:
134
+ raise ValueError(f"receipt {receipt_id} is already in the book with other figures")
135
+ return False
136
+ with self._db:
137
+ self._db.execute("INSERT INTO receipts VALUES (?, ?, ?, ?, ?, ?, ?, ?)", row)
138
+ return True
139
+
140
+ def _month(self, period: str) -> List[Dict[str, Any]]:
141
+ return [dict(r) for r in self._db.execute(
142
+ "SELECT * FROM receipts WHERE period = ? ORDER BY receipt_id", (period,))]
143
+
144
+ def periods(self) -> List[str]:
145
+ return [r[0] for r in self._db.execute("SELECT DISTINCT period FROM receipts ORDER BY period")]
146
+
147
+ def view(self) -> Dict[str, Any]:
148
+ """The public ledger page: one root a month, how many receipts it holds and what they total."""
149
+ months = []
150
+ for period in self.periods():
151
+ rows = self._month(period)
152
+ months.append({"period": period, "receipts": len(rows),
153
+ "settled_atomic": str(sum(r["amount_atomic"] for r in rows)),
154
+ "merkle_root": merkle_root([leaf_hash(r) for r in rows])})
155
+ return {"months": months, "merkle": {"leaf": LEAF, "node": NODE},
156
+ "how": "Ask for a receipt's proof, hash its entry into the leaf, fold the proof and compare with the "
157
+ "month's merkle_root."}
158
+
159
+ def proof(self, receipt_id: str) -> Optional[Dict[str, Any]]:
160
+ """A receipt's entry, leaf and proof against its month's root, with the delivery hash beside it (outside
161
+ the leaf)."""
162
+ row = self._db.execute("SELECT * FROM receipts WHERE receipt_id = ?", (receipt_id,)).fetchone()
163
+ if row is None:
164
+ return None
165
+ leaves = [leaf_hash(r) for r in self._month(row["period"])]
166
+ entry = {k: row[k] for k in FIELDS}
167
+ leaf = leaf_hash(entry)
168
+ return {"period": row["period"], "entry": entry, "leaf": leaf, "proof": merkle_proof(leaves, leaf),
169
+ "merkle_root": merkle_root(leaves), "delivery_sha256": row["delivery_sha256"]}
170
+
171
+ def matches(self, payer: str) -> List[Dict[str, Any]]:
172
+ """Every receipt one buyer paid, so it can match its own payments against the book."""
173
+ return [{k: r[k] for k in (*FIELDS, "period")} for r in self._db.execute(
174
+ "SELECT * FROM receipts WHERE payer = ? ORDER BY settled_at", (_address(payer),))]
fair_meter/meter.py ADDED
@@ -0,0 +1,56 @@
1
+ # Copyright 2026 Kamkar Foundation, LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """FO-9, the price follows what was measured: the charge under the buyer's ceiling.
16
+
17
+ With x402's `upto` scheme the buyer signs a ceiling (a Permit2 authorization of at most that much). After the
18
+ work is done the seller settles only what was delivered: units times the one public unit price, never more than
19
+ the ceiling, and nothing when nothing was delivered. In the x402 Python SDK (2.25) the route handler tells the
20
+ middleware what to settle with the `Settlement-Overrides` response header; an amount of 0 settles nothing.
21
+ """
22
+
23
+ import json
24
+ from decimal import Decimal
25
+ from typing import Optional, Tuple
26
+
27
+ OVERRIDES_HEADER = "Settlement-Overrides"
28
+
29
+
30
+ def unit_atomic(unit_price_usd: str, decimals: int = 6) -> int:
31
+ """The unit price in the asset's smallest units (USDC has 6 decimals): "0.0002" is 200. A price that doesn't
32
+ divide exactly is refused, since every buyer must pay the same for a unit."""
33
+ scaled = Decimal(unit_price_usd) * (Decimal(10) ** decimals)
34
+ if scaled != scaled.to_integral_value() or scaled < 0:
35
+ raise ValueError(f"{unit_price_usd} is not a whole number of the asset's smallest units")
36
+ return int(scaled)
37
+
38
+
39
+ def charge(units: int, unit_price_atomic: int, ceiling_atomic: int) -> int:
40
+ """What was delivered at the unit price, capped at the ceiling the buyer signed."""
41
+ if units < 0 or unit_price_atomic < 0 or ceiling_atomic < 0:
42
+ raise ValueError("units, prices and ceilings are never negative")
43
+ return min(units * unit_price_atomic, ceiling_atomic)
44
+
45
+
46
+ def overrides(charged_atomic: int) -> Tuple[str, str]:
47
+ """The response header that settles only the measured charge."""
48
+ return OVERRIDES_HEADER, json.dumps({"amount": str(int(charged_atomic))})
49
+
50
+
51
+ def fits(units: int, unit_price_atomic: int, ceiling_atomic: int) -> Optional[int]:
52
+ """How many units the ceiling pays for when `units` would cost more, else None. A seller that would deliver
53
+ more than the buyer signed for delivers this many instead, so the charge always matches the delivery."""
54
+ if unit_price_atomic and units * unit_price_atomic > ceiling_atomic:
55
+ return ceiling_atomic // unit_price_atomic
56
+ return None
fair_meter/pledge.py ADDED
@@ -0,0 +1,106 @@
1
+ # Copyright 2026 Kamkar Foundation, LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """FO-7, promises are verifiable: a public share of what a seller earns, paid once a month and proven in the open.
16
+
17
+ A seller that promises a share of its revenue to a cause publishes a pledge ledger in the standard's shape
18
+ (schema/pledge-ledger-0.1.schema.json): its terms, a proof URL per receipt, and month by month the Merkle root of the
19
+ receipts settled, the basis, the share, the recipient and the transfers made. `ledger_doc` builds that page from the
20
+ kit's receipts ledger (fair_meter.ledger), so the roots are the same ones the ledger publishes.
21
+
22
+ What a month owes is the share of its basis, rounded up to the next atomic unit, so the cause never loses a fraction.
23
+ Small sums follow the rule `carry-1`, Agoranome's: a month that owes under $1 carries over and shows as owed, and
24
+ nothing is carried past the end of a quarter. `standing` runs it over the months as a running balance of what was
25
+ owed less what was given: "kept", "carried" (under $1 left, inside the quarter) or "owed" (a transfer is due).
26
+
27
+ The transfers themselves are USDC payments on Base to the recipient; a buyer, or Agoranome's inspector, reads each
28
+ transaction on the chain. This module states the figures; it moves no money.
29
+ """
30
+
31
+ import math
32
+ from typing import Any, Dict, Iterable, List, Optional
33
+
34
+ from fair_meter.ledger import LEAF, Ledger
35
+
36
+ KIND = "fair-offer.pledge-ledger/1"
37
+ GRACE_DAYS = 45
38
+ CARRY_UNDER = 1_000_000 # $1 in USDC's six decimals
39
+ CARRY_RULE = "carry-1"
40
+ # The schema's own words for the same construction as fair_meter.ledger's LEAF and NODE.
41
+ SCHEMA_NODE = "sha256(0x01 || min(a, b) || max(a, b)); leaves sorted, an odd node carried up unchanged"
42
+
43
+
44
+ def owed(basis_atomic: int, share_bps: int) -> int:
45
+ """The share of `basis_atomic`, in basis points, rounded up to the next atomic unit."""
46
+ if not 0 < share_bps <= 10_000:
47
+ raise ValueError("share_bps must be between 1 and 10000")
48
+ return -(-int(basis_atomic) * share_bps // 10_000)
49
+
50
+
51
+ def quarter_ends(period: str) -> bool:
52
+ return int(period[5:7]) % 3 == 0
53
+
54
+
55
+ def standing(months: Iterable[Dict[str, Any]]) -> List[Dict[str, Any]]:
56
+ """carry-1 over months given as {period, owed_atomic, given_atomic}, in period order."""
57
+ balance, out = 0, []
58
+ for m in sorted(months, key=lambda m: m["period"]):
59
+ balance += int(m["owed_atomic"]) - int(m["given_atomic"])
60
+ state = ("kept" if balance <= 0 else
61
+ "carried" if balance < CARRY_UNDER and not quarter_ends(m["period"]) else "owed")
62
+ out.append({"period": m["period"], "owed_atomic": str(m["owed_atomic"]),
63
+ "given_atomic": str(m["given_atomic"]), "balance_atomic": str(max(balance, 0)),
64
+ "standing": state})
65
+ return out
66
+
67
+
68
+ def ledger_doc(book: Ledger, *, share_bps: int, proof_url: str, recipient: Optional[str] = None,
69
+ basis: str = "settled revenue", transfers: Optional[Dict[str, List[Dict[str, Any]]]] = None
70
+ ) -> Dict[str, Any]:
71
+ """The pledge ledger page (FO-7) from the receipts ledger. `transfers` maps a month to the transfers made for it,
72
+ each {tx_hash, amount_atomic}: what the seller sent the recipient, which anyone can read on the chain."""
73
+ if "{receipt_id}" not in proof_url:
74
+ raise ValueError("proof_url must hold {receipt_id}, where each receipt's proof answers")
75
+ if recipient is not None and not (len(recipient) == 42 and recipient.lower().startswith("0x")):
76
+ raise ValueError("recipient must be the cause's address on Base")
77
+ share = share_bps / 10_000
78
+ transfers = transfers or {}
79
+ rows = []
80
+ for month in book.view()["months"]:
81
+ basis_atomic = int(month["settled_atomic"])
82
+ sent = transfers.get(month["period"]) or []
83
+ rows.append({"period": month["period"], "merkle_root": month["merkle_root"], "receipts": month["receipts"],
84
+ "basis_atomic": str(basis_atomic), "share": share,
85
+ "recipient": recipient.lower() if recipient else None,
86
+ "donations": [t["tx_hash"].lower() for t in sent],
87
+ "owed_atomic": str(owed(basis_atomic, share_bps)),
88
+ "given_atomic": str(sum(int(t["amount_atomic"]) for t in sent))})
89
+ states = {r["period"]: r for r in standing(rows)}
90
+ for r in rows:
91
+ r["standing"] = states[r["period"]]["standing"]
92
+ return {"kind": KIND, "terms": {"share": share, "basis": basis,
93
+ "recipient": recipient.lower() if recipient else None},
94
+ "proof": proof_url, "leaf": LEAF, "node": SCHEMA_NODE,
95
+ "grace_days": GRACE_DAYS, "small_sums": CARRY_RULE, "months": rows}
96
+
97
+
98
+ def kept(month: Dict[str, Any], transferred_atomic: int) -> bool:
99
+ """Whether a month's transfers (as read on the chain) reach its share of the basis (the schema's check)."""
100
+ share_bps = round(float(month["share"]) * 10_000)
101
+ return transferred_atomic >= owed(int(month["basis_atomic"]), share_bps)
102
+
103
+
104
+ def at_bar(cost_usd: float, share_bps: int) -> float:
105
+ """What a seller must earn a month to cover `cost_usd` after the share: cost / (1 - share)."""
106
+ return math.ceil(cost_usd / (1 - share_bps / 10_000) * 100) / 100
fair_meter/receipt.py ADDED
@@ -0,0 +1,94 @@
1
+ # Copyright 2026 Kamkar Foundation, LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """FO-3, receipts are signed and (0.4) bound to what was delivered.
16
+
17
+ A receipt says what was bought, from whom, for how much and when, and names the SHA-256 of the RFC 8785 form of
18
+ the result it came with. It is signed with an EVM key (EIP-191 personal_sign over the receipt's RFC 8785 bytes),
19
+ so any EIP-191 library checks it and the signer can be the seller's pay-to address. A metered receipt (FO-9) also
20
+ names the ceiling the buyer signed for and the units delivered.
21
+
22
+ Signing needs `eth-account` (installed with the x402 SDK, or `pip install fair-meter[eth]`).
23
+ """
24
+
25
+ from datetime import datetime, timezone
26
+ from typing import Any, Dict, Optional
27
+
28
+ from fair_meter.jcs import canonical, delivery
29
+
30
+ SIGNATURE_SCHEME = "eip191-jcs"
31
+
32
+
33
+ def build(*, receipt_id: str, resource: str, network: str, asset: str, pay_to: str, amount_atomic: int,
34
+ result: Any, payer: Optional[str] = None, issued_at: Optional[str] = None,
35
+ ceiling_atomic: Optional[int] = None, units: Optional[int] = None,
36
+ unit: Optional[str] = None) -> Dict[str, Any]:
37
+ """The receipt for one paid result. Amounts are strings of the asset's smallest units."""
38
+ receipt: Dict[str, Any] = {
39
+ "receipt_id": receipt_id, "resource": resource, "network": network, "asset": asset,
40
+ "pay_to": pay_to.lower() if pay_to.lower().startswith("0x") else pay_to,
41
+ "amount_atomic": str(int(amount_atomic)),
42
+ "issued_at": issued_at or datetime.now(timezone.utc).isoformat(),
43
+ "delivery": delivery(result),
44
+ }
45
+ if payer:
46
+ receipt["payer"] = payer.lower() if payer.lower().startswith("0x") else payer
47
+ if ceiling_atomic is not None:
48
+ if int(amount_atomic) > int(ceiling_atomic):
49
+ raise ValueError("a metered charge is never more than the ceiling the buyer signed (FO-9)")
50
+ receipt["ceiling_atomic"] = str(int(ceiling_atomic))
51
+ if units is not None:
52
+ receipt["units"] = int(units)
53
+ if unit:
54
+ receipt["unit"] = unit
55
+ return receipt
56
+
57
+
58
+ def sign(receipt: Dict[str, Any], private_key: Any) -> Dict[str, Any]:
59
+ """The signature block for a receipt, by an EVM key (a hex string or an eth-account LocalAccount)."""
60
+ from eth_account import Account
61
+ from eth_account.messages import encode_defunct
62
+
63
+ account = private_key if hasattr(private_key, "sign_message") else Account.from_key(private_key)
64
+ signed = account.sign_message(encode_defunct(primitive=canonical(receipt)))
65
+ return {"scheme": SIGNATURE_SCHEME, "signer": account.address.lower(),
66
+ "value": "0x" + bytes(signed.signature).hex()}
67
+
68
+
69
+ def attach(result: Any, receipt: Dict[str, Any], private_key: Any) -> Dict[str, Any]:
70
+ """The paid body: the result, its receipt and the receipt's signature."""
71
+ return {"result": result, "receipt": receipt, "signature": sign(receipt, private_key)}
72
+
73
+
74
+ def verify(body: Dict[str, Any], signer: Optional[str] = None) -> bool:
75
+ """A paid body's receipt is signed by its stated signer (and by `signer`, when given), and bound to its
76
+ result. What a buyer runs on what it received."""
77
+ from eth_account import Account
78
+ from eth_account.messages import encode_defunct
79
+
80
+ receipt, signature = body.get("receipt") or {}, body.get("signature") or {}
81
+ if signature.get("scheme") != SIGNATURE_SCHEME or not bound(body.get("result"), receipt):
82
+ return False
83
+ try:
84
+ found = Account.recover_message(encode_defunct(primitive=canonical(receipt)),
85
+ signature=str(signature.get("value", "")))
86
+ except Exception:
87
+ return False
88
+ claimed = str(signature.get("signer") or "").lower()
89
+ return found.lower() == claimed and (signer is None or claimed == signer.lower())
90
+
91
+
92
+ def bound(result: Any, receipt: Dict[str, Any]) -> bool:
93
+ """The receipt names the hash of this very result."""
94
+ return (receipt.get("delivery") or {}).get("sha256") == delivery(result)["sha256"]
@@ -0,0 +1,125 @@
1
+ Metadata-Version: 2.4
2
+ Name: fair-meter
3
+ Version: 0.2.0
4
+ Summary: What an x402 seller needs to keep the Fair Offer Standard 0.4: the block, the metered charge, bound receipts, the FO-6 guard and an open receipts ledger.
5
+ License: Apache-2.0
6
+ Project-URL: Standard, https://agoranome.com/standard
7
+ Project-URL: Source, https://github.com/Agoranome/fair-offer/tree/main/kit
8
+ Requires-Python: >=3.10
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Provides-Extra: eth
12
+ Requires-Dist: eth-account>=0.10; extra == "eth"
13
+ Provides-Extra: test
14
+ Requires-Dist: pytest>=7; extra == "test"
15
+ Requires-Dist: jsonschema>=4; extra == "test"
16
+ Requires-Dist: eth-account>=0.10; extra == "test"
17
+ Dynamic: license-file
18
+
19
+ # fair-meter: the Fair Offer kit for x402 sellers
20
+
21
+ What a seller needs to keep the [Fair Offer Standard 0.4](https://agoranome.com/standard), in one small Python
22
+ package with no required dependencies:
23
+
24
+ | Module | Rule | What it does |
25
+ | --- | --- | --- |
26
+ | `fair_meter.declare` | FO-2 to FO-10 | Builds the `fair-offer` block for your 402, refusing anything the 0.4 schema doesn't allow. |
27
+ | `fair_meter.meter` | FO-9 | The charge under the buyer's ceiling with x402's `upto`: units times one public unit price, never more than the ceiling, nothing when nothing was delivered. |
28
+ | `fair_meter.receipt` | FO-3 | A receipt bound to the SHA-256 of the RFC 8785 form of the result, signed with an EVM key (EIP-191). |
29
+ | `fair_meter.guard` | FO-6 | Finds text that reads as an instruction to the buying agent in any string of a response, however it is hidden. |
30
+ | `fair_meter.ledger` | FO-10 | A receipts ledger that only grows, one Merkle root a month, a proof per receipt. |
31
+ | `fair_meter.pledge` | FO-7 | A public share paid once a month: the pledge ledger page (the standard's schema) from the receipts ledger, with each month's standing under the small-sums rule. |
32
+ | `fair_meter.jcs` | | RFC 8785, the canonical JSON the delivery hash is taken over. |
33
+
34
+ Signing receipts needs `eth-account`, which the x402 SDK already installs. Licence: Apache-2.0 (the standard's
35
+ text, schema and examples in the rest of this repository are CC BY 4.0).
36
+
37
+ ## Install
38
+
39
+ From this repository until it is published:
40
+
41
+ ```
42
+ pip install "git+https://github.com/Agoranome/fair-offer.git#subdirectory=kit"
43
+ ```
44
+
45
+ ## A metered route with the x402 SDK (Python, 2.25)
46
+
47
+ Register x402's `upto` scheme beside `exact` (the facilitator must list `upto` on your network), offer the metered
48
+ route with both, and declare the block:
49
+
50
+ ```python
51
+ from x402.mechanisms.evm.exact import ExactEvmServerScheme
52
+ from x402.mechanisms.evm.upto import UptoEvmServerScheme
53
+ from fair_meter import declare
54
+
55
+ server.register(NETWORK, ExactEvmServerScheme())
56
+ server.register(NETWORK, UptoEvmServerScheme())
57
+
58
+ BLOCK = declare.extension(declare.block(
59
+ signer=RECEIPT_ADDRESS, # the address that signs receipts
60
+ sample="/v1/rows/sample",
61
+ meter=declare.metered("row", "0.0002"), # one public price a row (FO-9)
62
+ ledger="/receipts/ledger", reports=None, # the open book (FO-10)
63
+ ))
64
+ # On the route's config: both options at the same price (for upto it is the ceiling), and extensions=BLOCK.
65
+ ```
66
+
67
+ In the handler, guard the result, settle only what was delivered, sign the receipt and put it in the book once the
68
+ payment settles:
69
+
70
+ ```python
71
+ from fair_meter import guard, meter, receipt
72
+
73
+ UNIT = meter.unit_atomic("0.0002") # 200 units of USDC
74
+
75
+ async def rows(request):
76
+ requirements = request.state.payment_requirements
77
+ found = guard.guard(lookup(request)) # FO-6: refuse to send instructions; the failed call isn't settled
78
+ charged = len(found["rows"]) * UNIT
79
+ if requirements.scheme == "upto":
80
+ charged = meter.charge(len(found["rows"]), UNIT, int(requirements.amount))
81
+ paid = receipt.build(receipt_id=new_id(), resource=str(request.url), network=requirements.network,
82
+ asset=requirements.asset, pay_to=requirements.pay_to, amount_atomic=charged,
83
+ result=found, ceiling_atomic=int(requirements.amount), units=len(found["rows"]),
84
+ unit="row")
85
+ response = JSONResponse(receipt.attach(found, paid, RECEIPT_KEY))
86
+ if requirements.scheme == "upto":
87
+ name, value = meter.overrides(charged) # the middleware settles this amount, never the ceiling
88
+ response.headers[name] = value
89
+ return response
90
+ ```
91
+
92
+ When the facilitator returns the settlement, record it: `book.record(receipt_id, payer=..., amount_atomic=...,
93
+ tx_hash=...)`, and serve `book.view()` at your ledger path and `book.proof(receipt_id)` beside it. A metered call
94
+ that charged nothing has no transaction and stays out of the book.
95
+
96
+ Read the field names on `requirements` from your SDK version; the shape above is the 2.25 Python SDK's.
97
+
98
+ ## A public share (FO-7)
99
+
100
+ If you promise a share of what you earn to a cause, publish the pledge ledger beside the receipts ledger:
101
+
102
+ from fair_meter import pledge
103
+ page = pledge.ledger_doc(book, share_bps=1500, proof_url="https://you.example/receipts/{receipt_id}/proof",
104
+ recipient=CAUSE, transfers={"2026-11": [{"tx_hash": "0x...", "amount_atomic": 300000}]})
105
+
106
+ Each month shows its root, its basis, what it owes (the share, rounded up), what was sent and its standing: a month
107
+ that owes under $1 carries over and shows as owed, and nothing is carried past the end of a quarter (`carry-1`).
108
+ Send one USDC transfer on Base to the recipient each month; anyone can read it on the chain.
109
+
110
+ ## What a buyer checks
111
+
112
+ - `receipt.verify(body)` (or any EIP-191 library over the receipt's RFC 8785 bytes): the receipt is signed by its
113
+ signer and names the hash of the result it came with.
114
+ - `agoranome-inspector check-delivery answer.json` recomputes the delivery hash with no trust in the seller.
115
+ - The ledger's month roots fold every receipt's proof; Agoranome's inspector can copy them into its open book
116
+ (`anchor-lab`) so a past month can't be changed quietly (`verify-receipt`).
117
+ - `https://api.agoranome.com/v1/fair-offer/check?url=` reads your live 402 against your block, free.
118
+
119
+ ## Tests
120
+
121
+ ```
122
+ cd kit && pip install -e ".[test]" && pytest
123
+ ```
124
+
125
+ The ledger's roots are tested against the construction Agoranome's lab ledger uses, so the same tools check both.
@@ -0,0 +1,13 @@
1
+ fair_meter/__init__.py,sha256=WjYOmegu2S5oS2CYWpJHNunRuma6nVZ90QnVfLE5rwg,1443
2
+ fair_meter/declare.py,sha256=SIkZ0Y3jiBavXZB79n_J_LM3YkfDtPPaJNyz0IV6G1E,5173
3
+ fair_meter/guard.py,sha256=JnkwlF4DWVRT_k4MUvTejNxV8bKn29MB3VoyHGbA3Xs,4677
4
+ fair_meter/jcs.py,sha256=ovbMjI7bL9gsuYBXpEWiDbPOICeoizyLTa853FHxyE8,3007
5
+ fair_meter/ledger.py,sha256=XK0M6d2_FHIXTOAhpKGs0zg5mn1W6ZCl77XLP2colf4,7863
6
+ fair_meter/meter.py,sha256=izvA6mIpfikFSAnR-ARz4ZWFIY20m_dPRQn76u2CTho,2751
7
+ fair_meter/pledge.py,sha256=dyh9UwKIQZouPTHQD7-oUmFXsZp3_0WUoAs-a5PoTqE,5774
8
+ fair_meter/receipt.py,sha256=uk9497SdZ3zb-RsfmJYY7Z-mBuQZpZfQzXe_iN-RRSg,4530
9
+ fair_meter-0.2.0.dist-info/licenses/LICENSE,sha256=qsc7MUj20dcRHbyjIJn2jSbGRMaBOuHk8F9leaomY_4,11360
10
+ fair_meter-0.2.0.dist-info/METADATA,sha256=ISkG9Bw-lDGoGiGfFfrYYYS_VTWeuohw5n24YTH8n-c,6310
11
+ fair_meter-0.2.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
12
+ fair_meter-0.2.0.dist-info/top_level.txt,sha256=WprupnWsN9NFLrOdYcg6Qki18aVTpY0eUsvTwkNSrMs,11
13
+ fair_meter-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ https://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ https://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1 @@
1
+ fair_meter