heph-forge 0.1.0b0__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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 HEPH Protocol
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,2 @@
1
+ include LICENSE
2
+ include README.md
@@ -0,0 +1,170 @@
1
+ Metadata-Version: 2.4
2
+ Name: heph-forge
3
+ Version: 0.1.0b0
4
+ Summary: HEPH Forge Python SDK — Hardware & autonomous machine finance protocol on Robinhood Chain
5
+ Author: HEPH Protocol
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/heph-fleet/heph
8
+ Project-URL: Repository, https://github.com/heph-fleet/heph
9
+ Project-URL: Issues, https://github.com/heph-fleet/heph/issues
10
+ Keywords: heph,uniswap-v4,erc-4337,x402,depin,robotics
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Typing :: Typed
18
+ Requires-Python: >=3.10
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Requires-Dist: web3>=7.0.0
22
+ Requires-Dist: eth-account>=0.13.0
23
+ Requires-Dist: requests>=2.31.0
24
+ Dynamic: license-file
25
+
26
+ # HEPH Forge Python SDK
27
+
28
+ Official Python package for the **HEPH** (*Hook for Embodied Physical Hardware*) autonomous physical-device financial protocol.
29
+ Main features:
30
+
31
+ - Machine session key management & Hardware Keystore abstraction (`DevKeyStore`, `KeyStore`).
32
+ - Standardized EIP-712 signing for revenue swaps (`SwapIntent`) and HTTP 402 payments (`Payment402Intent`).
33
+ - `hookData` calldata encoding for the HEPH Uniswap v4 Hook.
34
+ - Easy integration with robotics frameworks (ROS2/Python) and AI agent pipelines.
35
+
36
+ ## Installation
37
+
38
+ ```bash
39
+ pip install --upgrade pip # pip 22.x (Ubuntu 22.04 / ROS Humble) installs an empty 'UNKNOWN 0.0.0' package
40
+ pip install heph-forge # check: pip show heph-forge
41
+ # from a checkout: pip install ./sdk-python
42
+ ```
43
+
44
+ > **Status: beta (`0.1.0b0`), testnet only.** The contracts have not had an external audit and
45
+ > `DevKeyStore` (raw private key) is rejected in production. Use `CallbackKeyStore` with an
46
+ > external signer / hardware module for anything beyond testing.
47
+
48
+ ## Usage Example
49
+
50
+ ```python
51
+ from heph_forge import Forge
52
+
53
+ # 1. Forge client. rpc_url and bundler_url are required to read the chain and send swaps.
54
+ forge = Forge.connect(
55
+ private_key="0x...", # dev/test only; in production use CallbackKeyStore (see below)
56
+ chain="robinhoodTestnet",
57
+ rpc_url="https://rpc.testnet.chain.robinhood.com",
58
+ bundler_url="https://bundler.example", # ERC-4337 v0.7 bundler
59
+ )
60
+
61
+ # 2. Machine identity. `account` = Machine Account (compute it with the TypeScript SDK when using a factory + random salt).
62
+ machine = forge.machines.create(
63
+ name="autonomous-delivery-01",
64
+ operator="0xOperator...",
65
+ account="0xMachineAccount...",
66
+ )
67
+
68
+ # 3. Read on-chain status
69
+ machine.verify_registration() # unregistered | registered | RegistrationMismatch (claimed by another operator)
70
+ machine.get_info() # signer, operator, registeredAt, lastActiveAt, frozen, ...
71
+ machine.effective_tier() # tier used by HephHook for fees (inactive Silver = Bronze)
72
+ machine.is_frozen()
73
+ machine.usdg_balance()
74
+
75
+ # 4. Swap revenue to USDG (ERC-4337 v0.7 UserOperation: executeBatch([approve, router.swap]))
76
+ result = machine.swap(
77
+ token_in="0xRevenueToken...",
78
+ amount_in=10_000_000,
79
+ min_amount_out=9_000_000,
80
+ )
81
+ assert result["status"] == "executed" # amountOut, protocolFee, txHash, userOpHash
82
+
83
+ # 5. Pay for a service through the HEPH Facilitator (HTTP 402)
84
+ res = machine.pay(
85
+ url="https://charger.example/start",
86
+ max_amount=250_000, # $0.25 USDG
87
+ facilitator_url="https://facilitator.example",
88
+ merchant_address="0xMerchant...",
89
+ )
90
+ assert res["status"] == "settled" # only when the Facilitator confirms
91
+ ```
92
+
93
+ ## `swap()`: what it does and when it fails
94
+
95
+ It runs on-chain pre-checks first (fail fast with a clear error, sending nothing):
96
+ the account is registered and its identity matches, the registered `signer` = the keystore key, the account session key = the keystore key,
97
+ the machine is not frozen, and gas funds are sufficient (account ETH balance + EntryPoint deposit >= prefund). Then it signs the
98
+ `SwapIntent`, builds `executeBatch([approve, HephRouter.swap])`, signs the UserOperation with the session key
99
+ (EIP-191 over `userOpHash`, per `HephAccount.validateUserOp`), sends it to the bundler in the standard v0.7 RPC format
100
+ (`eth_sendUserOperation [userOp, entryPoint]`), and waits for the result.
101
+
102
+ | Condition | Result |
103
+ |---|---|
104
+ | Success | `{"status": "executed", "txHash", "userOpHash", "amountOut", "protocolFee", ...}` |
105
+ | `rpc_url`/`bundler_url` empty | `ChainNotConfigured` |
106
+ | Signer or session key is not the keystore key, account claimed by another operator | `RegistrationMismatch` |
107
+ | Machine or its fleet is frozen | `MachineFrozenError` |
108
+ | Insufficient gas funds | `InsufficientGasFunds` |
109
+ | Bundler rejects (signature, nonce, prefund, etc.) | `BundlerError` (carries the reason from the EntryPoint) |
110
+ | Lands on-chain but execution fails (e.g. slippage) | `UserOperationReverted` |
111
+ | Not confirmed within `timeout` | `UserOperationTimeout` |
112
+
113
+ There is never a false success. Gas is paid from the machine account's ETH; **paymaster is not supported yet** (the mainnet paymaster
114
+ is also not funded/staked yet). Account creation via `initCode` is not supported yet.
115
+
116
+ ## Hardware keystore / KMS: `CallbackKeyStore`
117
+
118
+ The SDK never holds the private key when using `CallbackKeyStore`: it computes the digest (EIP-191/EIP-712)
119
+ and asks an external signer to sign it. Suitable for KMS/HSM/secure elements that support
120
+ **secp256k1** and whose keys cannot be exported (e.g. AWS KMS `ECC_SECG_P256K1`, YubiHSM 2).
121
+
122
+ ```python
123
+ from heph_forge import CallbackKeyStore, Forge
124
+
125
+ def sign_hash(digest: bytes) -> bytes: # 65 bytes: r || s || v (v = 0/1 or 27/28)
126
+ return my_hsm.sign(digest) # the key never leaves the HSM
127
+
128
+ keystore = CallbackKeyStore("0xMachineSessionKeyAddress...", sign_hash)
129
+ forge = Forge(keystore=keystore, chain="robinhood", rpc_url=..., bundler_url=..., entry_point=...,
130
+ registry_address=..., router_address=..., hook_address=..., usdg_address=...)
131
+ ```
132
+
133
+ The SDK normalizes `s` to low form (required for OpenZeppelin contract ECDSA) and verifies that the signature
134
+ recovers the configured address, so a wrong configuration fails in the SDK, not as an on-chain revert.
135
+ `CallbackKeyStore` is allowed in production; `DevKeyStore` is not.
136
+
137
+ **Standard TPM 2.0 does not provide the secp256k1 curve** (only NIST P-256, etc.), so a TPM cannot be used directly
138
+ as an EVM signer. Using a TPM requires a P-256-based account design (`secp256r1`/RIP-7212 verification),
139
+ which `HephAccount` does not have yet.
140
+
141
+ ## `pay()` results — never "settled" without confirmation
142
+
143
+ | `status` | Meaning |
144
+ |---|---|
145
+ | `settled` | The Facilitator answered HTTP 200 with `status == "settled"`, `txHash`, and `accessToken` |
146
+ | `simulated` | `dry_run=True`: only signs the intent, no payment, no network access |
147
+ | `failed` | Every other condition (no `facilitator_url`, network error, non-200, invalid response, mock settlement without `allow_mock=True`) |
148
+
149
+ ## Verification (what is tested, and what is not)
150
+
151
+ `python -m unittest discover -s sdk-python/tests -t sdk-python`
152
+
153
+ - **Unit tests** (no chain): UserOperation (EntryPoint golden hash), bundler client, `CallbackKeyStore`, `pay()`, guards.
154
+ - **Integration tests** (`test_integration_anvil.py`, skipped automatically if `anvil`/`forge` is absent): real swaps
155
+ against **real contracts on Anvil**: Uniswap v4 PoolManager, `HephHook` (mined flag address), `HephRouter`,
156
+ `MachineRegistry`, `HephAccount`, and the **real EntryPoint v0.7** (bytecode from mainnet). Fixture:
157
+ `contracts/script/LocalSdkFixture.s.sol`.
158
+ - **NOT tested:** a production bundler. The bundler in tests is a mock that calls `EntryPoint.handleOps`
159
+ (without ERC-7562 rules, mempool, or gas estimation). Also not tested: paymaster, real HSM/KMS, and public chains.
160
+
161
+ ## Security Notes & Limitations
162
+
163
+ - The `SwapIntent` signature follows the contract typehash (`uint64 deadline`); the pool uses the dynamic fee flag
164
+ `0x800000`; the mainnet chain ID is `4663`. Guarded by golden vectors shared with Foundry and TypeScript.
165
+ - On mainnet (`chain="robinhood"`) all contract addresses must be explicit (no dummy addresses), and the chain ID from
166
+ the RPC must match the configured chain.
167
+ - `DevKeyStore` is rejected when `NODE_ENV`/`HEPH_ENV=production`.
168
+ - In production, `machines.create` requires an explicit `account`; the Python SDK does not predict the address via a factory
169
+ (a public signer address must not be used as the account, see SEC-FIX-01).
170
+ - Mainnet: `HephHook` and `HephRouter` are not deployed yet (Stage 2), so mainnet swaps cannot be performed yet.
@@ -0,0 +1,145 @@
1
+ # HEPH Forge Python SDK
2
+
3
+ Official Python package for the **HEPH** (*Hook for Embodied Physical Hardware*) autonomous physical-device financial protocol.
4
+ Main features:
5
+
6
+ - Machine session key management & Hardware Keystore abstraction (`DevKeyStore`, `KeyStore`).
7
+ - Standardized EIP-712 signing for revenue swaps (`SwapIntent`) and HTTP 402 payments (`Payment402Intent`).
8
+ - `hookData` calldata encoding for the HEPH Uniswap v4 Hook.
9
+ - Easy integration with robotics frameworks (ROS2/Python) and AI agent pipelines.
10
+
11
+ ## Installation
12
+
13
+ ```bash
14
+ pip install --upgrade pip # pip 22.x (Ubuntu 22.04 / ROS Humble) installs an empty 'UNKNOWN 0.0.0' package
15
+ pip install heph-forge # check: pip show heph-forge
16
+ # from a checkout: pip install ./sdk-python
17
+ ```
18
+
19
+ > **Status: beta (`0.1.0b0`), testnet only.** The contracts have not had an external audit and
20
+ > `DevKeyStore` (raw private key) is rejected in production. Use `CallbackKeyStore` with an
21
+ > external signer / hardware module for anything beyond testing.
22
+
23
+ ## Usage Example
24
+
25
+ ```python
26
+ from heph_forge import Forge
27
+
28
+ # 1. Forge client. rpc_url and bundler_url are required to read the chain and send swaps.
29
+ forge = Forge.connect(
30
+ private_key="0x...", # dev/test only; in production use CallbackKeyStore (see below)
31
+ chain="robinhoodTestnet",
32
+ rpc_url="https://rpc.testnet.chain.robinhood.com",
33
+ bundler_url="https://bundler.example", # ERC-4337 v0.7 bundler
34
+ )
35
+
36
+ # 2. Machine identity. `account` = Machine Account (compute it with the TypeScript SDK when using a factory + random salt).
37
+ machine = forge.machines.create(
38
+ name="autonomous-delivery-01",
39
+ operator="0xOperator...",
40
+ account="0xMachineAccount...",
41
+ )
42
+
43
+ # 3. Read on-chain status
44
+ machine.verify_registration() # unregistered | registered | RegistrationMismatch (claimed by another operator)
45
+ machine.get_info() # signer, operator, registeredAt, lastActiveAt, frozen, ...
46
+ machine.effective_tier() # tier used by HephHook for fees (inactive Silver = Bronze)
47
+ machine.is_frozen()
48
+ machine.usdg_balance()
49
+
50
+ # 4. Swap revenue to USDG (ERC-4337 v0.7 UserOperation: executeBatch([approve, router.swap]))
51
+ result = machine.swap(
52
+ token_in="0xRevenueToken...",
53
+ amount_in=10_000_000,
54
+ min_amount_out=9_000_000,
55
+ )
56
+ assert result["status"] == "executed" # amountOut, protocolFee, txHash, userOpHash
57
+
58
+ # 5. Pay for a service through the HEPH Facilitator (HTTP 402)
59
+ res = machine.pay(
60
+ url="https://charger.example/start",
61
+ max_amount=250_000, # $0.25 USDG
62
+ facilitator_url="https://facilitator.example",
63
+ merchant_address="0xMerchant...",
64
+ )
65
+ assert res["status"] == "settled" # only when the Facilitator confirms
66
+ ```
67
+
68
+ ## `swap()`: what it does and when it fails
69
+
70
+ It runs on-chain pre-checks first (fail fast with a clear error, sending nothing):
71
+ the account is registered and its identity matches, the registered `signer` = the keystore key, the account session key = the keystore key,
72
+ the machine is not frozen, and gas funds are sufficient (account ETH balance + EntryPoint deposit >= prefund). Then it signs the
73
+ `SwapIntent`, builds `executeBatch([approve, HephRouter.swap])`, signs the UserOperation with the session key
74
+ (EIP-191 over `userOpHash`, per `HephAccount.validateUserOp`), sends it to the bundler in the standard v0.7 RPC format
75
+ (`eth_sendUserOperation [userOp, entryPoint]`), and waits for the result.
76
+
77
+ | Condition | Result |
78
+ |---|---|
79
+ | Success | `{"status": "executed", "txHash", "userOpHash", "amountOut", "protocolFee", ...}` |
80
+ | `rpc_url`/`bundler_url` empty | `ChainNotConfigured` |
81
+ | Signer or session key is not the keystore key, account claimed by another operator | `RegistrationMismatch` |
82
+ | Machine or its fleet is frozen | `MachineFrozenError` |
83
+ | Insufficient gas funds | `InsufficientGasFunds` |
84
+ | Bundler rejects (signature, nonce, prefund, etc.) | `BundlerError` (carries the reason from the EntryPoint) |
85
+ | Lands on-chain but execution fails (e.g. slippage) | `UserOperationReverted` |
86
+ | Not confirmed within `timeout` | `UserOperationTimeout` |
87
+
88
+ There is never a false success. Gas is paid from the machine account's ETH; **paymaster is not supported yet** (the mainnet paymaster
89
+ is also not funded/staked yet). Account creation via `initCode` is not supported yet.
90
+
91
+ ## Hardware keystore / KMS: `CallbackKeyStore`
92
+
93
+ The SDK never holds the private key when using `CallbackKeyStore`: it computes the digest (EIP-191/EIP-712)
94
+ and asks an external signer to sign it. Suitable for KMS/HSM/secure elements that support
95
+ **secp256k1** and whose keys cannot be exported (e.g. AWS KMS `ECC_SECG_P256K1`, YubiHSM 2).
96
+
97
+ ```python
98
+ from heph_forge import CallbackKeyStore, Forge
99
+
100
+ def sign_hash(digest: bytes) -> bytes: # 65 bytes: r || s || v (v = 0/1 or 27/28)
101
+ return my_hsm.sign(digest) # the key never leaves the HSM
102
+
103
+ keystore = CallbackKeyStore("0xMachineSessionKeyAddress...", sign_hash)
104
+ forge = Forge(keystore=keystore, chain="robinhood", rpc_url=..., bundler_url=..., entry_point=...,
105
+ registry_address=..., router_address=..., hook_address=..., usdg_address=...)
106
+ ```
107
+
108
+ The SDK normalizes `s` to low form (required for OpenZeppelin contract ECDSA) and verifies that the signature
109
+ recovers the configured address, so a wrong configuration fails in the SDK, not as an on-chain revert.
110
+ `CallbackKeyStore` is allowed in production; `DevKeyStore` is not.
111
+
112
+ **Standard TPM 2.0 does not provide the secp256k1 curve** (only NIST P-256, etc.), so a TPM cannot be used directly
113
+ as an EVM signer. Using a TPM requires a P-256-based account design (`secp256r1`/RIP-7212 verification),
114
+ which `HephAccount` does not have yet.
115
+
116
+ ## `pay()` results — never "settled" without confirmation
117
+
118
+ | `status` | Meaning |
119
+ |---|---|
120
+ | `settled` | The Facilitator answered HTTP 200 with `status == "settled"`, `txHash`, and `accessToken` |
121
+ | `simulated` | `dry_run=True`: only signs the intent, no payment, no network access |
122
+ | `failed` | Every other condition (no `facilitator_url`, network error, non-200, invalid response, mock settlement without `allow_mock=True`) |
123
+
124
+ ## Verification (what is tested, and what is not)
125
+
126
+ `python -m unittest discover -s sdk-python/tests -t sdk-python`
127
+
128
+ - **Unit tests** (no chain): UserOperation (EntryPoint golden hash), bundler client, `CallbackKeyStore`, `pay()`, guards.
129
+ - **Integration tests** (`test_integration_anvil.py`, skipped automatically if `anvil`/`forge` is absent): real swaps
130
+ against **real contracts on Anvil**: Uniswap v4 PoolManager, `HephHook` (mined flag address), `HephRouter`,
131
+ `MachineRegistry`, `HephAccount`, and the **real EntryPoint v0.7** (bytecode from mainnet). Fixture:
132
+ `contracts/script/LocalSdkFixture.s.sol`.
133
+ - **NOT tested:** a production bundler. The bundler in tests is a mock that calls `EntryPoint.handleOps`
134
+ (without ERC-7562 rules, mempool, or gas estimation). Also not tested: paymaster, real HSM/KMS, and public chains.
135
+
136
+ ## Security Notes & Limitations
137
+
138
+ - The `SwapIntent` signature follows the contract typehash (`uint64 deadline`); the pool uses the dynamic fee flag
139
+ `0x800000`; the mainnet chain ID is `4663`. Guarded by golden vectors shared with Foundry and TypeScript.
140
+ - On mainnet (`chain="robinhood"`) all contract addresses must be explicit (no dummy addresses), and the chain ID from
141
+ the RPC must match the configured chain.
142
+ - `DevKeyStore` is rejected when `NODE_ENV`/`HEPH_ENV=production`.
143
+ - In production, `machines.create` requires an explicit `account`; the Python SDK does not predict the address via a factory
144
+ (a public signer address must not be used as the account, see SEC-FIX-01).
145
+ - Mainnet: `HephHook` and `HephRouter` are not deployed yet (Stage 2), so mainnet swaps cannot be performed yet.
@@ -0,0 +1,62 @@
1
+ """HEPH Forge Python SDK."""
2
+
3
+ from .client import Forge, MachineClient
4
+ from .eip712 import (
5
+ CHAIN_IDS,
6
+ DYNAMIC_FEE_FLAG,
7
+ PAYMENT_402_TYPES,
8
+ POOL_TICK_SPACING,
9
+ SWAP_INTENT_TYPES,
10
+ compute_machine_id,
11
+ compute_pool_id,
12
+ encode_hook_data,
13
+ get_heph_domain,
14
+ get_heph_facilitator_domain,
15
+ resolve_chain_id,
16
+ )
17
+ from .bundler import BundlerClient, BundlerError, UserOperationReverted, UserOperationTimeout
18
+ from .errors import (
19
+ ChainNotConfigured,
20
+ HephError,
21
+ InsufficientGasFunds,
22
+ MachineFrozenError,
23
+ RegistrationMismatch,
24
+ RpcError,
25
+ )
26
+ from .keystore import CallbackKeyStore, DevKeyStore, KeyStore, KeystoreError, is_production
27
+ from .userop import ENTRYPOINT_V07, UserOperation
28
+
29
+ __all__ = [
30
+ "Forge",
31
+ "MachineClient",
32
+ "KeyStore",
33
+ "DevKeyStore",
34
+ "compute_machine_id",
35
+ "compute_pool_id",
36
+ "encode_hook_data",
37
+ "get_heph_domain",
38
+ "get_heph_facilitator_domain",
39
+ "SWAP_INTENT_TYPES",
40
+ "PAYMENT_402_TYPES",
41
+ "CHAIN_IDS",
42
+ "DYNAMIC_FEE_FLAG",
43
+ "POOL_TICK_SPACING",
44
+ "resolve_chain_id",
45
+ "is_production",
46
+ "CallbackKeyStore",
47
+ "KeystoreError",
48
+ "BundlerClient",
49
+ "BundlerError",
50
+ "UserOperationReverted",
51
+ "UserOperationTimeout",
52
+ "UserOperation",
53
+ "ENTRYPOINT_V07",
54
+ "HephError",
55
+ "ChainNotConfigured",
56
+ "InsufficientGasFunds",
57
+ "MachineFrozenError",
58
+ "RegistrationMismatch",
59
+ "RpcError",
60
+ ]
61
+
62
+ __version__ = "0.1.0"
@@ -0,0 +1,131 @@
1
+ """Minimal ABIs of the HEPH contracts + EntryPoint v0.7 used by the Python SDK.
2
+
3
+ Only the functions/events used by the SDK. Compatibility with the real contracts is verified by
4
+ `tests/test_integration_anvil.py` (real contracts on Anvil), not by assumption.
5
+ """
6
+
7
+ from typing import Any, Dict, List
8
+
9
+
10
+ def _fn(name: str, inputs: List[Dict[str, Any]], outputs: List[Dict[str, Any]], mutability: str = "view") -> Dict[str, Any]:
11
+ return {"type": "function", "name": name, "inputs": inputs, "outputs": outputs, "stateMutability": mutability}
12
+
13
+
14
+ def _p(type_: str, name: str = "", components: List[Dict[str, Any]] | None = None) -> Dict[str, Any]:
15
+ out: Dict[str, Any] = {"type": type_, "name": name}
16
+ if components is not None:
17
+ out["components"] = components
18
+ return out
19
+
20
+
21
+ POOL_KEY_COMPONENTS = [
22
+ _p("address", "currency0"),
23
+ _p("address", "currency1"),
24
+ _p("uint24", "fee"),
25
+ _p("int24", "tickSpacing"),
26
+ _p("address", "hooks"),
27
+ ]
28
+
29
+ SWAP_REQUEST_COMPONENTS = [
30
+ _p("tuple", "key", POOL_KEY_COMPONENTS),
31
+ _p("bool", "zeroForOne"),
32
+ _p("uint128", "amountIn"),
33
+ _p("uint128", "minAmountOut"),
34
+ _p("bytes", "hookData"),
35
+ ]
36
+
37
+ MACHINE_COMPONENTS = [
38
+ _p("address", "account"),
39
+ _p("address", "operator"),
40
+ _p("address", "signer"),
41
+ _p("bytes32", "attestationHash"),
42
+ _p("uint64", "registeredAt"),
43
+ _p("uint64", "lastActiveAt"),
44
+ _p("uint64", "lastViolationAt"),
45
+ _p("bool", "attestationValid"),
46
+ _p("bool", "frozen"),
47
+ ]
48
+
49
+ PACKED_USER_OP_COMPONENTS = [
50
+ _p("address", "sender"),
51
+ _p("uint256", "nonce"),
52
+ _p("bytes", "initCode"),
53
+ _p("bytes", "callData"),
54
+ _p("bytes32", "accountGasLimits"),
55
+ _p("uint256", "preVerificationGas"),
56
+ _p("bytes32", "gasFees"),
57
+ _p("bytes", "paymasterAndData"),
58
+ _p("bytes", "signature"),
59
+ ]
60
+
61
+ REGISTRY_ABI = [
62
+ _fn("machineIdOf", [_p("address", "account")], [_p("bytes32")]),
63
+ _fn("getMachine", [_p("bytes32", "machineId")], [_p("tuple", "", MACHINE_COMPONENTS)]),
64
+ _fn("tierOf", [_p("bytes32", "machineId")], [_p("uint8")]),
65
+ _fn("isFrozen", [_p("bytes32", "machineId")], [_p("bool")]),
66
+ _fn("dailySpent", [_p("bytes32", "machineId"), _p("uint64", "day")], [_p("uint256")]),
67
+ ]
68
+
69
+ HOOK_ABI = [
70
+ _fn("effectiveTierOf", [_p("bytes32", "machineId")], [_p("uint8")]),
71
+ ]
72
+
73
+ ROUTER_ABI = [
74
+ _fn("swap", [_p("tuple", "req", SWAP_REQUEST_COMPONENTS)], [_p("uint256", "amountOut")], "nonpayable"),
75
+ {
76
+ "type": "event",
77
+ "name": "MachineSwap",
78
+ "anonymous": False,
79
+ "inputs": [
80
+ {**_p("bytes32", "machineId"), "indexed": True},
81
+ {**_p("address", "account"), "indexed": True},
82
+ {**_p("address", "tokenIn"), "indexed": False},
83
+ {**_p("uint256", "amountIn"), "indexed": False},
84
+ {**_p("uint256", "amountOut"), "indexed": False},
85
+ {**_p("uint256", "protocolFee"), "indexed": False},
86
+ ],
87
+ },
88
+ ]
89
+
90
+ ERC20_ABI = [
91
+ _fn("balanceOf", [_p("address", "owner")], [_p("uint256")]),
92
+ _fn("decimals", [], [_p("uint8")]),
93
+ _fn("approve", [_p("address", "spender"), _p("uint256", "amount")], [_p("bool")], "nonpayable"),
94
+ ]
95
+
96
+ ACCOUNT_ABI = [
97
+ _fn("sessionKey", [], [_p("address")]),
98
+ _fn("owner", [], [_p("address")]),
99
+ _fn(
100
+ "executeBatch",
101
+ [_p("address[]", "dests"), _p("uint256[]", "values"), _p("bytes[]", "datas")],
102
+ [],
103
+ "nonpayable",
104
+ ),
105
+ ]
106
+
107
+ ENTRYPOINT_ABI = [
108
+ _fn("getNonce", [_p("address", "sender"), _p("uint192", "key")], [_p("uint256")]),
109
+ _fn("balanceOf", [_p("address", "account")], [_p("uint256")]),
110
+ _fn("getUserOpHash", [_p("tuple", "userOp", PACKED_USER_OP_COMPONENTS)], [_p("bytes32")]),
111
+ _fn(
112
+ "handleOps",
113
+ [_p("tuple[]", "ops", PACKED_USER_OP_COMPONENTS), _p("address", "beneficiary")],
114
+ [],
115
+ "nonpayable",
116
+ ),
117
+ {
118
+ "type": "event",
119
+ "name": "UserOperationEvent",
120
+ "anonymous": False,
121
+ "inputs": [
122
+ {**_p("bytes32", "userOpHash"), "indexed": True},
123
+ {**_p("address", "sender"), "indexed": True},
124
+ {**_p("address", "paymaster"), "indexed": True},
125
+ {**_p("uint256", "nonce"), "indexed": False},
126
+ {**_p("bool", "success"), "indexed": False},
127
+ {**_p("uint256", "actualGasCost"), "indexed": False},
128
+ {**_p("uint256", "actualGasUsed"), "indexed": False},
129
+ ],
130
+ },
131
+ ]
@@ -0,0 +1,76 @@
1
+ """ERC-4337 bundler JSON-RPC client (eth_sendUserOperation / eth_getUserOperationReceipt)."""
2
+
3
+ import time
4
+ from typing import Any, Dict, Optional
5
+
6
+ import requests
7
+
8
+
9
+ class BundlerError(Exception):
10
+ """The bundler rejected the UserOperation or is unreachable."""
11
+
12
+
13
+ class UserOperationTimeout(BundlerError):
14
+ """The UserOperation was sent but not confirmed within the time limit."""
15
+
16
+
17
+ class UserOperationReverted(BundlerError):
18
+ """The UserOperation landed on-chain but its execution failed (success == false)."""
19
+
20
+
21
+ class BundlerClient:
22
+ def __init__(self, url: str, timeout: float = 15.0) -> None:
23
+ if not url:
24
+ raise ValueError("bundler url is required")
25
+ self.url = url
26
+ self.timeout = timeout
27
+ self._id = 0
28
+
29
+ def _rpc(self, method: str, params: list) -> Any:
30
+ self._id += 1
31
+ try:
32
+ response = requests.post(
33
+ self.url,
34
+ json={"jsonrpc": "2.0", "id": self._id, "method": method, "params": params},
35
+ timeout=self.timeout,
36
+ )
37
+ except Exception as exc: # noqa: BLE001
38
+ raise BundlerError(f"Bundler is unreachable: {exc}") from exc
39
+
40
+ try:
41
+ body = response.json()
42
+ except Exception as exc: # noqa: BLE001
43
+ raise BundlerError(f"Bundler response is not JSON (HTTP {response.status_code})") from exc
44
+
45
+ if not isinstance(body, dict):
46
+ raise BundlerError("Invalid bundler response")
47
+ if body.get("error"):
48
+ err = body["error"]
49
+ message = err.get("message") if isinstance(err, dict) else str(err)
50
+ raise BundlerError(f"Bundler rejected {method}: {message}")
51
+ if response.status_code != 200:
52
+ raise BundlerError(f"Bundler replied with HTTP {response.status_code}")
53
+ return body.get("result")
54
+
55
+ def send_user_operation(self, user_op_rpc: Dict[str, str], entry_point: str) -> str:
56
+ """Sends a UserOperation; returns the userOpHash from the bundler."""
57
+ result = self._rpc("eth_sendUserOperation", [user_op_rpc, entry_point])
58
+ if not isinstance(result, str) or not result.startswith("0x"):
59
+ raise BundlerError("Bundler did not return a valid userOpHash")
60
+ return result
61
+
62
+ def get_user_operation_receipt(self, user_op_hash: str) -> Optional[Dict[str, Any]]:
63
+ result = self._rpc("eth_getUserOperationReceipt", [user_op_hash])
64
+ return result if isinstance(result, dict) else None
65
+
66
+ def wait_for_receipt(self, user_op_hash: str, timeout: float = 60.0, poll_interval: float = 1.0) -> Dict[str, Any]:
67
+ deadline = time.monotonic() + timeout
68
+ while True:
69
+ receipt = self.get_user_operation_receipt(user_op_hash)
70
+ if receipt is not None:
71
+ return receipt
72
+ if time.monotonic() >= deadline:
73
+ raise UserOperationTimeout(
74
+ f"UserOperation {user_op_hash} was not confirmed after {timeout:.0f} seconds"
75
+ )
76
+ time.sleep(poll_interval)