usdf 0.1.2__tar.gz → 0.1.3__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.
@@ -1,3 +1,22 @@
1
+ Metadata-Version: 2.5
2
+ Name: usdf
3
+ Version: 0.1.3
4
+ Summary: Client for the USDF metered inference gateway: every listed model and tool at or below list price, with zero retention by default. Run a prompt paid from a prepaid key or per request with x402 in USDF or USDG, OpenAI-compatible chat completions with receipts, batch jobs, quotes, balances, keys, links, agents, and a LangChain chat model.
5
+ Project-URL: Homepage, https://usdf.fi
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ Keywords: inference,langchain,openai-compatible,receipts,robinhood-chain,usdf,x402
9
+ Classifier: Operating System :: OS Independent
10
+ Classifier: Programming Language :: Python :: 3
11
+ Requires-Python: >=3.9
12
+ Provides-Extra: httpx
13
+ Requires-Dist: httpx>=0.27; extra == 'httpx'
14
+ Provides-Extra: langchain
15
+ Requires-Dist: langchain-core>=0.3; extra == 'langchain'
16
+ Provides-Extra: wallet
17
+ Requires-Dist: eth-account>=0.13; extra == 'wallet'
18
+ Description-Content-Type: text/markdown
19
+
1
20
  # usdf
2
21
 
3
22
  Client for the USDF metered inference gateway, and a LangChain chat model. No required dependencies: the standard library's `urllib`, or `httpx` when it is installed. Python 3.9+. Paying from a wallet uses `eth-account`; the LangChain model uses `langchain-core`.
@@ -15,7 +34,7 @@ from usdf import USDF
15
34
 
16
35
  # Pay per request from a wallet, no account: an eth-account account (or a private key).
17
36
  client = USDF(wallet=wallet)
18
- result = client.run("deepseek-v3.2", "Hello")
37
+ result = client.run("deepseek-v3.2", "Hello", max_tokens=16384)
19
38
  print(result.text, result.receipt.paid.usdf, result.receipt.asset)
20
39
 
21
40
  # Or charge a prepaid balance with an API key.
@@ -30,7 +49,9 @@ Unset, `api_key`, `base_url` (the gateway origin, default `https://api.usdf.fi`)
30
49
 
31
50
  ### Paying from a wallet (x402)
32
51
 
33
- The gateway answers an unpaid request with 402 and two accepted payments for the same amount: USDF through Permit2 and USDG through an EIP-3009 authorization. Neither costs the payer gas. The client reads the wallet's USDF allowance to Permit2 first, through `rpc_url` (or `USDF_RPC_URL`; unset, the chain's public RPC `https://rpc.mainnet.chain.robinhood.com`), which must answer for chain 4663: when it covers the amount it pays in USDF, otherwise in USDG, which needs no approval. A first-time payer whose USDF is not approved therefore pays USDG rather than a USDF payment the gateway would refuse. `asset="USDF"` or `"USDG"` fixes the choice; `approve=True` signs and sends the one approval a USDF payer ever needs, `approve(Permit2, max)` on USDF, through the same RPC. The receipt carries `paid` (what was charged, the quote), `usage_cost`, and the payment's `asset`, `method`, `payer` and `payment_tx`.
52
+ The gateway answers an unpaid request with 402 and two accepted payments for the same amount: USDF through Permit2 and USDG through an EIP-3009 authorization. Neither costs the payer gas. The client reads the wallet's USDF allowance to Permit2 first, through `rpc_url` (or `USDF_RPC_URL`; unset, the chain's public RPC `https://rpc.mainnet.chain.robinhood.com`), which must answer for chain 4663: when it covers the amount it pays in USDF, otherwise in USDG, which needs no approval. A first-time payer whose USDF is not approved therefore pays USDG rather than a USDF payment the gateway would refuse. `asset="USDF"` or `"USDG"` fixes the choice; `approve=True` signs and sends the one approval a USDF payer ever needs, `approve(Permit2, max)` on USDF, through the same RPC. The receipt carries `paid` (what was charged: what the request used, at most the quote), `usage_cost`, and the payment's `asset`, `method`, `payer` and `payment_tx`.
53
+
54
+ A request is refused before anything is signed when its quote is below the gas of returning a payment at the chain's gas price now (`400 quote_below_refund_gas`, a few thousandths of a USDF; the message names it). A short prompt at the model's default output budget usually is, so pass a `max_tokens` that clears it, as above: the request is still charged only what it uses, and the rest is refunded.
34
55
 
35
56
  The 402 comes from whatever server answers at the base URL, so the client signs nothing on its word alone. It pays only: on Robinhood Chain (`eip155:4663`); USDF (`0x4A35a5eC2A50A4d2957B2F2366E017f526cAB318`) through Permit2 or USDG (`0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168`) through EIP-3009 under USDG's own domain (`Global Dollar`, version `1`); to the payee the gateway names: its own 402 when the base URL is the gateway (`https://api.usdf.fi`), else the address the gateway's `GET https://api.usdf.fi/v1/config` publishes (`x402.pay_to`), else the gateway's hot wallet (`0x13009Bd7116f8C955f92409467743ee67AB1990b`); `pay_to` (or `USDF_PAY_TO`, comma-separated) pins another payee, and then only that one; with a validity window of at most an hour; and at most `max_amount` base units per payment (`USDF_MAX_AMOUNT`; default 1000000, 1 USDF). Anything else raises `USDFError` with type `payment_refused` and a code (`untrusted_network`, `untrusted_asset`, `untrusted_domain`, `untrusted_payee`, `amount_over_limit`, `untrusted_amount`, `untrusted_timeout`, `wrong_chain`) before any approval, read or signature. The exact scheme charges the quote, the request's worst case at its `max_tokens`, so a lower `max_tokens` is the way to a smaller payment.
36
57
 
@@ -98,8 +119,64 @@ Money: base units (1 unit = $0.000001 = 0.000001 USDF); amounts are `Amount(unit
98
119
 
99
120
  Every refusal raises `USDFError` with the gateway's `status`, `type`, `code`, `message`, `request_id` and `retry_after`. Nothing is charged for a refusal.
100
121
 
122
+ ## Accept USDF on your x402 API (your own forwarder)
123
+
124
+ With your own forwarder, each payment goes from the payer straight to your forwarder contract, never through a wallet of Foundry's. `usdf.accept.AcceptUsdfX402` answers an unpaid request 402 with the USDF option (`PAYMENT-REQUIRED`, with your forwarder as `payTo`), built on your server with no call out. A request with a payment is verified and then settled by Foundry's facilitator with your facilitator key (`pfk_...`, from `USDF_FACILITATOR_KEY`); your route runs only after the payment settled, and the response carries `PAYMENT-RESPONSE`. Your forwarder's address and the key come from registering the forwarder on usdf.fi.
125
+
126
+ FastAPI:
127
+
128
+ ```python
129
+ from fastapi import Depends, FastAPI
130
+ from usdf.accept import AcceptUsdfX402, X402Payment
131
+
132
+ app = FastAPI()
133
+ paid = AcceptUsdfX402(forwarder="0xYourForwarder", price="0.001")
134
+
135
+ @app.get("/v1/thing")
136
+ async def thing(payment: X402Payment = Depends(paid)):
137
+ return {"ok": True, "tx": payment.transaction}
138
+ ```
139
+
140
+ Behind `Depends(paid)` an unpaid or refused request is answered for you: 402 with `PAYMENT-REQUIRED` (FastAPI puts the same JSON under `detail` in the body), 500 for a refused facilitator key, and 503 for a facilitator that is busy, down or slower than 15 seconds (with its `retry-after`). With Starlette or any other framework, take the decision yourself:
141
+
142
+ ```python
143
+ result = await paid.check(request) # a Starlette request; paid.charge(url, headers) is the same, synchronous
144
+ if not result.paid:
145
+ return Response(result.body, result.status, headers=result.headers)
146
+ # serve it, with result.headers (PAYMENT-RESPONSE) on the answer; result.payment is the settled payment
147
+ ```
148
+
149
+ Options: `forwarder` (required), `price` (USDF as a string, from `"0.001"` to `"10000"` with at most 6 decimals, or a function of the URL and headers), `api_key` (default `USDF_FACILITATOR_KEY`), `description`, `mime_type`, `resource_url`, `base_url` (default `USDF_BASE_URL`, else `https://api.usdf.fi`), `max_timeout_seconds` (default 300, at most 3600) and `timeout` (default 15 seconds). A bad option raises `ValueError` when you build it. `payment.amount` is in base units (`"1000"` is 0.001 USDF). No dependency of its own.
150
+
101
151
  ## Changes
102
152
 
153
+ **0.1.3.** `pricing()` and `models.list()` send the API key (or the session token) when the client has one. `GET /v1/pricing` answers only to a key or a signed-in session, and 0.1.2 called it without either, so it failed with 404. With neither set, both behave as 0.1.2.
154
+
103
155
  **0.1.2.** A wallet payment goes to the payee the gateway names, not to a hot wallet fixed in the package: the gateway rotated its custody hot wallet on 2026-10-26, and 0.1.1, which pays only the retired one (`0x52Fe...9F05`), refuses the new one's 402 with `untrusted_payee` before signing anything. The 402's payee is taken as it stands from `https://api.usdf.fi`; through any other base URL it must be the one `https://api.usdf.fi/v1/config` publishes, or the new hot wallet (`GATEWAY_PAYEE`). `pay_to` and `USDF_PAY_TO` still pin a payee.
104
156
 
105
157
  **0.1.1.** The default base URL is `https://api.usdf.fi`, the gateway's own domain; 0.1.0 used the hosting provider's hostname for the same gateway, which still answers. `base_url` or `USDF_BASE_URL` still points the client elsewhere. No other change.
158
+
159
+ ## Add funds from another chain
160
+
161
+ ```python
162
+ from usdf import USDF
163
+
164
+ usdf = USDF(api_key="sk_...")
165
+ routes = usdf.transit.routes("deposit")["data"]
166
+ q = usdf.transit.quote(42161, "USDC", 250_000_000, 4663, "USDG", sender=WALLET, recipient=WALLET)
167
+ # Sign usdf.transit.deposit_authorization(q["receive_units"])["typed_data"] with the wallet, record the order with it,
168
+ # then send q["approval"]["approve"] if needed and q["transaction"] (exactly its value) from the wallet.
169
+ order = usdf.transit.record(q["quote_token"], purpose="deposit", deposit_authorization={"authorization": ..., "signature": ...})
170
+ usdf.transit.submitted(order["id"], tx_hash)
171
+ done = usdf.transit.wait(order["id"]) # fulfilled, its deposit credited (or waiting for the wallet's signature)
172
+ ```
173
+
174
+ How payouts are converted is the account's payout preference, read and set with its own key or its session:
175
+ `usdf.transit.payout_preference()`, `usdf.transit.set_payout_preference(want_asset, destination_chain_id, destination_address=None)`
176
+ (USDC or USDG on 42161 or 1; no address is the linked wallet's own there) and `usdf.transit.clear_payout_preference()`.
177
+ With one, each paid payout the API shows carries `convert`, the conversion pre-filled. An address other than the linked
178
+ wallet is set from the signed-in session only, after a recent sign-in, and the account is emailed.
179
+
180
+ ## Staked USDF (sUSDF)
181
+
182
+ Public reads, no key: `usdf.susdf.get()`, `usdf.susdf.position(address)`, `usdf.susdf.history(address)`, `usdf.susdf.days(30)`, `usdf.susdf.eligibility()`. `usdf.susdf.quote("stake", address, amount="10")` answers the transactions the wallet signs and sends itself, in order; `quote("unstake", address, amount=... or all=True)` the same, paid at once (no request, cooldown or claim). The gateway signs and sends nothing. A stake quote carries the representation the stake makes ("By staking you confirm you don't live in the EU or EEA.") and is refused where sUSDF is not offered (451 `susdf_region_restricted`); an unstake never is.
@@ -1,22 +1,3 @@
1
- Metadata-Version: 2.5
2
- Name: usdf
3
- Version: 0.1.2
4
- Summary: Client for the USDF metered inference gateway: run a prompt paid from a prepaid key or per request with x402 in USDF or USDG, OpenAI-compatible chat completions with receipts, batch jobs, quotes, balances, keys, links, agents, and a LangChain chat model.
5
- Project-URL: Homepage, https://usdf.fi
6
- License-Expression: MIT
7
- License-File: LICENSE
8
- Keywords: inference,langchain,openai-compatible,receipts,robinhood-chain,usdf,x402
9
- Classifier: Operating System :: OS Independent
10
- Classifier: Programming Language :: Python :: 3
11
- Requires-Python: >=3.9
12
- Provides-Extra: httpx
13
- Requires-Dist: httpx>=0.27; extra == 'httpx'
14
- Provides-Extra: langchain
15
- Requires-Dist: langchain-core>=0.3; extra == 'langchain'
16
- Provides-Extra: wallet
17
- Requires-Dist: eth-account>=0.13; extra == 'wallet'
18
- Description-Content-Type: text/markdown
19
-
20
1
  # usdf
21
2
 
22
3
  Client for the USDF metered inference gateway, and a LangChain chat model. No required dependencies: the standard library's `urllib`, or `httpx` when it is installed. Python 3.9+. Paying from a wallet uses `eth-account`; the LangChain model uses `langchain-core`.
@@ -34,7 +15,7 @@ from usdf import USDF
34
15
 
35
16
  # Pay per request from a wallet, no account: an eth-account account (or a private key).
36
17
  client = USDF(wallet=wallet)
37
- result = client.run("deepseek-v3.2", "Hello")
18
+ result = client.run("deepseek-v3.2", "Hello", max_tokens=16384)
38
19
  print(result.text, result.receipt.paid.usdf, result.receipt.asset)
39
20
 
40
21
  # Or charge a prepaid balance with an API key.
@@ -49,7 +30,9 @@ Unset, `api_key`, `base_url` (the gateway origin, default `https://api.usdf.fi`)
49
30
 
50
31
  ### Paying from a wallet (x402)
51
32
 
52
- The gateway answers an unpaid request with 402 and two accepted payments for the same amount: USDF through Permit2 and USDG through an EIP-3009 authorization. Neither costs the payer gas. The client reads the wallet's USDF allowance to Permit2 first, through `rpc_url` (or `USDF_RPC_URL`; unset, the chain's public RPC `https://rpc.mainnet.chain.robinhood.com`), which must answer for chain 4663: when it covers the amount it pays in USDF, otherwise in USDG, which needs no approval. A first-time payer whose USDF is not approved therefore pays USDG rather than a USDF payment the gateway would refuse. `asset="USDF"` or `"USDG"` fixes the choice; `approve=True` signs and sends the one approval a USDF payer ever needs, `approve(Permit2, max)` on USDF, through the same RPC. The receipt carries `paid` (what was charged, the quote), `usage_cost`, and the payment's `asset`, `method`, `payer` and `payment_tx`.
33
+ The gateway answers an unpaid request with 402 and two accepted payments for the same amount: USDF through Permit2 and USDG through an EIP-3009 authorization. Neither costs the payer gas. The client reads the wallet's USDF allowance to Permit2 first, through `rpc_url` (or `USDF_RPC_URL`; unset, the chain's public RPC `https://rpc.mainnet.chain.robinhood.com`), which must answer for chain 4663: when it covers the amount it pays in USDF, otherwise in USDG, which needs no approval. A first-time payer whose USDF is not approved therefore pays USDG rather than a USDF payment the gateway would refuse. `asset="USDF"` or `"USDG"` fixes the choice; `approve=True` signs and sends the one approval a USDF payer ever needs, `approve(Permit2, max)` on USDF, through the same RPC. The receipt carries `paid` (what was charged: what the request used, at most the quote), `usage_cost`, and the payment's `asset`, `method`, `payer` and `payment_tx`.
34
+
35
+ A request is refused before anything is signed when its quote is below the gas of returning a payment at the chain's gas price now (`400 quote_below_refund_gas`, a few thousandths of a USDF; the message names it). A short prompt at the model's default output budget usually is, so pass a `max_tokens` that clears it, as above: the request is still charged only what it uses, and the rest is refunded.
53
36
 
54
37
  The 402 comes from whatever server answers at the base URL, so the client signs nothing on its word alone. It pays only: on Robinhood Chain (`eip155:4663`); USDF (`0x4A35a5eC2A50A4d2957B2F2366E017f526cAB318`) through Permit2 or USDG (`0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168`) through EIP-3009 under USDG's own domain (`Global Dollar`, version `1`); to the payee the gateway names: its own 402 when the base URL is the gateway (`https://api.usdf.fi`), else the address the gateway's `GET https://api.usdf.fi/v1/config` publishes (`x402.pay_to`), else the gateway's hot wallet (`0x13009Bd7116f8C955f92409467743ee67AB1990b`); `pay_to` (or `USDF_PAY_TO`, comma-separated) pins another payee, and then only that one; with a validity window of at most an hour; and at most `max_amount` base units per payment (`USDF_MAX_AMOUNT`; default 1000000, 1 USDF). Anything else raises `USDFError` with type `payment_refused` and a code (`untrusted_network`, `untrusted_asset`, `untrusted_domain`, `untrusted_payee`, `amount_over_limit`, `untrusted_amount`, `untrusted_timeout`, `wrong_chain`) before any approval, read or signature. The exact scheme charges the quote, the request's worst case at its `max_tokens`, so a lower `max_tokens` is the way to a smaller payment.
55
38
 
@@ -117,8 +100,64 @@ Money: base units (1 unit = $0.000001 = 0.000001 USDF); amounts are `Amount(unit
117
100
 
118
101
  Every refusal raises `USDFError` with the gateway's `status`, `type`, `code`, `message`, `request_id` and `retry_after`. Nothing is charged for a refusal.
119
102
 
103
+ ## Accept USDF on your x402 API (your own forwarder)
104
+
105
+ With your own forwarder, each payment goes from the payer straight to your forwarder contract, never through a wallet of Foundry's. `usdf.accept.AcceptUsdfX402` answers an unpaid request 402 with the USDF option (`PAYMENT-REQUIRED`, with your forwarder as `payTo`), built on your server with no call out. A request with a payment is verified and then settled by Foundry's facilitator with your facilitator key (`pfk_...`, from `USDF_FACILITATOR_KEY`); your route runs only after the payment settled, and the response carries `PAYMENT-RESPONSE`. Your forwarder's address and the key come from registering the forwarder on usdf.fi.
106
+
107
+ FastAPI:
108
+
109
+ ```python
110
+ from fastapi import Depends, FastAPI
111
+ from usdf.accept import AcceptUsdfX402, X402Payment
112
+
113
+ app = FastAPI()
114
+ paid = AcceptUsdfX402(forwarder="0xYourForwarder", price="0.001")
115
+
116
+ @app.get("/v1/thing")
117
+ async def thing(payment: X402Payment = Depends(paid)):
118
+ return {"ok": True, "tx": payment.transaction}
119
+ ```
120
+
121
+ Behind `Depends(paid)` an unpaid or refused request is answered for you: 402 with `PAYMENT-REQUIRED` (FastAPI puts the same JSON under `detail` in the body), 500 for a refused facilitator key, and 503 for a facilitator that is busy, down or slower than 15 seconds (with its `retry-after`). With Starlette or any other framework, take the decision yourself:
122
+
123
+ ```python
124
+ result = await paid.check(request) # a Starlette request; paid.charge(url, headers) is the same, synchronous
125
+ if not result.paid:
126
+ return Response(result.body, result.status, headers=result.headers)
127
+ # serve it, with result.headers (PAYMENT-RESPONSE) on the answer; result.payment is the settled payment
128
+ ```
129
+
130
+ Options: `forwarder` (required), `price` (USDF as a string, from `"0.001"` to `"10000"` with at most 6 decimals, or a function of the URL and headers), `api_key` (default `USDF_FACILITATOR_KEY`), `description`, `mime_type`, `resource_url`, `base_url` (default `USDF_BASE_URL`, else `https://api.usdf.fi`), `max_timeout_seconds` (default 300, at most 3600) and `timeout` (default 15 seconds). A bad option raises `ValueError` when you build it. `payment.amount` is in base units (`"1000"` is 0.001 USDF). No dependency of its own.
131
+
120
132
  ## Changes
121
133
 
134
+ **0.1.3.** `pricing()` and `models.list()` send the API key (or the session token) when the client has one. `GET /v1/pricing` answers only to a key or a signed-in session, and 0.1.2 called it without either, so it failed with 404. With neither set, both behave as 0.1.2.
135
+
122
136
  **0.1.2.** A wallet payment goes to the payee the gateway names, not to a hot wallet fixed in the package: the gateway rotated its custody hot wallet on 2026-10-26, and 0.1.1, which pays only the retired one (`0x52Fe...9F05`), refuses the new one's 402 with `untrusted_payee` before signing anything. The 402's payee is taken as it stands from `https://api.usdf.fi`; through any other base URL it must be the one `https://api.usdf.fi/v1/config` publishes, or the new hot wallet (`GATEWAY_PAYEE`). `pay_to` and `USDF_PAY_TO` still pin a payee.
123
137
 
124
138
  **0.1.1.** The default base URL is `https://api.usdf.fi`, the gateway's own domain; 0.1.0 used the hosting provider's hostname for the same gateway, which still answers. `base_url` or `USDF_BASE_URL` still points the client elsewhere. No other change.
139
+
140
+ ## Add funds from another chain
141
+
142
+ ```python
143
+ from usdf import USDF
144
+
145
+ usdf = USDF(api_key="sk_...")
146
+ routes = usdf.transit.routes("deposit")["data"]
147
+ q = usdf.transit.quote(42161, "USDC", 250_000_000, 4663, "USDG", sender=WALLET, recipient=WALLET)
148
+ # Sign usdf.transit.deposit_authorization(q["receive_units"])["typed_data"] with the wallet, record the order with it,
149
+ # then send q["approval"]["approve"] if needed and q["transaction"] (exactly its value) from the wallet.
150
+ order = usdf.transit.record(q["quote_token"], purpose="deposit", deposit_authorization={"authorization": ..., "signature": ...})
151
+ usdf.transit.submitted(order["id"], tx_hash)
152
+ done = usdf.transit.wait(order["id"]) # fulfilled, its deposit credited (or waiting for the wallet's signature)
153
+ ```
154
+
155
+ How payouts are converted is the account's payout preference, read and set with its own key or its session:
156
+ `usdf.transit.payout_preference()`, `usdf.transit.set_payout_preference(want_asset, destination_chain_id, destination_address=None)`
157
+ (USDC or USDG on 42161 or 1; no address is the linked wallet's own there) and `usdf.transit.clear_payout_preference()`.
158
+ With one, each paid payout the API shows carries `convert`, the conversion pre-filled. An address other than the linked
159
+ wallet is set from the signed-in session only, after a recent sign-in, and the account is emailed.
160
+
161
+ ## Staked USDF (sUSDF)
162
+
163
+ Public reads, no key: `usdf.susdf.get()`, `usdf.susdf.position(address)`, `usdf.susdf.history(address)`, `usdf.susdf.days(30)`, `usdf.susdf.eligibility()`. `usdf.susdf.quote("stake", address, amount="10")` answers the transactions the wallet signs and sends itself, in order; `quote("unstake", address, amount=... or all=True)` the same, paid at once (no request, cooldown or claim). The gateway signs and sends nothing. A stake quote carries the representation the stake makes ("By staking you confirm you don't live in the EU or EEA.") and is refused where sUSDF is not offered (451 `susdf_region_restricted`); an unstake never is.
@@ -4,8 +4,8 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "usdf"
7
- version = "0.1.2"
8
- description = "Client for the USDF metered inference gateway: run a prompt paid from a prepaid key or per request with x402 in USDF or USDG, OpenAI-compatible chat completions with receipts, batch jobs, quotes, balances, keys, links, agents, and a LangChain chat model."
7
+ version = "0.1.3"
8
+ description = "Client for the USDF metered inference gateway: every listed model and tool at or below list price, with zero retention by default. Run a prompt paid from a prepaid key or per request with x402 in USDF or USDG, OpenAI-compatible chat completions with receipts, batch jobs, quotes, balances, keys, links, agents, and a LangChain chat model."
9
9
  readme = "README.md"
10
10
  license = "MIT"
11
11
  license-files = ["LICENSE"]
@@ -0,0 +1,499 @@
1
+ """Accept USDF on your own x402 API, paid straight into a forwarder contract only you control.
2
+
3
+ AcceptUSDF (payments settled into Foundry's own settlement wallet and paid out later) is retired: it answers every
4
+ request 503 accept_usdf_retired, charges nothing and calls nothing. Use AcceptUsdfX402.
5
+
6
+ Take each payment straight into your own forwarder (AcceptUsdfX402): the 402 is built here, with your forwarder as
7
+ payTo, and a payment is verified and then settled by Foundry's facilitator (POST /v1/facilitator/verify, then
8
+ /v1/facilitator/settle, with your facilitator key, pfk_..., in USDF_FACILITATOR_KEY) from the payer to your forwarder,
9
+ never through a wallet of Foundry's. The route runs only once the settlement succeeded:
10
+
11
+ from fastapi import Depends, FastAPI
12
+ from usdf.accept import AcceptUsdfX402
13
+
14
+ app = FastAPI()
15
+ paid = AcceptUsdfX402(forwarder="0x...", price="0.001")
16
+
17
+ @app.get("/v1/thing")
18
+ async def thing(payment=Depends(paid)):
19
+ return {"tx": payment.transaction}
20
+
21
+ paid.charge(url, headers) gives the same decision for one request in any framework, and await paid.check(request) for
22
+ a Starlette request.
23
+
24
+ Standard library only."""
25
+
26
+ from __future__ import annotations
27
+
28
+ import asyncio
29
+ import base64
30
+ import time
31
+ import warnings
32
+ import json
33
+ import os
34
+ import re
35
+ import urllib.error
36
+ import urllib.parse
37
+ import urllib.request
38
+ from dataclasses import dataclass, field
39
+ from typing import Any, Callable, Dict, Iterable, List, Mapping, Optional, Tuple, Union
40
+
41
+ from ._http import Transport
42
+ from .x402 import CHAIN_ID, PERMIT2_ADDRESS, USDF_ADDRESS, USDG_ADDRESS, X402_EXACT_PERMIT2_PROXY
43
+
44
+ DEFAULT_FACILITATOR_URL = "https://api.usdf.fi"
45
+ _PRICE = re.compile(r"^\d{1,5}(\.\d{1,6})?$")
46
+
47
+
48
+ @dataclass
49
+ class Accepted:
50
+ """A settled payment: its transaction, payer and network, and what it came to for you."""
51
+
52
+ transaction: str
53
+ payer: str
54
+ network: str
55
+ amount: str
56
+ fee: str
57
+ paid_on: str
58
+ settle_as: str
59
+ settlement_id: str
60
+
61
+
62
+ @dataclass
63
+ class ChargeResult:
64
+ """paid: the payment settled (payment holds it; add headers to your answer). Otherwise answer with status,
65
+ headers and body instead of running the request."""
66
+
67
+ paid: bool
68
+ status: int = 200
69
+ headers: Dict[str, str] = field(default_factory=dict)
70
+ body: bytes = b""
71
+ payment: Optional[Accepted] = None
72
+
73
+
74
+ def _refusal(status: int, code: str, message: str) -> ChargeResult:
75
+ body = json.dumps({"error": {"message": message, "type": "payment_error", "code": code}}).encode()
76
+ return ChargeResult(paid=False, status=status, headers={"content-type": "application/json"}, body=body)
77
+
78
+
79
+ def _header(headers: Mapping[str, str], name: str) -> Optional[str]:
80
+ for k, v in headers.items():
81
+ if k.lower() == name:
82
+ return v
83
+ return None
84
+
85
+
86
+ ACCEPT_USDF_RETIRED = "this API's USDF payments are not set up: AcceptUSDF is retired (Foundry no longer takes payments into a wallet of its own); the server moves to AcceptUsdfX402 with its own forwarder (usdf.fi/docs/accept-usdf-x402); nothing was charged"
87
+
88
+
89
+ class AcceptUSDF:
90
+ """Retired: answers every request 503 accept_usdf_retired. Use AcceptUsdfX402 with your own forwarder."""
91
+
92
+ def __init__(
93
+ self,
94
+ price: Union[str, Callable[[str, Mapping[str, str]], str]],
95
+ api_key: Optional[str] = None,
96
+ settle_as: str = "usdf",
97
+ description: str = "",
98
+ mime_type: str = "application/json",
99
+ base_url: Optional[str] = None,
100
+ timeout: float = 30.0,
101
+ opener: Optional[Callable[..., Any]] = None,
102
+ ) -> None:
103
+ if settle_as not in ("usdf", "usdg"):
104
+ raise ValueError('settle_as is "usdf" or "usdg"')
105
+ self.price = price
106
+ self.api_key = api_key
107
+ self.settle_as = settle_as
108
+ self.description = description
109
+ self.mime_type = mime_type
110
+ self.base_url = (base_url or os.environ.get("USDF_BASE_URL") or DEFAULT_FACILITATOR_URL).rstrip("/")
111
+ self.timeout = timeout
112
+ self._open = opener or urllib.request.urlopen
113
+ warnings.warn("usdf.accept.AcceptUSDF is retired and answers every request 503; use AcceptUsdfX402 with your own forwarder (usdf.fi/docs/accept-usdf-x402)", DeprecationWarning, stacklevel=2)
114
+
115
+ def charge(self, url: str, headers: Mapping[str, str]) -> ChargeResult:
116
+ """Retired: every request answered 503 accept_usdf_retired; nothing charged, no call made."""
117
+ return _refusal(503, "accept_usdf_retired", ACCEPT_USDF_RETIRED)
118
+
119
+ def wsgi(self, app: Callable[..., Iterable[bytes]]) -> Callable[..., Iterable[bytes]]:
120
+ """A WSGI app that charges every request before `app` runs it (the payment in environ["usdf.payment"])."""
121
+
122
+ def wrapped(environ: Dict[str, Any], start_response: Callable[..., Any]) -> Iterable[bytes]:
123
+ headers = {k[5:].replace("_", "-").lower(): v for k, v in environ.items() if k.startswith("HTTP_")}
124
+ scheme = environ.get("HTTP_X_FORWARDED_PROTO", environ.get("wsgi.url_scheme", "https")).split(",")[0].strip()
125
+ host = environ.get("HTTP_X_FORWARDED_HOST") or environ.get("HTTP_HOST") or environ.get("SERVER_NAME", "localhost")
126
+ path = environ.get("PATH_INFO", "/") + (("?" + environ["QUERY_STRING"]) if environ.get("QUERY_STRING") else "")
127
+ result = self.charge(f"{'http' if scheme == 'http' else 'https'}://{host}{path}", headers)
128
+ if not result.paid:
129
+ reason = {402: "Payment Required", 429: "Too Many Requests", 500: "Internal Server Error"}.get(result.status, "Service Unavailable")
130
+ start_response(f"{result.status} {reason}", list(result.headers.items()))
131
+ return [result.body]
132
+ environ["usdf.payment"] = result.payment
133
+
134
+ def start(status: str, response_headers: list, exc_info: Any = None) -> Any:
135
+ return start_response(status, list(response_headers) + list(result.headers.items()), exc_info) if exc_info else start_response(status, list(response_headers) + list(result.headers.items()))
136
+
137
+ return app(environ, start)
138
+
139
+ return wrapped
140
+
141
+ # ── Your own forwarder: USDF on your x402 API, settled straight to it ─────────────────────────────────
142
+
143
+ # A facilitator key's prefix, and what one payment may be: from 0.001 to 10,000 USDF (base units, 6 decimals).
144
+ FACILITATOR_KEY_PREFIX = "pfk_"
145
+ X402_MIN_UNITS = 1_000
146
+ X402_MAX_UNITS = 10_000_000_000
147
+ # How long a payer's signature is good for, in seconds: 300 unless set, at most 3600 (the facilitator's bound).
148
+ X402_DEFAULT_TIMEOUT_SECONDS = 300
149
+ X402_MAX_TIMEOUT_SECONDS = 3600
150
+ # How long one facilitator call may take, in seconds, before the request is answered 503.
151
+ FACILITATOR_TIMEOUT = 15.0
152
+ NETWORK = f"eip155:{CHAIN_ID}"
153
+
154
+ _X402_PRICE = re.compile(r"[0-9]{1,5}(\.[0-9]{1,6})?")
155
+ _FACILITATOR_KEY = re.compile(r"pfk_[\x21-\x7e]{32,196}")
156
+ _HEX_ADDRESS = re.compile(r"0x[0-9a-fA-F]{40}")
157
+ _REASON = re.compile(r"[A-Za-z0-9_.:-]{1,100}")
158
+ _HEADER_VALUE = re.compile(r"[\x20-\x7e]{1,64}")
159
+ _B64 = re.compile(r"[A-Za-z0-9+/_-]+={0,2}")
160
+ _PAYMENT_HEADER_MAX = 32 * 1024
161
+ _NOT_A_FORWARDER = {a.lower() for a in ("0x" + "0" * 40, USDF_ADDRESS, USDG_ADDRESS, PERMIT2_ADDRESS, X402_EXACT_PERMIT2_PROXY)}
162
+ _PRICE_RULE = 'price is an amount of USDF as a decimal string, from 0.001 to 10000 with at most 6 decimals (for example "0.001")'
163
+
164
+
165
+ @dataclass
166
+ class X402Payment:
167
+ """A settled payment: its transaction, payer and network, and its amount in base units of USDF ("1000" is 0.001)."""
168
+
169
+ transaction: str
170
+ payer: str
171
+ network: str
172
+ amount: str
173
+
174
+
175
+ @dataclass
176
+ class X402ChargeResult:
177
+ """paid: the payment settled to your forwarder (payment holds it; add headers, PAYMENT-RESPONSE, to your answer).
178
+ Otherwise answer with status, headers and body instead of running the request."""
179
+
180
+ paid: bool
181
+ status: int = 200
182
+ headers: Dict[str, str] = field(default_factory=dict)
183
+ body: bytes = b""
184
+ payment: Optional[X402Payment] = None
185
+
186
+
187
+ def _price_units(price: Any) -> Optional[int]:
188
+ if not isinstance(price, str):
189
+ return None
190
+ p = price.strip()
191
+ if not _X402_PRICE.fullmatch(p):
192
+ return None
193
+ whole, _, frac = p.partition(".")
194
+ units = int(whole) * 1_000_000 + int(frac.ljust(6, "0"))
195
+ return units if X402_MIN_UNITS <= units <= X402_MAX_UNITS else None
196
+
197
+
198
+ # Keccak-256 (the hash an address's checksum is taken from), so no library is needed for it.
199
+ _KECCAK_RC = (
200
+ 0x0000000000000001, 0x0000000000008082, 0x800000000000808A, 0x8000000080008000, 0x000000000000808B, 0x0000000080000001,
201
+ 0x8000000080008081, 0x8000000000008009, 0x000000000000008A, 0x0000000000000088, 0x0000000080008009, 0x000000008000000A,
202
+ 0x000000008000808B, 0x800000000000008B, 0x8000000000008089, 0x8000000000008003, 0x8000000000008002, 0x8000000000000080,
203
+ 0x000000000000800A, 0x800000008000000A, 0x8000000080008081, 0x8000000000008080, 0x0000000080000001, 0x8000000080008008,
204
+ )
205
+ # Each lane's rotation, by lane index x + 5y.
206
+ _KECCAK_ROT = (0, 1, 62, 28, 27, 36, 44, 6, 55, 20, 3, 10, 43, 25, 39, 41, 45, 15, 21, 8, 18, 2, 61, 56, 14)
207
+ _M64 = (1 << 64) - 1
208
+
209
+
210
+ def _rotl(v: int, n: int) -> int:
211
+ return ((v << n) | (v >> (64 - n))) & _M64 if n else v
212
+
213
+
214
+ def _keccak_f(s: List[int]) -> None:
215
+ for rc in _KECCAK_RC:
216
+ c = [s[x] ^ s[x + 5] ^ s[x + 10] ^ s[x + 15] ^ s[x + 20] for x in range(5)]
217
+ for x in range(5):
218
+ d = c[(x + 4) % 5] ^ _rotl(c[(x + 1) % 5], 1)
219
+ for y in range(0, 25, 5):
220
+ s[x + y] ^= d
221
+ b = [0] * 25
222
+ for x in range(5):
223
+ for y in range(5):
224
+ b[y + 5 * ((2 * x + 3 * y) % 5)] = _rotl(s[x + 5 * y], _KECCAK_ROT[x + 5 * y])
225
+ for y in range(0, 25, 5):
226
+ for x in range(5):
227
+ s[x + y] = b[x + y] ^ (~b[(x + 1) % 5 + y] & b[(x + 2) % 5 + y])
228
+ s[0] ^= rc
229
+
230
+
231
+ def _keccak256(data: bytes) -> bytes:
232
+ rate = 136
233
+ padded = bytearray(data)
234
+ padded.append(0x01)
235
+ padded.extend(b"\x00" * (-len(padded) % rate))
236
+ padded[-1] |= 0x80
237
+ s = [0] * 25
238
+ for off in range(0, len(padded), rate):
239
+ for i in range(rate // 8):
240
+ s[i] ^= int.from_bytes(padded[off + 8 * i : off + 8 * i + 8], "little")
241
+ _keccak_f(s)
242
+ return b"".join(s[i].to_bytes(8, "little") for i in range(4))
243
+
244
+
245
+ def _checksummed(address: str) -> str:
246
+ """An address in its checksummed form (EIP-55)."""
247
+ h = address[2:].lower()
248
+ digest = _keccak256(h.encode("ascii")).hex()
249
+ return "0x" + "".join(ch.upper() if int(digest[i], 16) >= 8 else ch for i, ch in enumerate(h))
250
+
251
+
252
+ def _forwarder(v: Any) -> str:
253
+ """The forwarder as given, checksummed. Any case is taken; mixed case only when it is the address's own checksum (a
254
+ mistyped digit then shows), and never a token's or the payment contracts' address."""
255
+ a = v.strip() if isinstance(v, str) else ""
256
+ if not _HEX_ADDRESS.fullmatch(a):
257
+ raise ValueError("forwarder is your forwarder's address, 0x and 40 hex digits")
258
+ s, h = _checksummed(a), a[2:]
259
+ if h != h.lower() and h != h.upper() and a != s:
260
+ raise ValueError(f"forwarder {a} is in mixed case that is not its checksum ({s}); copy it again, or give it in lowercase")
261
+ if a.lower() in _NOT_A_FORWARDER:
262
+ raise ValueError("forwarder is your own forwarder's address, not a token's or a payment contract's")
263
+ return s
264
+
265
+
266
+ def _facilitator_base(raw: Any) -> str:
267
+ """The facilitator's origin: https, or http on this machine only (the key goes there)."""
268
+ s = raw.strip().rstrip("/") if isinstance(raw, str) else ""
269
+ try:
270
+ u = urllib.parse.urlsplit(s)
271
+ host = u.hostname
272
+ except ValueError:
273
+ host, u = None, None
274
+ if u is not None and host and (u.scheme == "https" or (u.scheme == "http" and host in ("localhost", "127.0.0.1", "::1"))):
275
+ return s
276
+ raise ValueError("base_url is the facilitator's origin over https (http only for localhost), such as https://api.usdf.fi: your facilitator key is sent there")
277
+
278
+
279
+ def _decode_payment(raw: str) -> Optional[Dict[str, Any]]:
280
+ t = raw.strip()
281
+ if not t or len(t) > _PAYMENT_HEADER_MAX or not _B64.fullmatch(t):
282
+ return None
283
+ t = t.replace("-", "+").replace("_", "/")
284
+ try:
285
+ v = json.loads(base64.b64decode(t + "=" * (-len(t) % 4)).decode("utf-8"))
286
+ except Exception: # noqa: BLE001 - anything that is not base64 of JSON
287
+ return None
288
+ return v if isinstance(v, dict) else None
289
+
290
+
291
+ def _accepted_is(a: Any, r: Dict[str, Any]) -> bool:
292
+ """Whether the payment accepted exactly this requirement (scheme, network, asset, payTo, amount); addresses in any case."""
293
+ if not isinstance(a, dict):
294
+ return False
295
+
296
+ def low(v: Any) -> Optional[str]:
297
+ return v.lower() if isinstance(v, str) else None
298
+
299
+ return a.get("scheme") == r["scheme"] and a.get("network") == r["network"] and low(a.get("asset")) == r["asset"].lower() and low(a.get("payTo")) == r["payTo"].lower() and str(a.get("amount")) == r["amount"]
300
+
301
+
302
+ def _x402_refusal(status: int, code: str, message: str, extra: Optional[Dict[str, str]] = None) -> X402ChargeResult:
303
+ r = _refusal(status, code, message)
304
+ return X402ChargeResult(paid=False, status=r.status, headers={**r.headers, **(extra or {})}, body=r.body)
305
+
306
+
307
+ class AcceptUsdfX402:
308
+ """Charges each request `price` USDF (a string like "0.001", or a function of the request's URL and headers), paid
309
+ straight to your forwarder. A FastAPI dependency (Depends(paid): the settled X402Payment, or the request answered for
310
+ you), and charge(url, headers) / await check(request) give the decision for one request anywhere else. Every option
311
+ is checked here: a bad one raises ValueError before any request."""
312
+
313
+ def __init__(
314
+ self,
315
+ forwarder: str,
316
+ price: Union[str, Callable[[str, Mapping[str, str]], str]],
317
+ api_key: Optional[str] = None,
318
+ description: str = "",
319
+ mime_type: str = "application/json",
320
+ resource_url: Union[str, Callable[[str, Mapping[str, str]], str], None] = None,
321
+ base_url: Optional[str] = None,
322
+ max_timeout_seconds: int = X402_DEFAULT_TIMEOUT_SECONDS,
323
+ timeout: float = FACILITATOR_TIMEOUT,
324
+ transport: Any = None,
325
+ pending_retries: int = 4,
326
+ pending_wait: float = 2.5,
327
+ ) -> None:
328
+ self.forwarder = _forwarder(forwarder)
329
+ self._price_fn = price if callable(price) else None
330
+ self._units = None if callable(price) else _price_units(price)
331
+ if self._price_fn is None and self._units is None:
332
+ raise ValueError(_PRICE_RULE)
333
+ key = api_key if api_key is not None else (os.environ.get("USDF_FACILITATOR_KEY") or None)
334
+ if key is not None and (not isinstance(key, str) or not _FACILITATOR_KEY.fullmatch(key)):
335
+ raise ValueError("api_key is your facilitator key, which starts with pfk_ (default: USDF_FACILITATOR_KEY)")
336
+ self._key = key
337
+ if isinstance(max_timeout_seconds, bool) or not isinstance(max_timeout_seconds, int) or not 1 <= max_timeout_seconds <= X402_MAX_TIMEOUT_SECONDS:
338
+ raise ValueError(f"max_timeout_seconds is a whole number of seconds from 1 to {X402_MAX_TIMEOUT_SECONDS}")
339
+ if isinstance(timeout, bool) or not isinstance(timeout, (int, float)) or not 0 < timeout <= 120:
340
+ raise ValueError("timeout is a number of seconds above 0 and at most 120")
341
+ if not isinstance(description, str) or not isinstance(mime_type, str):
342
+ raise ValueError("description and mime_type are strings")
343
+ if resource_url is not None and not isinstance(resource_url, str) and not callable(resource_url):
344
+ raise ValueError("resource_url is a URL or a function of the request's URL and headers")
345
+ self.description = description
346
+ self.mime_type = mime_type
347
+ self.resource_url = resource_url
348
+ self.max_timeout_seconds = max_timeout_seconds
349
+ self.timeout = float(timeout)
350
+ # A settlement still being confirmed is asked again pending_retries times, pending_wait seconds apart.
351
+ self.pending_retries = max(0, int(pending_retries))
352
+ self.pending_wait = max(0.0, float(pending_wait))
353
+ self.base_url = _facilitator_base(base_url or os.environ.get("USDF_BASE_URL") or DEFAULT_FACILITATOR_URL)
354
+ self._transport = transport if transport is not None else Transport()
355
+
356
+ def requirement(self, units: int) -> Dict[str, Any]:
357
+ """The one payment option the 402 offers: USDF on Robinhood Chain through the signature-transfer contract."""
358
+ return {"scheme": "exact", "network": NETWORK, "amount": str(units), "asset": USDF_ADDRESS, "payTo": self.forwarder, "maxTimeoutSeconds": self.max_timeout_seconds, "extra": {"assetTransferMethod": "permit2"}}
359
+
360
+ def charge(self, url: str, headers: Mapping[str, str]) -> X402ChargeResult:
361
+ """One request checked: settled to your forwarder, or the answer to give instead."""
362
+ try:
363
+ return self._charge(url, headers)
364
+ except Exception: # noqa: BLE001 - a price or resource_url function that raised
365
+ return _x402_refusal(500, "accept_failed", "this API could not price the request; nothing was charged")
366
+
367
+ def _charge(self, url: str, headers: Mapping[str, str]) -> X402ChargeResult:
368
+ key = self._key or os.environ.get("USDF_FACILITATOR_KEY") or None
369
+ if not key:
370
+ return _x402_refusal(503, "not_configured", "this API takes USDF, but its facilitator key is not set")
371
+ if not _FACILITATOR_KEY.fullmatch(key):
372
+ return _x402_refusal(500, "not_configured", "this API's facilitator key is not a facilitator key (pfk_...)")
373
+ units = self._units if self._price_fn is None else _price_units(self._price_fn(url, headers))
374
+ if units is None:
375
+ return _x402_refusal(500, "bad_price", "this API's price is not an amount of USDF from 0.001 to 10000")
376
+ req = self.requirement(units)
377
+ if self.resource_url is None:
378
+ where = url
379
+ elif isinstance(self.resource_url, str):
380
+ where = self.resource_url
381
+ else:
382
+ where = self.resource_url(url, headers)
383
+ resource = {"url": where, "description": self.description, "mimeType": self.mime_type}
384
+
385
+ def required(error: str) -> X402ChargeResult:
386
+ raw = json.dumps({"x402Version": 2, "error": error, "resource": resource, "accepts": [req]}, separators=(",", ":"))
387
+ return X402ChargeResult(paid=False, status=402, headers={"content-type": "application/json", "payment-required": base64.b64encode(raw.encode()).decode("ascii")}, body=raw.encode())
388
+
389
+ sent = _header(headers, "payment-signature") or _header(headers, "x-payment")
390
+ if not sent or not sent.strip():
391
+ return required("payment_required")
392
+ payment = _decode_payment(sent)
393
+ if payment is None:
394
+ return required("invalid_payload")
395
+ if payment.get("x402Version") != 2:
396
+ return required("invalid_x402_version")
397
+ # A payment made out to anything but this request's requirement is refused here, without a call.
398
+ if not _accepted_is(payment.get("accepted"), req):
399
+ return required("payment_requirements_mismatch")
400
+ body = json.dumps({"x402Version": 2, "paymentPayload": payment, "paymentRequirements": req}).encode()
401
+ verified, answer = self._call("verify", body, key)
402
+ if verified is None:
403
+ return answer # type: ignore[return-value]
404
+ if verified.get("isValid") is not True:
405
+ reason = verified.get("invalidReason")
406
+ return required(reason if isinstance(reason, str) and _REASON.fullmatch(reason) else "invalid_payment")
407
+ settled, answer = self._call("settle", body, key)
408
+ # A settlement the facilitator signed but has not seen mined yet: asked again a few times, then the caller is told
409
+ # to send the same request again (the facilitator answers it from the chain: served once if it mined).
410
+ tries = 0
411
+ while settled is not None and settled.get("success") is not True and settled.get("errorReason") == "settlement_pending" and tries < self.pending_retries:
412
+ time.sleep(self.pending_wait)
413
+ tries += 1
414
+ settled, answer = self._call("settle", body, key)
415
+ if settled is None:
416
+ return answer # type: ignore[return-value]
417
+ if settled.get("success") is not True and settled.get("errorReason") == "settlement_pending":
418
+ return _x402_refusal(503, "settlement_pending", "the payment is being confirmed; send the same request again in a few seconds", {"retry-after": "5"})
419
+ if settled.get("success") is not True and settled.get("errorReason") == "settlement_unavailable":
420
+ return _x402_refusal(503, "payment_unavailable", "the payment could not be taken just now; nothing was charged, try again later", {"retry-after": "3600"})
421
+ if settled.get("success") is not True:
422
+ reason = settled.get("errorReason")
423
+ return required(reason if isinstance(reason, str) and _REASON.fullmatch(reason) else "settlement_failed")
424
+ response = base64.b64encode(json.dumps(settled, separators=(",", ":")).encode()).decode("ascii")
425
+ return X402ChargeResult(
426
+ paid=True,
427
+ headers={"payment-response": response, "x-payment-response": response},
428
+ payment=X402Payment(
429
+ transaction=str(settled.get("transaction", "")),
430
+ payer=str(settled.get("payer", "")),
431
+ network=str(settled.get("network", NETWORK)),
432
+ amount=str(settled.get("amount", req["amount"])),
433
+ ),
434
+ )
435
+
436
+ def _call(self, path: str, body: bytes, key: str) -> Tuple[Optional[Dict[str, Any]], Optional[X402ChargeResult]]:
437
+ lost = "the payment could not be checked just now; nothing was charged, try again" if path == "verify" else "the payment's settlement could not be confirmed just now; try again"
438
+ try:
439
+ r = self._transport.request("POST", f"{self.base_url}/v1/facilitator/{path}", {"authorization": "Bearer " + key, "content-type": "application/json", "accept": "application/json"}, body, self.timeout)
440
+ except Exception: # noqa: BLE001 - unreachable, refused, past the timeout
441
+ return None, _x402_refusal(503, "facilitator_unreachable", lost)
442
+ # The key itself is never repeated, here or anywhere.
443
+ if r.status == 401:
444
+ return None, _x402_refusal(500, "facilitator_key_refused", "facilitator key refused")
445
+ if r.status != 200:
446
+ code = "rate_limited" if r.status == 429 else "payment_unavailable"
447
+ try:
448
+ c = json.loads(r.body.decode("utf-8") or "{}").get("error", {}).get("code")
449
+ if isinstance(c, str) and _REASON.fullmatch(c):
450
+ code = c
451
+ except Exception: # noqa: BLE001 - not the facilitator's JSON
452
+ pass
453
+ retry = str({k.lower(): v for k, v in (r.headers or {}).items()}.get("retry-after", "")).strip()
454
+ message = lost if path == "verify" else "the payment could not be settled just now; try again"
455
+ return None, _x402_refusal(503, code, message, {"retry-after": retry} if _HEADER_VALUE.fullmatch(retry) else None)
456
+ try:
457
+ v = json.loads(r.body.decode("utf-8"))
458
+ except Exception: # noqa: BLE001 - below
459
+ v = None
460
+ if not isinstance(v, dict):
461
+ return None, _x402_refusal(503, "payment_unavailable", lost)
462
+ return v, None
463
+
464
+ async def check(self, request: Any) -> X402ChargeResult:
465
+ """The decision for a Starlette (or FastAPI) request, the facilitator called off the event loop."""
466
+ url = str(request.url)
467
+ headers = {k.lower(): v for k, v in request.headers.items()}
468
+ try:
469
+ import anyio.to_thread
470
+ except ImportError:
471
+ return await asyncio.to_thread(self.charge, url, headers)
472
+ return await anyio.to_thread.run_sync(self.charge, url, headers)
473
+
474
+ async def __call__(self, request: Any, response: Any = None) -> X402Payment:
475
+ """The FastAPI dependency: the settled payment (PAYMENT-RESPONSE set on the route's response), or the request
476
+ answered for you with an HTTPException (402 with PAYMENT-REQUIRED, its JSON under detail; 500; 503)."""
477
+ result = await self.check(request)
478
+ if not result.paid or result.payment is None:
479
+ from starlette.exceptions import HTTPException
480
+
481
+ try:
482
+ detail: Any = json.loads(result.body.decode("utf-8"))
483
+ except ValueError:
484
+ detail = result.body.decode("utf-8", "replace")
485
+ raise HTTPException(status_code=result.status, detail=detail, headers={k: v for k, v in result.headers.items() if k != "content-type"})
486
+ if response is not None:
487
+ for k, v in result.headers.items():
488
+ response.headers[k] = v
489
+ return result.payment
490
+
491
+
492
+ # FastAPI reads a dependency's parameters by their types: the request, and the response its headers go on.
493
+ try:
494
+ from starlette.requests import Request as _StarletteRequest
495
+ from starlette.responses import Response as _StarletteResponse
496
+
497
+ AcceptUsdfX402.__call__.__annotations__ = {"request": _StarletteRequest, "response": _StarletteResponse, "return": X402Payment}
498
+ except ImportError:
499
+ pass
@@ -18,7 +18,7 @@ from . import x402 as _x402
18
18
  from .x402 import CHAIN_ID, PaymentLimits, Signer, approve_permit2, check_accept, choose_accept, decode_payment_required, decode_payment_response, encode_payment_signature, known_asset, payment_limits, read_permit2_allowance, rpc_chain_id, sign_exact_payment, wallet_signer
19
19
 
20
20
  DEFAULT_BASE_URL = "https://api.usdf.fi"
21
- SDK_VERSION = "0.1.2"
21
+ SDK_VERSION = "0.1.3"
22
22
  _UA = f"usdf-sdk-py/{SDK_VERSION}"
23
23
  _REQUEST_ID = __import__("re").compile(r"^[A-Za-z0-9_-]{1,64}$")
24
24
 
@@ -158,8 +158,8 @@ class _Models:
158
158
  self._c = client
159
159
 
160
160
  def list(self) -> List[Model]:
161
- """GET /v1/models: what a key can call right now."""
162
- return [Model.of(m) for m in self._c._json("GET", "/v1/models", auth="none").get("data") or []]
161
+ """GET /v1/models: what a key can call right now (sent with the client's key, else its session, when it has one)."""
162
+ return [Model.of(m) for m in self._c._json("GET", "/v1/models", auth="any").get("data") or []]
163
163
 
164
164
 
165
165
  class _Mcp:
@@ -574,13 +574,114 @@ class _Links:
574
574
  return self._c._json("POST", f"/v1/links/{urllib.parse.quote(link_id, safe='')}/cancel", {}, auth="session")
575
575
 
576
576
 
577
+ class _Transit:
578
+ """Dollars from and to other chains: USDC or PYUSD on Ethereum, USDC on Arbitrum, and
579
+ Global Dollar (USDG), issued by Paxos, on either, in and out of USDF. The gateway quotes and follows each order;
580
+ the wallet signs and sends it itself
581
+ (with your own signer: a quote's ``transaction`` is to, data and the exact value to send). Add funds with the account's
582
+ key or session (purpose ``deposit``, its gasless deposit signed ahead from ``deposit_authorization``); a cash out with
583
+ the signed-in session."""
584
+
585
+ def __init__(self, client: "USDF"):
586
+ self._c = client
587
+
588
+ def routes(self, purpose: Optional[str] = None) -> Dict[str, Any]:
589
+ """GET /v1/transit/routes: the routes served now; purpose ``deposit`` or ``cashout`` for a flow's."""
590
+ return self._c._json("GET", "/v1/transit/routes" + _qs({"purpose": purpose}), auth="none")
591
+
592
+ def quote(self, source_chain_id: int, offer_asset: str, amount_units: int, destination_chain_id: int, want_asset: str, sender: str, recipient: Optional[str] = None) -> Dict[str, Any]:
593
+ """POST /v1/transit/quote: the transaction the sender's wallet signs and sends (exactly its value), the fee, the
594
+ expected time, the approval the asset needs, and quote_token."""
595
+ body: Dict[str, Any] = {"source_chain_id": source_chain_id, "offer_asset": offer_asset, "amount_units": str(int(amount_units)), "destination_chain_id": destination_chain_id, "want_asset": want_asset, "sender": sender}
596
+ if recipient is not None:
597
+ body["recipient"] = recipient
598
+ return self._c._json("POST", "/v1/transit/quote", body, auth="none")
599
+
600
+ def deposit_authorization(self, receive_units: int) -> Dict[str, Any]:
601
+ """GET /v1/transit/deposit/authorization: the gasless deposit's typed data to sign with an Add funds order."""
602
+ return self._c._json("GET", "/v1/transit/deposit/authorization" + _qs({"amount_units": str(int(receive_units))}), auth="any")
603
+
604
+ def record(self, quote_token: str, purpose: str = "transfer", deposit_authorization: Optional[Mapping[str, Any]] = None, ref: Optional[str] = None) -> Dict[str, Any]:
605
+ """POST /v1/transit/orders: the quote recorded as the account's order, before the wallet sends it."""
606
+ body: Dict[str, Any] = {"quote_token": quote_token, "purpose": purpose}
607
+ if deposit_authorization is not None:
608
+ body["deposit_authorization"] = dict(deposit_authorization)
609
+ if ref is not None:
610
+ body["ref"] = ref
611
+ return self._c._json("POST", "/v1/transit/orders", body, auth="any")
612
+
613
+ def submitted(self, order_id: str, tx_hash: str) -> Dict[str, Any]:
614
+ """POST /v1/transit/orders/{id}/submitted: the hash of the transaction the wallet sent."""
615
+ return self._c._json("POST", f"/v1/transit/orders/{urllib.parse.quote(order_id, safe='')}/submitted", {"tx_hash": tx_hash}, auth="any")
616
+
617
+ def order(self, order_id: str) -> Dict[str, Any]:
618
+ return self._c._json("GET", f"/v1/transit/orders/{urllib.parse.quote(order_id, safe='')}", auth="any")
619
+
620
+ def orders(self) -> List[Dict[str, Any]]:
621
+ return (self._c._json("GET", "/v1/transit/orders", auth="any") or {}).get("data") or []
622
+
623
+ def network_order(self, order_id: str) -> Dict[str, Any]:
624
+ """GET /v1/transit/network/orders/{order_id}: any order's status on the network, by its 32-byte id."""
625
+ return self._c._json("GET", f"/v1/transit/network/orders/{urllib.parse.quote(order_id, safe='')}", auth="none")
626
+
627
+ def wait(self, order_id: str, interval_s: float = 10.0, timeout_s: float = 3600.0) -> Dict[str, Any]:
628
+ """Polls GET /v1/transit/orders/{id} until the order lands: fulfilled, failed or expired and, for Add funds, until
629
+ its deposit is credited or waits for the wallet's signature (next_step done, awaiting_signature or failed).
630
+ Raises USDFError 408 (transit_pending) with the order as it stands when timeout_s passes first."""
631
+ until = time.monotonic() + timeout_s
632
+ while True:
633
+ o = self.order(order_id)
634
+ state, purpose, step = o.get("state"), o.get("purpose"), o.get("next_step")
635
+ if state in ("failed", "expired") or (state == "fulfilled" and (purpose != "deposit" or step in ("done", "awaiting_signature", "failed"))):
636
+ return o
637
+ if time.monotonic() > until:
638
+ raise USDFError(408, f"order {order_id} is still {state}", "timeout", "transit_pending", body=o)
639
+ time.sleep(interval_s)
640
+
641
+ def cashout_preview(self, amount: str, destination_chain_id: int, want_asset: str) -> Dict[str, Any]:
642
+ """GET /v1/account/cashout/preview (session): what a cash out gives and costs, the gas drip included."""
643
+ return self._c._json("GET", "/v1/account/cashout/preview" + _qs({"amount": amount, "destination_chain_id": destination_chain_id, "want_asset": want_asset}), auth="session")
644
+
645
+ def cashout(self, amount: str, destination_chain_id: int, want_asset: str, idempotency_key: str, gas_drip: Optional[bool] = None) -> Dict[str, Any]:
646
+ """POST /v1/account/cashout (session): the route and a live quote checked, then the redemption to the linked wallet."""
647
+ body: Dict[str, Any] = {"amount": amount, "destination_chain_id": destination_chain_id, "want_asset": want_asset, "idempotency_key": idempotency_key}
648
+ if gas_drip is not None:
649
+ body["gas_drip"] = gas_drip
650
+ return self._c._json("POST", "/v1/account/cashout", body, auth="session")
651
+
652
+ def cashouts(self) -> List[Dict[str, Any]]:
653
+ return (self._c._json("GET", "/v1/account/cashout", auth="session") or {}).get("data") or []
654
+
655
+ def payout_preference(self) -> Optional[Dict[str, Any]]:
656
+ """GET /v1/account/payout-preference (the account's own key or its session): how the account's payouts are
657
+ converted (``want_asset`` USDC or USDG, ``destination_chain_id`` 42161 or 1, ``destination_address``, None for the
658
+ linked wallet's own address there), or None when none is set. With one, each paid payout the API shows carries
659
+ ``convert``, the conversion pre-filled."""
660
+ return (self._c._json("GET", "/v1/account/payout-preference", auth="any") or {}).get("preference")
661
+
662
+ def set_payout_preference(self, want_asset: str, destination_chain_id: int, destination_address: Optional[str] = None) -> Optional[Dict[str, Any]]:
663
+ """PUT /v1/account/payout-preference: sets it; no ``destination_address`` is the linked wallet's own address there.
664
+ Another address is set from the signed-in session only, after a recent sign-in (403 ``reauth_required``
665
+ otherwise; with a key, 403 ``session_required``), and the account is emailed: a named address goes with the
666
+ session when the client has one. Returns the preference as set."""
667
+ body: Dict[str, Any] = {"want_asset": want_asset, "destination_chain_id": destination_chain_id}
668
+ if destination_address is not None:
669
+ body["destination_address"] = destination_address
670
+ auth = "session" if destination_address and self._c.session_token else "any"
671
+ return (self._c._json("PUT", "/v1/account/payout-preference", body, auth=auth) or {}).get("preference")
672
+
673
+ def clear_payout_preference(self) -> Optional[Dict[str, Any]]:
674
+ """DELETE /v1/account/payout-preference: cleared; payouts stay in USDF and none carries a conversion (None)."""
675
+ return (self._c._json("DELETE", "/v1/account/payout-preference", auth="any") or {}).get("preference")
676
+
677
+
577
678
  class _Zap:
578
679
  def __init__(self, client: "USDF"):
579
680
  self._c = client
580
681
 
581
682
  def quote(self, token: str, amount: int, recipient: Optional[str] = None, slippage_bps: Optional[int] = None) -> Dict[str, Any]:
582
683
  """GET /v1/zap/quote: ETH ("eth") or an ERC-20 with a Uniswap pool against USDG, swapped and
583
- wrapped into USDF for ``recipient``, with the transactions to send. No key."""
684
+ converted into USDF for ``recipient``, with the transactions to send. No key."""
584
685
  return self._c._json("GET", "/v1/zap/quote" + _qs({"token": token, "amount": str(int(amount)), "recipient": recipient, "slippage_bps": slippage_bps}), auth="none")
585
686
 
586
687
 
@@ -594,6 +695,42 @@ class _Pool:
594
695
  return self._c._json("GET", "/v1/pool", auth="none")
595
696
 
596
697
 
698
+ class _Susdf:
699
+ """Staked USDF (sUSDF): an ownerless ERC-4626 vault over USDF. Public reads, and the transactions a wallet signs and
700
+ sends itself; the gateway signs and sends nothing. Unstaking is instant (withdraw or redeem, paid at once; nothing to
701
+ claim). A stake quote carries the representation the stake makes (the EU and the EEA) and is refused (451
702
+ susdf_region_restricted) where sUSDF is not offered; an unstake never is."""
703
+
704
+ def __init__(self, client: "USDF"):
705
+ self._c = client
706
+
707
+ def get(self) -> Dict[str, Any]:
708
+ """GET /v1/susdf: the vault, its stream, the terms, where it is not offered, and what it earned."""
709
+ return self._c._json("GET", "/v1/susdf", auth="none")
710
+
711
+ def position(self, address: str) -> Dict[str, Any]:
712
+ """GET /v1/susdf/{address}: one wallet's shares and their value, what unstaking them all pays at once."""
713
+ return self._c._json("GET", "/v1/susdf/" + urllib.parse.quote(address, safe=""), auth="none")
714
+
715
+ def history(self, address: str) -> Dict[str, Any]:
716
+ """GET /v1/susdf/{address}/history: one wallet's events with the vault, newest first."""
717
+ return self._c._json("GET", "/v1/susdf/" + urllib.parse.quote(address, safe="") + "/history", auth="none")
718
+
719
+ def days(self, limit: Optional[int] = None) -> Dict[str, Any]:
720
+ """GET /v1/susdf/history: the share price by UTC day and the stream's payments, newest first (1 to 400 days)."""
721
+ return self._c._json("GET", "/v1/susdf/history" + _qs({"limit": limit}), auth="none")
722
+
723
+ def eligibility(self) -> Dict[str, Any]:
724
+ """GET /v1/susdf/eligibility: whether sUSDF is offered where this caller is placed, and the representation a stake
725
+ carries."""
726
+ return self._c._json("GET", "/v1/susdf/eligibility", auth="none")
727
+
728
+ def quote(self, action: str, address: str, amount: Optional[str] = None, all: bool = False) -> Dict[str, Any]:
729
+ """GET /v1/susdf/quote: the transactions to sign, in order, to stake an amount of USDF ("stake") or to unstake an
730
+ amount or everything at once ("unstake", all=True). Amounts are USDF text, at most 6 decimals."""
731
+ return self._c._json("GET", "/v1/susdf/quote" + _qs({"action": action, "address": address, "amount": amount, "all": 1 if all else None}), auth="none")
732
+
733
+
597
734
  class _Agents:
598
735
  """Agents with a ledger account of their own: created and funded by the owner, paying each other."""
599
736
 
@@ -696,6 +833,8 @@ class USDF:
696
833
  self.links = _Links(self)
697
834
  self.zap = _Zap(self)
698
835
  self.pool = _Pool(self)
836
+ self.susdf = _Susdf(self)
837
+ self.transit = _Transit(self)
699
838
  self.agents = _Agents(self)
700
839
 
701
840
  @property
@@ -816,8 +955,9 @@ class USDF:
816
955
  # ── Public reads ──────────────────────────────────────────────────────────
817
956
 
818
957
  def pricing(self) -> Pricing:
819
- """GET /v1/pricing: the price sheet in force, with routes and data policy per route."""
820
- return Pricing.of(self._json("GET", "/v1/pricing"))
958
+ """GET /v1/pricing: the price sheet in force, with routes and data policy per route. The gateway answers it only to a
959
+ key or a session, so the client's key (else its session) goes with it; with neither the call goes out as before."""
960
+ return Pricing.of(self._json("GET", "/v1/pricing", auth="any"))
821
961
 
822
962
  def tools(self) -> Dict[str, Any]:
823
963
  """GET /v1/tools."""
@@ -1,187 +0,0 @@
1
- """Accept USDF in one integration: charge your own API's callers in USDF over x402, settled by Foundry's facilitator
2
- and paid on to your payout address in USDF (or in USDG, 1:1, with settle_as="usdg"). Your server needs your Foundry API
3
- key (an approved partner's, in USDF_API_KEY) and a price.
4
-
5
- from usdf.accept import AcceptUSDF
6
-
7
- paid = AcceptUSDF(price="0.01")
8
- app = paid.wsgi(app) # any WSGI app (Flask's app.wsgi_app, Django's application)
9
-
10
- Or for one request, whatever the framework:
11
-
12
- result = paid.charge(url, headers)
13
- if not result.paid:
14
- return result.status, result.headers, result.body # 402 asking for payment, or a refusal
15
- # serve it; add result.headers (PAYMENT-RESPONSE) to the answer
16
-
17
- A request without a payment is answered 402 with the PAYMENT-REQUIRED header any x402 client reads; one with a payment
18
- (PAYMENT-SIGNATURE, or X-PAYMENT) is settled before the app runs, and the app runs only for a payment that settled.
19
- Standard library only."""
20
-
21
- from __future__ import annotations
22
-
23
- import json
24
- import os
25
- import re
26
- import urllib.error
27
- import urllib.request
28
- from dataclasses import dataclass, field
29
- from typing import Any, Callable, Dict, Iterable, Mapping, Optional, Union
30
-
31
- DEFAULT_FACILITATOR_URL = "https://api.usdf.fi"
32
- _PRICE = re.compile(r"^\d{1,5}(\.\d{1,6})?$")
33
-
34
-
35
- @dataclass
36
- class Accepted:
37
- """A settled payment: its transaction, payer and network, and what it came to for you."""
38
-
39
- transaction: str
40
- payer: str
41
- network: str
42
- amount: str
43
- fee: str
44
- paid_on: str
45
- settle_as: str
46
- settlement_id: str
47
-
48
-
49
- @dataclass
50
- class ChargeResult:
51
- """paid: the payment settled (payment holds it; add headers to your answer). Otherwise answer with status,
52
- headers and body instead of running the request."""
53
-
54
- paid: bool
55
- status: int = 200
56
- headers: Dict[str, str] = field(default_factory=dict)
57
- body: bytes = b""
58
- payment: Optional[Accepted] = None
59
-
60
-
61
- def _refusal(status: int, code: str, message: str) -> ChargeResult:
62
- body = json.dumps({"error": {"message": message, "type": "payment_error", "code": code}}).encode()
63
- return ChargeResult(paid=False, status=status, headers={"content-type": "application/json"}, body=body)
64
-
65
-
66
- def _header(headers: Mapping[str, str], name: str) -> Optional[str]:
67
- for k, v in headers.items():
68
- if k.lower() == name:
69
- return v
70
- return None
71
-
72
-
73
- class AcceptUSDF:
74
- """Charges each request `price` USDF (a string like "0.01", or a function of the request's URL and headers)."""
75
-
76
- def __init__(
77
- self,
78
- price: Union[str, Callable[[str, Mapping[str, str]], str]],
79
- api_key: Optional[str] = None,
80
- settle_as: str = "usdf",
81
- description: str = "",
82
- mime_type: str = "application/json",
83
- base_url: Optional[str] = None,
84
- timeout: float = 30.0,
85
- opener: Optional[Callable[..., Any]] = None,
86
- ) -> None:
87
- if settle_as not in ("usdf", "usdg"):
88
- raise ValueError('settle_as is "usdf" or "usdg"')
89
- self.price = price
90
- self.api_key = api_key
91
- self.settle_as = settle_as
92
- self.description = description
93
- self.mime_type = mime_type
94
- self.base_url = (base_url or os.environ.get("USDF_BASE_URL") or DEFAULT_FACILITATOR_URL).rstrip("/")
95
- self.timeout = timeout
96
- self._open = opener or urllib.request.urlopen
97
-
98
- def charge(self, url: str, headers: Mapping[str, str]) -> ChargeResult:
99
- """One request checked: settled, or the answer to give instead."""
100
- key = self.api_key or os.environ.get("USDF_API_KEY")
101
- if not key:
102
- return _refusal(503, "not_configured", "this API takes USDF, but its key is not set")
103
- price = self.price(url, headers) if callable(self.price) else self.price
104
- if not isinstance(price, str) or not _PRICE.match(price.strip()):
105
- return _refusal(500, "bad_price", "this API's price is not an amount of USDF")
106
- payment = _header(headers, "payment-signature") or _header(headers, "x-payment")
107
- body: Dict[str, Any] = {
108
- "amount": price.strip(),
109
- "settle_as": self.settle_as,
110
- "resource": {"url": url, "description": self.description, "mime_type": self.mime_type},
111
- }
112
- if payment:
113
- body["payment"] = payment
114
- req = urllib.request.Request(
115
- self.base_url + "/v1/facilitator/charge",
116
- data=json.dumps(body).encode(),
117
- method="POST",
118
- headers={"authorization": "Bearer " + key, "content-type": "application/json"},
119
- )
120
- try:
121
- with self._open(req, timeout=self.timeout) as r:
122
- status, raw, got = r.status, r.read(), {k.lower(): v for k, v in r.headers.items()}
123
- except urllib.error.HTTPError as e:
124
- status, raw, got = e.code, e.read(), {k.lower(): v for k, v in (e.headers or {}).items()}
125
- except (urllib.error.URLError, OSError, ValueError):
126
- return _refusal(503, "facilitator_unreachable", "the payment could not be checked just now; nothing was charged, try again")
127
- if status == 402:
128
- out = {"content-type": "application/json"}
129
- for h in ("payment-required", "www-authenticate"):
130
- if got.get(h):
131
- out[h] = got[h]
132
- return ChargeResult(paid=False, status=402, headers=out, body=raw)
133
- if status != 200:
134
- code = "payment_unavailable"
135
- try:
136
- code = str(json.loads(raw.decode() or "{}").get("error", {}).get("code") or code)
137
- except (ValueError, AttributeError):
138
- pass
139
- return _refusal(429 if status == 429 else 503, code, "the payment could not be taken just now; nothing was charged, try again")
140
- try:
141
- v = json.loads(raw.decode())
142
- except ValueError:
143
- return _refusal(503, "payment_unavailable", "the payment could not be taken just now; try again")
144
- if v.get("paid") is not True or not isinstance(v.get("transaction"), str):
145
- return _refusal(503, "payment_unavailable", "the payment could not be taken just now; try again")
146
- response = v.get("payment_response") or got.get("payment-response")
147
- s = v.get("settlement") or {}
148
-
149
- def usdf(x: Any) -> str:
150
- return str((x or {}).get("usdf", ""))
151
-
152
- return ChargeResult(
153
- paid=True,
154
- headers={"payment-response": response, "x-payment-response": response} if response else {},
155
- payment=Accepted(
156
- transaction=v["transaction"],
157
- payer=str(v.get("payer", "")),
158
- network=str(v.get("network", "")),
159
- amount=usdf(s.get("amount")),
160
- fee=usdf(s.get("fee")),
161
- paid_on=usdf(s.get("paid_on")),
162
- settle_as="usdg" if s.get("settle_as") == "usdg" else "usdf",
163
- settlement_id=str(s.get("id", "")),
164
- ),
165
- )
166
-
167
- def wsgi(self, app: Callable[..., Iterable[bytes]]) -> Callable[..., Iterable[bytes]]:
168
- """A WSGI app that charges every request before `app` runs it (the payment in environ["usdf.payment"])."""
169
-
170
- def wrapped(environ: Dict[str, Any], start_response: Callable[..., Any]) -> Iterable[bytes]:
171
- headers = {k[5:].replace("_", "-").lower(): v for k, v in environ.items() if k.startswith("HTTP_")}
172
- scheme = environ.get("HTTP_X_FORWARDED_PROTO", environ.get("wsgi.url_scheme", "https")).split(",")[0].strip()
173
- host = environ.get("HTTP_X_FORWARDED_HOST") or environ.get("HTTP_HOST") or environ.get("SERVER_NAME", "localhost")
174
- path = environ.get("PATH_INFO", "/") + (("?" + environ["QUERY_STRING"]) if environ.get("QUERY_STRING") else "")
175
- result = self.charge(f"{'http' if scheme == 'http' else 'https'}://{host}{path}", headers)
176
- if not result.paid:
177
- reason = {402: "Payment Required", 429: "Too Many Requests", 500: "Internal Server Error"}.get(result.status, "Service Unavailable")
178
- start_response(f"{result.status} {reason}", list(result.headers.items()))
179
- return [result.body]
180
- environ["usdf.payment"] = result.payment
181
-
182
- def start(status: str, response_headers: list, exc_info: Any = None) -> Any:
183
- return start_response(status, list(response_headers) + list(result.headers.items()), exc_info) if exc_info else start_response(status, list(response_headers) + list(result.headers.items()))
184
-
185
- return app(environ, start)
186
-
187
- return wrapped
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes