diff --git a/pyexchange/airswap.py b/pyexchange/airswap.py index 1ae3cde9..75be0ab9 100644 --- a/pyexchange/airswap.py +++ b/pyexchange/airswap.py @@ -18,12 +18,14 @@ import logging import time import json +import random from pprint import pformat from typing import Optional, List import requests +from pymaker import Address from pymaker.util import hexstring_to_bytes, http_response_summary from web3 import Web3 @@ -43,13 +45,51 @@ def __init__(self, api_server: str, timeout: float): self.api_server = api_server self.timeout = timeout - def set_intents(self, maker_token_address, taker_token_address): - intents = self._build_intents(maker_token_address, taker_token_address) + def set_intents(self, buy_token: Address, sell_token: Address): + assert(isinstance(buy_token, Address)) + assert(isinstance(sell_token, Address)) + + intents = self._build_intents(buy_token.__str__(), sell_token.__str__()) return self._http_post(f"/setIntents", intents) - def sign_order(self, order): + def sign_order(self, + maker_address, + maker_token, + maker_amount, + taker_address, + taker_token, + taker_amount): + + order = self._build_order(maker_address, + maker_token, + maker_amount, + taker_address, + taker_token, + taker_amount) + return self._http_post(f"/signOrder", order) + + def approve(self, buy_token: Address, sell_token: Address): + assert(isinstance(buy_token, Address)) + assert(isinstance(sell_token, Address)) + + try: + buy_token_data = self._build_approve(buy_token.__str__()) + sell_token_data = self._build_approve(sell_token.__str__()) + + self._http_post(f"/approveTokenForTrade", buy_token_data) + self._http_post(f"/approveTokenForTrade", sell_token_data) + logging.getLogger().info(f"token approval success: {buy_token.__str__()}, {sell_token.__str__()}") + return 'ok' + + except Exception as e: + logging.getLogger().exception(f"Encountered an error when attempting to approve tokens with Airswap contract({e}).") + + + def _build_approve(self, token): + return {"tokenContractAddr": token} + def _result(self, result) -> Optional[dict]: if not result.ok: raise Exception(f"Airswap API invalid HTTP response: {http_response_summary(result)}") @@ -80,3 +120,28 @@ def _build_intents(self, maker_token_address, taker_token_address): "takerToken": maker_token_address, "role": "maker" }] + + def _build_order(self, + maker_address, + maker_token, + maker_amount, + taker_address, + taker_token, + taker_amount): + + # Set 5-minute expiration on this order + expiration = str(int(time.time()) + 300) + nonce = random.randint(0, 99999) + + new_order = { + "makerAddress": maker_address, + "makerToken": maker_token, + "makerAmount": maker_amount, + "takerAddress": taker_address, + "takerToken": taker_token, + "takerAmount": taker_amount, + "expiration": expiration, + "nonce": nonce + } + + return new_order