ravnexchange 0.1.0__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,69 @@
1
+ # See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
2
+
3
+ # dependencies
4
+ /node_modules
5
+ sdk/*/node_modules
6
+ /.pnp
7
+ .pnp.*
8
+ .yarn/*
9
+ !.yarn/patches
10
+ !.yarn/plugins
11
+ !.yarn/releases
12
+ !.yarn/versions
13
+
14
+ # testing
15
+ /coverage
16
+
17
+ # sdk build output
18
+ sdk/*/dist
19
+ sdk/python/*.egg-info
20
+ sdk/python/__pycache__
21
+ sdk/python/**/__pycache__
22
+
23
+ # next.js
24
+ /.next/
25
+ /out/
26
+
27
+ # production
28
+ /build
29
+
30
+ # misc
31
+ .DS_Store
32
+ *.pem
33
+
34
+ # debug
35
+ npm-debug.log*
36
+ yarn-debug.log*
37
+ yarn-error.log*
38
+ .pnpm-debug.log*
39
+
40
+ # env files
41
+ .env
42
+ .env.local
43
+ .env.*.local
44
+
45
+ # vercel
46
+ .vercel
47
+
48
+ # typescript
49
+ *.tsbuildinfo
50
+ next-env.d.ts
51
+
52
+ # context files (not part of app)
53
+ RAVN_Full_Context.md
54
+ RAVN Stack & Routes.md
55
+ memory.md
56
+ .env*
57
+
58
+ # local Claude Code dev-tooling config (kept on disk, not tracked)
59
+ .claude/launch.json
60
+ .claude/settings.json
61
+ CLAUDE.md
62
+
63
+ # Third-party venue docs — large, someone else's copyright, re-pullable via docs/venues/refresh.sh
64
+ docs/venues/*.txt
65
+ docs/venues/*.json
66
+ docs/venues/*.html
67
+
68
+ # graphify knowledge graph — local build artifact, regenerate with /graphify .
69
+ /graphify-out/
@@ -0,0 +1,64 @@
1
+ Metadata-Version: 2.5
2
+ Name: ravnexchange
3
+ Version: 0.1.0
4
+ Summary: Typed client for the RAVN integrator API (/api/v1) — quote, execute, submit-signature, status. Zero dependencies.
5
+ Project-URL: Homepage, https://ravn.exchange
6
+ Project-URL: Documentation, https://docs.ravn.exchange
7
+ Project-URL: Repository, https://github.com/ravndex/ravn-mvp
8
+ Author: RAVN
9
+ License: MIT
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Typing :: Typed
13
+ Requires-Python: >=3.9
14
+ Description-Content-Type: text/markdown
15
+
16
+ # ravnexchange
17
+
18
+ Typed Python client for RAVN's public `/api/v1` — quote, execute, submit-signature, status,
19
+ tokens, chains. Zero runtime dependencies (built on `urllib.request`, not `requests`).
20
+
21
+ Same scope as the official TS client (`@ravnexchange/sdk`) — for an agent that already speaks
22
+ MCP, RAVN's MCP server (see the main `sdk/README.md`) covers this and more; this package is
23
+ for a plain, non-agent Python backend that wants a typed wrapper instead of hand-rolling HTTP
24
+ calls against the JSON API.
25
+
26
+ ## Install
27
+
28
+ ```bash
29
+ pip install ravnexchange
30
+ ```
31
+
32
+ ## Usage
33
+
34
+ ```python
35
+ from ravnexchange import RavnClient, RavnApiError
36
+
37
+ client = RavnClient(api_key="rvn_live_...") # omit for the anonymous tier
38
+
39
+ try:
40
+ quote = client.get_quote({
41
+ "inputChainId": 1,
42
+ "outputChainId": 8453,
43
+ "inputToken": "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",
44
+ "outputToken": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
45
+ "inputAmount": "1000000000000000000",
46
+ "userAddress": "0xYourAddress",
47
+ "destinationAddress": "0xYourAddress",
48
+ })
49
+ except RavnApiError as e:
50
+ print(e.code, str(e))
51
+ else:
52
+ execution = client.execute({"quoteToken": quote["quoteToken"]})
53
+ # branch on execution["executionType"]: TRANSACTION / SIGNATURE / DEPOSIT
54
+ ```
55
+
56
+ Pass `"sandbox": True` on `get_quote` to test the full quote → execute → status flow with no
57
+ real funds — see the API's own docs for per-venue exceptions (THORChain BTC-source and
58
+ Chainflip can't be sandboxed).
59
+
60
+ ## Status
61
+
62
+ Published to PyPI via `.github/workflows/publish-python-sdk.yml` using trusted publishing
63
+ (OIDC, no stored token) — same model as the npm packages in `sdk/`, on a push to `main` that
64
+ bumps `pyproject.toml`'s version.
@@ -0,0 +1,49 @@
1
+ # ravnexchange
2
+
3
+ Typed Python client for RAVN's public `/api/v1` — quote, execute, submit-signature, status,
4
+ tokens, chains. Zero runtime dependencies (built on `urllib.request`, not `requests`).
5
+
6
+ Same scope as the official TS client (`@ravnexchange/sdk`) — for an agent that already speaks
7
+ MCP, RAVN's MCP server (see the main `sdk/README.md`) covers this and more; this package is
8
+ for a plain, non-agent Python backend that wants a typed wrapper instead of hand-rolling HTTP
9
+ calls against the JSON API.
10
+
11
+ ## Install
12
+
13
+ ```bash
14
+ pip install ravnexchange
15
+ ```
16
+
17
+ ## Usage
18
+
19
+ ```python
20
+ from ravnexchange import RavnClient, RavnApiError
21
+
22
+ client = RavnClient(api_key="rvn_live_...") # omit for the anonymous tier
23
+
24
+ try:
25
+ quote = client.get_quote({
26
+ "inputChainId": 1,
27
+ "outputChainId": 8453,
28
+ "inputToken": "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",
29
+ "outputToken": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
30
+ "inputAmount": "1000000000000000000",
31
+ "userAddress": "0xYourAddress",
32
+ "destinationAddress": "0xYourAddress",
33
+ })
34
+ except RavnApiError as e:
35
+ print(e.code, str(e))
36
+ else:
37
+ execution = client.execute({"quoteToken": quote["quoteToken"]})
38
+ # branch on execution["executionType"]: TRANSACTION / SIGNATURE / DEPOSIT
39
+ ```
40
+
41
+ Pass `"sandbox": True` on `get_quote` to test the full quote → execute → status flow with no
42
+ real funds — see the API's own docs for per-venue exceptions (THORChain BTC-source and
43
+ Chainflip can't be sandboxed).
44
+
45
+ ## Status
46
+
47
+ Published to PyPI via `.github/workflows/publish-python-sdk.yml` using trusted publishing
48
+ (OIDC, no stored token) — same model as the npm packages in `sdk/`, on a push to `main` that
49
+ bumps `pyproject.toml`'s version.
@@ -0,0 +1,25 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "ravnexchange"
7
+ version = "0.1.0"
8
+ description = "Typed client for the RAVN integrator API (/api/v1) — quote, execute, submit-signature, status. Zero dependencies."
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = { text = "MIT" }
12
+ authors = [{ name = "RAVN" }]
13
+ classifiers = [
14
+ "License :: OSI Approved :: MIT License",
15
+ "Programming Language :: Python :: 3",
16
+ "Typing :: Typed",
17
+ ]
18
+
19
+ [project.urls]
20
+ Homepage = "https://ravn.exchange"
21
+ Documentation = "https://docs.ravn.exchange"
22
+ Repository = "https://github.com/ravndex/ravn-mvp"
23
+
24
+ [tool.hatch.build.targets.wheel]
25
+ packages = ["ravnexchange"]
@@ -0,0 +1,17 @@
1
+ from .client import (
2
+ DEFAULT_BASE_URL,
3
+ ExecuteParams,
4
+ GetQuoteParams,
5
+ RavnApiError,
6
+ RavnClient,
7
+ SubmitSignatureParams,
8
+ )
9
+
10
+ __all__ = [
11
+ "DEFAULT_BASE_URL",
12
+ "ExecuteParams",
13
+ "GetQuoteParams",
14
+ "RavnApiError",
15
+ "RavnClient",
16
+ "SubmitSignatureParams",
17
+ ]
@@ -0,0 +1,148 @@
1
+ """Typed client for RAVN's public /api/v1 surface.
2
+
3
+ Deliberately a standalone mirror of @ravnexchange/sdk's RavnClient
4
+ (sdk/core/src/client.ts) — same scope (quote, execute, submit-signature, status, tokens,
5
+ chains), same envelope-unwrapping/error-throwing behavior, snake_cased. Keep the two in sync
6
+ by hand when the API's public contract changes; ships to PyPI on its own and can't import
7
+ from the TS package or the app's internal source tree.
8
+
9
+ Zero runtime dependencies — built on urllib.request, not requests, so installing this adds
10
+ nothing to a project's dependency tree.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import urllib.error
17
+ import urllib.parse
18
+ import urllib.request
19
+ from typing import Any, Callable, Dict, List, Optional, TypedDict
20
+
21
+ DEFAULT_BASE_URL = "https://ravn.exchange/api/v1"
22
+
23
+
24
+ class RavnApiError(Exception):
25
+ """Raised for every non-2xx response, or a 2xx body that still carries an `error` field."""
26
+
27
+ def __init__(
28
+ self,
29
+ code: str,
30
+ message: str,
31
+ details: Any = None,
32
+ meta: Optional[Dict[str, Any]] = None,
33
+ ) -> None:
34
+ super().__init__(message)
35
+ self.code = code
36
+ self.details = details
37
+ self.meta = meta
38
+
39
+
40
+ class GetQuoteParams(TypedDict, total=False):
41
+ inputChainId: int
42
+ outputChainId: int
43
+ inputToken: str
44
+ outputToken: str
45
+ inputAmount: str
46
+ userAddress: str
47
+ destinationAddress: str
48
+ refundAddress: str
49
+ slippageBps: int
50
+ rankingMode: str
51
+ excludeVenues: List[str]
52
+ sandbox: bool
53
+
54
+
55
+ class ExecuteParams(TypedDict, total=False):
56
+ quoteToken: str
57
+ destinationAddress: str
58
+ refundAddress: str
59
+
60
+
61
+ class SubmitSignatureParams(TypedDict, total=False):
62
+ quoteToken: str
63
+ signature: str
64
+ approvalSignature: str
65
+
66
+
67
+ # Injectable transport, mirroring RavnClientConfig.fetch in the TS client — lets tests (and
68
+ # unusual runtimes) supply their own opener instead of hitting the network.
69
+ UrlOpener = Callable[[urllib.request.Request], Any]
70
+
71
+
72
+ class RavnClient:
73
+ def __init__(
74
+ self,
75
+ api_key: Optional[str] = None,
76
+ base_url: str = DEFAULT_BASE_URL,
77
+ urlopen: UrlOpener = urllib.request.urlopen,
78
+ ) -> None:
79
+ self._api_key = api_key
80
+ self._base_url = base_url.rstrip("/")
81
+ self._urlopen = urlopen
82
+
83
+ def _request(self, path: str, method: str = "GET", body: Optional[Dict[str, Any]] = None) -> Any:
84
+ headers = {"content-type": "application/json"}
85
+ if self._api_key:
86
+ headers["x-api-key"] = self._api_key
87
+ data = json.dumps(body).encode("utf-8") if body is not None else None
88
+ req = urllib.request.Request(
89
+ f"{self._base_url}{path}", data=data, headers=headers, method=method
90
+ )
91
+
92
+ try:
93
+ with self._urlopen(req) as res:
94
+ status = res.status
95
+ raw = res.read()
96
+ except urllib.error.HTTPError as e:
97
+ # A non-2xx still carries a JSON error envelope for this API — read it the same
98
+ # way a successful response would be, rather than letting HTTPError propagate.
99
+ status = e.code
100
+ raw = e.read()
101
+
102
+ try:
103
+ envelope = json.loads(raw) if raw else {}
104
+ except json.JSONDecodeError:
105
+ # A non-JSON body (an intermediary's HTML error page, an empty response) must
106
+ # still surface as the one error type this client promises.
107
+ raise RavnApiError("INTERNAL", f"HTTP {status}: response was not valid JSON") from None
108
+
109
+ error = envelope.get("error")
110
+ if status >= 400 or error:
111
+ err = error or {"code": "INTERNAL", "message": f"HTTP {status}"}
112
+ raise RavnApiError(
113
+ err.get("code", "INTERNAL"),
114
+ err.get("message", "Unknown error"),
115
+ err.get("details"),
116
+ envelope.get("meta"),
117
+ )
118
+
119
+ return envelope.get("data")
120
+
121
+ def get_quote(self, params: GetQuoteParams) -> Dict[str, Any]:
122
+ """POST /v1/quote — omitting destinationAddress/refundAddress returns a preview-only
123
+ quote (see the response's `executable` field)."""
124
+ return self._request("/quote", "POST", dict(params))
125
+
126
+ def execute(self, params: ExecuteParams) -> Dict[str, Any]:
127
+ """POST /v1/execute — branch on the returned executionType (TRANSACTION / SIGNATURE / DEPOSIT)."""
128
+ return self._request("/execute", "POST", dict(params))
129
+
130
+ def submit_signature(self, params: SubmitSignatureParams) -> Dict[str, Any]:
131
+ """POST /v1/submit-signature — SIGNATURE-type executions only. Returns {"statusRef": ...}
132
+ to poll get_status with."""
133
+ return self._request("/submit-signature", "POST", dict(params))
134
+
135
+ def get_status(self, quote_token: str, ref: str) -> Dict[str, Any]:
136
+ """GET /v1/status — ref is the DEPOSIT address or the statusRef from submit_signature."""
137
+ qs = urllib.parse.urlencode({"quoteToken": quote_token, "ref": ref})
138
+ return self._request(f"/status?{qs}")
139
+
140
+ def get_tokens(self, chain_id: int) -> List[Dict[str, Any]]:
141
+ """GET /v1/tokens — RAVN's listed token registry for one chain. Not a per-pair
142
+ routability guarantee."""
143
+ qs = urllib.parse.urlencode({"chainId": chain_id})
144
+ return self._request(f"/tokens?{qs}")
145
+
146
+ def get_chains(self) -> List[Dict[str, Any]]:
147
+ """GET /v1/chains — every chain RAVN lists tokens for. Static; safe to cache client-side."""
148
+ return self._request("/chains")
@@ -0,0 +1,82 @@
1
+ """Stdlib unittest, no pytest dependency — mirrors sdk/core/src/client.test.ts's approach of
2
+ injecting a fake transport instead of hitting the network."""
3
+
4
+ import io
5
+ import json
6
+ import unittest
7
+ import urllib.error
8
+
9
+ from ravnexchange import RavnApiError, RavnClient
10
+
11
+
12
+ class FakeResponse:
13
+ def __init__(self, body: dict, status: int = 200):
14
+ self.status = status
15
+ self._body = json.dumps(body).encode("utf-8")
16
+
17
+ def read(self) -> bytes:
18
+ return self._body
19
+
20
+ def __enter__(self) -> "FakeResponse":
21
+ return self
22
+
23
+ def __exit__(self, *args: object) -> None:
24
+ return None
25
+
26
+
27
+ def fake_urlopen_returning(body: dict, status: int = 200):
28
+ def _urlopen(req):
29
+ if status >= 400:
30
+ raise urllib.error.HTTPError(
31
+ req.full_url, status, "error", None, io.BytesIO(json.dumps(body).encode("utf-8"))
32
+ )
33
+ return FakeResponse(body, status)
34
+
35
+ return _urlopen
36
+
37
+
38
+ class RavnClientTest(unittest.TestCase):
39
+ def test_get_quote_returns_unwrapped_data(self):
40
+ client = RavnClient(
41
+ api_key="rvn_test",
42
+ urlopen=fake_urlopen_returning({"data": {"quoteToken": "abc", "executable": True}}),
43
+ )
44
+ result = client.get_quote(
45
+ {
46
+ "inputChainId": 1,
47
+ "outputChainId": 1,
48
+ "inputToken": "0xEeee",
49
+ "outputToken": "0xA0b8",
50
+ "inputAmount": "1000000000000000000",
51
+ "userAddress": "0xabc",
52
+ "sandbox": True,
53
+ }
54
+ )
55
+ self.assertEqual(result, {"quoteToken": "abc", "executable": True})
56
+
57
+ def test_error_envelope_raises_ravn_api_error(self):
58
+ client = RavnClient(
59
+ urlopen=fake_urlopen_returning(
60
+ {"error": {"code": "NO_LIQUIDITY", "message": "No liquidity"}}, status=422
61
+ )
62
+ )
63
+ with self.assertRaises(RavnApiError) as ctx:
64
+ client.get_quote({})
65
+ self.assertEqual(ctx.exception.code, "NO_LIQUIDITY")
66
+
67
+ def test_non_json_body_raises_internal_error(self):
68
+ def _urlopen(req):
69
+ raise urllib.error.HTTPError(req.full_url, 502, "bad gateway", None, io.BytesIO(b"<html>"))
70
+
71
+ client = RavnClient(urlopen=_urlopen)
72
+ with self.assertRaises(RavnApiError) as ctx:
73
+ client.get_status("tok", "ref")
74
+ self.assertEqual(ctx.exception.code, "INTERNAL")
75
+
76
+ def test_get_chains_returns_list(self):
77
+ client = RavnClient(urlopen=fake_urlopen_returning({"data": [{"chainId": 1}]}))
78
+ self.assertEqual(client.get_chains(), [{"chainId": 1}])
79
+
80
+
81
+ if __name__ == "__main__":
82
+ unittest.main()