agentcrab 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.
- agentcrab-0.1.0/.gitignore +30 -0
- agentcrab-0.1.0/LICENSE +21 -0
- agentcrab-0.1.0/PKG-INFO +155 -0
- agentcrab-0.1.0/README.md +130 -0
- agentcrab-0.1.0/agentcrab/__init__.py +55 -0
- agentcrab-0.1.0/agentcrab/_auth.py +39 -0
- agentcrab-0.1.0/agentcrab/_exceptions.py +42 -0
- agentcrab-0.1.0/agentcrab/_http.py +138 -0
- agentcrab-0.1.0/agentcrab/_signer.py +42 -0
- agentcrab-0.1.0/agentcrab/_types.py +168 -0
- agentcrab-0.1.0/agentcrab/client.py +851 -0
- agentcrab-0.1.0/agentcrab/py.typed +0 -0
- agentcrab-0.1.0/pyproject.toml +39 -0
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
# Environment variables / secrets
|
|
2
|
+
.env*
|
|
3
|
+
*.pem
|
|
4
|
+
*.key
|
|
5
|
+
|
|
6
|
+
# Node
|
|
7
|
+
node_modules/
|
|
8
|
+
|
|
9
|
+
# Python
|
|
10
|
+
__pycache__/
|
|
11
|
+
*.pyc
|
|
12
|
+
.venv/
|
|
13
|
+
|
|
14
|
+
# OS
|
|
15
|
+
.DS_Store
|
|
16
|
+
|
|
17
|
+
# IDE
|
|
18
|
+
.vscode/
|
|
19
|
+
.idea/
|
|
20
|
+
|
|
21
|
+
# Foundry
|
|
22
|
+
Polymarket/contracts/out/
|
|
23
|
+
Polymarket/contracts/cache/
|
|
24
|
+
Polymarket/contracts/broadcast/
|
|
25
|
+
|
|
26
|
+
# Wrangler (Cloudflare)
|
|
27
|
+
.wrangler/
|
|
28
|
+
|
|
29
|
+
# SQLite
|
|
30
|
+
*.db
|
agentcrab-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 agentCrab
|
|
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.
|
agentcrab-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: agentcrab
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Python SDK for agentCrab — turn any AI agent into a Polymarket assistant
|
|
5
|
+
Project-URL: Homepage, https://agentcrab.ai
|
|
6
|
+
Project-URL: Documentation, https://github.com/agentcrab/agentcrab-python
|
|
7
|
+
Project-URL: Repository, https://github.com/agentcrab/agentcrab-python
|
|
8
|
+
Author-email: agentCrab <dev@agentcrab.ai>
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: ai-agent,polymarket,prediction-market,sdk,web3
|
|
12
|
+
Classifier: Development Status :: 3 - Alpha
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
20
|
+
Requires-Python: >=3.11
|
|
21
|
+
Requires-Dist: eth-account>=0.13.0
|
|
22
|
+
Requires-Dist: hexbytes>=1.0.0
|
|
23
|
+
Requires-Dist: httpx>=0.27.0
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
|
|
26
|
+
# agentcrab
|
|
27
|
+
|
|
28
|
+
Python SDK for [agentCrab](https://agentcrab.ai) — turn any AI agent into a Polymarket assistant with 3 lines of code.
|
|
29
|
+
|
|
30
|
+
## Install
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
pip install agentcrab
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
## Quick Start
|
|
37
|
+
|
|
38
|
+
```python
|
|
39
|
+
from agentcrab import AgentCrab
|
|
40
|
+
|
|
41
|
+
client = AgentCrab("https://api.agentcrab.ai/polymarket", "0xYOUR_PRIVATE_KEY")
|
|
42
|
+
|
|
43
|
+
# Search markets
|
|
44
|
+
markets = client.search("bitcoin")
|
|
45
|
+
for m in markets:
|
|
46
|
+
print(m.title, m.outcomes)
|
|
47
|
+
|
|
48
|
+
# Check balance
|
|
49
|
+
balance = client.get_balance()
|
|
50
|
+
print(f"{balance.calls_remaining} API calls remaining")
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
## Trading
|
|
54
|
+
|
|
55
|
+
```python
|
|
56
|
+
# One-time setup (deploys Safe + approvals + L2 credentials)
|
|
57
|
+
setup = client.setup_trading()
|
|
58
|
+
print(f"Safe: {setup.safe_address}")
|
|
59
|
+
|
|
60
|
+
# Buy shares
|
|
61
|
+
result = client.buy(token_id="TOKEN_ID", size=5.0, price=0.65)
|
|
62
|
+
print(f"Order {result.status}: {result.order_id}")
|
|
63
|
+
|
|
64
|
+
# Sell shares
|
|
65
|
+
result = client.sell(token_id="TOKEN_ID", size=5.0, price=0.70)
|
|
66
|
+
|
|
67
|
+
# View positions
|
|
68
|
+
for pos in client.get_positions():
|
|
69
|
+
print(f"{pos.outcome}: {pos.size} shares, PnL: {pos.pnl}")
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
## Full API
|
|
73
|
+
|
|
74
|
+
### Balance & Payment
|
|
75
|
+
|
|
76
|
+
| Method | Description | Cost |
|
|
77
|
+
|--------|-------------|------|
|
|
78
|
+
| `get_balance()` | Prepaid balance | Free |
|
|
79
|
+
| `deposit(amount_usdt)` | Deposit to agentCrab | Free |
|
|
80
|
+
| `deposit_to_polymarket(amount_usdt)` | Deposit to Polymarket | 0.01 USDT |
|
|
81
|
+
|
|
82
|
+
### Market Data
|
|
83
|
+
|
|
84
|
+
| Method | Description | Cost |
|
|
85
|
+
|--------|-------------|------|
|
|
86
|
+
| `search(query, tag, category)` | Search events | 0.01 USDT |
|
|
87
|
+
| `browse(category, mood)` | Browse events | 0.01 USDT |
|
|
88
|
+
| `get_event(event_id)` | Get single event | 0.01 USDT |
|
|
89
|
+
| `get_market(market_id)` | Get single market | 0.01 USDT |
|
|
90
|
+
| `get_orderbook(token_id)` | Get orderbook | 0.01 USDT |
|
|
91
|
+
| `get_price(token_id)` | Get price | 0.01 USDT |
|
|
92
|
+
|
|
93
|
+
### Positions & History
|
|
94
|
+
|
|
95
|
+
| Method | Description | Cost |
|
|
96
|
+
|--------|-------------|------|
|
|
97
|
+
| `get_positions()` | Your positions | 0.01 USDT |
|
|
98
|
+
| `get_trades(limit, offset)` | Your trades | 0.01 USDT |
|
|
99
|
+
| `get_leaderboard(limit, offset)` | Leaderboard | 0.01 USDT |
|
|
100
|
+
|
|
101
|
+
### Trading (requires `setup_trading()` first)
|
|
102
|
+
|
|
103
|
+
| Method | Description | Cost |
|
|
104
|
+
|--------|-------------|------|
|
|
105
|
+
| `setup_trading()` | Deploy Safe + approvals + creds | 0.01-0.03 USDT |
|
|
106
|
+
| `set_credentials(key, secret, passphrase)` | Manual cred set | Free |
|
|
107
|
+
| `buy(token_id, size, price)` | Buy shares | 0.01 USDT |
|
|
108
|
+
| `sell(token_id, size, price)` | Sell shares | 0.01 USDT |
|
|
109
|
+
| `cancel_order(order_id)` | Cancel order | 0.01 USDT |
|
|
110
|
+
| `cancel_all_orders()` | Cancel all | 0.01 USDT |
|
|
111
|
+
| `get_open_orders(market)` | Open orders | 0.01 USDT |
|
|
112
|
+
|
|
113
|
+
### Wallet
|
|
114
|
+
|
|
115
|
+
| Method | Description |
|
|
116
|
+
|--------|-------------|
|
|
117
|
+
| `AgentCrab.create_wallet(api_url)` | Create new wallet (static) |
|
|
118
|
+
|
|
119
|
+
## Typed Responses
|
|
120
|
+
|
|
121
|
+
All methods return typed dataclasses with a `.raw` escape hatch:
|
|
122
|
+
|
|
123
|
+
```python
|
|
124
|
+
balance = client.get_balance()
|
|
125
|
+
print(balance.calls_remaining) # typed field
|
|
126
|
+
print(balance.raw) # full server response dict
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
## Error Handling
|
|
130
|
+
|
|
131
|
+
```python
|
|
132
|
+
from agentcrab import AgentCrabError, InsufficientBalance, SetupRequired
|
|
133
|
+
|
|
134
|
+
try:
|
|
135
|
+
result = client.buy(token_id, size=5.0, price=0.65)
|
|
136
|
+
except SetupRequired:
|
|
137
|
+
client.setup_trading()
|
|
138
|
+
result = client.buy(token_id, size=5.0, price=0.65)
|
|
139
|
+
except InsufficientBalance as e:
|
|
140
|
+
print(f"Top up: {e.message}")
|
|
141
|
+
except AgentCrabError as e:
|
|
142
|
+
print(f"Error [{e.error_code}]: {e.message}")
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
## Dependencies
|
|
146
|
+
|
|
147
|
+
Minimal — no `web3` required:
|
|
148
|
+
|
|
149
|
+
- `eth-account` — EIP-191, EIP-712, tx signing
|
|
150
|
+
- `httpx` — Sync HTTP
|
|
151
|
+
- `hexbytes` — SafeTx hash signing
|
|
152
|
+
|
|
153
|
+
## License
|
|
154
|
+
|
|
155
|
+
MIT
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
# agentcrab
|
|
2
|
+
|
|
3
|
+
Python SDK for [agentCrab](https://agentcrab.ai) — turn any AI agent into a Polymarket assistant with 3 lines of code.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pip install agentcrab
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Quick Start
|
|
12
|
+
|
|
13
|
+
```python
|
|
14
|
+
from agentcrab import AgentCrab
|
|
15
|
+
|
|
16
|
+
client = AgentCrab("https://api.agentcrab.ai/polymarket", "0xYOUR_PRIVATE_KEY")
|
|
17
|
+
|
|
18
|
+
# Search markets
|
|
19
|
+
markets = client.search("bitcoin")
|
|
20
|
+
for m in markets:
|
|
21
|
+
print(m.title, m.outcomes)
|
|
22
|
+
|
|
23
|
+
# Check balance
|
|
24
|
+
balance = client.get_balance()
|
|
25
|
+
print(f"{balance.calls_remaining} API calls remaining")
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## Trading
|
|
29
|
+
|
|
30
|
+
```python
|
|
31
|
+
# One-time setup (deploys Safe + approvals + L2 credentials)
|
|
32
|
+
setup = client.setup_trading()
|
|
33
|
+
print(f"Safe: {setup.safe_address}")
|
|
34
|
+
|
|
35
|
+
# Buy shares
|
|
36
|
+
result = client.buy(token_id="TOKEN_ID", size=5.0, price=0.65)
|
|
37
|
+
print(f"Order {result.status}: {result.order_id}")
|
|
38
|
+
|
|
39
|
+
# Sell shares
|
|
40
|
+
result = client.sell(token_id="TOKEN_ID", size=5.0, price=0.70)
|
|
41
|
+
|
|
42
|
+
# View positions
|
|
43
|
+
for pos in client.get_positions():
|
|
44
|
+
print(f"{pos.outcome}: {pos.size} shares, PnL: {pos.pnl}")
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## Full API
|
|
48
|
+
|
|
49
|
+
### Balance & Payment
|
|
50
|
+
|
|
51
|
+
| Method | Description | Cost |
|
|
52
|
+
|--------|-------------|------|
|
|
53
|
+
| `get_balance()` | Prepaid balance | Free |
|
|
54
|
+
| `deposit(amount_usdt)` | Deposit to agentCrab | Free |
|
|
55
|
+
| `deposit_to_polymarket(amount_usdt)` | Deposit to Polymarket | 0.01 USDT |
|
|
56
|
+
|
|
57
|
+
### Market Data
|
|
58
|
+
|
|
59
|
+
| Method | Description | Cost |
|
|
60
|
+
|--------|-------------|------|
|
|
61
|
+
| `search(query, tag, category)` | Search events | 0.01 USDT |
|
|
62
|
+
| `browse(category, mood)` | Browse events | 0.01 USDT |
|
|
63
|
+
| `get_event(event_id)` | Get single event | 0.01 USDT |
|
|
64
|
+
| `get_market(market_id)` | Get single market | 0.01 USDT |
|
|
65
|
+
| `get_orderbook(token_id)` | Get orderbook | 0.01 USDT |
|
|
66
|
+
| `get_price(token_id)` | Get price | 0.01 USDT |
|
|
67
|
+
|
|
68
|
+
### Positions & History
|
|
69
|
+
|
|
70
|
+
| Method | Description | Cost |
|
|
71
|
+
|--------|-------------|------|
|
|
72
|
+
| `get_positions()` | Your positions | 0.01 USDT |
|
|
73
|
+
| `get_trades(limit, offset)` | Your trades | 0.01 USDT |
|
|
74
|
+
| `get_leaderboard(limit, offset)` | Leaderboard | 0.01 USDT |
|
|
75
|
+
|
|
76
|
+
### Trading (requires `setup_trading()` first)
|
|
77
|
+
|
|
78
|
+
| Method | Description | Cost |
|
|
79
|
+
|--------|-------------|------|
|
|
80
|
+
| `setup_trading()` | Deploy Safe + approvals + creds | 0.01-0.03 USDT |
|
|
81
|
+
| `set_credentials(key, secret, passphrase)` | Manual cred set | Free |
|
|
82
|
+
| `buy(token_id, size, price)` | Buy shares | 0.01 USDT |
|
|
83
|
+
| `sell(token_id, size, price)` | Sell shares | 0.01 USDT |
|
|
84
|
+
| `cancel_order(order_id)` | Cancel order | 0.01 USDT |
|
|
85
|
+
| `cancel_all_orders()` | Cancel all | 0.01 USDT |
|
|
86
|
+
| `get_open_orders(market)` | Open orders | 0.01 USDT |
|
|
87
|
+
|
|
88
|
+
### Wallet
|
|
89
|
+
|
|
90
|
+
| Method | Description |
|
|
91
|
+
|--------|-------------|
|
|
92
|
+
| `AgentCrab.create_wallet(api_url)` | Create new wallet (static) |
|
|
93
|
+
|
|
94
|
+
## Typed Responses
|
|
95
|
+
|
|
96
|
+
All methods return typed dataclasses with a `.raw` escape hatch:
|
|
97
|
+
|
|
98
|
+
```python
|
|
99
|
+
balance = client.get_balance()
|
|
100
|
+
print(balance.calls_remaining) # typed field
|
|
101
|
+
print(balance.raw) # full server response dict
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
## Error Handling
|
|
105
|
+
|
|
106
|
+
```python
|
|
107
|
+
from agentcrab import AgentCrabError, InsufficientBalance, SetupRequired
|
|
108
|
+
|
|
109
|
+
try:
|
|
110
|
+
result = client.buy(token_id, size=5.0, price=0.65)
|
|
111
|
+
except SetupRequired:
|
|
112
|
+
client.setup_trading()
|
|
113
|
+
result = client.buy(token_id, size=5.0, price=0.65)
|
|
114
|
+
except InsufficientBalance as e:
|
|
115
|
+
print(f"Top up: {e.message}")
|
|
116
|
+
except AgentCrabError as e:
|
|
117
|
+
print(f"Error [{e.error_code}]: {e.message}")
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
## Dependencies
|
|
121
|
+
|
|
122
|
+
Minimal — no `web3` required:
|
|
123
|
+
|
|
124
|
+
- `eth-account` — EIP-191, EIP-712, tx signing
|
|
125
|
+
- `httpx` — Sync HTTP
|
|
126
|
+
- `hexbytes` — SafeTx hash signing
|
|
127
|
+
|
|
128
|
+
## License
|
|
129
|
+
|
|
130
|
+
MIT
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"""agentcrab — Python SDK for the agentCrab Polymarket API."""
|
|
2
|
+
|
|
3
|
+
__version__ = "0.1.0"
|
|
4
|
+
|
|
5
|
+
from .client import AgentCrab
|
|
6
|
+
from ._exceptions import (
|
|
7
|
+
AgentCrabError,
|
|
8
|
+
APIError,
|
|
9
|
+
AuthError,
|
|
10
|
+
InsufficientBalance,
|
|
11
|
+
NetworkError,
|
|
12
|
+
OrderError,
|
|
13
|
+
PaymentError,
|
|
14
|
+
SetupRequired,
|
|
15
|
+
)
|
|
16
|
+
from ._types import (
|
|
17
|
+
Balance,
|
|
18
|
+
BatchOrderResult,
|
|
19
|
+
DepositResult,
|
|
20
|
+
Market,
|
|
21
|
+
Orderbook,
|
|
22
|
+
OrderResult,
|
|
23
|
+
Position,
|
|
24
|
+
Price,
|
|
25
|
+
SetupResult,
|
|
26
|
+
Trade,
|
|
27
|
+
Trigger,
|
|
28
|
+
TriggerResult,
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
__all__ = [
|
|
32
|
+
"AgentCrab",
|
|
33
|
+
# Exceptions
|
|
34
|
+
"AgentCrabError",
|
|
35
|
+
"APIError",
|
|
36
|
+
"AuthError",
|
|
37
|
+
"InsufficientBalance",
|
|
38
|
+
"NetworkError",
|
|
39
|
+
"OrderError",
|
|
40
|
+
"PaymentError",
|
|
41
|
+
"SetupRequired",
|
|
42
|
+
# Types
|
|
43
|
+
"Balance",
|
|
44
|
+
"BatchOrderResult",
|
|
45
|
+
"DepositResult",
|
|
46
|
+
"Market",
|
|
47
|
+
"Orderbook",
|
|
48
|
+
"OrderResult",
|
|
49
|
+
"Position",
|
|
50
|
+
"Price",
|
|
51
|
+
"SetupResult",
|
|
52
|
+
"Trade",
|
|
53
|
+
"Trigger",
|
|
54
|
+
"TriggerResult",
|
|
55
|
+
]
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""EIP-191 authentication header building."""
|
|
2
|
+
|
|
3
|
+
import time
|
|
4
|
+
|
|
5
|
+
from eth_account import Account
|
|
6
|
+
from eth_account.messages import encode_defunct
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def build_auth_headers(
|
|
10
|
+
private_key: str,
|
|
11
|
+
address: str,
|
|
12
|
+
payment_mode: str = "prepaid",
|
|
13
|
+
) -> dict[str, str]:
|
|
14
|
+
"""Build authentication headers for API requests.
|
|
15
|
+
|
|
16
|
+
Signs ``agentcrab:{unix_timestamp}`` with EIP-191 personal_sign.
|
|
17
|
+
"""
|
|
18
|
+
ts = int(time.time())
|
|
19
|
+
message = f"agentcrab:{ts}"
|
|
20
|
+
sig = Account.sign_message(
|
|
21
|
+
encode_defunct(text=message),
|
|
22
|
+
private_key=private_key,
|
|
23
|
+
)
|
|
24
|
+
headers = {
|
|
25
|
+
"X-Wallet-Address": address,
|
|
26
|
+
"X-Signature": "0x" + sig.signature.hex(),
|
|
27
|
+
"X-Message": message,
|
|
28
|
+
"X-Payment-Mode": payment_mode,
|
|
29
|
+
}
|
|
30
|
+
return headers
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def build_l2_headers(api_key: str, secret: str, passphrase: str) -> dict[str, str]:
|
|
34
|
+
"""Build Polymarket L2 credential headers."""
|
|
35
|
+
return {
|
|
36
|
+
"X-Poly-Api-Key": api_key,
|
|
37
|
+
"X-Poly-Secret": secret,
|
|
38
|
+
"X-Poly-Passphrase": passphrase,
|
|
39
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""Typed exception hierarchy for the agentcrab SDK."""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class AgentCrabError(Exception):
|
|
5
|
+
"""Base exception for all agentcrab errors."""
|
|
6
|
+
|
|
7
|
+
def __init__(self, message: str, error_code: str | None = None, status_code: int | None = None):
|
|
8
|
+
self.message = message
|
|
9
|
+
self.error_code = error_code
|
|
10
|
+
self.status_code = status_code
|
|
11
|
+
super().__init__(message)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class AuthError(AgentCrabError):
|
|
15
|
+
"""Signature verification failed (401)."""
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class PaymentError(AgentCrabError):
|
|
19
|
+
"""Payment-related error (402)."""
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class InsufficientBalance(PaymentError):
|
|
23
|
+
"""Prepaid balance too low."""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class APIError(AgentCrabError):
|
|
27
|
+
"""Server returned an error response (4xx/5xx)."""
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class SetupRequired(AgentCrabError):
|
|
31
|
+
"""Trading operation called before setup_trading()."""
|
|
32
|
+
|
|
33
|
+
def __init__(self, message: str = "Call setup_trading() first to get L2 credentials."):
|
|
34
|
+
super().__init__(message, error_code="SETUP_REQUIRED")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class OrderError(AgentCrabError):
|
|
38
|
+
"""Order placement or cancellation failed."""
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class NetworkError(AgentCrabError):
|
|
42
|
+
"""HTTP transport failure (timeout, connection refused, etc.)."""
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
"""Sync HTTP transport with auto-auth and error mapping."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
import httpx
|
|
8
|
+
|
|
9
|
+
from ._auth import build_auth_headers, build_l2_headers
|
|
10
|
+
from ._exceptions import (
|
|
11
|
+
APIError,
|
|
12
|
+
AuthError,
|
|
13
|
+
InsufficientBalance,
|
|
14
|
+
NetworkError,
|
|
15
|
+
OrderError,
|
|
16
|
+
PaymentError,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
# Map server error_code to exception class
|
|
20
|
+
_ERROR_MAP: dict[str, type] = {
|
|
21
|
+
"INVALID_SIGNATURE": AuthError,
|
|
22
|
+
"MISSING_TX_HASH": PaymentError,
|
|
23
|
+
"PAYMENT_NOT_VERIFIED": PaymentError,
|
|
24
|
+
"INSUFFICIENT_BALANCE": InsufficientBalance,
|
|
25
|
+
"BALANCE_DEDUCTION_FAILED": PaymentError,
|
|
26
|
+
"INVALID_PAYMENT_MODE": PaymentError,
|
|
27
|
+
"ORDER_REJECTED": OrderError,
|
|
28
|
+
"ORDER_ERROR": OrderError,
|
|
29
|
+
"ORDER_BUILD_FAILED": OrderError,
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class HttpTransport:
|
|
34
|
+
"""Sync HTTP client with auto-injected auth headers."""
|
|
35
|
+
|
|
36
|
+
def __init__(
|
|
37
|
+
self,
|
|
38
|
+
base_url: str,
|
|
39
|
+
private_key: str,
|
|
40
|
+
address: str,
|
|
41
|
+
payment_mode: str = "prepaid",
|
|
42
|
+
timeout: float = 60.0,
|
|
43
|
+
):
|
|
44
|
+
self._base_url = base_url.rstrip("/")
|
|
45
|
+
self._private_key = private_key
|
|
46
|
+
self._address = address
|
|
47
|
+
self._payment_mode = payment_mode
|
|
48
|
+
self._client = httpx.Client(base_url=self._base_url, timeout=timeout)
|
|
49
|
+
|
|
50
|
+
def close(self) -> None:
|
|
51
|
+
self._client.close()
|
|
52
|
+
|
|
53
|
+
def _auth_headers(self) -> dict[str, str]:
|
|
54
|
+
return build_auth_headers(self._private_key, self._address, self._payment_mode)
|
|
55
|
+
|
|
56
|
+
def _raise_for_error(self, resp: httpx.Response) -> None:
|
|
57
|
+
"""Parse server error response and raise typed exception."""
|
|
58
|
+
if resp.status_code < 400:
|
|
59
|
+
return
|
|
60
|
+
try:
|
|
61
|
+
body = resp.json()
|
|
62
|
+
# Handle FastAPI's HTTPException detail format
|
|
63
|
+
detail = body if isinstance(body, dict) and "error_code" in body else body.get("detail", body)
|
|
64
|
+
if isinstance(detail, dict):
|
|
65
|
+
error_code = detail.get("error_code", "")
|
|
66
|
+
message = detail.get("message", resp.text)
|
|
67
|
+
else:
|
|
68
|
+
error_code = ""
|
|
69
|
+
message = str(detail) if detail else resp.text
|
|
70
|
+
except Exception:
|
|
71
|
+
error_code = ""
|
|
72
|
+
message = resp.text
|
|
73
|
+
|
|
74
|
+
exc_cls = _ERROR_MAP.get(error_code, APIError)
|
|
75
|
+
raise exc_cls(message=message, error_code=error_code, status_code=resp.status_code)
|
|
76
|
+
|
|
77
|
+
def get(
|
|
78
|
+
self,
|
|
79
|
+
path: str,
|
|
80
|
+
params: dict | None = None,
|
|
81
|
+
auth: bool = True,
|
|
82
|
+
paid: bool = False,
|
|
83
|
+
l2_creds: dict | None = None,
|
|
84
|
+
) -> dict:
|
|
85
|
+
"""Send GET request. Returns parsed JSON body."""
|
|
86
|
+
headers = self._auth_headers() if (auth or paid) else {}
|
|
87
|
+
if l2_creds:
|
|
88
|
+
headers.update(build_l2_headers(**l2_creds))
|
|
89
|
+
try:
|
|
90
|
+
resp = self._client.get(path, params=params, headers=headers)
|
|
91
|
+
except httpx.HTTPError as e:
|
|
92
|
+
raise NetworkError(message=str(e)) from e
|
|
93
|
+
self._raise_for_error(resp)
|
|
94
|
+
return resp.json()
|
|
95
|
+
|
|
96
|
+
def post(
|
|
97
|
+
self,
|
|
98
|
+
path: str,
|
|
99
|
+
json: Any = None,
|
|
100
|
+
auth: bool = True,
|
|
101
|
+
paid: bool = False,
|
|
102
|
+
l2_creds: dict | None = None,
|
|
103
|
+
) -> dict:
|
|
104
|
+
"""Send POST request. Returns parsed JSON body."""
|
|
105
|
+
headers = self._auth_headers() if (auth or paid) else {}
|
|
106
|
+
if l2_creds:
|
|
107
|
+
headers.update(build_l2_headers(**l2_creds))
|
|
108
|
+
try:
|
|
109
|
+
resp = self._client.post(path, json=json, headers=headers)
|
|
110
|
+
except httpx.HTTPError as e:
|
|
111
|
+
raise NetworkError(message=str(e)) from e
|
|
112
|
+
self._raise_for_error(resp)
|
|
113
|
+
return resp.json()
|
|
114
|
+
|
|
115
|
+
def delete(
|
|
116
|
+
self,
|
|
117
|
+
path: str,
|
|
118
|
+
params: dict | None = None,
|
|
119
|
+
json: Any = None,
|
|
120
|
+
auth: bool = True,
|
|
121
|
+
paid: bool = False,
|
|
122
|
+
l2_creds: dict | None = None,
|
|
123
|
+
) -> dict:
|
|
124
|
+
"""Send DELETE request. Returns parsed JSON body."""
|
|
125
|
+
headers = self._auth_headers() if (auth or paid) else {}
|
|
126
|
+
if l2_creds:
|
|
127
|
+
headers.update(build_l2_headers(**l2_creds))
|
|
128
|
+
try:
|
|
129
|
+
resp = self._client.request("DELETE", path, params=params, json=json, headers=headers)
|
|
130
|
+
except httpx.HTTPError as e:
|
|
131
|
+
raise NetworkError(message=str(e)) from e
|
|
132
|
+
self._raise_for_error(resp)
|
|
133
|
+
return resp.json()
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _extract_data(resp: dict) -> Any:
|
|
137
|
+
"""Extract ``data`` field from SuccessResponse envelope."""
|
|
138
|
+
return resp.get("data", resp)
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""Signing utilities: EIP-712 typed data, raw transactions, Safe tx hashes."""
|
|
2
|
+
|
|
3
|
+
from eth_account import Account
|
|
4
|
+
from eth_account.messages import encode_defunct
|
|
5
|
+
from hexbytes import HexBytes
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def sign_typed_data(private_key: str, typed_data: dict) -> str:
|
|
9
|
+
"""Sign EIP-712 typed data and return 0x-prefixed hex signature.
|
|
10
|
+
|
|
11
|
+
Used for: Safe deploy (CreateProxy), CLOB auth, order placement.
|
|
12
|
+
"""
|
|
13
|
+
sig = Account.sign_typed_data(
|
|
14
|
+
private_key,
|
|
15
|
+
typed_data["domain"],
|
|
16
|
+
typed_data["types"],
|
|
17
|
+
typed_data["message"],
|
|
18
|
+
)
|
|
19
|
+
return "0x" + sig.signature.hex()
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def sign_transaction(private_key: str, tx: dict) -> str:
|
|
23
|
+
"""Sign a raw transaction and return 0x-prefixed hex of the signed bytes.
|
|
24
|
+
|
|
25
|
+
Used for: BSC deposits, Polygon approve txs.
|
|
26
|
+
"""
|
|
27
|
+
account = Account.from_key(private_key)
|
|
28
|
+
signed = account.sign_transaction(tx)
|
|
29
|
+
raw = signed.raw_transaction
|
|
30
|
+
if isinstance(raw, (bytes, bytearray)):
|
|
31
|
+
return "0x" + raw.hex()
|
|
32
|
+
return "0x" + bytes(raw).hex()
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def sign_safe_tx_hash(private_key: str, hash_hex: str) -> str:
|
|
36
|
+
"""Personal-sign a SafeTx hash (bytes32) and return 0x-prefixed hex signature.
|
|
37
|
+
|
|
38
|
+
Used for: Safe token approvals via relayer.
|
|
39
|
+
"""
|
|
40
|
+
account = Account.from_key(private_key)
|
|
41
|
+
sig = account.sign_message(encode_defunct(HexBytes(hash_hex)))
|
|
42
|
+
return "0x" + sig.signature.hex()
|