pyxie-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,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 HEPH Protocol
4
+ Copyright (c) 2026 PYXIE
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
@@ -0,0 +1,2 @@
1
+ include LICENSE
2
+ include README.md
@@ -0,0 +1,167 @@
1
+ Metadata-Version: 2.4
2
+ Name: pyxie-forge
3
+ Version: 0.1.0b0
4
+ Summary: PYXIE Forge Python SDK — machine finance on Robinhood Chain
5
+ Author: PYXIE
6
+ License: MIT
7
+ Keywords: pyxie,uniswap-v4,erc-4337,x402,depin,robotics
8
+ Classifier: Development Status :: 4 - Beta
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.10
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Typing :: Typed
15
+ Requires-Python: >=3.10
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Requires-Dist: web3>=7.0.0
19
+ Requires-Dist: eth-account>=0.13.0
20
+ Requires-Dist: requests>=2.31.0
21
+ Dynamic: license-file
22
+
23
+ # PYXIE Forge Python SDK
24
+
25
+ Official Python package for the **PYXIE** (*Programmable Yield & eXchange for Intelligent Equipment*) autonomous physical-device financial protocol.
26
+ Main features:
27
+
28
+ - Machine session key management & Hardware Keystore abstraction (`DevKeyStore`, `KeyStore`).
29
+ - Standardized EIP-712 signing for revenue swaps (`SwapIntent`) and HTTP 402 payments (`Payment402Intent`).
30
+ - `hookData` calldata encoding for the PYXIE Uniswap v4 Hook.
31
+ - Easy integration with robotics frameworks (ROS2/Python) and AI agent pipelines.
32
+
33
+ ## Installation
34
+
35
+ ```bash
36
+ pip install --upgrade pip # pip 22.x (Ubuntu 22.04 / ROS Humble) installs an empty 'UNKNOWN 0.0.0' package
37
+ pip install pyxie-forge # check: pip show pyxie-forge
38
+ # from a checkout: pip install ./sdk-python
39
+ ```
40
+
41
+ > **Status: beta (`0.1.0b0`), testnet only.** The contracts have not had an external audit and
42
+ > `DevKeyStore` (raw private key) is rejected in production. Use `CallbackKeyStore` with an
43
+ > external signer / hardware module for anything beyond testing.
44
+
45
+ ## Usage Example
46
+
47
+ ```python
48
+ from pyxie_forge import Forge
49
+
50
+ # 1. Forge client. rpc_url and bundler_url are required to read the chain and send swaps.
51
+ forge = Forge.connect(
52
+ private_key="0x...", # dev/test only; in production use CallbackKeyStore (see below)
53
+ chain="robinhoodTestnet",
54
+ rpc_url="https://rpc.testnet.chain.robinhood.com",
55
+ bundler_url="https://bundler.example", # ERC-4337 v0.7 bundler
56
+ )
57
+
58
+ # 2. Machine identity. `account` = Machine Account (compute it with the TypeScript SDK when using a factory + random salt).
59
+ machine = forge.machines.create(
60
+ name="autonomous-delivery-01",
61
+ operator="0xOperator...",
62
+ account="0xMachineAccount...",
63
+ )
64
+
65
+ # 3. Read on-chain status
66
+ machine.verify_registration() # unregistered | registered | RegistrationMismatch (claimed by another operator)
67
+ machine.get_info() # signer, operator, registeredAt, lastActiveAt, frozen, ...
68
+ machine.effective_tier() # tier used by PyxieHook for fees (inactive Silver = Bronze)
69
+ machine.is_frozen()
70
+ machine.usdg_balance()
71
+
72
+ # 4. Swap revenue to USDG (ERC-4337 v0.7 UserOperation: executeBatch([approve, router.swap]))
73
+ result = machine.swap(
74
+ token_in="0xRevenueToken...",
75
+ amount_in=10_000_000,
76
+ min_amount_out=9_000_000,
77
+ )
78
+ assert result["status"] == "executed" # amountOut, protocolFee, txHash, userOpHash
79
+
80
+ # 5. Pay for a service through the PYXIE Facilitator (HTTP 402)
81
+ res = machine.pay(
82
+ url="https://charger.example/start",
83
+ max_amount=250_000, # $0.25 USDG
84
+ facilitator_url="https://facilitator.example",
85
+ merchant_address="0xMerchant...",
86
+ )
87
+ assert res["status"] == "settled" # only when the Facilitator confirms
88
+ ```
89
+
90
+ ## `swap()`: what it does and when it fails
91
+
92
+ It runs on-chain pre-checks first (fail fast with a clear error, sending nothing):
93
+ the account is registered and its identity matches, the registered `signer` = the keystore key, the account session key = the keystore key,
94
+ the machine is not frozen, and gas funds are sufficient (account ETH balance + EntryPoint deposit >= prefund). Then it signs the
95
+ `SwapIntent`, builds `executeBatch([approve, PyxieRouter.swap])`, signs the UserOperation with the session key
96
+ (EIP-191 over `userOpHash`, per `PyxieAccount.validateUserOp`), sends it to the bundler in the standard v0.7 RPC format
97
+ (`eth_sendUserOperation [userOp, entryPoint]`), and waits for the result.
98
+
99
+ | Condition | Result |
100
+ |---|---|
101
+ | Success | `{"status": "executed", "txHash", "userOpHash", "amountOut", "protocolFee", ...}` |
102
+ | `rpc_url`/`bundler_url` empty | `ChainNotConfigured` |
103
+ | Signer or session key is not the keystore key, account claimed by another operator | `RegistrationMismatch` |
104
+ | Machine or its fleet is frozen | `MachineFrozenError` |
105
+ | Insufficient gas funds | `InsufficientGasFunds` |
106
+ | Bundler rejects (signature, nonce, prefund, etc.) | `BundlerError` (carries the reason from the EntryPoint) |
107
+ | Lands on-chain but execution fails (e.g. slippage) | `UserOperationReverted` |
108
+ | Not confirmed within `timeout` | `UserOperationTimeout` |
109
+
110
+ There is never a false success. Gas is paid from the machine account's ETH; **paymaster is not supported yet** (the mainnet paymaster
111
+ is also not funded/staked yet). Account creation via `initCode` is not supported yet.
112
+
113
+ ## Hardware keystore / KMS: `CallbackKeyStore`
114
+
115
+ The SDK never holds the private key when using `CallbackKeyStore`: it computes the digest (EIP-191/EIP-712)
116
+ and asks an external signer to sign it. Suitable for KMS/HSM/secure elements that support
117
+ **secp256k1** and whose keys cannot be exported (e.g. AWS KMS `ECC_SECG_P256K1`, YubiHSM 2).
118
+
119
+ ```python
120
+ from pyxie_forge import CallbackKeyStore, Forge
121
+
122
+ def sign_hash(digest: bytes) -> bytes: # 65 bytes: r || s || v (v = 0/1 or 27/28)
123
+ return my_hsm.sign(digest) # the key never leaves the HSM
124
+
125
+ keystore = CallbackKeyStore("0xMachineSessionKeyAddress...", sign_hash)
126
+ forge = Forge(keystore=keystore, chain="robinhood", rpc_url=..., bundler_url=..., entry_point=...,
127
+ registry_address=..., router_address=..., hook_address=..., usdg_address=...)
128
+ ```
129
+
130
+ The SDK normalizes `s` to low form (required for OpenZeppelin contract ECDSA) and verifies that the signature
131
+ recovers the configured address, so a wrong configuration fails in the SDK, not as an on-chain revert.
132
+ `CallbackKeyStore` is allowed in production; `DevKeyStore` is not.
133
+
134
+ **Standard TPM 2.0 does not provide the secp256k1 curve** (only NIST P-256, etc.), so a TPM cannot be used directly
135
+ as an EVM signer. Using a TPM requires a P-256-based account design (`secp256r1`/RIP-7212 verification),
136
+ which `PyxieAccount` does not have yet.
137
+
138
+ ## `pay()` results — never "settled" without confirmation
139
+
140
+ | `status` | Meaning |
141
+ |---|---|
142
+ | `settled` | The Facilitator answered HTTP 200 with `status == "settled"`, `txHash`, and `accessToken` |
143
+ | `simulated` | `dry_run=True`: only signs the intent, no payment, no network access |
144
+ | `failed` | Every other condition (no `facilitator_url`, network error, non-200, invalid response, mock settlement without `allow_mock=True`) |
145
+
146
+ ## Verification (what is tested, and what is not)
147
+
148
+ `python -m unittest discover -s sdk-python/tests -t sdk-python`
149
+
150
+ - **Unit tests** (no chain): UserOperation (EntryPoint golden hash), bundler client, `CallbackKeyStore`, `pay()`, guards.
151
+ - **Integration tests** (`test_integration_anvil.py`, skipped automatically if `anvil`/`forge` is absent): real swaps
152
+ against **real contracts on Anvil**: Uniswap v4 PoolManager, `PyxieHook` (mined flag address), `PyxieRouter`,
153
+ `MachineRegistry`, `PyxieAccount`, and the **real EntryPoint v0.7** (bytecode from mainnet). Fixture:
154
+ `contracts/script/LocalSdkFixture.s.sol`.
155
+ - **NOT tested:** a production bundler. The bundler in tests is a mock that calls `EntryPoint.handleOps`
156
+ (without ERC-7562 rules, mempool, or gas estimation). Also not tested: paymaster, real HSM/KMS, and public chains.
157
+
158
+ ## Security Notes & Limitations
159
+
160
+ - The `SwapIntent` signature follows the contract typehash (`uint64 deadline`); the pool uses the dynamic fee flag
161
+ `0x800000`; the mainnet chain ID is `4663`. Guarded by golden vectors shared with Foundry and TypeScript.
162
+ - On mainnet (`chain="robinhood"`) all contract addresses must be explicit (no dummy addresses), and the chain ID from
163
+ the RPC must match the configured chain.
164
+ - `DevKeyStore` is rejected when `NODE_ENV`/`PYXIE_ENV=production`.
165
+ - In production, `machines.create` requires an explicit `account`; the Python SDK does not predict the address via a factory
166
+ (a public signer address must not be used as the account, see SEC-FIX-01).
167
+ - Mainnet: `PyxieHook` and `PyxieRouter` are not deployed yet (Stage 2), so mainnet swaps cannot be performed yet.
@@ -0,0 +1,145 @@
1
+ # PYXIE Forge Python SDK
2
+
3
+ Official Python package for the **PYXIE** (*Programmable Yield & eXchange for Intelligent Equipment*) 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 PYXIE 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 pyxie-forge # check: pip show pyxie-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 pyxie_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 PyxieHook 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 PYXIE 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, PyxieRouter.swap])`, signs the UserOperation with the session key
74
+ (EIP-191 over `userOpHash`, per `PyxieAccount.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 pyxie_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 `PyxieAccount` 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, `PyxieHook` (mined flag address), `PyxieRouter`,
131
+ `MachineRegistry`, `PyxieAccount`, 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`/`PYXIE_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: `PyxieHook` and `PyxieRouter` are not deployed yet (Stage 2), so mainnet swaps cannot be performed yet.
@@ -0,0 +1,35 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "pyxie-forge"
7
+ version = "0.1.0b0"
8
+ description = "PYXIE Forge Python SDK — machine finance on Robinhood Chain"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = { text = "MIT" }
12
+ keywords = ["pyxie", "uniswap-v4", "erc-4337", "x402", "depin", "robotics"]
13
+ classifiers = [
14
+ "Development Status :: 4 - Beta",
15
+ "License :: OSI Approved :: MIT License",
16
+ "Programming Language :: Python :: 3",
17
+ "Programming Language :: Python :: 3.10",
18
+ "Programming Language :: Python :: 3.11",
19
+ "Programming Language :: Python :: 3.12",
20
+ "Typing :: Typed",
21
+ ]
22
+ authors = [{ name = "PYXIE" }]
23
+ dependencies = [
24
+ "web3>=7.0.0",
25
+ "eth-account>=0.13.0",
26
+ "requests>=2.31.0",
27
+ ]
28
+
29
+ # Without this, setuptools auto-discovery fails because there are two top-level directories (pyxie_forge and tests):
30
+ # `pip install sdk-python` produces an empty "UNKNOWN 0.0.0" package or fails to build the wheel.
31
+ [tool.setuptools]
32
+ packages = ["pyxie_forge"]
33
+
34
+ [tool.setuptools.package-data]
35
+ pyxie_forge = ["py.typed"]
@@ -0,0 +1,62 @@
1
+ """PYXIE 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_pyxie_domain,
14
+ get_pyxie_facilitator_domain,
15
+ resolve_chain_id,
16
+ )
17
+ from .bundler import BundlerClient, BundlerError, UserOperationReverted, UserOperationTimeout
18
+ from .errors import (
19
+ ChainNotConfigured,
20
+ PyxieError,
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_pyxie_domain",
38
+ "get_pyxie_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
+ "PyxieError",
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 PYXIE 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)