fair-meter 0.2.0__tar.gz

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.
@@ -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,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,107 @@
1
+ # fair-meter: the Fair Offer kit for x402 sellers
2
+
3
+ What a seller needs to keep the [Fair Offer Standard 0.4](https://agoranome.com/standard), in one small Python
4
+ package with no required dependencies:
5
+
6
+ | Module | Rule | What it does |
7
+ | --- | --- | --- |
8
+ | `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. |
9
+ | `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. |
10
+ | `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). |
11
+ | `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. |
12
+ | `fair_meter.ledger` | FO-10 | A receipts ledger that only grows, one Merkle root a month, a proof per receipt. |
13
+ | `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. |
14
+ | `fair_meter.jcs` | | RFC 8785, the canonical JSON the delivery hash is taken over. |
15
+
16
+ Signing receipts needs `eth-account`, which the x402 SDK already installs. Licence: Apache-2.0 (the standard's
17
+ text, schema and examples in the rest of this repository are CC BY 4.0).
18
+
19
+ ## Install
20
+
21
+ From this repository until it is published:
22
+
23
+ ```
24
+ pip install "git+https://github.com/Agoranome/fair-offer.git#subdirectory=kit"
25
+ ```
26
+
27
+ ## A metered route with the x402 SDK (Python, 2.25)
28
+
29
+ Register x402's `upto` scheme beside `exact` (the facilitator must list `upto` on your network), offer the metered
30
+ route with both, and declare the block:
31
+
32
+ ```python
33
+ from x402.mechanisms.evm.exact import ExactEvmServerScheme
34
+ from x402.mechanisms.evm.upto import UptoEvmServerScheme
35
+ from fair_meter import declare
36
+
37
+ server.register(NETWORK, ExactEvmServerScheme())
38
+ server.register(NETWORK, UptoEvmServerScheme())
39
+
40
+ BLOCK = declare.extension(declare.block(
41
+ signer=RECEIPT_ADDRESS, # the address that signs receipts
42
+ sample="/v1/rows/sample",
43
+ meter=declare.metered("row", "0.0002"), # one public price a row (FO-9)
44
+ ledger="/receipts/ledger", reports=None, # the open book (FO-10)
45
+ ))
46
+ # On the route's config: both options at the same price (for upto it is the ceiling), and extensions=BLOCK.
47
+ ```
48
+
49
+ In the handler, guard the result, settle only what was delivered, sign the receipt and put it in the book once the
50
+ payment settles:
51
+
52
+ ```python
53
+ from fair_meter import guard, meter, receipt
54
+
55
+ UNIT = meter.unit_atomic("0.0002") # 200 units of USDC
56
+
57
+ async def rows(request):
58
+ requirements = request.state.payment_requirements
59
+ found = guard.guard(lookup(request)) # FO-6: refuse to send instructions; the failed call isn't settled
60
+ charged = len(found["rows"]) * UNIT
61
+ if requirements.scheme == "upto":
62
+ charged = meter.charge(len(found["rows"]), UNIT, int(requirements.amount))
63
+ paid = receipt.build(receipt_id=new_id(), resource=str(request.url), network=requirements.network,
64
+ asset=requirements.asset, pay_to=requirements.pay_to, amount_atomic=charged,
65
+ result=found, ceiling_atomic=int(requirements.amount), units=len(found["rows"]),
66
+ unit="row")
67
+ response = JSONResponse(receipt.attach(found, paid, RECEIPT_KEY))
68
+ if requirements.scheme == "upto":
69
+ name, value = meter.overrides(charged) # the middleware settles this amount, never the ceiling
70
+ response.headers[name] = value
71
+ return response
72
+ ```
73
+
74
+ When the facilitator returns the settlement, record it: `book.record(receipt_id, payer=..., amount_atomic=...,
75
+ tx_hash=...)`, and serve `book.view()` at your ledger path and `book.proof(receipt_id)` beside it. A metered call
76
+ that charged nothing has no transaction and stays out of the book.
77
+
78
+ Read the field names on `requirements` from your SDK version; the shape above is the 2.25 Python SDK's.
79
+
80
+ ## A public share (FO-7)
81
+
82
+ If you promise a share of what you earn to a cause, publish the pledge ledger beside the receipts ledger:
83
+
84
+ from fair_meter import pledge
85
+ page = pledge.ledger_doc(book, share_bps=1500, proof_url="https://you.example/receipts/{receipt_id}/proof",
86
+ recipient=CAUSE, transfers={"2026-11": [{"tx_hash": "0x...", "amount_atomic": 300000}]})
87
+
88
+ Each month shows its root, its basis, what it owes (the share, rounded up), what was sent and its standing: a month
89
+ that owes under $1 carries over and shows as owed, and nothing is carried past the end of a quarter (`carry-1`).
90
+ Send one USDC transfer on Base to the recipient each month; anyone can read it on the chain.
91
+
92
+ ## What a buyer checks
93
+
94
+ - `receipt.verify(body)` (or any EIP-191 library over the receipt's RFC 8785 bytes): the receipt is signed by its
95
+ signer and names the hash of the result it came with.
96
+ - `agoranome-inspector check-delivery answer.json` recomputes the delivery hash with no trust in the seller.
97
+ - The ledger's month roots fold every receipt's proof; Agoranome's inspector can copy them into its open book
98
+ (`anchor-lab`) so a past month can't be changed quietly (`verify-receipt`).
99
+ - `https://api.agoranome.com/v1/fair-offer/check?url=` reads your live 402 against your block, free.
100
+
101
+ ## Tests
102
+
103
+ ```
104
+ cd kit && pip install -e ".[test]" && pytest
105
+ ```
106
+
107
+ The ledger's roots are tested against the construction Agoranome's lab ledger uses, so the same tools check both.
@@ -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"
@@ -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}}}
@@ -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