langchain-helmswap 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.
- langchain_helmswap-0.1.0/LICENSE +21 -0
- langchain_helmswap-0.1.0/PKG-INFO +49 -0
- langchain_helmswap-0.1.0/README.md +32 -0
- langchain_helmswap-0.1.0/langchain_helmswap/__init__.py +6 -0
- langchain_helmswap-0.1.0/langchain_helmswap/helmswap_client.py +269 -0
- langchain_helmswap-0.1.0/langchain_helmswap/tools.py +161 -0
- langchain_helmswap-0.1.0/langchain_helmswap.egg-info/PKG-INFO +49 -0
- langchain_helmswap-0.1.0/langchain_helmswap.egg-info/SOURCES.txt +12 -0
- langchain_helmswap-0.1.0/langchain_helmswap.egg-info/dependency_links.txt +1 -0
- langchain_helmswap-0.1.0/langchain_helmswap.egg-info/requires.txt +4 -0
- langchain_helmswap-0.1.0/langchain_helmswap.egg-info/top_level.txt +1 -0
- langchain_helmswap-0.1.0/pyproject.toml +24 -0
- langchain_helmswap-0.1.0/setup.cfg +4 -0
- langchain_helmswap-0.1.0/tests/test_tools.py +115 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Summit Private Credit LLC
|
|
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,49 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: langchain-helmswap
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: LangChain tools for HelmSwap: quote and build unsigned swap transactions. The agent's wallet signs and sends. Never holds keys.
|
|
5
|
+
Author: Summit Private Credit LLC
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://helmswap.com/developers
|
|
8
|
+
Project-URL: Repository, https://github.com/gambrelcolby63/langchain-helmswap
|
|
9
|
+
Keywords: helmswap,langchain,swap,non-custodial
|
|
10
|
+
Requires-Python: >=3.10
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Requires-Dist: langchain-core>=0.3
|
|
14
|
+
Provides-Extra: dev
|
|
15
|
+
Requires-Dist: pytest>=8; extra == "dev"
|
|
16
|
+
Dynamic: license-file
|
|
17
|
+
|
|
18
|
+
# langchain-helmswap
|
|
19
|
+
|
|
20
|
+
LangChain tools for [HelmSwap](https://helmswap.com/developers). They quote a swap and return an **unsigned** transaction. The agent's own wallet signs and sends it. The tools never hold, store, or accept private keys, and the HelmSwap API never signs or broadcasts.
|
|
21
|
+
|
|
22
|
+
Do not publish this package until helmswap.com is back up and Colby has approved a PyPI publish.
|
|
23
|
+
|
|
24
|
+
## Install (after publish)
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
pip install langchain-helmswap
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
```python
|
|
31
|
+
from langchain_helmswap import HelmswapQuoteTool, HelmswapBuildTool
|
|
32
|
+
|
|
33
|
+
tools = [HelmswapQuoteTool(), HelmswapBuildTool()]
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
## Settings
|
|
37
|
+
|
|
38
|
+
| Name | Required | Purpose |
|
|
39
|
+
| --- | --- | --- |
|
|
40
|
+
| `HELMSWAP_API_KEY` | For Solana builds | Free key from [helmswap.com/developers](https://helmswap.com/developers). Quotes work without it. Never a wallet key. |
|
|
41
|
+
| `HELMSWAP_BASE_URL` | No | API origin. Defaults to `https://helmswap.com`. |
|
|
42
|
+
|
|
43
|
+
`amount_in` is integer base units. `chain` accepts `solana`, `base`, `ethereum`, `bsc`, or a numeric chain id.
|
|
44
|
+
|
|
45
|
+
Arbitrum and Polygon can be quoted but cannot be built. Tokenized stocks are refused.
|
|
46
|
+
|
|
47
|
+
## License
|
|
48
|
+
|
|
49
|
+
MIT © Summit Private Credit LLC
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
# langchain-helmswap
|
|
2
|
+
|
|
3
|
+
LangChain tools for [HelmSwap](https://helmswap.com/developers). They quote a swap and return an **unsigned** transaction. The agent's own wallet signs and sends it. The tools never hold, store, or accept private keys, and the HelmSwap API never signs or broadcasts.
|
|
4
|
+
|
|
5
|
+
Do not publish this package until helmswap.com is back up and Colby has approved a PyPI publish.
|
|
6
|
+
|
|
7
|
+
## Install (after publish)
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
pip install langchain-helmswap
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
```python
|
|
14
|
+
from langchain_helmswap import HelmswapQuoteTool, HelmswapBuildTool
|
|
15
|
+
|
|
16
|
+
tools = [HelmswapQuoteTool(), HelmswapBuildTool()]
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## Settings
|
|
20
|
+
|
|
21
|
+
| Name | Required | Purpose |
|
|
22
|
+
| --- | --- | --- |
|
|
23
|
+
| `HELMSWAP_API_KEY` | For Solana builds | Free key from [helmswap.com/developers](https://helmswap.com/developers). Quotes work without it. Never a wallet key. |
|
|
24
|
+
| `HELMSWAP_BASE_URL` | No | API origin. Defaults to `https://helmswap.com`. |
|
|
25
|
+
|
|
26
|
+
`amount_in` is integer base units. `chain` accepts `solana`, `base`, `ethereum`, `bsc`, or a numeric chain id.
|
|
27
|
+
|
|
28
|
+
Arbitrum and Polygon can be quoted but cannot be built. Tokenized stocks are refused.
|
|
29
|
+
|
|
30
|
+
## License
|
|
31
|
+
|
|
32
|
+
MIT © Summit Private Credit LLC
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
"""LangChain tools for HelmSwap: quote and build unsigned swap transactions."""
|
|
2
|
+
|
|
3
|
+
from .tools import HelmswapBuildTool, HelmswapQuoteTool, build_swap, quote_swap
|
|
4
|
+
|
|
5
|
+
__all__ = ["HelmswapQuoteTool", "HelmswapBuildTool", "quote_swap", "build_swap"]
|
|
6
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
"""HelmSwap public v1 HTTP client.
|
|
2
|
+
|
|
3
|
+
Verified against the 26 Nov 2026 audit fix-tree:
|
|
4
|
+
GET /api/v1/quote and POST /api/v1/build-tx.
|
|
5
|
+
|
|
6
|
+
Returns quotes and unsigned transactions. This client never holds keys,
|
|
7
|
+
never signs, and never broadcasts.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
import urllib.error
|
|
15
|
+
import urllib.parse
|
|
16
|
+
import urllib.request
|
|
17
|
+
from dataclasses import dataclass
|
|
18
|
+
from typing import Any, Callable, Mapping, MutableMapping
|
|
19
|
+
|
|
20
|
+
DEFAULT_BASE_URL = "https://helmswap.com"
|
|
21
|
+
KEY_DOCS = "https://helmswap.com/developers"
|
|
22
|
+
WSOL = "So11111111111111111111111111111111111111112"
|
|
23
|
+
LIVE_EVM_CHAIN_IDS = (8453, 56, 1, 4663, 57073, 999, 99901, 5042)
|
|
24
|
+
QUOTE_ONLY_CHAIN_IDS = (42161, 137)
|
|
25
|
+
|
|
26
|
+
CHAIN_ALIASES: dict[str, int | str] = {
|
|
27
|
+
"solana": "solana",
|
|
28
|
+
"sol": "solana",
|
|
29
|
+
"base": 8453,
|
|
30
|
+
"8453": 8453,
|
|
31
|
+
"bnb": 56,
|
|
32
|
+
"bsc": 56,
|
|
33
|
+
"bnbchain": 56,
|
|
34
|
+
"56": 56,
|
|
35
|
+
"eth": 1,
|
|
36
|
+
"ethereum": 1,
|
|
37
|
+
"mainnet": 1,
|
|
38
|
+
"1": 1,
|
|
39
|
+
"robinhood": 4663,
|
|
40
|
+
"4663": 4663,
|
|
41
|
+
"ink": 57073,
|
|
42
|
+
"57073": 57073,
|
|
43
|
+
"hyperevm": 999,
|
|
44
|
+
"999": 999,
|
|
45
|
+
"elysium": 99901,
|
|
46
|
+
"99901": 99901,
|
|
47
|
+
"arc": 5042,
|
|
48
|
+
"5042": 5042,
|
|
49
|
+
"arbitrum": 42161,
|
|
50
|
+
"42161": 42161,
|
|
51
|
+
"polygon": 137,
|
|
52
|
+
"137": 137,
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class HelmswapApiError(Exception):
|
|
57
|
+
def __init__(self, message: str, status: int, code: str | None = None, body: Any = None):
|
|
58
|
+
super().__init__(message)
|
|
59
|
+
self.status = status
|
|
60
|
+
self.code = code
|
|
61
|
+
self.body = body
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def parse_chain(raw: str | int | None) -> int | str | None:
|
|
65
|
+
if raw is None or raw == "":
|
|
66
|
+
return None
|
|
67
|
+
if isinstance(raw, int):
|
|
68
|
+
return raw
|
|
69
|
+
trimmed = str(raw).strip()
|
|
70
|
+
if trimmed.isdigit():
|
|
71
|
+
return int(trimmed)
|
|
72
|
+
return CHAIN_ALIASES.get(trimmed.lower().replace(" ", ""))
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def is_live_build_chain(chain: int | str) -> bool:
|
|
76
|
+
return chain == "solana" or chain in LIVE_EVM_CHAIN_IDS
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def to_base_units(amount: str | int | float, decimals: int) -> str:
|
|
80
|
+
trimmed = str(amount).strip()
|
|
81
|
+
if not trimmed or trimmed.startswith("-"):
|
|
82
|
+
raise ValueError("amount must be greater than zero")
|
|
83
|
+
if "." in trimmed:
|
|
84
|
+
whole, frac = trimmed.split(".", 1)
|
|
85
|
+
else:
|
|
86
|
+
whole, frac = trimmed, ""
|
|
87
|
+
if not whole.isdigit() or (frac and not frac.isdigit()):
|
|
88
|
+
raise ValueError("amount must be a positive number")
|
|
89
|
+
frac_padded = (frac + ("0" * decimals))[:decimals]
|
|
90
|
+
raw = (whole + frac_padded).lstrip("0") or "0"
|
|
91
|
+
if raw == "0":
|
|
92
|
+
raise ValueError("amount must be greater than zero")
|
|
93
|
+
return raw
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def from_base_units(raw: str, decimals: int) -> float:
|
|
97
|
+
if not str(raw).isdigit():
|
|
98
|
+
raise ValueError("base units must be a non-negative integer string")
|
|
99
|
+
padded = str(raw).zfill(decimals + 1)
|
|
100
|
+
whole, frac = padded[:-decimals], padded[-decimals:]
|
|
101
|
+
return float(f"{whole}.{frac}")
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def native_or_mint(token: str, chain: int | str) -> str:
|
|
105
|
+
token = token.strip()
|
|
106
|
+
if chain == "solana" and token.upper() == "SOL":
|
|
107
|
+
return WSOL
|
|
108
|
+
return token
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
@dataclass
|
|
112
|
+
class SwapParams:
|
|
113
|
+
chain: int | str
|
|
114
|
+
token_in: str
|
|
115
|
+
token_out: str
|
|
116
|
+
amount_in: str
|
|
117
|
+
slippage_bps: int | None = None
|
|
118
|
+
referrer: str | None = None
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def quote_query(params: SwapParams) -> dict[str, str]:
|
|
122
|
+
q: dict[str, str]
|
|
123
|
+
if params.chain == "solana":
|
|
124
|
+
q = {
|
|
125
|
+
"chain": "solana",
|
|
126
|
+
"inputMint": native_or_mint(params.token_in, "solana"),
|
|
127
|
+
"outputMint": native_or_mint(params.token_out, "solana"),
|
|
128
|
+
"amount": params.amount_in,
|
|
129
|
+
}
|
|
130
|
+
else:
|
|
131
|
+
q = {
|
|
132
|
+
"chainId": str(params.chain),
|
|
133
|
+
"tokenIn": params.token_in,
|
|
134
|
+
"tokenOut": params.token_out,
|
|
135
|
+
"amountIn": params.amount_in,
|
|
136
|
+
}
|
|
137
|
+
if params.slippage_bps is not None:
|
|
138
|
+
q["slippageBps"] = str(params.slippage_bps)
|
|
139
|
+
if params.referrer:
|
|
140
|
+
q["referrer"] = params.referrer
|
|
141
|
+
return q
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def build_body(params: SwapParams, quote: Mapping[str, Any], recipient: str) -> dict[str, Any]:
|
|
145
|
+
ticket = quote.get("quoteTicket")
|
|
146
|
+
if not isinstance(ticket, Mapping):
|
|
147
|
+
raise HelmswapApiError(
|
|
148
|
+
"quote.quoteTicket is missing; call quote() first and pass the result unchanged.",
|
|
149
|
+
400,
|
|
150
|
+
"NO_TICKET",
|
|
151
|
+
)
|
|
152
|
+
if params.chain == "solana":
|
|
153
|
+
q = quote_query(params)
|
|
154
|
+
body: dict[str, Any] = {
|
|
155
|
+
"chain": "solana",
|
|
156
|
+
"inputMint": q["inputMint"],
|
|
157
|
+
"outputMint": q["outputMint"],
|
|
158
|
+
"amount": q["amount"],
|
|
159
|
+
"recipient": recipient,
|
|
160
|
+
"quoteTicket": ticket,
|
|
161
|
+
}
|
|
162
|
+
else:
|
|
163
|
+
body = {
|
|
164
|
+
"chainId": params.chain,
|
|
165
|
+
"tokenIn": params.token_in,
|
|
166
|
+
"tokenOut": params.token_out,
|
|
167
|
+
"amountIn": params.amount_in,
|
|
168
|
+
"recipient": recipient,
|
|
169
|
+
"quoteTicket": ticket,
|
|
170
|
+
}
|
|
171
|
+
if params.slippage_bps is not None:
|
|
172
|
+
body["slippageBps"] = params.slippage_bps
|
|
173
|
+
if params.referrer:
|
|
174
|
+
body["referrer"] = params.referrer
|
|
175
|
+
return body
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def net_out_amount(quote: Mapping[str, Any]) -> str:
|
|
179
|
+
inner = quote.get("quote") if isinstance(quote.get("quote"), Mapping) else {}
|
|
180
|
+
ticket = quote.get("quoteTicket") if isinstance(quote.get("quoteTicket"), Mapping) else {}
|
|
181
|
+
raw = inner.get("netOutAmount") or quote.get("netOutAmount") or ticket.get("quotedOutNet")
|
|
182
|
+
if raw is None:
|
|
183
|
+
raise HelmswapApiError("HelmSwap quote had no netOutAmount.", 502, "NO_NET_OUT", quote)
|
|
184
|
+
return str(raw)
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def min_out_amount(quote: Mapping[str, Any]) -> str:
|
|
188
|
+
inner = quote.get("quote") if isinstance(quote.get("quote"), Mapping) else {}
|
|
189
|
+
return str(inner.get("minOutNet") or inner.get("minNetOutAmount") or net_out_amount(quote))
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def evm_tx(built: Mapping[str, Any]) -> dict[str, Any]:
|
|
193
|
+
tx = built.get("tx")
|
|
194
|
+
if not isinstance(tx, Mapping) or not tx.get("to") or not tx.get("data"):
|
|
195
|
+
raise HelmswapApiError("HelmSwap build-tx response had no EVM tx.", 502, "NO_TX", built)
|
|
196
|
+
return dict(tx)
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def solana_tx_base64(built: Mapping[str, Any]) -> str:
|
|
200
|
+
tx = built.get("tx")
|
|
201
|
+
if isinstance(tx, Mapping) and isinstance(tx.get("transactionBase64"), str):
|
|
202
|
+
return tx["transactionBase64"]
|
|
203
|
+
raise HelmswapApiError("HelmSwap build-tx response had no Solana transaction.", 502, "NO_TX", built)
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
class HelmswapApi:
|
|
207
|
+
def __init__(
|
|
208
|
+
self,
|
|
209
|
+
base_url: str | None = None,
|
|
210
|
+
api_key: str | None = None,
|
|
211
|
+
opener: Callable[..., Any] | None = None,
|
|
212
|
+
):
|
|
213
|
+
self.base_url = (base_url or os.environ.get("HELMSWAP_BASE_URL") or DEFAULT_BASE_URL).rstrip("/")
|
|
214
|
+
self.api_key = api_key if api_key is not None else os.environ.get("HELMSWAP_API_KEY")
|
|
215
|
+
self._opener = opener or urllib.request.urlopen
|
|
216
|
+
|
|
217
|
+
@property
|
|
218
|
+
def has_api_key(self) -> bool:
|
|
219
|
+
return bool(self.api_key)
|
|
220
|
+
|
|
221
|
+
def quote(self, params: SwapParams) -> dict[str, Any]:
|
|
222
|
+
query = urllib.parse.urlencode(quote_query(params))
|
|
223
|
+
return self._request("GET", f"/api/v1/quote?{query}")
|
|
224
|
+
|
|
225
|
+
def build_tx(self, params: SwapParams, quote: Mapping[str, Any], recipient: str) -> dict[str, Any]:
|
|
226
|
+
if params.chain == "solana" and not self.api_key:
|
|
227
|
+
raise HelmswapApiError(
|
|
228
|
+
"A free HelmSwap API key is required to build Solana transactions. Create one at https://helmswap.com/developers.",
|
|
229
|
+
401,
|
|
230
|
+
"API_KEY_REQUIRED",
|
|
231
|
+
)
|
|
232
|
+
if not is_live_build_chain(params.chain):
|
|
233
|
+
raise HelmswapApiError(
|
|
234
|
+
f"build-tx is not available on chain {params.chain} (quote-only).",
|
|
235
|
+
503,
|
|
236
|
+
"FEE_ROUTER_NOT_CONFIGURED",
|
|
237
|
+
)
|
|
238
|
+
return self._request("POST", "/api/v1/build-tx", build_body(params, quote, recipient))
|
|
239
|
+
|
|
240
|
+
def _request(self, method: str, path: str, body: Mapping[str, Any] | None = None) -> dict[str, Any]:
|
|
241
|
+
headers: dict[str, str] = {"Accept": "application/json"}
|
|
242
|
+
data = None
|
|
243
|
+
if body is not None:
|
|
244
|
+
headers["Content-Type"] = "application/json"
|
|
245
|
+
data = json.dumps(body).encode("utf-8")
|
|
246
|
+
if self.api_key:
|
|
247
|
+
headers["X-Helm-Key"] = self.api_key
|
|
248
|
+
req = urllib.request.Request(self.base_url + path, data=data, headers=headers, method=method)
|
|
249
|
+
try:
|
|
250
|
+
with self._opener(req) as resp:
|
|
251
|
+
raw = resp.read()
|
|
252
|
+
status = getattr(resp, "status", 200)
|
|
253
|
+
except urllib.error.HTTPError as err:
|
|
254
|
+
raw = err.read()
|
|
255
|
+
status = err.code
|
|
256
|
+
try:
|
|
257
|
+
payload = json.loads(raw.decode("utf-8") or "{}")
|
|
258
|
+
except json.JSONDecodeError as err:
|
|
259
|
+
raise HelmswapApiError(f"HelmSwap returned a non-JSON response ({status})", status) from err
|
|
260
|
+
if not isinstance(payload, dict):
|
|
261
|
+
raise HelmswapApiError(f"HelmSwap returned a non-object response ({status})", status, body=payload)
|
|
262
|
+
if status >= 400 or payload.get("ok") is False:
|
|
263
|
+
raise HelmswapApiError(
|
|
264
|
+
payload.get("error") if isinstance(payload.get("error"), str) else f"HelmSwap request failed ({status})",
|
|
265
|
+
status,
|
|
266
|
+
payload.get("code") if isinstance(payload.get("code"), str) else None,
|
|
267
|
+
payload,
|
|
268
|
+
)
|
|
269
|
+
return payload
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
"""LangChain tools for the HelmSwap public API.
|
|
2
|
+
|
|
3
|
+
These tools quote a swap and return an unsigned transaction. The agent's own
|
|
4
|
+
wallet signs and sends. They never hold, store, or accept private keys.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
from .helmswap_client import (
|
|
13
|
+
HelmswapApi,
|
|
14
|
+
HelmswapApiError,
|
|
15
|
+
SwapParams,
|
|
16
|
+
evm_tx,
|
|
17
|
+
is_live_build_chain,
|
|
18
|
+
min_out_amount,
|
|
19
|
+
net_out_amount,
|
|
20
|
+
parse_chain,
|
|
21
|
+
solana_tx_base64,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
try:
|
|
25
|
+
from langchain_core.tools import BaseTool
|
|
26
|
+
from pydantic import BaseModel, Field
|
|
27
|
+
except ImportError: # tools still work as plain functions
|
|
28
|
+
BaseTool = object # type: ignore
|
|
29
|
+
class BaseModel: # type: ignore
|
|
30
|
+
pass
|
|
31
|
+
def Field(*_args, **_kwargs): # type: ignore
|
|
32
|
+
return None
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class HelmswapQuoteInput(BaseModel):
|
|
36
|
+
token_in: str = Field(description="Token to spend (address, or ETH, BNB, or SOL)")
|
|
37
|
+
token_out: str = Field(description="Token to receive (address, or ETH, BNB, or SOL)")
|
|
38
|
+
amount_in: str = Field(description="Integer base units of token_in")
|
|
39
|
+
chain: str = Field(
|
|
40
|
+
default="base",
|
|
41
|
+
description="Chain name or id: solana, base, ethereum, bsc, or a numeric chain id",
|
|
42
|
+
)
|
|
43
|
+
slippage_bps: int = Field(default=50, description="Slippage tolerance in basis points (0-1000, default 50)")
|
|
44
|
+
referrer: str | None = Field(default=None, description="Optional payout address. Address only, never a key.")
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class HelmswapBuildInput(HelmswapQuoteInput):
|
|
48
|
+
recipient: str = Field(description="Wallet that will sign the unsigned transaction (0x or Solana base58)")
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _params(chain: str, token_in: str, token_out: str, amount_in: str, slippage_bps: int = 50, referrer: str | None = None) -> SwapParams:
|
|
52
|
+
parsed = parse_chain(chain)
|
|
53
|
+
if parsed is None:
|
|
54
|
+
raise HelmswapApiError(f"Unknown chain '{chain}'.", 400, "BAD_CHAIN")
|
|
55
|
+
return SwapParams(parsed, token_in, token_out, amount_in, slippage_bps, referrer)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def quote_swap(
|
|
59
|
+
token_in: str,
|
|
60
|
+
token_out: str,
|
|
61
|
+
amount_in: str,
|
|
62
|
+
chain: str = "base",
|
|
63
|
+
slippage_bps: int = 50,
|
|
64
|
+
referrer: str | None = None,
|
|
65
|
+
api: HelmswapApi | None = None,
|
|
66
|
+
) -> str:
|
|
67
|
+
"""Return a JSON quote. Nothing is signed or sent."""
|
|
68
|
+
client = api or HelmswapApi()
|
|
69
|
+
params = _params(chain, token_in, token_out, amount_in, slippage_bps, referrer)
|
|
70
|
+
quote = client.quote(params)
|
|
71
|
+
fee = quote.get("fee") or (quote.get("quote") or {}).get("fee") or {}
|
|
72
|
+
payload = {
|
|
73
|
+
"ok": True,
|
|
74
|
+
"chain": params.chain,
|
|
75
|
+
"tokenIn": token_in,
|
|
76
|
+
"tokenOut": token_out,
|
|
77
|
+
"amountIn": amount_in,
|
|
78
|
+
"netOutAmount": net_out_amount(quote),
|
|
79
|
+
"minOutAmount": min_out_amount(quote),
|
|
80
|
+
"fee": fee,
|
|
81
|
+
"priceImpactPct": quote.get("priceImpactPct"),
|
|
82
|
+
"quoteTicket": quote.get("quoteTicket"),
|
|
83
|
+
"buildable": is_live_build_chain(params.chain),
|
|
84
|
+
"note": "This is a quote only. The user's wallet must sign any later transaction. HelmSwap never holds keys and never broadcasts.",
|
|
85
|
+
"raw": quote,
|
|
86
|
+
}
|
|
87
|
+
return json.dumps(payload)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def build_swap(
|
|
91
|
+
token_in: str,
|
|
92
|
+
token_out: str,
|
|
93
|
+
amount_in: str,
|
|
94
|
+
recipient: str,
|
|
95
|
+
chain: str = "base",
|
|
96
|
+
slippage_bps: int = 50,
|
|
97
|
+
referrer: str | None = None,
|
|
98
|
+
api: HelmswapApi | None = None,
|
|
99
|
+
) -> str:
|
|
100
|
+
"""Quote, then return an unsigned transaction for the recipient wallet to sign and send."""
|
|
101
|
+
if not recipient or not recipient.strip():
|
|
102
|
+
raise HelmswapApiError("recipient is required to build an unsigned transaction.", 400, "NO_RECIPIENT")
|
|
103
|
+
client = api or HelmswapApi()
|
|
104
|
+
params = _params(chain, token_in, token_out, amount_in, slippage_bps, referrer)
|
|
105
|
+
quote = client.quote(params)
|
|
106
|
+
built = client.build_tx(params, quote, recipient.strip())
|
|
107
|
+
if params.chain == "solana":
|
|
108
|
+
tx = {"chain": "solana", "transactionBase64": solana_tx_base64(built)}
|
|
109
|
+
else:
|
|
110
|
+
tx = evm_tx(built)
|
|
111
|
+
payload = {
|
|
112
|
+
"ok": True,
|
|
113
|
+
"chain": params.chain,
|
|
114
|
+
"recipient": recipient.strip(),
|
|
115
|
+
"netOutAmount": net_out_amount(quote),
|
|
116
|
+
"minOutAmount": min_out_amount(quote),
|
|
117
|
+
"fee": built.get("fee") or quote.get("fee"),
|
|
118
|
+
"tx": tx,
|
|
119
|
+
"approvals": built.get("approvals") or [],
|
|
120
|
+
"note": "Unsigned transaction. The recipient wallet signs and sends it. HelmSwap never holds keys and never broadcasts.",
|
|
121
|
+
}
|
|
122
|
+
return json.dumps(payload)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
class HelmswapQuoteTool(BaseTool):
|
|
126
|
+
name: str = "helmswap_quote"
|
|
127
|
+
description: str = (
|
|
128
|
+
"Get a HelmSwap quote for a token swap on Solana, Base, Ethereum, BNB Chain, or other live HelmSwap chains. "
|
|
129
|
+
"Returns expected output, minimum output, and the disclosed fee. Nothing is signed or sent."
|
|
130
|
+
)
|
|
131
|
+
args_schema: type = HelmswapQuoteInput
|
|
132
|
+
|
|
133
|
+
def _run(self, **kwargs: Any) -> str:
|
|
134
|
+
return quote_swap(
|
|
135
|
+
token_in=kwargs["token_in"],
|
|
136
|
+
token_out=kwargs["token_out"],
|
|
137
|
+
amount_in=kwargs["amount_in"],
|
|
138
|
+
chain=kwargs.get("chain") or "base",
|
|
139
|
+
slippage_bps=int(kwargs.get("slippage_bps") or 50),
|
|
140
|
+
referrer=kwargs.get("referrer"),
|
|
141
|
+
)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
class HelmswapBuildTool(BaseTool):
|
|
145
|
+
name: str = "helmswap_build_swap"
|
|
146
|
+
description: str = (
|
|
147
|
+
"Build an unsigned HelmSwap transaction. The recipient wallet signs and sends it. "
|
|
148
|
+
"This tool never holds private keys. Solana builds need HELMSWAP_API_KEY (a free API key, not a wallet key)."
|
|
149
|
+
)
|
|
150
|
+
args_schema: type = HelmswapBuildInput
|
|
151
|
+
|
|
152
|
+
def _run(self, **kwargs: Any) -> str:
|
|
153
|
+
return build_swap(
|
|
154
|
+
token_in=kwargs["token_in"],
|
|
155
|
+
token_out=kwargs["token_out"],
|
|
156
|
+
amount_in=kwargs["amount_in"],
|
|
157
|
+
recipient=kwargs["recipient"],
|
|
158
|
+
chain=kwargs.get("chain") or "base",
|
|
159
|
+
slippage_bps=int(kwargs.get("slippage_bps") or 50),
|
|
160
|
+
referrer=kwargs.get("referrer"),
|
|
161
|
+
)
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: langchain-helmswap
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: LangChain tools for HelmSwap: quote and build unsigned swap transactions. The agent's wallet signs and sends. Never holds keys.
|
|
5
|
+
Author: Summit Private Credit LLC
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://helmswap.com/developers
|
|
8
|
+
Project-URL: Repository, https://github.com/gambrelcolby63/langchain-helmswap
|
|
9
|
+
Keywords: helmswap,langchain,swap,non-custodial
|
|
10
|
+
Requires-Python: >=3.10
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Requires-Dist: langchain-core>=0.3
|
|
14
|
+
Provides-Extra: dev
|
|
15
|
+
Requires-Dist: pytest>=8; extra == "dev"
|
|
16
|
+
Dynamic: license-file
|
|
17
|
+
|
|
18
|
+
# langchain-helmswap
|
|
19
|
+
|
|
20
|
+
LangChain tools for [HelmSwap](https://helmswap.com/developers). They quote a swap and return an **unsigned** transaction. The agent's own wallet signs and sends it. The tools never hold, store, or accept private keys, and the HelmSwap API never signs or broadcasts.
|
|
21
|
+
|
|
22
|
+
Do not publish this package until helmswap.com is back up and Colby has approved a PyPI publish.
|
|
23
|
+
|
|
24
|
+
## Install (after publish)
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
pip install langchain-helmswap
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
```python
|
|
31
|
+
from langchain_helmswap import HelmswapQuoteTool, HelmswapBuildTool
|
|
32
|
+
|
|
33
|
+
tools = [HelmswapQuoteTool(), HelmswapBuildTool()]
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
## Settings
|
|
37
|
+
|
|
38
|
+
| Name | Required | Purpose |
|
|
39
|
+
| --- | --- | --- |
|
|
40
|
+
| `HELMSWAP_API_KEY` | For Solana builds | Free key from [helmswap.com/developers](https://helmswap.com/developers). Quotes work without it. Never a wallet key. |
|
|
41
|
+
| `HELMSWAP_BASE_URL` | No | API origin. Defaults to `https://helmswap.com`. |
|
|
42
|
+
|
|
43
|
+
`amount_in` is integer base units. `chain` accepts `solana`, `base`, `ethereum`, `bsc`, or a numeric chain id.
|
|
44
|
+
|
|
45
|
+
Arbitrum and Polygon can be quoted but cannot be built. Tokenized stocks are refused.
|
|
46
|
+
|
|
47
|
+
## License
|
|
48
|
+
|
|
49
|
+
MIT © Summit Private Credit LLC
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
langchain_helmswap/__init__.py
|
|
5
|
+
langchain_helmswap/helmswap_client.py
|
|
6
|
+
langchain_helmswap/tools.py
|
|
7
|
+
langchain_helmswap.egg-info/PKG-INFO
|
|
8
|
+
langchain_helmswap.egg-info/SOURCES.txt
|
|
9
|
+
langchain_helmswap.egg-info/dependency_links.txt
|
|
10
|
+
langchain_helmswap.egg-info/requires.txt
|
|
11
|
+
langchain_helmswap.egg-info/top_level.txt
|
|
12
|
+
tests/test_tools.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
langchain_helmswap
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "langchain-helmswap"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "LangChain tools for HelmSwap: quote and build unsigned swap transactions. The agent's wallet signs and sends. Never holds keys."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.10"
|
|
7
|
+
license = { text = "MIT" }
|
|
8
|
+
authors = [{ name = "Summit Private Credit LLC" }]
|
|
9
|
+
keywords = ["helmswap", "langchain", "swap", "non-custodial"]
|
|
10
|
+
dependencies = ["langchain-core>=0.3"]
|
|
11
|
+
|
|
12
|
+
[project.optional-dependencies]
|
|
13
|
+
dev = ["pytest>=8"]
|
|
14
|
+
|
|
15
|
+
[project.urls]
|
|
16
|
+
Homepage = "https://helmswap.com/developers"
|
|
17
|
+
Repository = "https://github.com/gambrelcolby63/langchain-helmswap"
|
|
18
|
+
|
|
19
|
+
[build-system]
|
|
20
|
+
requires = ["setuptools>=69"]
|
|
21
|
+
build-backend = "setuptools.build_meta"
|
|
22
|
+
|
|
23
|
+
[tool.setuptools.packages.find]
|
|
24
|
+
include = ["langchain_helmswap*"]
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import io
|
|
4
|
+
import json
|
|
5
|
+
import sys
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from urllib.error import HTTPError
|
|
8
|
+
|
|
9
|
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
|
10
|
+
|
|
11
|
+
from langchain_helmswap.helmswap_client import HelmswapApi, HelmswapApiError
|
|
12
|
+
from langchain_helmswap.tools import build_swap, quote_swap
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
SAMPLE_QUOTE = {
|
|
16
|
+
"ok": True,
|
|
17
|
+
"dryRun": True,
|
|
18
|
+
"broadcast": False,
|
|
19
|
+
"quoteTicket": {"sig": "ticket", "quotedOutNet": "149250000", "expiresAt": 1},
|
|
20
|
+
"quote": {"netOutAmount": "149250000", "minNetOutAmount": "148500000", "fee": {"disclosed": True, "feeBps": 25}},
|
|
21
|
+
"fee": {"disclosed": True, "feeBps": 25, "feeAmount": "750000"},
|
|
22
|
+
"priceImpactPct": 0.2,
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
SAMPLE_BUILD = {
|
|
26
|
+
"ok": True,
|
|
27
|
+
"tx": {"to": "0xrouter", "data": "0xabc", "value": "0x0", "chainId": 8453},
|
|
28
|
+
"approvals": [],
|
|
29
|
+
"fee": {"disclosed": True, "feeBps": 25, "feeAmount": "750000"},
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class FakeResponse(io.BytesIO):
|
|
34
|
+
def __init__(self, payload, status=200):
|
|
35
|
+
super().__init__(json.dumps(payload).encode())
|
|
36
|
+
self.status = status
|
|
37
|
+
|
|
38
|
+
def __enter__(self):
|
|
39
|
+
return self
|
|
40
|
+
|
|
41
|
+
def __exit__(self, *args):
|
|
42
|
+
return False
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def test_quote_swap_json():
|
|
46
|
+
def opener(req):
|
|
47
|
+
assert "/api/v1/quote" in req.full_url
|
|
48
|
+
assert "chainId=8453" in req.full_url
|
|
49
|
+
return FakeResponse(SAMPLE_QUOTE)
|
|
50
|
+
|
|
51
|
+
raw = quote_swap(
|
|
52
|
+
"ETH",
|
|
53
|
+
"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
|
|
54
|
+
"10000000000000000",
|
|
55
|
+
chain="base",
|
|
56
|
+
api=HelmswapApi(base_url="https://helmswap.com", opener=opener),
|
|
57
|
+
)
|
|
58
|
+
data = json.loads(raw)
|
|
59
|
+
assert data["ok"] is True
|
|
60
|
+
assert data["netOutAmount"] == "149250000"
|
|
61
|
+
assert data["minOutAmount"] == "148500000"
|
|
62
|
+
assert data["fee"]["feeBps"] == 25
|
|
63
|
+
assert "never broadcasts" in data["note"]
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def test_build_swap_returns_unsigned_tx():
|
|
67
|
+
calls = []
|
|
68
|
+
|
|
69
|
+
def opener(req):
|
|
70
|
+
calls.append(req.full_url)
|
|
71
|
+
if req.get_method() == "GET":
|
|
72
|
+
return FakeResponse(SAMPLE_QUOTE)
|
|
73
|
+
body = json.loads(req.data.decode())
|
|
74
|
+
assert body["recipient"] == "0x1111111111111111111111111111111111111111"
|
|
75
|
+
assert body["quoteTicket"]["sig"] == "ticket"
|
|
76
|
+
return FakeResponse(SAMPLE_BUILD)
|
|
77
|
+
|
|
78
|
+
raw = build_swap(
|
|
79
|
+
"ETH",
|
|
80
|
+
"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
|
|
81
|
+
"10000000000000000",
|
|
82
|
+
recipient="0x1111111111111111111111111111111111111111",
|
|
83
|
+
chain="base",
|
|
84
|
+
api=HelmswapApi(base_url="https://helmswap.com", opener=opener),
|
|
85
|
+
)
|
|
86
|
+
data = json.loads(raw)
|
|
87
|
+
assert data["tx"]["to"] == "0xrouter"
|
|
88
|
+
assert data["tx"]["data"] == "0xabc"
|
|
89
|
+
assert len(calls) == 2
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def test_build_swap_requires_recipient_and_solana_key():
|
|
93
|
+
try:
|
|
94
|
+
build_swap("ETH", "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", "1", recipient=" ", chain="base")
|
|
95
|
+
raise AssertionError("expected error")
|
|
96
|
+
except HelmswapApiError as err:
|
|
97
|
+
assert err.code == "NO_RECIPIENT"
|
|
98
|
+
|
|
99
|
+
def opener(req):
|
|
100
|
+
if req.get_method() == "GET":
|
|
101
|
+
return FakeResponse(SAMPLE_QUOTE)
|
|
102
|
+
raise AssertionError("should not build without a key")
|
|
103
|
+
|
|
104
|
+
try:
|
|
105
|
+
build_swap(
|
|
106
|
+
"SOL",
|
|
107
|
+
"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
|
|
108
|
+
"10000000",
|
|
109
|
+
recipient="11111111111111111111111111111111",
|
|
110
|
+
chain="solana",
|
|
111
|
+
api=HelmswapApi(base_url="https://helmswap.com", opener=opener),
|
|
112
|
+
)
|
|
113
|
+
raise AssertionError("expected error")
|
|
114
|
+
except HelmswapApiError as err:
|
|
115
|
+
assert err.code == "API_KEY_REQUIRED"
|