Metadata-Version: 2.4
Name: heph-forge
Version: 0.1.0b0
Summary: HEPH Forge Python SDK — Hardware & autonomous machine finance protocol on Robinhood Chain
Author: HEPH Protocol
License: MIT
Project-URL: Homepage, https://github.com/heph-fleet/heph
Project-URL: Repository, https://github.com/heph-fleet/heph
Project-URL: Issues, https://github.com/heph-fleet/heph/issues
Keywords: heph,uniswap-v4,erc-4337,x402,depin,robotics
Classifier: Development Status :: 4 - Beta
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Typing :: Typed
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: web3>=7.0.0
Requires-Dist: eth-account>=0.13.0
Requires-Dist: requests>=2.31.0
Dynamic: license-file

# HEPH Forge Python SDK

Official Python package for the **HEPH** (*Hook for Embodied Physical Hardware*) autonomous physical-device financial protocol.
Main features:

- Machine session key management & Hardware Keystore abstraction (`DevKeyStore`, `KeyStore`).
- Standardized EIP-712 signing for revenue swaps (`SwapIntent`) and HTTP 402 payments (`Payment402Intent`).
- `hookData` calldata encoding for the HEPH Uniswap v4 Hook.
- Easy integration with robotics frameworks (ROS2/Python) and AI agent pipelines.

## Installation

```bash
pip install --upgrade pip      # pip 22.x (Ubuntu 22.04 / ROS Humble) installs an empty 'UNKNOWN 0.0.0' package
pip install heph-forge         # check: pip show heph-forge
# from a checkout: pip install ./sdk-python
```

> **Status: beta (`0.1.0b0`), testnet only.** The contracts have not had an external audit and
> `DevKeyStore` (raw private key) is rejected in production. Use `CallbackKeyStore` with an
> external signer / hardware module for anything beyond testing.

## Usage Example

```python
from heph_forge import Forge

# 1. Forge client. rpc_url and bundler_url are required to read the chain and send swaps.
forge = Forge.connect(
    private_key="0x...",                     # dev/test only; in production use CallbackKeyStore (see below)
    chain="robinhoodTestnet",
    rpc_url="https://rpc.testnet.chain.robinhood.com",
    bundler_url="https://bundler.example",   # ERC-4337 v0.7 bundler
)

# 2. Machine identity. `account` = Machine Account (compute it with the TypeScript SDK when using a factory + random salt).
machine = forge.machines.create(
    name="autonomous-delivery-01",
    operator="0xOperator...",
    account="0xMachineAccount...",
)

# 3. Read on-chain status
machine.verify_registration()   # unregistered | registered | RegistrationMismatch (claimed by another operator)
machine.get_info()              # signer, operator, registeredAt, lastActiveAt, frozen, ...
machine.effective_tier()        # tier used by HephHook for fees (inactive Silver = Bronze)
machine.is_frozen()
machine.usdg_balance()

# 4. Swap revenue to USDG (ERC-4337 v0.7 UserOperation: executeBatch([approve, router.swap]))
result = machine.swap(
    token_in="0xRevenueToken...",
    amount_in=10_000_000,
    min_amount_out=9_000_000,
)
assert result["status"] == "executed"       # amountOut, protocolFee, txHash, userOpHash

# 5. Pay for a service through the HEPH Facilitator (HTTP 402)
res = machine.pay(
    url="https://charger.example/start",
    max_amount=250_000,                      # $0.25 USDG
    facilitator_url="https://facilitator.example",
    merchant_address="0xMerchant...",
)
assert res["status"] == "settled"           # only when the Facilitator confirms
```

## `swap()`: what it does and when it fails

It runs on-chain pre-checks first (fail fast with a clear error, sending nothing):
the account is registered and its identity matches, the registered `signer` = the keystore key, the account session key = the keystore key,
the machine is not frozen, and gas funds are sufficient (account ETH balance + EntryPoint deposit >= prefund). Then it signs the
`SwapIntent`, builds `executeBatch([approve, HephRouter.swap])`, signs the UserOperation with the session key
(EIP-191 over `userOpHash`, per `HephAccount.validateUserOp`), sends it to the bundler in the standard v0.7 RPC format
(`eth_sendUserOperation [userOp, entryPoint]`), and waits for the result.

| Condition | Result |
|---|---|
| Success | `{"status": "executed", "txHash", "userOpHash", "amountOut", "protocolFee", ...}` |
| `rpc_url`/`bundler_url` empty | `ChainNotConfigured` |
| Signer or session key is not the keystore key, account claimed by another operator | `RegistrationMismatch` |
| Machine or its fleet is frozen | `MachineFrozenError` |
| Insufficient gas funds | `InsufficientGasFunds` |
| Bundler rejects (signature, nonce, prefund, etc.) | `BundlerError` (carries the reason from the EntryPoint) |
| Lands on-chain but execution fails (e.g. slippage) | `UserOperationReverted` |
| Not confirmed within `timeout` | `UserOperationTimeout` |

There is never a false success. Gas is paid from the machine account's ETH; **paymaster is not supported yet** (the mainnet paymaster
is also not funded/staked yet). Account creation via `initCode` is not supported yet.

## Hardware keystore / KMS: `CallbackKeyStore`

The SDK never holds the private key when using `CallbackKeyStore`: it computes the digest (EIP-191/EIP-712)
and asks an external signer to sign it. Suitable for KMS/HSM/secure elements that support
**secp256k1** and whose keys cannot be exported (e.g. AWS KMS `ECC_SECG_P256K1`, YubiHSM 2).

```python
from heph_forge import CallbackKeyStore, Forge

def sign_hash(digest: bytes) -> bytes:       # 65 bytes: r || s || v (v = 0/1 or 27/28)
    return my_hsm.sign(digest)                # the key never leaves the HSM

keystore = CallbackKeyStore("0xMachineSessionKeyAddress...", sign_hash)
forge = Forge(keystore=keystore, chain="robinhood", rpc_url=..., bundler_url=..., entry_point=...,
              registry_address=..., router_address=..., hook_address=..., usdg_address=...)
```

The SDK normalizes `s` to low form (required for OpenZeppelin contract ECDSA) and verifies that the signature
recovers the configured address, so a wrong configuration fails in the SDK, not as an on-chain revert.
`CallbackKeyStore` is allowed in production; `DevKeyStore` is not.

**Standard TPM 2.0 does not provide the secp256k1 curve** (only NIST P-256, etc.), so a TPM cannot be used directly
as an EVM signer. Using a TPM requires a P-256-based account design (`secp256r1`/RIP-7212 verification),
which `HephAccount` does not have yet.

## `pay()` results — never "settled" without confirmation

| `status` | Meaning |
|---|---|
| `settled` | The Facilitator answered HTTP 200 with `status == "settled"`, `txHash`, and `accessToken` |
| `simulated` | `dry_run=True`: only signs the intent, no payment, no network access |
| `failed` | Every other condition (no `facilitator_url`, network error, non-200, invalid response, mock settlement without `allow_mock=True`) |

## Verification (what is tested, and what is not)

`python -m unittest discover -s sdk-python/tests -t sdk-python`

- **Unit tests** (no chain): UserOperation (EntryPoint golden hash), bundler client, `CallbackKeyStore`, `pay()`, guards.
- **Integration tests** (`test_integration_anvil.py`, skipped automatically if `anvil`/`forge` is absent): real swaps
  against **real contracts on Anvil**: Uniswap v4 PoolManager, `HephHook` (mined flag address), `HephRouter`,
  `MachineRegistry`, `HephAccount`, and the **real EntryPoint v0.7** (bytecode from mainnet). Fixture:
  `contracts/script/LocalSdkFixture.s.sol`.
- **NOT tested:** a production bundler. The bundler in tests is a mock that calls `EntryPoint.handleOps`
  (without ERC-7562 rules, mempool, or gas estimation). Also not tested: paymaster, real HSM/KMS, and public chains.

## Security Notes & Limitations

- The `SwapIntent` signature follows the contract typehash (`uint64 deadline`); the pool uses the dynamic fee flag
  `0x800000`; the mainnet chain ID is `4663`. Guarded by golden vectors shared with Foundry and TypeScript.
- On mainnet (`chain="robinhood"`) all contract addresses must be explicit (no dummy addresses), and the chain ID from
  the RPC must match the configured chain.
- `DevKeyStore` is rejected when `NODE_ENV`/`HEPH_ENV=production`.
- In production, `machines.create` requires an explicit `account`; the Python SDK does not predict the address via a factory
  (a public signer address must not be used as the account, see SEC-FIX-01).
- Mainnet: `HephHook` and `HephRouter` are not deployed yet (Stage 2), so mainnet swaps cannot be performed yet.
