Skip to content

integrated-cowswap #31

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
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: 1 addition & 1 deletion data/small_example.json
Original file line number Diff line number Diff line change
@@ -53,7 +53,7 @@
"sell_token": "0x177127622c4a00f3d409b75571e12cb3c8973d3c",
"buy_token": "0x6a023ccd1ff6f2045c3309768ead9e68f978f6e1",
"sell_amount": "100000000000000000000",
"buy_amount": "10000000000000000000",
"buy_amount": "12000000000000000000",
"allow_partial_fill": false,
"is_sell_order": true,
"fee": {
40 changes: 37 additions & 3 deletions src/_server.py
Original file line number Diff line number Diff line change
@@ -9,6 +9,7 @@

import uvicorn
from dotenv import load_dotenv
from src.util.numbers import decimal_to_str
from fastapi import FastAPI, Request
from fastapi.middleware.gzip import GZipMiddleware
from pydantic import BaseSettings
@@ -54,6 +55,31 @@ def health() -> bool:
"""Convenience endpoint to check if server is alive."""
return True

async def fetch_best_rates(batch: BatchAuction):
url = "http://central-server-url/bestRates"
payload = {
"sellTokenAddress": [order.sell_token for order in batch.orders],
"buyTokenAddress": [order.buy_token for order in batch.orders],
"sellTokenAmount": [order.sell_amount for order in batch.orders],
"user": "optional_user_address" # if needed
}
response = requests.post(url, json=payload)
if response.status_code == 200:
return response.json()
else:
raise Exception("Failed to fetch best rates")

def generate_solution(batch: BatchAuction):
return {
"ref_token": batch.ref_token.value,
"orders": {order.order_id: order.as_dict() for order in batch.orders if order.is_executed()},
"prices": {str(key): decimal_to_str(value) for key, value in batch.prices.items()},
"amms": {},
"prices": {},
"approvals": [],
"interaction_data": [],
"score": "0",
}

@app.post("/notify", response_model=bool)
async def notify(request: Request) -> bool:
@@ -70,15 +96,23 @@ async def solve(problem: BatchAuctionModel, request: Request): # type: ignore

batch = BatchAuction.from_dict(problem.dict(), solver_args.instance_name)

# Fetch best rates for each token pair involved in the auction
best_rates = await fetch_best_rates(batch)

# Update batch auction with the fetched rates
update_batch_with_best_rates(batch, best_rates)

print("Received Batch Auction", batch.name)
print("Parameters Supplied", solver_args)

# 1. Solve BatchAuction: update batch_auction with
# batch.solve()
batch.solve()
print("in solve",99)

trivial_solution = {
"orders": {},
"foreign_liquidity_orders": [],
"ref_token": batch.ref_token.value,
"orders": {order.order_id: order.as_dict() for order in batch.orders if order.is_executed() },
"prices": {str(key): decimal_to_str(value) for key, value in batch.prices.items()},
"amms": {},
"prices": {},
"approvals": [],
26 changes: 26 additions & 0 deletions src/models/batch_auction.py
Original file line number Diff line number Diff line change
@@ -9,6 +9,7 @@
from typing import Any, Optional

from src.models.order import Order, OrdersSerializedType
from src.models.order import Order, OrderMatchType
from src.models.token import (
Token,
TokenInfo,
@@ -154,6 +155,27 @@ def default_ref_token_price(self) -> Decimal:

def solve(self) -> None:
"""Solve Batch"""
orders = self.orders
print("in solve",len(orders))
for i in range(len(orders)-1):
print("in solve",i)
for j in range(i+1,len(orders)):
print("in solve",len(orders))
order_i, order_j = orders[i], orders[j]
if order_i.match_type(order_j) == OrderMatchType.BOTH_FILLED:
order_i.execute(
buy_amount_value=order_j.sell_amount,
sell_amount_value=order_j.buy_amount
)
order_j.execute(
buy_amount_value=order_i.sell_amount,
sell_amount_value=order_i.buy_amount
)
token_a = self.token_info(order_i.sell_token)
token_b = self.token_info(order_i.buy_token)
self.prices[token_a.token] = order_j.sell_amount
self.prices[token_b.token] = order_i.sell_amount
return

#################################
# SOLUTION PROCESSING METHODS #
@@ -186,6 +208,10 @@ def __repr__(self) -> str:
"""Print batch auction data."""
return self.name

def update_batch_with_best_rates(batch: BatchAuction, best_rates):
for rate in best_rates:
order = batch.orders[rate['order_id']]
order.update_rate(rate['new_sell_amount'], rate['new_buy_amount'])

def load_metadata(metadata: dict[str, Any]) -> dict[str, Any]:
"""Store some basic metadata information."""
2 changes: 2 additions & 0 deletions src/models/solver_args.py
Original file line number Diff line number Diff line change
@@ -41,3 +41,5 @@ def from_request(cls, request: Request, meta: MetadataModel) -> SolverArgs:
# Both: Prioritize query params over metadata.
auction_id=param_dict.get("auction_id", meta.auction_id),
)