Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion modules/copying/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,4 +57,9 @@ ADR-0001's. Changing any of them is a new ADR.

## Non-standard commands

None yet. `commands.check` and `commands.test` are declared with the first file of code.
- **Venue tests** (`tests/test_venue.py`, marker `venue`) reach the venue's testnet and need
`FLET_TESTNET_MAIN_KEY` in the environment and `api.hyperliquid-testnet.xyz` allowed out.
Without the key they are skipped — `nstack test copying` then reports them as `s`, which is
*not run*. D2 is not accepted on a run where they were skipped.
- The command reads `FLET_KEY_DIR` and `FLET_KEY_SECRET` (a Fernet key:
`uv run python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"`).
3 changes: 3 additions & 0 deletions modules/copying/MANIFEST.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,9 @@ dependencies:
# No stack is imposed. check and test are required once the module holds more than its
# description (fitness M7): declare them before its first file of code.
commands:
check: "uv run ruff format --check . && uv run ruff check . && uv run mypy"
test: "uv run pytest"
bootstrap: "uv sync --all-groups"
# check: # under 2 min: format, lint, types
# test: # NEVER starts another module
# bootstrap: # optional: make the module usable from a fresh clone
Expand Down
8 changes: 7 additions & 1 deletion modules/copying/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,13 @@ nstack test copying # never starts another module
nstack run copying # locally, with doubles for the dependencies
```

Commands: the `commands` section of the MANIFEST, to declare for this module's stack.
Commands: the `commands` section of the MANIFEST.

```bash
uv run copying authorise <member main address> [--testnet] # a fresh agent, to approve on the venue
uv run copying status <member main address> [--testnet] # alive, per the venue — or no answer
uv run copying forget <member main address> # flet drops its copy; not a revocation
```

## Contracts

Expand Down
43 changes: 43 additions & 0 deletions modules/copying/pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
[project]
name = "flet-copying"
version = "0.1.0"
description = "Holds each member's trade-only agent key on the venue."
requires-python = ">=3.12"
# ADR-0001: the venue's official SDK signs trading actions as the member's agent; Fernet
# holds the key at rest. Nothing here may ever sign with a member's main key.
dependencies = ["hyperliquid-python-sdk==0.24.0", "cryptography>=43"]

[project.scripts]
copying = "copying.cli:main"

[dependency-groups]
dev = ["pytest>=8.3", "ruff>=0.6", "mypy>=1.11"]

[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"

[tool.hatch.build.targets.wheel]
packages = ["src/copying"]

[tool.ruff]
line-length = 100
src = ["src", "tests"]
extend-exclude = [".claude"]

[tool.ruff.lint]
select = ["E", "F", "I", "UP", "B", "SIM", "RUF"]

[tool.mypy]
strict = true
files = ["src", "tests"]

[[tool.mypy.overrides]]
# The SDK ships no type information.
module = ["hyperliquid.*", "eth_account.*"]
ignore_missing_imports = true

[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "-q"
markers = ["venue: reaches the venue's testnet; needs FLET_TESTNET_MAIN_KEY"]
File renamed without changes.
91 changes: 91 additions & 0 deletions modules/copying/src/copying/cli.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
"""copying authorise | status | forget MEMBER — the member's key, as the venue sees it.

Exit codes: 0 done or alive · 1 flet holds no live key · 2 refused input or setup ·
3 no answer from the venue, nothing done.
"""

import argparse
import os
import sys
import time
from datetime import UTC, datetime
from pathlib import Path

from copying.guard import alive
from copying.key import member_address, new_agent
from copying.store import KeyStore
from copying.venue import NoAnswer, Venue

PAGES = {False: "https://app.hyperliquid.xyz/API", True: "https://app.hyperliquid-testnet.xyz/API"}


def venue_for(testnet: bool) -> Venue:
from hyperliquid.info import Info
from hyperliquid.utils.constants import MAINNET_API_URL, TESTNET_API_URL

return Info(TESTNET_API_URL if testnet else MAINNET_API_URL, skip_ws=True) # type: ignore[no-any-return]


def _now_ms() -> int:
return int(time.time() * 1000)


def _day(ms: int) -> str:
return datetime.fromtimestamp(ms / 1000, UTC).strftime("%Y-%m-%d %H:%M UTC")


def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(prog="copying")
parser.add_argument("command", choices=["authorise", "status", "forget"])
parser.add_argument("member", help="the member's main address on the venue")
parser.add_argument("--testnet", action="store_true")
args = parser.parse_args(argv)

try:
member = member_address(args.member)
store = KeyStore(Path(os.environ["FLET_KEY_DIR"]), os.environ["FLET_KEY_SECRET"].encode())
except (ValueError, KeyError):
print(
"Refused: a member address and FLET_KEY_DIR, FLET_KEY_SECRET are needed.",
file=sys.stderr,
)
return 2

if args.command == "authorise":
agent = new_agent(_now_ms())
store.put(member, agent)
print(f"Approve this agent with your main wallet at {PAGES[args.testnet]}")
print(f" Address: {agent.address}")
print(f" Name: {agent.name}")
print(f"It expires on {_day(agent.valid_until_ms)}. It can place and cancel orders,")
print("nothing else. Remove it on the same page to take it back at any time.")
return 0

if args.command == "forget":
store.forget(member)
print("flet no longer holds a key for this member.")
print(f"This does not revoke it on the venue: remove it at {PAGES[args.testnet]}")
return 0

if store.get(member) is None:
print("flet holds no key for this member.")
return 1
try:
try:
venue = venue_for(args.testnet)
except Exception as e: # the SDK reads the venue while being built
raise NoAnswer(type(e).__name__) from None
found = alive(member, store, venue, _now_ms())
except NoAnswer:
print("No answer from the venue: nothing was done, nothing is known.", file=sys.stderr)
return 3
if found is None:
print("Not listed on the venue, or expired: flet will not act for this member.")
return 1
listing = found[1]
print(f"alive: {listing.address}, until {_day(listing.valid_until_ms)} per the venue.")
return 0


if __name__ == "__main__":
sys.exit(main())
38 changes: 38 additions & 0 deletions modules/copying/src/copying/guard.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
"""The only way anything in flet acts for a member: after the venue says the agent lives."""

from collections.abc import Callable
from typing import Any

from eth_account import Account

from copying.store import Held, KeyStore
from copying.venue import Listing, Venue, listed


def alive(member: str, store: KeyStore, venue: Venue, now_ms: int) -> tuple[Held, Listing] | None:
"""The member's agent and the venue's listing of it, if listed and unexpired; else None.

One question to the venue, no retry. NoAnswer propagates with the key kept: an unheard
venue is not a revocation. A key the venue has stopped honouring is deleted.
"""
held = store.get(member)
if held is None:
return None
listing = listed(venue, member, held.agent.address)
if listing is None or listing.valid_until_ms <= now_ms:
if held.confirmed or held.agent.valid_until_ms <= now_ms or listing is not None:
store.forget(member)
return None
if not held.confirmed:
store.confirm(member)
return held, listing


def act_for[T](
member: str, store: KeyStore, venue: Venue, now_ms: int, action: Callable[[Any], T]
) -> T | None:
"""Runs `action` with the member's agent only if `alive` says so; otherwise nothing."""
found = alive(member, store, venue, now_ms)
if found is None:
return None
return action(Account.from_key(found[0].agent.private_key))
37 changes: 37 additions & 0 deletions modules/copying/src/copying/key.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
"""A member's agent: a fresh key pair flet generates, which the member approves on the venue."""

import re
from dataclasses import dataclass, field

from eth_account import Account

# The decider, 2026-09-24: 30 days, well under the venue's 180-day ceiling (ADR-0001).
LIFETIME_MS = 30 * 24 * 3600 * 1000

_ADDRESS = re.compile(r"0x[0-9a-f]{40}")


@dataclass(frozen=True)
class Agent:
address: str
valid_until_ms: int
private_key: str = field(repr=False)

@property
def name(self) -> str:
"""What the member types on the venue's API page; the venue reads the expiry from it."""
return f"flet valid_until {self.valid_until_ms}"


def new_agent(now_ms: int, lifetime_ms: int = LIFETIME_MS) -> Agent:
"""Always a fresh address: a deregistered agent's old signatures may be replayable."""
account = Account.create()
return Agent(account.address, now_ms + lifetime_ms, account.key.hex())


def member_address(raw: str) -> str:
"""A member's main address, lower-cased; anything else is refused before any use."""
address = raw.lower()
if not _ADDRESS.fullmatch(address):
raise ValueError("not an address")
return address
68 changes: 68 additions & 0 deletions modules/copying/src/copying/store.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
"""Agent keys at rest: one Fernet-encrypted file per member, readable by its owner only."""

import json
import os
from dataclasses import dataclass
from pathlib import Path

from cryptography.fernet import Fernet, InvalidToken

from copying.key import Agent, member_address


@dataclass(frozen=True)
class Held:
agent: Agent
# Seen listed by the venue at least once: absent afterwards means revoked, not pending.
confirmed: bool


class KeyStore:
def __init__(self, directory: Path, secret: bytes) -> None:
self._directory = directory
self._fernet = Fernet(secret)

def _path(self, member: str) -> Path:
return self._directory / f"{member_address(member)}.key"

def _write(self, member: str, agent: Agent, confirmed: bool) -> None:
path = self._path(member)
plain = json.dumps(
{
"address": agent.address,
"valid_until_ms": agent.valid_until_ms,
"private_key": agent.private_key,
"confirmed": confirmed,
}
).encode()
staged = path.with_suffix(".tmp")
fd = os.open(staged, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(fd, "wb") as f:
f.write(self._fernet.encrypt(plain))
os.replace(staged, path)

def put(self, member: str, agent: Agent) -> None:
self._write(member, agent, confirmed=False)

def get(self, member: str) -> Held | None:
path = self._path(member)
if not path.exists():
return None
try:
data = json.loads(self._fernet.decrypt(path.read_bytes()))
except InvalidToken:
raise ValueError("the key file cannot be read with this secret") from None
agent = Agent(data["address"], data["valid_until_ms"], data["private_key"])
return Held(agent, data["confirmed"])

def confirm(self, member: str) -> None:
held = self.get(member)
if held is not None:
self._write(member, held.agent, confirmed=True)

def forget(self, member: str) -> bool:
path = self._path(member)
if not path.exists():
return False
path.unlink()
return True
40 changes: 40 additions & 0 deletions modules/copying/src/copying/venue.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
"""What the venue says about a member's agents. It is the record; flet's state is a cache."""

from dataclasses import dataclass
from typing import Any, Protocol


class NoAnswer(Exception):
"""The venue did not answer usably. Never to be read as "not listed"."""


class Venue(Protocol):
def extra_agents(self, user: str) -> Any: ...


@dataclass(frozen=True)
class Listing:
address: str
name: str
valid_until_ms: int


def listed(venue: Venue, member: str, agent_address: str) -> Listing | None:
"""Our agent as the venue lists it under the member's main address, or None."""
try:
answer = venue.extra_agents(member)
except Exception as e: # any failure to hear the venue is no answer, never an absence
raise NoAnswer(type(e).__name__) from None
if not isinstance(answer, list):
raise NoAnswer("malformed answer")
for entry in answer:
if not (
isinstance(entry, dict)
and isinstance(entry.get("address"), str)
and isinstance(entry.get("name"), str)
and isinstance(entry.get("validUntil"), int)
):
raise NoAnswer("malformed answer")
if entry["address"].lower() == agent_address.lower():
return Listing(entry["address"], entry["name"], entry["validUntil"])
return None
File renamed without changes.
20 changes: 20 additions & 0 deletions modules/copying/tests/fakes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
from typing import Any


class FakeVenue:
"""Answers `extraAgents` from a fixed list, or fails like an unreachable venue."""

def __init__(self, agents: list[dict[str, Any]] | None = None, fail: bool = False) -> None:
self.agents = agents or []
self.fail = fail
self.calls: list[str] = []

def extra_agents(self, user: str) -> Any:
self.calls.append(user)
if self.fail:
raise ConnectionError("egress denied")
return self.agents


def listing(address: str, name: str, valid_until_ms: int) -> dict[str, Any]:
return {"address": address, "name": name, "validUntil": valid_until_ms}
Loading
Loading