Exemple #1
0
    def test_should_be_hashable(self):
        # given
        order = Order(
            exchange=None,
            sender=Address("0x0000000000000000000000000000000000000000"),
            maker=Address("0x9e56625509c2f60af937f23b7b532600390e8c8b"),
            taker=Address("0x0000000000000000000000000000000000000000"),
            maker_fee=Wad.from_number(123),
            taker_fee=Wad.from_number(456),
            pay_asset=ERC20Asset(
                Address("0x323b5d4c32345ced77393b3530b1eed0f346429d")),
            pay_amount=Wad(10000000000000000),
            buy_asset=ERC20Asset(
                Address("0xef7fff64389b814a946f3e92105513705ca6b990")),
            buy_amount=Wad(20000000000000000),
            salt=
            67006738228878699843088602623665307406148487219438534730168799356281242528500,
            fee_recipient=Address(
                '0x6666666666666666666666666666666666666666'),
            expiration=42,
            exchange_contract_address=Address(
                "0x12459c951127e0c374ff9105dda097662a027093"),
            signature=
            "0x1bf9f6a3b67b52d40c16387df2cd6283bbdbfc174577743645dd6f4bd828c7dbc315baf69f6c3cc8ac0f62c89264d73accf1ae165cce5d6e2a0b6325c6e4bab96403"
        )

        # expect
        assert is_hashable(order)
Exemple #2
0
    def test_create_order(self):
        # when
        order = self.exchange.create_order(
            pay_asset=ERC20Asset(
                Address("0x0202020202020202020202020202020202020202")),
            pay_amount=Wad.from_number(100),
            buy_asset=ERC20Asset(
                Address("0x0101010101010101010101010101010101010101")),
            buy_amount=Wad.from_number(2.5),
            expiration=1763920792)

        # then
        assert order.maker == Address(self.web3.eth.defaultAccount)
        assert order.taker == Address(
            "0x0000000000000000000000000000000000000000")
        assert order.pay_asset == ERC20Asset(
            Address("0x0202020202020202020202020202020202020202"))
        assert order.pay_amount == Wad.from_number(100)
        assert order.buy_asset == ERC20Asset(
            Address("0x0101010101010101010101010101010101010101"))
        assert order.buy_amount == Wad.from_number(2.5)
        assert order.salt >= 0
        assert order.expiration == 1763920792
        assert order.exchange_contract_address == self.exchange.address

        # and
        # [fees should be zero by default]
        assert order.maker_fee == Wad.from_number(0)
        assert order.taker_fee == Wad.from_number(0)
        assert order.fee_recipient == Address(
            "0x0000000000000000000000000000000000000000")
Exemple #3
0
    def test_past_cancel(self):
        # given
        self.exchange.approve([self.token1, self.token2], directly())

        # when
        order = self.exchange.create_order(
            pay_asset=ERC20Asset(self.token1.address),
            pay_amount=Wad.from_number(10),
            buy_asset=ERC20Asset(self.token2.address),
            buy_amount=Wad.from_number(4),
            expiration=1763920792)
        # and
        self.exchange.cancel_order(self.exchange.sign_order(order)).transact()

        # then
        past_cancel = self.exchange.past_cancel(PAST_BLOCKS)
        assert len(past_cancel) == 1
        assert past_cancel[0].maker == self.our_address
        assert past_cancel[0].fee_recipient == Address(
            "0x0000000000000000000000000000000000000000")
        assert past_cancel[0].sender == self.our_address
        assert past_cancel[0].pay_asset == ERC20Asset(self.token1.address)
        assert past_cancel[0].buy_asset == ERC20Asset(self.token2.address)
        assert past_cancel[0].order_hash == self.exchange.get_order_hash(
            self.exchange.sign_order(order))
        assert past_cancel[0].raw['blockNumber'] > 0
Exemple #4
0
    def place_order(self, pair: Pair, is_sell: bool, price: Wad, amount: Wad, expiration: int) -> pymaker.zrxv2.Order:
        assert(isinstance(pair, Pair))
        assert(isinstance(is_sell, bool))
        assert(isinstance(price, Wad))
        assert(isinstance(amount, Wad))
        assert(isinstance(expiration, int))

        pay_token = pair.sell_token_address if is_sell else pair.buy_token_address
        pay_amount = amount if is_sell else amount * price

        buy_token = pair.buy_token_address if is_sell else pair.sell_token_address
        buy_amount = amount * price if is_sell else amount

        order = self.zrx_exchange.create_order(pay_asset=ERC20Asset(pay_token),
                                               pay_amount=self._wad_to_blockchain(pair, pay_amount, pay_token),
                                               buy_asset=ERC20Asset(buy_token),
                                               buy_amount=self._wad_to_blockchain(pair, buy_amount, buy_token),
                                               expiration=expiration)
        order = self.zrx_api.configure_order(order)
        order = self.zrx_exchange.sign_order(order)

        if self.zrx_api.submit_order(order):
            return order
        else:
            return None
Exemple #5
0
    def __init__(self, sell_token_address: Address, sell_token_decimals: int, buy_token_address: Address, buy_token_decimals: int):
        assert(isinstance(sell_token_address, Address))
        assert(isinstance(sell_token_decimals, int))
        assert(isinstance(buy_token_address, Address))
        assert(isinstance(buy_token_decimals, int))

        self.sell_token_address = sell_token_address
        self.sell_token_decimals = sell_token_decimals
        self.buy_token_address = buy_token_address
        self.buy_token_decimals = buy_token_decimals

        self.sell_asset = ERC20Asset(sell_token_address)
        self.buy_asset = ERC20Asset(buy_token_address)
Exemple #6
0
 def from_list(trade: list):
     return Trade(
         trade_id=trade['id'],
         timestamp=trade['attributes']['updated-at'],
         pair=trade['attributes']['pair-name'],
         maker_address=Address(trade['attributes']['maker-address']),
         taker_address=Address(trade['attributes']['taker-address']),
         maker_amount=Wad(
             int(trade['attributes']['maker-asset-filled-amount'])),
         taker_amount=Wad(
             int(trade['attributes']['taker-asset-filled-amount'])),
         taker_asset_data=ERC20Asset.deserialize(
             trade['attributes']['taker-asset-data']).token_address,
         maker_asset_data=ERC20Asset.deserialize(
             trade['attributes']['maker-asset-data']).token_address)
Exemple #7
0
    def test_serialize_order_to_json(self):
        # given
        order = Order(
            exchange=None,
            sender=Address("0x0000000000000000000000000000000000000000"),
            maker=Address("0x9e56625509c2f60af937f23b7b532600390e8c8b"),
            taker=Address("0x0000000000000000000000000000000000000000"),
            maker_fee=Wad.from_number(123),
            taker_fee=Wad.from_number(456),
            pay_asset=ERC20Asset(
                Address("0x323b5d4c32345ced77393b3530b1eed0f346429d")),
            pay_amount=Wad(10000000000000000),
            buy_asset=ERC20Asset(
                Address("0xef7fff64389b814a946f3e92105513705ca6b990")),
            buy_amount=Wad(20000000000000000),
            salt=
            67006738228878699843088602623665307406148487219438534730168799356281242528500,
            fee_recipient=Address(
                '0x6666666666666666666666666666666666666666'),
            expiration=42,
            exchange_contract_address=Address(
                "0x12459c951127e0c374ff9105dda097662a027093"),
            signature=
            "0x1bf9f6a3b67b52d40c16387df2cd6283bbdbfc174577743645dd6f4bd828c7dbc315baf69f6c3cc8ac0f62c89264d73accf1ae165cce5d6e2a0b6325c6e4bab96403"
        )

        # when
        json_order = order.to_json()

        # then
        assert json_order == json.loads("""{
            "exchangeAddress": "0x12459c951127e0c374ff9105dda097662a027093",
            "senderAddress": "0x0000000000000000000000000000000000000000",
            "makerAddress": "0x9e56625509c2f60af937f23b7b532600390e8c8b",
            "takerAddress": "0x0000000000000000000000000000000000000000",
            "makerAssetData": "0xf47261b0000000000000000000000000323b5d4c32345ced77393b3530b1eed0f346429d",
            "takerAssetData": "0xf47261b0000000000000000000000000ef7fff64389b814a946f3e92105513705ca6b990",
            "makerAssetAmount": "10000000000000000",
            "takerAssetAmount": "20000000000000000",
            "feeRecipientAddress": "0x6666666666666666666666666666666666666666",
            "makerFee": "123000000000000000000",
            "takerFee": "456000000000000000000",
            "expirationTimeSeconds": "42",
            "salt": "67006738228878699843088602623665307406148487219438534730168799356281242528500",
            "signature": "0x1bf9f6a3b67b52d40c16387df2cd6283bbdbfc174577743645dd6f4bd828c7dbc315baf69f6c3cc8ac0f62c89264d73accf1ae165cce5d6e2a0b6325c6e4bab96403"
        }""")
Exemple #8
0
    def test_get_order_hash(self):
        # given
        order = self.exchange.create_order(
            pay_asset=ERC20Asset(
                Address("0x0202020202020202020202020202020202020202")),
            pay_amount=Wad.from_number(100),
            buy_asset=ERC20Asset(
                Address("0x0101010101010101010101010101010101010101")),
            buy_amount=Wad.from_number(2.5),
            expiration=1763920792)

        # when
        order_hash = self.exchange.get_order_hash(order)

        # then
        assert order_hash.startswith('0x')
        assert len(order_hash) == 66
Exemple #9
0
    def test_parse_signed_json_order(self):
        # given
        json_order = json.loads("""{
            "orderHash": "0x02266a4887256fdf16b47ca13e3f2cca76f93724842f3f7ddf55d92fb6601b6f",
            "exchangeAddress": "0x12459C951127e0c374FF9105DdA097662A027093",
            "senderAddress": "0x0000000000000000000000000000000000000000",
            "makerAddress": "0x0046cac6668bef45b517a1b816a762f4f8add2a9",
            "takerAddress": "0x0000000000000000000000000000000000000000",
            "makerAssetData": "0xf47261b059adcf176ed2f6788a41b8ea4c4904518e62b6a4",
            "takerAssetData": "0xf47261b02956356cd2a2bf3202f771f50d3d14a367b48070",
            "feeRecipientAddress": "0xa258b39954cef5cb142fd567a46cddb31a670124",
            "makerAssetAmount": "11000000000000000000",
            "takerAssetAmount": "30800000000000000",
            "makerFee": "0",
            "takerFee": "0",
            "expirationTimeSeconds": "1511988904",
            "salt": "50626048444772008084444062440502087868712695090943879708059561407114509847312",
            "signature": "0x1bf9f6a3b67b52d40c16387df2cd6283bbdbfc174577743645dd6f4bd828c7dbc315baf69f6c3cc8ac0f62c89264d73accf1ae165cce5d6e2a0b6325c6e4bab96403"
        }""")

        # when
        order = Order.from_json(None, json_order)

        # then
        assert order.exchange_contract_address == Address(
            "0x12459c951127e0c374ff9105dda097662a027093")
        assert order.sender == Address(
            "0x0000000000000000000000000000000000000000")
        assert order.maker == Address(
            "0x0046cac6668bef45b517a1b816a762f4f8add2a9")
        assert order.taker == Address(
            "0x0000000000000000000000000000000000000000")
        assert order.pay_asset == ERC20Asset(
            Address("0x59adcf176ed2f6788a41b8ea4c4904518e62b6a4"))
        assert order.buy_asset == ERC20Asset(
            Address("0x2956356cd2a2bf3202f771f50d3d14a367b48070"))
        assert order.fee_recipient == Address(
            "0xa258b39954cef5cb142fd567a46cddb31a670124")
        assert order.pay_amount == Wad.from_number(11)
        assert order.buy_amount == Wad.from_number(0.0308)
        assert order.maker_fee == Wad.from_number(0)
        assert order.taker_fee == Wad.from_number(0)
        assert order.expiration == 1511988904
        assert order.salt == 50626048444772008084444062440502087868712695090943879708059561407114509847312
        assert order.signature == "0x1bf9f6a3b67b52d40c16387df2cd6283bbdbfc174577743645dd6f4bd828c7dbc315baf69f6c3cc8ac0f62c89264d73accf1ae165cce5d6e2a0b6325c6e4bab96403"
Exemple #10
0
    def test_sign_order(self):
        # given
        order = self.exchange.create_order(
            pay_asset=ERC20Asset(
                Address("0x0202020202020202020202020202020202020202")),
            pay_amount=Wad.from_number(100),
            buy_asset=ERC20Asset(
                Address("0x0101010101010101010101010101010101010101")),
            buy_amount=Wad.from_number(2.5),
            expiration=1763920792)

        # when
        signed_order = self.exchange.sign_order(order)

        # then
        assert signed_order.signature.startswith('0x')
        assert signed_order.signature.endswith('03')
        assert len(signed_order.signature) == 134
Exemple #11
0
    def test_fill_order(self):
        # given
        self.exchange.approve([self.token1, self.token2], directly())

        # when
        order = self.exchange.create_order(
            pay_asset=ERC20Asset(self.token1.address),
            pay_amount=Wad.from_number(10),
            buy_asset=ERC20Asset(self.token2.address),
            buy_amount=Wad.from_number(4),
            expiration=1763920792)
        # and
        signed_order = self.exchange.sign_order(order)

        # then
        assert self.exchange.get_unavailable_buy_amount(signed_order) == Wad(0)

        # when
        self.exchange.fill_order(signed_order, Wad.from_number(3.5)).transact()

        # then
        assert self.exchange.get_unavailable_buy_amount(
            signed_order) == Wad.from_number(3.5)
Exemple #12
0
    def test_remaining_buy_amount_and_remaining_sell_amount(self):
        # given
        self.exchange.approve([self.token1, self.token2], directly())

        # when
        order = self.exchange.create_order(
            pay_asset=ERC20Asset(self.token1.address),
            pay_amount=Wad.from_number(10),
            buy_asset=ERC20Asset(self.token2.address),
            buy_amount=Wad.from_number(4),
            expiration=1763920792)
        # and
        signed_order = self.exchange.sign_order(order)

        # then
        assert signed_order.remaining_sell_amount == Wad.from_number(10)
        assert signed_order.remaining_buy_amount == Wad.from_number(4)

        # when
        self.exchange.fill_order(signed_order, Wad.from_number(3.5)).transact()

        # then
        assert signed_order.remaining_sell_amount == Wad.from_number(1.25)
        assert signed_order.remaining_buy_amount == Wad.from_number(0.5)
Exemple #13
0
    def place_order(self, is_sell: bool, pay_token: Address, pay_amount: Wad,
                    buy_token: Address, buy_amount: Wad,
                    ethfinex_address: Address, pair: str) -> Order:

        assert (isinstance(is_sell, bool))
        assert (isinstance(pay_token, Address))
        assert (isinstance(pay_amount, Wad))
        assert (isinstance(buy_token, Address))
        assert (isinstance(buy_amount, Wad))
        assert (isinstance(ethfinex_address, Address))
        assert (isinstance(pair, str))

        # check if symbol pair exists in tethefinex exchange
        symbols_details = self.get_symbols_details()
        pair_exist = False
        precision = 0
        for symbol in symbols_details:
            if symbol['pair'] == pair.lower():
                pair_exist = True
                precision = symbol["price_precision"]
        assert (pair_exist)

        symbol_one = pair[0:3]
        symbol_two = pair[3:6]

        sell_symbol = symbol_one if is_sell else symbol_two
        sell_amount = pay_amount if is_sell else buy_amount
        sell_token = pay_token if is_sell else buy_token

        buy_symbol = symbol_two if is_sell else symbol_one
        buy_amount = buy_amount if is_sell else pay_amount
        buy_token = buy_token if is_sell else pay_token

        # retrieve the minimun order size for each pair symbol
        ethfinex_config = self.get_config()['0x']
        sell_currency_min_order = Wad.from_number(
            ethfinex_config['tokenRegistry'][sell_symbol]['minOrderSize'])
        buy_currency_min_order = Wad.from_number(
            ethfinex_config['tokenRegistry'][buy_symbol]['minOrderSize'])

        # fee rate
        # use 0.0025 for 0.25% fee
        # use 0.01   for 1% fee
        # use 0.05   for 5% fee
        fee_rate = Wad.from_number(0.0025)
        price = float(buy_amount /
                      sell_amount) if is_sell else float(sell_amount /
                                                         buy_amount)
        # return price with precision
        price = self.add_price_precision(price, precision)
        amount = round(float(sell_amount), 6) if is_sell else round(
            float(buy_amount), 6)

        buy_amount_order_no_fees = Wad.from_number(
            price * amount) if is_sell else buy_amount
        buy_amount_order = buy_amount_order_no_fees - buy_amount_order_no_fees / Wad.from_number(
            100) * fee_rate * Wad.from_number(100)
        buy_asset_order = ERC20Asset(buy_token)
        sell_asset_order = ERC20Asset(sell_token)
        sell_amount_order = Wad.from_number(
            amount) if is_sell else Wad.from_number(price * amount)
        assert (buy_amount_order_no_fees >= buy_currency_min_order)
        assert (sell_amount_order >= sell_currency_min_order)

        expiration = int((datetime.datetime.today() +
                          datetime.timedelta(hours=6)).strftime("%s"))
        order = ZrxV2Order(exchange=self.tethfinex,
                           sender=ethfinex_address,
                           maker=Address(
                               self.tethfinex.web3.eth.defaultAccount),
                           taker=self.tethfinex._ZERO_ADDRESS,
                           maker_fee=Wad(0),
                           taker_fee=Wad(0),
                           pay_asset=sell_asset_order,
                           pay_amount=sell_amount_order,
                           buy_asset=buy_asset_order,
                           buy_amount=buy_amount_order,
                           salt=self.tethfinex.generate_salt(),
                           fee_recipient=ethfinex_address,
                           expiration=expiration,
                           exchange_contract_address=self.tethfinex.address,
                           signature=None)

        signed_order = self.tethfinex.sign_order(order)
        data = {
            "type": 'EXCHANGE LIMIT',
            "symbol": f"t{pair}",
            "amount": str(f"-{amount}") if is_sell else str(amount),
            "price": str(price),
            "meta": signed_order.to_json(),
            "protocol": '0x',
            "fee_rate": float(fee_rate)
        }

        side = "SELL" if is_sell else "BUY"
        self.logger.info(
            f"Placing order ({side}, amount {data['amount']} of {pair},"
            f" price {data['price']})...")

        result = self._http_post("/trustless/v1/w/on", data)

        self.logger.info(f"Placed order  #{result[0]}")

        return result[0]
Exemple #14
0
    def place_order(self, pair: Pair, is_sell: bool, price: Wad,
                    amount: Wad) -> ZrxOrder:
        assert (isinstance(pair, Pair))
        assert (isinstance(is_sell, bool))
        assert (isinstance(price, Wad))
        assert (isinstance(amount, Wad))

        pay_token = pair.sell_token_address if is_sell else pair.buy_token_address
        pay_amount = amount if is_sell else amount * price

        buy_token = pair.buy_token_address if is_sell else pair.sell_token_address
        buy_amount = amount * price if is_sell else amount

        expiration = int((datetime.datetime.today() +
                          datetime.timedelta(days=3)).strftime("%s"))

        order = self.zrx_exchange.create_order(pay_asset=ERC20Asset(pay_token),
                                               pay_amount=pay_amount,
                                               buy_asset=ERC20Asset(buy_token),
                                               buy_amount=buy_amount,
                                               expiration=expiration)

        order.fee_recipient = self.fee_recipient
        signed_order = self.zrx_exchange.sign_order(order)

        request = {
            "data": {
                "type": "orders",
                "attributes": {
                    "exchange-address":
                    signed_order.exchange_contract_address.address.lower(),
                    "expiration-time-seconds":
                    str(signed_order.expiration),
                    "fee-recipient-address":
                    self.fee_recipient.address.lower(),
                    "maker-address":
                    signed_order.maker.address.lower(),
                    "maker-asset-amount":
                    str(signed_order.pay_amount.value),
                    "maker-asset-data":
                    ERC20Asset(pay_token).serialize(),
                    "maker-fee":
                    str(signed_order.maker_fee.value),
                    "salt":
                    str(signed_order.salt),
                    "sender-address":
                    signed_order.sender.address.lower(),
                    "taker-address":
                    signed_order.taker.address.lower(),
                    "taker-asset-amount":
                    str(signed_order.buy_amount.value),
                    "taker-asset-data":
                    ERC20Asset(buy_token).serialize(),
                    "taker-fee":
                    str(signed_order.taker_fee.value),
                    "signature":
                    signed_order.signature
                }
            }
        }

        side = "SELL" if is_sell else "BUY"
        self.logger.info(f"Placing order ({side}, amount {amount} of {pair},"
                         f" price {price})...")

        result = self._http_authenticated("POST", "/orders", request)
        order_id = result['data']['id']

        self.logger.info(f"Placed order (#{result}) as #{order_id}")

        return order
Exemple #15
0
#EXCHANGE_ADDR = '0x4f833a24e1f95d70f028921e27040ca56e09ab0b'  # Mainnet
EXCHANGE_ADDR = sys.argv[1]
SRAV2_URL = 'https://kovan-staging.ercdex.com/api'

KOVAN_DAI = Address('0xc4375b7de8af5a38a93548eb8453a498222c4ff2')
KOVAN_WETH = Address('0xd0a1e359811322d97991e03f863a0c30c2cf029c')

web3 = Web3(HTTPProvider('http://localhost:8545'))
web3.eth.defaultAccount = web3.eth.accounts[0]

exchange = ZrxExchangeV2(web3=web3, address=Address(EXCHANGE_ADDR))
#exchange.approve([ERC20Token(web3=web3, address=KOVAN_DAI),
#                  ERC20Token(web3=web3, address=KOVAN_WETH)], directly())

order = exchange.create_order(pay_asset=ERC20Asset(KOVAN_WETH),
                              pay_amount=Wad.from_number(0.1),
                              buy_asset=ERC20Asset(KOVAN_DAI),
                              buy_amount=Wad.from_number(25),
                              expiration=int(time.time()) + 60 * 35)

api = ZrxRelayerApiV2(exchange=exchange, api_server=SRAV2_URL)
order = api.configure_order(order)
order = exchange.sign_order(order)
#print(order)

#print(api.submit_order(order))
#print(api.get_orders(KOVAN_WETH, KOVAN_DAI))
print(api.get_orders_by_maker(Address(web3.eth.defaultAccount)))

#print(exchange.past_fill(500))