Skip to content
Merged
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
2 changes: 2 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,8 @@ Unit tests in `tests/unit/` have no external dependencies. Integration tests in
- **STOP/STOPLIMIT: reserved on-chain, unplaceable, but read-labelled**: the contract `Type1` enum is `{MARKET, LIMIT, STOP, STOPLIMIT}` (verified against `ITradePairs.sol`), but STOP/STOPLIMIT are unused — `NewOrder` has no trigger-price field and no pair enables them. So the write-side `OrderType` enum is `{MARKET, LIMIT}` (the SDK never originates a stop order) while the read map `ORDER_TYPE_NAMES` includes all four contract names so reads stay faithful. Genuinely-unknown integers still map to `"UNKNOWN(<n>)"`.
- **`time_in_force` / `stp` default to today's behavior**: `add_order` (and per-order dicts in `add_limit_order_list` / `cancel_add_list`) accept optional `time_in_force` (default `GTC`) and `stp` (default `CANCEL_TAKER`), replacing the previously hardcoded `type2=0` / `stp=0`. `validate_order_combo` enforces only the one contract-faithful rule — **LIMIT requires a price** — verified against `TradePairs.sol`: the contract ignores `type2`/price for MARKET (no revert), and PO / per-pair-allowed-type / self-trade / FOK rules are enforced on-chain (`T-T2PO-01`, `T-POOA-01`, `T-IVOT-01`, `T-FOKF-01`, `T-STPR-01`). Do **not** re-add a MARKET-must-be-IOC/FOK check — it is stricter than the contract and rejected the default (GTC) MARKET order. `type2`/`stp` integer values are confirmed against the contract enums.
- **MARKET BUY skips the pre-flight balance check**: without a price the quote-token notional is unknown, so `add_order` / `_build_order_tuple` / `_process_replacement` skip the balance check for a MARKET BUY and let the contract enforce it. MARKET SELL (base amount known) and all LIMIT paths keep the check.
- **RFQ swaps execute on `tx.to` / `order.maker`, never on the deployments `MainnetRFQ` address**: mainnet firm quotes are signed by one of several maker contracts (legacy MainnetRFQ 1.2.8 plus DexalotRFQ 2.x instances, each with its own `swapSigner` and EIP-712 domain) sitting behind `DexalotRouter` (`MainnetRFQ.trustedForwarder()`), whose fallback forwards `simpleSwap` calldata to `order.maker` with the sender appended. The deployments endpoint only lists the legacy address, so sending a quote there fails `RF-IS-01` whenever another maker won the quote. `execute_rfq_swap` resolves the target via `_resolve_rfq_execution_target`: `order.maker` must be in `router.getAllowedRFQs()` (discovered by `_get_rfq_targets`: router from the deployments endpoint's `DexalotRouter` entry, loaded best-effort by `_fetch_optional_contract_deployment`, else `MainnetRFQ.trustedForwarder()` on-chain; makers always on-chain since the API does not list them; cached in the static tier, lookup failures degrade to deployment-only and are not cached), `tx.to` must be the router or the maker, and `tx.data`/`tx.value` (when present) must equal the SDK's own encoding. The SDK always encodes `simpleSwap` itself from the embedded `_SIMPLE_SWAP_ABI`. `MainnetRFQ`/`DexalotRouter` deployments are keyed by the connected chain's `chain_config` name (`"Avalanche"` on mainnet, `"Fuji"` on testnet, via `_connected_chain_key`), which is what `_get_rfq_contract` looks up; before this, Fuji RFQ lookups always missed.
- **ERC20 RFQ sells need an allowance on `order.maker`**: the maker contract does `transferFrom(taker)` itself, so approving the router or the legacy address does nothing. `execute_rfq_swap` pre-checks `allowance(taker, maker)` and fails with an actionable message; `approve_rfq_maker(quote)` grants exactly `takerAmount` (or `amount_wei`) after validating the maker against the allow-list. Native sells carry the amount as `msg.value` and skip both.
- **`replace_order` cannot change order type/TIF/stp**: `cancelReplaceOrder` carries only a new price and quantity, so the replacement inherits the original `type1`/`type2`/`stp`. To change those, cancel and re-place (e.g. `cancel_add_list`). The method intentionally exposes no `time_in_force`/`stp` params.

---
Expand Down
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1013,6 +1013,27 @@ Enum-style fields are normalized to human-readable strings such as `BUY`, `SELL`

**Swap Operations:**
- `execute_rfq_swap(quote, wait_for_receipt=True)`
- `approve_rfq_maker(quote, amount_wei=None, wait_for_receipt=True)`

**RFQ execution target.** Firm quotes are served by several maker contracts
(the legacy `MainnetRFQ` plus `DexalotRFQ` instances) behind the
`DexalotRouter`, and each maker verifies its own signer. `execute_rfq_swap`
therefore sends `simpleSwap` to the quote's `tx.to` (the router) or, when the
quote carries no `tx`, to `order.maker` directly. It never uses the
`MainnetRFQ` address from the deployments endpoint as the target. The router
address comes from the deployments endpoint (`DexalotRouter`), falling back to
`MainnetRFQ.trustedForwarder()` on-chain; the makers come from the router's
`getAllowedRFQs()`. Before
broadcasting it checks that `order.maker` is on that
allow-list, that `tx.to` is the router or the maker, and that any `tx.data` /
`tx.value` in the quote match the call the SDK encodes itself. Errors carry a
`[target=..., maker=..., quote_id=..., nonce_and_meta=..., expiry=...]` suffix.

**ERC20 sells need a per-maker allowance.** The maker contract pulls the taker
asset with `transferFrom`, so the allowance must be granted to `order.maker`,
not to the router and not to the legacy address. `execute_rfq_swap` fails fast
with an actionable message when the allowance is short; call
`approve_rfq_maker(quote)` first. Native-asset sells (AVAX) need no approval.

### Example: Batch Order Placement

Expand Down
2 changes: 1 addition & 1 deletion VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
0.6.0
0.6.1
22 changes: 21 additions & 1 deletion docs/python-sdk-user-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -350,12 +350,32 @@ if result.success:
print("Firm quote ID:", quote["quote_id"])
```

### Approve the maker (ERC20 sells only)

Firm quotes come from several maker contracts behind the Dexalot router, and
each maker pulls the taker asset itself. Grant the allowance to the quote's
`order.maker` (the SDK validates the maker against the router's on-chain
allow-list before approving). Native-asset sells skip this step.

```python
result = await client.approve_rfq_maker(quote)
if result.success and result.data["approved"]:
print("Approval tx:", result.data["tx_hash"])
```

### Execute swap

`execute_rfq_swap` targets the quote's `tx.to` (the router) or `order.maker`,
never the legacy `MainnetRFQ` deployment address, and refuses quotes whose
maker or `tx` envelope fail validation. Errors include a
`[target=..., maker=..., quote_id=...]` trail for diagnosis.

```python
result = await client.execute_rfq_swap(quote)
if result.success:
print("Swap tx:", result.data)
print("Swap tx:", result.data["tx_hash"], "via", result.data["target"])
else:
print("Swap failed:", result.error)
```

---
Expand Down
13 changes: 10 additions & 3 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ license = "MIT"
license-files = [
"LICENSE.txt"
]
version = "0.6.0"
version = "0.6.1"
description = "Dexalot Python SDK - Core library for Dexalot interaction"
readme = "README.md"
requires-python = ">=3.12,<3.15"
Expand All @@ -29,11 +29,11 @@ classifiers = [
]
dependencies = [
"web3>=6.0.0,<8",
"aiohttp>=3.14.1,<4",
"aiohttp>=3.14.3,<4",
"python-dotenv>=1.0,<2",
"eth-account>=0.11,<1",
"websockets>=13.0,<15",
"cryptography>=48.0.1,<49",
"cryptography>=50.0.0,<51",
# Pin transitive deps to versions free of known CVEs (pip-audit gate).
# - idna>=3.15 closes CVE-2026-45409
# - urllib3>=2.7.0 closes PYSEC-2026-141 and PYSEC-2026-142
Expand All @@ -60,13 +60,20 @@ dev = [
docs = [
"mkdocstrings[python]>=0.29",
"zensical>=0.0.29",
# Transitive floor: pymdown-extensions<11.0.1 is flagged by pip-audit
# (PYSEC-2026-3609, PYSEC-2026-3654).
"pymdown-extensions>=11.0.1",
]

# Security audit tooling — kept out of `dev` so a normal contributor install
# stays lean. CI installs this group explicitly via `uv sync --group security`.
security = [
"bandit[toml]",
"pip-audit",
# Transitive floors for pip-audit's own dependency tree, flagged by the
# pip-audit gate: msgpack (PYSEC-2026-3625) and pip (PYSEC-2026-3721).
"msgpack>=1.2.1",
"pip>=26.2",
]

[project.scripts]
Expand Down
2 changes: 1 addition & 1 deletion src/dexalot_sdk/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
secrets_vault_set,
)

__version__ = "0.6.0"
__version__ = "0.6.1"


def get_version() -> str:
Expand Down
48 changes: 45 additions & 3 deletions src/dexalot_sdk/core/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -278,6 +278,7 @@ def _initialize_data_structures(self):
"PortfolioMain": {},
"PortfolioSub": {},
"MainnetRFQ": {},
"DexalotRouter": {},
}
self.pairs: dict[str, Any] = {}
self.token_data: dict[str, Any] = {}
Expand Down Expand Up @@ -1396,8 +1397,23 @@ async def _fetch_deployments(self):
self._fetch_contract_deployment(deploy_url, "TradePairs"),
self._fetch_contract_deployment(deploy_url, "Portfolio"),
self._fetch_contract_deployment(deploy_url, "MainnetRFQ"),
# The RFQ router is newer than the other contract types; a backend
# that does not publish it must not break initialization (the swap
# path falls back to MainnetRFQ.trustedForwarder() on-chain).
self._fetch_optional_contract_deployment(deploy_url, "DexalotRouter"),
)

async def _fetch_optional_contract_deployment(self, deploy_url, contract_type):
"""Best-effort ``_fetch_contract_deployment``: log and continue on failure."""
try:
await self._fetch_contract_deployment(deploy_url, contract_type)
except Exception as exc:
self.logger.warning(
"Deployment lookup for %s failed (%s); continuing without it",
contract_type,
exc,
)

async def _fetch_clob_pairs(self):
"""Fetch CLOB pairs if get_clob_pairs method is available.

Expand Down Expand Up @@ -1495,9 +1511,35 @@ def _process_deployment_item(self, item: dict[str, Any], contract_type: str) ->
address=address, abi=abi
)

elif contract_type == "MainnetRFQ":
if env in [self.ENV_PROD_MULTI_AVAX, self.ENV_FUJI_MULTI_AVAX]:
self.deployments["MainnetRFQ"]["Avalanche"] = {"address": address, "abi": abi}
elif contract_type in ("MainnetRFQ", "DexalotRouter"):
self._store_connected_chain_deployment(contract_type, env, address, abi)

def _connected_chain_key(self, env: str | None) -> str:
"""Deployment-map key for a connected-chain env.

``chain_config`` names the chain (``"Avalanche"`` on mainnet,
``"Fuji"`` on testnet) and ``_get_rfq_contract`` looks deployments up
by that name, so store them under it. Falls back to ``"Avalanche"``
when the environments have not been loaded.
"""
chain_id = (
self.CHAIN_ID_AVAX_MAINNET
if env == self.ENV_PROD_MULTI_AVAX
else self.CHAIN_ID_AVAX_FUJI
)
for name, cfg in (self.chain_config or {}).items():
if cfg.get("chain_id") == chain_id:
return name
return "Avalanche"

def _store_connected_chain_deployment(
self, contract_type: str, env: str | None, address: Any, abi: Any
) -> None:
"""Record a connected-chain (AVAX env) deployment keyed by chain name."""
if env not in (self.ENV_PROD_MULTI_AVAX, self.ENV_FUJI_MULTI_AVAX):
return
key = self._connected_chain_key(env)
self.deployments.setdefault(contract_type, {})[key] = {"address": address, "abi": abi}

def _transform_deployment_from_api(self, item: dict) -> dict:
"""Transform API deployment response to match standardized field names.
Expand Down
Loading
Loading