def test_removeOrder(contractsFixture, market): orders = contractsFixture.contracts['Orders'] orderId1 = orders.saveOrder(BID, market.address, fix('10'), 5000, tester.a1, NO, 0, fix('10'), longTo32Bytes(0), longTo32Bytes(0), "1") assert(orderId1 != bytearray(32)), "saveOrder wasn't executed successfully" orderId2 = orders.saveOrder(BID, market.address, fix('10'), 5000, tester.a2, NO, fix('10', '5000'), 0, longTo32Bytes(0), longTo32Bytes(0), "1") assert(orderId2 != bytearray(32)), "saveOrder wasn't executed successfully" orderId3 = orders.saveOrder(BID, market.address, fix('10'), 5000, tester.a1, YES, 0, fix('10'), longTo32Bytes(0), longTo32Bytes(0), "1") assert(orderId3 != bytearray(32)), "saveOrder wasn't executed successfully" assert orders.getAmount(orderId3) == fix('10') assert orders.getPrice(orderId3) == 5000 assert orders.getOrderCreator(orderId3) == bytesToHexString(tester.a1) assert orders.getOrderMoneyEscrowed(orderId3) == 0 assert orders.getOrderSharesEscrowed(orderId3) == fix('10') assert orders.getBetterOrderId(orderId3) == longTo32Bytes(0) assert orders.getWorseOrderId(orderId3) == longTo32Bytes(0) assert(orders.removeOrder(orderId3) == 1), "removeOrder wasn't executed successfully" assert orders.getAmount(orderId3) == 0 assert orders.getPrice(orderId3) == 0 assert orders.getOrderCreator(orderId3) == longToHexString(0) assert orders.getOrderMoneyEscrowed(orderId3) == 0 assert orders.getOrderSharesEscrowed(orderId3) == 0 assert orders.getBetterOrderId(orderId3) == longTo32Bytes(0) assert orders.getWorseOrderId(orderId3) == longTo32Bytes(0) assert(orders.removeOrder(orderId1) == 1), "Remove order 1" assert(orders.removeOrder(orderId2) == 1), "Remove order 2"
def test_saveOrder(contractsFixture, market): orders = contractsFixture.contracts['Orders'] orderId1 = orders.saveOrder(BID, market.address, fix(10), 5000, tester.a1, NO, 0, fix(10), longTo32Bytes(0), longTo32Bytes(0), "1") assert(orderId1 != bytearray(32)), "saveOrder wasn't executed successfully" orderId2 = orders.saveOrder(ASK, market.address, fix(10), 5000, tester.a2, NO, fix('10', '5000'), 0, longTo32Bytes(0), longTo32Bytes(0), "1") assert(orderId2 != bytearray(32)), "saveOrder wasn't executed successfully" assert(orders.getAmount(orderId1) == fix(10)), "amount for order1 should be set to 10" assert(orders.getAmount(orderId2) == fix(10)), "amount for order2 should be set to 10" assert(orders.getPrice(orderId1) == 5000), "price for order1 should be set to 5000 wei" assert(orders.getPrice(orderId2) == 5000), "price for order2 should be set to 5000 wei" assert(orders.getOrderCreator(orderId1) == bytesToHexString(tester.a1)), "orderOwner for order1 should be tester.a1" assert(orders.getOrderCreator(orderId2) == bytesToHexString(tester.a2)), "orderOwner for order2 should be tester.a2" assert orders.getOrderMoneyEscrowed(orderId1) == 0, "money escrowed should be 0" assert orders.getOrderMoneyEscrowed(orderId2) == fix('10', '5000'), "money escrowed should be 50000 ETH" assert orders.getOrderSharesEscrowed(orderId1) == fix(10), "shares escrowed should be fix(10)" assert orders.getOrderSharesEscrowed(orderId2) == 0, "shares escrowed should be 0" assert orders.getBetterOrderId(orderId1) == longTo32Bytes(0), "better order id should be 0" assert orders.getBetterOrderId(orderId2) == longTo32Bytes(0), "better order id should be 0" assert orders.getWorseOrderId(orderId1) == longTo32Bytes(0), "worse order id should be 0" assert orders.getWorseOrderId(orderId2) == longTo32Bytes(0), "worse order id should be 0" assert(orders.removeOrder(orderId1) == 1), "Remove order 1" assert(orders.removeOrder(orderId2) == 1), "Remove order 2"
def test_fill_order_with_shares_escrowed_sell_with_shares(contractsFixture, cash, market, universe): createOrder = contractsFixture.contracts['CreateOrder'] fillOrder = contractsFixture.contracts['FillOrder'] orders = contractsFixture.contracts['Orders'] completeSets = contractsFixture.contracts['CompleteSets'] yesShareToken = contractsFixture.applySignature('ShareToken', market.getShareToken(YES)) noShareToken = contractsFixture.applySignature('ShareToken', market.getShareToken(NO)) # buy complete sets for both users assert completeSets.publicBuyCompleteSets(market.address, fix(1), sender=tester.k1, value=fix('1', '10000')) assert yesShareToken.balanceOf(tester.a1) == fix(1) assert completeSets.publicBuyCompleteSets(market.address, fix(1), sender=tester.k2, value=fix('1', '10000')) assert noShareToken.balanceOf(tester.a2) == fix(1) # create order with shares orderID = createOrder.publicCreateOrder(ASK, fix(1), 6000, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), "42", sender=tester.k1) assert orderID # fill order with shares assert fillOrder.publicFillOrder(orderID, fix(1), "43", sender=tester.k2) == 0 assert orders.getAmount(orderID) == 0 assert orders.getPrice(orderID) == 0 assert orders.getOrderCreator(orderID) == longToHexString(0) assert orders.getOrderMoneyEscrowed(orderID) == 0 assert orders.getOrderSharesEscrowed(orderID) == 0 assert orders.getBetterOrderId(orderID) == longTo32Bytes(0) assert orders.getWorseOrderId(orderID) == longTo32Bytes(0)
def test_finalize(localFixture, chain, initializedMarket, mockInitialReporter, mockNextFeeWindow, mockUniverse): with raises(TransactionFailed, message="can't finalize without an initial report"): initializedMarket.finalize() localFixture.contracts["Time"].setTimestamp(initializedMarket.getEndTime() + 1) assert initializedMarket.doInitialReport([initializedMarket.getNumTicks(), 0, 0, 0, 0], False, sender=tester.k1) mockInitialReporter.setReportTimestamp(1) with raises(TransactionFailed, message="can't finalize before the fee window is over"): initializedMarket.finalize() mockNextFeeWindow.setIsOver(True) mockUniverse.setForkingMarket(longToHexString(1)) with raises(TransactionFailed, message="can't finalize if there is a forking market"): initializedMarket.finalize() mockUniverse.setForkingMarket(longToHexString(0)) mockInitialReporter.setPayoutDistributionHash(longTo32Bytes(2)) assert initializedMarket.finalize() # since market is not the forking market tentative winning hash will be the winner assert initializedMarket.getWinningPayoutDistributionHash() == longTo32Bytes(2)
def test_take_best_order_multiple_orders(contractsFixture, cash, market, universe): createOrder = contractsFixture.contracts['CreateOrder'] trade = contractsFixture.contracts['Trade'] orders = contractsFixture.contracts['Orders'] initialTester1ETH = contractsFixture.chain.head_state.get_balance(tester.a1) initialTester2ETH = contractsFixture.chain.head_state.get_balance(tester.a2) # create orders with cash orderIDs = [] numOrders = 5 for i in range(numOrders): orderID = createOrder.publicCreateOrder(ASK, fix(1), 6000 + i, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), "42", sender=tester.k1, value=fix('1', 4000 - i)) assert orderID orderIDs.append(orderID) # fill orders with cash using on-chain matcher price = 6000 + numOrders assert trade.publicFillBestOrder(BID, market.address, YES, fix(numOrders), price, "43", sender=tester.k2, value=fix(numOrders, price)) == 0 for i in range(numOrders): orderID = orderIDs[i] assert orders.getAmount(orderID) == 0 assert orders.getPrice(orderID) == 0 assert orders.getOrderCreator(orderID) == longToHexString(0) assert orders.getOrderMoneyEscrowed(orderID) == 0 assert orders.getOrderSharesEscrowed(orderID) == 0 assert orders.getBetterOrderId(orderID) == longTo32Bytes(0) assert orders.getWorseOrderId(orderID) == longTo32Bytes(0)
def test_one_bid_on_books_buy_partial_order(useTrade, contractsFixture, cash, market, universe): createOrder = contractsFixture.contracts['CreateOrder'] trade = contractsFixture.contracts['Trade'] fillOrder = contractsFixture.contracts['FillOrder'] orders = contractsFixture.contracts['Orders'] tradeGroupID = "42" # create order orderID = createOrder.publicCreateOrder(BID, fix(2), 6000, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), tradeGroupID, sender = tester.k1, value=fix('2', '6000')) # fill best order fillOrderID = None if useTrade: fillOrderID = trade.publicTrade(1, market.address, YES, fix(1), 6000, "0", "0", tradeGroupID, sender = tester.k2, value=fix('1', '4000')) else: fillOrderID = trade.publicSell(market.address, YES, fix(1), 6000, "0", "0", tradeGroupID, sender = tester.k2, value=fix('1', '4000')) assert orders.getAmount(orderID) == fix(1) assert orders.getPrice(orderID) == 6000 assert orders.getOrderCreator(orderID) == bytesToHexString(tester.a1) assert orders.getOrderMoneyEscrowed(orderID) == fix('1', '6000') assert orders.getOrderSharesEscrowed(orderID) == 0 assert orders.getBetterOrderId(orderID) == longTo32Bytes(0) assert orders.getWorseOrderId(orderID) == longTo32Bytes(0) assert fillOrderID == longTo32Bytes(1)
def test_take_best_order_with_shares_escrowed_buy_with_cash(contractsFixture, cash, market, universe): createOrder = contractsFixture.contracts['CreateOrder'] trade = contractsFixture.contracts['Trade'] orders = contractsFixture.contracts['Orders'] completeSets = contractsFixture.contracts['CompleteSets'] yesShareToken = contractsFixture.applySignature('ShareToken', market.getShareToken(YES)) # buy complete sets assert completeSets.publicBuyCompleteSets(market.address, fix(1), sender=tester.k1, value=fix('1', '10000')) assert yesShareToken.balanceOf(tester.a1) == fix(1) # create order with shares orderID = createOrder.publicCreateOrder(ASK, fix(1), 6000, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), "42", sender=tester.k1) assert orderID # fill order with cash using on-chain matcher assert trade.publicFillBestOrder(BID, market.address, YES, fix(1), 6000, "43", sender=tester.k2, value=fix('1', '6000')) == 0 assert orders.getAmount(orderID) == 0 assert orders.getPrice(orderID) == 0 assert orders.getOrderCreator(orderID) == longToHexString(0) assert orders.getOrderMoneyEscrowed(orderID) == 0 assert orders.getOrderSharesEscrowed(orderID) == 0 assert orders.getBetterOrderId(orderID) == longTo32Bytes(0) assert orders.getWorseOrderId(orderID) == longTo32Bytes(0)
def test_fill_buy_order_with_buy_categorical(contractsFixture, cash, categoricalMarket, universe): market = categoricalMarket createOrder = contractsFixture.contracts['CreateOrder'] fillOrder = contractsFixture.contracts['FillOrder'] orders = contractsFixture.contracts['Orders'] firstShareToken = contractsFixture.applySignature('ShareToken', market.getShareToken(0)) secondShareToken = contractsFixture.applySignature('ShareToken', market.getShareToken(1)) thirdShareToken = contractsFixture.applySignature('ShareToken', market.getShareToken(2)) # create order with cash price = 6000 numTicks = market.getNumTicks() orderID = createOrder.publicCreateOrder(BID, fix(1), price, market.address, 0, longTo32Bytes(0), longTo32Bytes(0), "42", value=fix(1, price), sender=tester.k1) assert orderID # fill order with cash assert fillOrder.publicFillOrder(orderID, fix(1), "43", sender=tester.k2, value=fix(1, numTicks - price)) == 0 # A complete set was purchased with the provided cash and the shares were provided to each user assert firstShareToken.balanceOf(tester.a1) == fix(1) assert secondShareToken.balanceOf(tester.a1) == 0 assert thirdShareToken.balanceOf(tester.a1) == 0 assert firstShareToken.balanceOf(tester.a2) == 0 assert secondShareToken.balanceOf(tester.a2) == fix(1) assert thirdShareToken.balanceOf(tester.a2) == fix(1) assert orders.getAmount(orderID) == 0 assert orders.getPrice(orderID) == 0 assert orders.getOrderCreator(orderID) == longToHexString(0) assert orders.getOrderMoneyEscrowed(orderID) == 0 assert orders.getOrderSharesEscrowed(orderID) == 0 assert orders.getBetterOrderId(orderID) == longTo32Bytes(0) assert orders.getWorseOrderId(orderID) == longTo32Bytes(0)
def test_publicFillOrder_ask(contractsFixture, cash, market, universe): createOrder = contractsFixture.contracts['CreateOrder'] fillOrder = contractsFixture.contracts['FillOrder'] orders = contractsFixture.contracts['Orders'] tradeGroupID = "42" initialMakerETH = contractsFixture.chain.head_state.get_balance(tester.a1) initialFillerETH = contractsFixture.chain.head_state.get_balance(tester.a2) creatorCost = fix('2', '4000') fillerCost = fix('2', '6000') # create order orderID = createOrder.publicCreateOrder(ASK, fix(2), 6000, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), tradeGroupID, sender = tester.k1, value=creatorCost) # fill best order fillOrderID = fillOrder.publicFillOrder(orderID, fix(2), tradeGroupID, sender = tester.k2, value=fillerCost) assert contractsFixture.chain.head_state.get_balance(tester.a1) == initialMakerETH - creatorCost assert contractsFixture.chain.head_state.get_balance(tester.a2) == initialFillerETH - fillerCost assert orders.getAmount(orderID) == 0 assert orders.getPrice(orderID) == 0 assert orders.getOrderCreator(orderID) == longToHexString(0) assert orders.getOrderMoneyEscrowed(orderID) == 0 assert orders.getOrderSharesEscrowed(orderID) == 0 assert orders.getBetterOrderId(orderID) == longTo32Bytes(0) assert orders.getWorseOrderId(orderID) == longTo32Bytes(0) assert fillOrderID == 0
def test_one_ask_on_books_buy_excess_order(contractsFixture, cash, market, universe): createOrder = contractsFixture.contracts['CreateOrder'] trade = contractsFixture.contracts['Trade'] fillOrder = contractsFixture.contracts['FillOrder'] orders = contractsFixture.contracts['Orders'] tradeGroupID = "42" # create order orderID = createOrder.publicCreateOrder(ASK, fix(12), 6000, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), tradeGroupID, sender = tester.k1, value=fix('12', '4000')) # fill best order fillOrderID = trade.publicBuy(market.address, YES, fix(15), 6000, "0", "0", tradeGroupID, sender = tester.k2, value=fix('15', '6000')) assert orders.getAmount(orderID) == 0 assert orders.getPrice(orderID) == 0 assert orders.getOrderCreator(orderID) == longToHexString(0) assert orders.getOrderMoneyEscrowed(orderID) == 0 assert orders.getOrderSharesEscrowed(orderID) == 0 assert orders.getBetterOrderId(orderID) == longTo32Bytes(0) assert orders.getWorseOrderId(orderID) == longTo32Bytes(0) assert orders.getAmount(fillOrderID) == fix(3) assert orders.getPrice(fillOrderID) == 6000 assert orders.getOrderCreator(fillOrderID) == bytesToHexString(tester.a2) assert orders.getOrderMoneyEscrowed(fillOrderID) == fix('3', '6000') assert orders.getOrderSharesEscrowed(fillOrderID) == 0 assert orders.getBetterOrderId(fillOrderID) == longTo32Bytes(0) assert orders.getWorseOrderId(fillOrderID) == longTo32Bytes(0)
def test_one_bid_on_books_buy_full_order(contractsFixture, cash, market, universe): createOrder = contractsFixture.contracts['CreateOrder'] trade = contractsFixture.contracts['Trade'] fillOrder = contractsFixture.contracts['FillOrder'] orders = contractsFixture.contracts['Orders'] tradeGroupID = "42" # create order orderID = createOrder.publicCreateOrder(BID, fix(2), 6000, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), tradeGroupID, sender = tester.k1, value=fix('2', '6000')) # fill best order orderFilledLog = { "filler": bytesToHexString(tester.a2), "numCreatorShares": 0, "numCreatorTokens": fix('2', '6000'), "numFillerShares": 0, "numFillerTokens": fix('2', '4000'), "marketCreatorFees": 0, "reporterFees": 0, "shareToken": market.getShareToken(YES), "tradeGroupId": stringToBytes("42"), } with AssertLog(contractsFixture, "OrderFilled", orderFilledLog): assert trade.publicSell(market.address, YES, fix(2), 6000, "0", "0", tradeGroupID, sender = tester.k2, value=fix('2', '4000')) assert orders.getAmount(orderID) == 0 assert orders.getPrice(orderID) == 0 assert orders.getOrderCreator(orderID) == longToHexString(0) assert orders.getOrderMoneyEscrowed(orderID) == 0 assert orders.getOrderSharesEscrowed(orderID) == 0 assert orders.getBetterOrderId(orderID) == longTo32Bytes(0) assert orders.getWorseOrderId(orderID) == longTo32Bytes(0)
def test_publicFillOrder_bid_scalar(contractsFixture, cash, scalarMarket, universe): createOrder = contractsFixture.contracts['CreateOrder'] fillOrder = contractsFixture.contracts['FillOrder'] orders = contractsFixture.contracts['Orders'] # We're testing the scalar market because it has a different numTicks than 10**18 as the other do. In particular it's numTicks is 40*18**18 market = scalarMarket tradeGroupID = "42" initialMakerETH = contractsFixture.chain.head_state.get_balance(tester.a1) initialFillerETH = contractsFixture.chain.head_state.get_balance(tester.a2) creatorCost = fix('2', '6000') fillerCost = fix('2', '394000') # create order orderID = createOrder.publicCreateOrder(BID, fix(2), 6000, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), tradeGroupID, sender = tester.k1, value=creatorCost) # fill best order fillOrderID = fillOrder.publicFillOrder(orderID, fix(2), tradeGroupID, sender = tester.k2, value=fillerCost) assert contractsFixture.chain.head_state.get_balance(tester.a1) == initialMakerETH - creatorCost assert contractsFixture.chain.head_state.get_balance(tester.a2) == initialFillerETH - fillerCost assert orders.getAmount(orderID) == 0 assert orders.getPrice(orderID) == 0 assert orders.getOrderCreator(orderID) == longToHexString(0) assert orders.getOrderMoneyEscrowed(orderID) == 0 assert orders.getOrderSharesEscrowed(orderID) == 0 assert orders.getBetterOrderId(orderID) == longTo32Bytes(0) assert orders.getWorseOrderId(orderID) == longTo32Bytes(0) assert fillOrderID == 0
def test_cancelBid(contractsFixture, cash, market, universe): createOrder = contractsFixture.contracts['CreateOrder'] cancelOrder = contractsFixture.contracts['CancelOrder'] orders = contractsFixture.contracts['Orders'] orderType = BID fxpAmount = fix(1) fxpPrice = 6000 outcomeID = YES tradeGroupID = "42" yesShareToken = contractsFixture.applySignature('ShareToken', market.getShareToken(YES)) noShareToken = contractsFixture.applySignature('ShareToken', market.getShareToken(NO)) creatorInitialETH = contractsFixture.chain.head_state.get_balance(tester.a1) creatorInitialShares = yesShareToken.balanceOf(tester.a1) marketInitialCash = cash.balanceOf(market.address) marketInitialYesShares = yesShareToken.totalSupply() marketInitialNoShares = noShareToken.totalSupply() orderID = createOrder.publicCreateOrder(orderType, fxpAmount, fxpPrice, market.address, outcomeID, longTo32Bytes(0), longTo32Bytes(0), tradeGroupID, sender=tester.k1, value = fix('10000')) assert orderID, "Order ID should be non-zero" assert orders.getOrderCreator(orderID), "Order should have an owner" assert contractsFixture.chain.head_state.get_balance(tester.a1) == creatorInitialETH - fix('1', '6000'), "ETH should be deducted from the creator balance" orderCanceledLog = { 'orderId': orderID, 'shareToken': yesShareToken.address, 'sender': bytesToHexString(tester.a1), 'orderType': orderType, 'sharesRefund': 0, 'tokenRefund': fix('1', '6000'), } with AssertLog(contractsFixture, 'OrderCanceled', orderCanceledLog): assert(cancelOrder.cancelOrder(orderID, sender=tester.k1) == 1), "cancelOrder should succeed" assert orders.getAmount(orderID) == 0 assert orders.getPrice(orderID) == 0 assert orders.getOrderCreator(orderID) == longToHexString(0) assert orders.getOrderMoneyEscrowed(orderID) == 0 assert orders.getOrderSharesEscrowed(orderID) == 0 assert orders.getBetterOrderId(orderID) == longTo32Bytes(0) assert orders.getWorseOrderId(orderID) == longTo32Bytes(0) assert(creatorInitialETH == contractsFixture.chain.head_state.get_balance(tester.a1)), "Maker's ETH should be the same as before the order was placed" assert(marketInitialCash == cash.balanceOf(market.address)), "Market's cash balance should be the same as before the order was placed" assert(creatorInitialShares == yesShareToken.balanceOf(tester.a1)), "Maker's shares should be unchanged" assert(marketInitialYesShares == yesShareToken.totalSupply()), "Market's yes shares should be unchanged" assert marketInitialNoShares == noShareToken.totalSupply(), "Market's no shares should be unchanged"
def test_cancelWithSharesInEscrow(contractsFixture, cash, market, universe): completeSets = contractsFixture.contracts['CompleteSets'] createOrder = contractsFixture.contracts['CreateOrder'] cancelOrder = contractsFixture.contracts['CancelOrder'] orders = contractsFixture.contracts['Orders'] yesShareToken = contractsFixture.applySignature('ShareToken', market.getShareToken(YES)) noShareToken = contractsFixture.applySignature('ShareToken', market.getShareToken(NO)) totalProceeds = fix('12', market.getNumTicks()) marketCreatorFee = totalProceeds / market.getMarketCreatorSettlementFeeDivisor() reporterFee = totalProceeds / universe.getOrCacheReportingFeeDivisor() completeSetFees = marketCreatorFee + reporterFee # buy complete sets assert completeSets.publicBuyCompleteSets(market.address, fix(12), sender = tester.k1, value=fix('12', market.getNumTicks())) assert cash.balanceOf(tester.a1) == fix('0') assert yesShareToken.balanceOf(tester.a1) == fix(12) assert noShareToken.balanceOf(tester.a1) == fix(12) creatorInitialETH = contractsFixture.chain.head_state.get_balance(tester.a1) creatorInitialShares = yesShareToken.balanceOf(tester.a1) marketInitialCash = cash.balanceOf(market.address) marketInitialYesShares = yesShareToken.totalSupply() marketInitialNoShares = noShareToken.totalSupply() # create BID order for YES with NO shares escrowed assert noShareToken.approve(createOrder.address, fix(12), sender = tester.k1) orderID = createOrder.publicCreateOrder(BID, fix(12), 6000, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), "42", sender = tester.k1) assert orderID assert cash.balanceOf(tester.a1) == fix('0') assert yesShareToken.balanceOf(tester.a1) == fix(12) assert noShareToken.balanceOf(tester.a1) == 0 # now cancel the order assert(cancelOrder.cancelOrder(orderID, sender=tester.k1) == 1), "cancelOrder should succeed" assert orders.getAmount(orderID) == 0 assert orders.getPrice(orderID) == 0 assert orders.getOrderCreator(orderID) == longToHexString(0) assert orders.getOrderMoneyEscrowed(orderID) == 0 assert orders.getOrderSharesEscrowed(orderID) == 0 assert orders.getBetterOrderId(orderID) == longTo32Bytes(0) assert orders.getWorseOrderId(orderID) == longTo32Bytes(0) assert(creatorInitialETH == contractsFixture.chain.head_state.get_balance(tester.a1)), "Maker's ETH should be the same as before the order was placed" assert(marketInitialCash == cash.balanceOf(market.address)), "Market's cash balance should be the same as before the order was placed" assert(creatorInitialShares == yesShareToken.balanceOf(tester.a1)), "Maker's shares should be unchanged" assert(marketInitialYesShares == yesShareToken.totalSupply()), "Market's yes shares should be unchanged" assert marketInitialNoShares == noShareToken.totalSupply(), "Market's no shares should be unchanged"
def test_take_best_order_with_shares_escrowed_buy_with_shares_categorical(contractsFixture, cash, categoricalMarket, universe): market = categoricalMarket createOrder = contractsFixture.contracts['CreateOrder'] trade = contractsFixture.contracts['Trade'] orders = contractsFixture.contracts['Orders'] completeSets = contractsFixture.contracts['CompleteSets'] firstShareToken = contractsFixture.applySignature('ShareToken', market.getShareToken(0)) secondShareToken = contractsFixture.applySignature('ShareToken', market.getShareToken(1)) thirdShareToken = contractsFixture.applySignature('ShareToken', market.getShareToken(2)) # buy complete sets for both users numTicks = market.getNumTicks() assert completeSets.publicBuyCompleteSets(market.address, fix(1), sender=tester.k1, value=fix('1', numTicks)) assert completeSets.publicBuyCompleteSets(market.address, fix(1), sender=tester.k2, value=fix('1', numTicks)) assert firstShareToken.balanceOf(tester.a1) == firstShareToken.balanceOf(tester.a2) == fix(1) assert secondShareToken.balanceOf(tester.a1) == secondShareToken.balanceOf(tester.a2) == fix(1) assert thirdShareToken.balanceOf(tester.a1) == thirdShareToken.balanceOf(tester.a2) == fix(1) # create order with shares orderID = createOrder.publicCreateOrder(ASK, fix(1), 6000, market.address, 0, longTo32Bytes(0), longTo32Bytes(0), "42", sender=tester.k1) assert orderID # fill order with shares using on-chain matcher totalProceeds = fix(1, numTicks) totalProceeds -= fix(1, numTicks) / market.getMarketCreatorSettlementFeeDivisor() totalProceeds -= fix(1, numTicks) / universe.getOrCacheReportingFeeDivisor() expectedTester1Payout = totalProceeds * 6000 / numTicks expectedTester2Payout = totalProceeds * (numTicks - 6000) / numTicks with EtherDelta(expectedTester1Payout, tester.a1, contractsFixture.chain, "Tester 1 ETH delta wrong"): with EtherDelta(expectedTester2Payout, tester.a2, contractsFixture.chain, "Tester 2 ETH delta wrong"): assert trade.publicFillBestOrder(BID, market.address, 0, fix(1), 6000, "43", sender=tester.k2) == 0 assert firstShareToken.balanceOf(tester.a1) == 0 assert secondShareToken.balanceOf(tester.a1) == fix(1) assert thirdShareToken.balanceOf(tester.a1) == fix(1) assert firstShareToken.balanceOf(tester.a2) == fix(1) assert secondShareToken.balanceOf(tester.a2) == 0 assert thirdShareToken.balanceOf(tester.a2) == 0 assert orders.getAmount(orderID) == 0 assert orders.getPrice(orderID) == 0 assert orders.getOrderCreator(orderID) == longToHexString(0) assert orders.getOrderMoneyEscrowed(orderID) == 0 assert orders.getOrderSharesEscrowed(orderID) == 0 assert orders.getBetterOrderId(orderID) == longTo32Bytes(0) assert orders.getWorseOrderId(orderID) == longTo32Bytes(0)
def test_two_bids_on_books_buy_both(contractsFixture, cash, market, universe): createOrder = contractsFixture.contracts['CreateOrder'] trade = contractsFixture.contracts['Trade'] fillOrder = contractsFixture.contracts['FillOrder'] orders = contractsFixture.contracts['Orders'] tradeGroupID = "42" # create order 1 orderID1 = createOrder.publicCreateOrder(BID, fix(4), 6000, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), tradeGroupID, sender = tester.k1, value=fix('4', '6000')) # create order 2 orderID2 = createOrder.publicCreateOrder(BID, fix(1), 6000, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), tradeGroupID, sender = tester.k3, value=fix('1', '6000')) # fill best order fillOrderID = trade.publicSell(market.address, YES, fix(5), 6000, "0", "0", tradeGroupID, sender = tester.k2, value=fix('5', '4000')) assert orders.getAmount(orderID1) == 0 assert orders.getPrice(orderID1) == 0 assert orders.getOrderCreator(orderID1) == longToHexString(0) assert orders.getOrderMoneyEscrowed(orderID1) == 0 assert orders.getOrderSharesEscrowed(orderID1) == 0 assert orders.getBetterOrderId(orderID1) == longTo32Bytes(0) assert orders.getWorseOrderId(orderID1) == longTo32Bytes(0) assert orders.getAmount(orderID2) == 0 assert orders.getPrice(orderID2) == 0 assert orders.getOrderCreator(orderID2) == longToHexString(0) assert orders.getOrderMoneyEscrowed(orderID2) == 0 assert orders.getOrderSharesEscrowed(orderID2) == 0 assert orders.getBetterOrderId(orderID2) == longTo32Bytes(0) assert orders.getWorseOrderId(orderID2) == longTo32Bytes(0) assert fillOrderID == longTo32Bytes(1)
def test_orderCreation(hints, localFixture, categoricalMarket): createOrder = localFixture.contracts['CreateOrder'] for i in range(3900, 4003): createOrder.publicCreateOrder(BID, fix(1), i, categoricalMarket.address, 1, longTo32Bytes(0), longTo32Bytes(0), "7", value = fix(1, i)) worseOrderId = createOrder.publicCreateOrder(BID, fix(1), 4004, categoricalMarket.address, 1, longTo32Bytes(0), longTo32Bytes(0), "7", value = fix(1, 4004)) betterOrderId = createOrder.publicCreateOrder(BID, fix(1), 4006, categoricalMarket.address, 1, longTo32Bytes(0), longTo32Bytes(0), "7", value = fix(1, 4006)) for i in range(4007, 4107): createOrder.publicCreateOrder(BID, fix(1), i, categoricalMarket.address, 1, longTo32Bytes(0), longTo32Bytes(0), "7", value = fix(1, i)) if not hints: with PrintGasUsed(localFixture, "CreateOrder:publicCreateOrder NO Hints", CREATE_ORDER): orderID = createOrder.publicCreateOrder(BID, fix(1), 4005, categoricalMarket.address, 1, longTo32Bytes(0), longTo32Bytes(0), "7", value = fix(1, 4005)) else: with PrintGasUsed(localFixture, "CreateOrder:publicCreateOrder HINTS", CREATE_ORDER): orderID = createOrder.publicCreateOrder(BID, fix(1), 4005, categoricalMarket.address, 1, betterOrderId, worseOrderId, "7", value = fix(1, 4005))
def test_minimum_gas_failure(contractsFixture, cash, market, universe): createOrder = contractsFixture.contracts['CreateOrder'] trade = contractsFixture.contracts['Trade'] tradeGroupID = "42" # create order orderID = createOrder.publicCreateOrder(BID, fix(4), 6000, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), tradeGroupID, sender = tester.k1, value=fix('4', '6000')) # We need to provide a minimum gas amount or we'll get back a failure. In testing we use a much higher minimum since in some cases we alter the contracts in a way that massively increases gas cost. In production this value is 500000 minGas = 5000000 fillOrderID = trade.publicSell(market.address, YES, fix(5), 6000, "0", "0", tradeGroupID, sender = tester.k2, value=fix('5', '4000'), startgas=minGas-1) # We get back a sentinal byte value since not enough gas was provided assert fillOrderID == longTo32Bytes(1) # If we provide enough gas we get a legitimate value fillOrderID = trade.publicSell(market.address, YES, fix(5), 6000, "0", "0", tradeGroupID, sender = tester.k2, value=fix('5', '4000')) assert fillOrderID != longTo32Bytes(1)
def test_duplicate_creation_transaction(contractsFixture, cash, market): orders = contractsFixture.contracts['Orders'] createOrder = contractsFixture.contracts['CreateOrder'] with EtherDelta(-fix(1, 4000), tester.a0, contractsFixture.chain): orderID = createOrder.publicCreateOrder(BID, fix(1), 4000, market.address, 1, longTo32Bytes(0), longTo32Bytes(0), "7", value = fix(1, 4000)) assert orderID with raises(TransactionFailed): createOrder.publicCreateOrder(BID, fix(1), 4000, market.address, 1, longTo32Bytes(0), longTo32Bytes(0), "7", value = fix(1, 4000))
def test_case_1(contractsFixture, cash, market, universe): createOrder = contractsFixture.contracts['CreateOrder'] orders = contractsFixture.contracts['Orders'] ordersFinder = contractsFixture.contracts['OrdersFinder'] tradeGroupID = "42" nullAddress = longTo32Bytes(0) # Orphaned order due to early exit logic from bad data caused by Orders worst order setting bug assert orders.getBestOrderId(BID, market.address, 1) == nullAddress orderID1 = createOrder.publicCreateOrder(BID, fix(1), 3000, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), tradeGroupID, value=fix('1', '3000')) orderID2 = createOrder.publicCreateOrder(BID, fix(2), 3000, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), tradeGroupID, value=fix('2', '3000')) orderID3 = createOrder.publicCreateOrder(BID, fix(3), 2999, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), tradeGroupID, value=fix('3', '2999')) assert orders.getWorseOrderId(orderID1) == orderID3 assert orders.getWorseOrderId(orderID3) == longTo32Bytes(0) # order 2 orphaned orderIds = ordersFinder.getExistingOrders5(BID, market.address, 1) assert orderID1 in orderIds assert orderID3 in orderIds assert orderID2 not in orderIds
def test_createOrder_failure(contractsFixture, universe, cash, market): orders = contractsFixture.contracts['Orders'] createOrder = contractsFixture.contracts['CreateOrder'] fillOrder = contractsFixture.contracts['FillOrder'] completeSets = contractsFixture.contracts['CompleteSets'] yesShareToken = contractsFixture.applySignature('ShareToken', market.getShareToken(YES)) noShareToken = contractsFixture.applySignature('ShareToken', market.getShareToken(NO)) with raises(TransactionFailed): createOrder.createOrder(tester.a1, ASK, fix(1), 4000, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), "42", sender=tester.k1) # createOrder exceptions (pre-escrowFunds) with raises(TransactionFailed): createOrder.publicCreateOrder(3, fix(1), 4000, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), "42", sender=tester.k1) # escrowFundsForBid exceptions with raises(TransactionFailed): createOrder.publicCreateOrder(BID, fix(1), 4000, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), "42", sender=tester.k1) with raises(TransactionFailed): createOrder.publicCreateOrder(BID, fix(1), 4000, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), "42", sender=tester.k1) # escrowFundsForAsk exceptions with raises(TransactionFailed): createOrder.publicCreateOrder(ASK, 1, 1, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), "42", sender=tester.k1) with raises(TransactionFailed): createOrder.publicCreateOrder(ASK, fix(1), 4000, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), "42", sender=tester.k1) assert completeSets.publicBuyCompleteSets(market.address, fix(12), sender=tester.k1, value=fix('12', market.getNumTicks())) with raises(TransactionFailed): createOrder.publicCreateOrder(ASK, fix(1), 12000, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), "42", sender=tester.k1) assert yesShareToken.approve(createOrder.address, fix(12), sender=tester.k1) == 1, "Approve createOrder contract to spend shares from the user's account (account 1)" assert yesShareToken.allowance(tester.a1, createOrder.address) == fix(12), "CreateOrder contract's allowance should be equal to the amount approved" with raises(TransactionFailed): createOrder.publicCreateOrder(ASK, fix(1), 4000, tester.a1, YES, longTo32Bytes(0), longTo32Bytes(0), "42", sender=tester.k1) assert createOrder.publicCreateOrder(ASK, fix(1), 4000, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), "42", sender=tester.k1) != 0, "Order ID should be non-zero" # createOrder exceptions (post-escrowFunds) with raises(TransactionFailed): createOrder.publicCreateOrder(ASK, fix(1), 4000, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), "42", sender=tester.k1)
def test_take_best_order(contractsFixture, cash, market, universe): createOrder = contractsFixture.contracts['CreateOrder'] trade = contractsFixture.contracts['Trade'] orders = contractsFixture.contracts['Orders'] initialTester1ETH = contractsFixture.chain.head_state.get_balance(tester.a1) initialTester2ETH = contractsFixture.chain.head_state.get_balance(tester.a2) # create order with cash orderID = createOrder.publicCreateOrder(ASK, fix(1), 6000, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), "42", sender=tester.k1, value=fix('1', '4000')) assert orderID # fill order with cash using on-chain matcher assert trade.publicFillBestOrder(BID, market.address, YES, fix(1), 6000, "43", sender=tester.k2, value=fix('1', '6000')) == 0 assert orders.getAmount(orderID) == 0 assert orders.getPrice(orderID) == 0 assert orders.getOrderCreator(orderID) == longToHexString(0) assert orders.getOrderMoneyEscrowed(orderID) == 0 assert orders.getOrderSharesEscrowed(orderID) == 0 assert orders.getBetterOrderId(orderID) == longTo32Bytes(0) assert orders.getWorseOrderId(orderID) == longTo32Bytes(0)
def test_publicFillOrder_bid(contractsFixture, cash, market, universe): createOrder = contractsFixture.contracts['CreateOrder'] fillOrder = contractsFixture.contracts['FillOrder'] orders = contractsFixture.contracts['Orders'] tradeGroupID = "42" initialMakerETH = contractsFixture.chain.head_state.get_balance(tester.a1) initialFillerETH = contractsFixture.chain.head_state.get_balance(tester.a2) creatorCost = fix('2', '6000') fillerCost = fix('2', '4000') # create order orderID = createOrder.publicCreateOrder(BID, fix(2), 6000, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), tradeGroupID, sender = tester.k1, value=creatorCost) # fill best order orderFilledLog = { "filler": bytesToHexString(tester.a2), "numCreatorShares": 0, "numCreatorTokens": creatorCost, "numFillerShares": 0, "numFillerTokens": fillerCost, "marketCreatorFees": 0, "reporterFees": 0, "shareToken": market.getShareToken(YES), "tradeGroupId": stringToBytes("42"), "amountFilled": fix(2), } with AssertLog(contractsFixture, "OrderFilled", orderFilledLog): fillOrderID = fillOrder.publicFillOrder(orderID, fix(2), tradeGroupID, sender = tester.k2, value=fillerCost) assert fillOrderID == 0 assert contractsFixture.chain.head_state.get_balance(tester.a1) == initialMakerETH - creatorCost assert contractsFixture.chain.head_state.get_balance(tester.a2) == initialFillerETH - fillerCost assert orders.getAmount(orderID) == 0 assert orders.getPrice(orderID) == 0 assert orders.getOrderCreator(orderID) == longToHexString(0) assert orders.getOrderMoneyEscrowed(orderID) == 0 assert orders.getOrderSharesEscrowed(orderID) == 0 assert orders.getBetterOrderId(orderID) == longTo32Bytes(0) assert orders.getWorseOrderId(orderID) == longTo32Bytes(0)
def test_two_asks_on_books_buy_full_and_partial(contractsFixture, cash, market, universe): createOrder = contractsFixture.contracts['CreateOrder'] trade = contractsFixture.contracts['Trade'] fillOrder = contractsFixture.contracts['FillOrder'] orders = contractsFixture.contracts['Orders'] tradeGroupID = "42" # create order 1 orderID1 = createOrder.publicCreateOrder(ASK, fix(12), 6000, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), tradeGroupID, sender = tester.k1, value=fix('12', '4000')) # create order 2 orderID2 = createOrder.publicCreateOrder(ASK, fix(7), 6000, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), tradeGroupID, sender = tester.k3, value=fix('7', '4000')) # fill best order fillOrderID = trade.publicBuy(market.address, YES, fix(15), 6000, "0", "0", tradeGroupID, sender = tester.k2, value=fix('15', '6000')) assert orders.getAmount(orderID1) == 0 assert orders.getPrice(orderID1) == 0 assert orders.getOrderCreator(orderID1) == longToHexString(0) assert orders.getOrderMoneyEscrowed(orderID1) == 0 assert orders.getOrderSharesEscrowed(orderID1) == 0 assert orders.getBetterOrderId(orderID1) == longTo32Bytes(0) assert orders.getWorseOrderId(orderID1) == longTo32Bytes(0) assert orders.getAmount(orderID2) == fix(4) assert orders.getPrice(orderID2) == 6000 assert orders.getOrderCreator(orderID2) == bytesToHexString(tester.a3) assert orders.getOrderMoneyEscrowed(orderID2) == fix('4', '4000') assert orders.getOrderSharesEscrowed(orderID2) == 0 assert orders.getBetterOrderId(orderID2) == longTo32Bytes(0) assert orders.getWorseOrderId(orderID2) == longTo32Bytes(0) assert fillOrderID == longTo32Bytes(1)
def test_orderFilling(localFixture, market): createOrder = localFixture.contracts['CreateOrder'] fillOrder = localFixture.contracts['FillOrder'] tradeGroupID = "42" creatorCost = fix('2', '4000') fillerCost = fix('2', '6000') # create order orderID = createOrder.publicCreateOrder(ASK, fix(2), 6000, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), tradeGroupID, sender = tester.k1, value=creatorCost) with PrintGasUsed(localFixture, "FillOrder:publicFillOrder", FILL_ORDER): fillOrderID = fillOrder.publicFillOrder(orderID, fix(2), tradeGroupID, sender = tester.k2, value=fillerCost)
def test_case_2(contractsFixture, cash, market, universe): createOrder = contractsFixture.contracts['CreateOrder'] cancelOrder = contractsFixture.contracts['CancelOrder'] orders = contractsFixture.contracts['Orders'] ordersFinder = contractsFixture.contracts['OrdersFinder'] tradeGroupID = "42" nullAddress = longTo32Bytes(0) # create orders assert orders.getBestOrderId(BID, market.address, 1) == nullAddress orderID1 = createOrder.publicCreateOrder(BID, fix(1), 3000, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), tradeGroupID, value=fix('1', '3000')) orderID2 = createOrder.publicCreateOrder(BID, fix(2), 3000, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), tradeGroupID, value=fix('2', '3000')) assert cancelOrder.cancelOrder(orderID1) orderID3 = createOrder.publicCreateOrder(BID, fix(3), 4000, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), tradeGroupID, value=fix('3', '4000')) assert orders.getBestOrderId(BID, market.address, 1) == orderID3 assert orders.getWorseOrderId(orderID3) == nullAddress # order 2 orphaned orderIds = ordersFinder.getExistingOrders5(BID, market.address, 1) assert orderID1 not in orderIds assert orderID2 not in orderIds assert orderID3 in orderIds
def test_fill_order_with_shares_escrowed_sell_with_shares_categorical(contractsFixture, cash, categoricalMarket, universe): market = categoricalMarket createOrder = contractsFixture.contracts['CreateOrder'] fillOrder = contractsFixture.contracts['FillOrder'] orders = contractsFixture.contracts['Orders'] completeSets = contractsFixture.contracts['CompleteSets'] firstShareToken = contractsFixture.applySignature('ShareToken', market.getShareToken(0)) secondShareToken = contractsFixture.applySignature('ShareToken', market.getShareToken(1)) thirdShareToken = contractsFixture.applySignature('ShareToken', market.getShareToken(2)) # buy complete sets for both users numTicks = market.getNumTicks() assert completeSets.publicBuyCompleteSets(market.address, fix(1), sender=tester.k1, value=fix('1', numTicks)) assert completeSets.publicBuyCompleteSets(market.address, fix(1), sender=tester.k2, value=fix('1', numTicks)) assert firstShareToken.balanceOf(tester.a1) == firstShareToken.balanceOf(tester.a2) == fix(1) assert secondShareToken.balanceOf(tester.a1) == secondShareToken.balanceOf(tester.a2) == fix(1) assert thirdShareToken.balanceOf(tester.a1) == thirdShareToken.balanceOf(tester.a2) == fix(1) # create order with shares price = 6000 orderID = createOrder.publicCreateOrder(ASK, fix(1), price, market.address, 0, longTo32Bytes(0), longTo32Bytes(0), "42", sender=tester.k1) assert orderID # fill order with shares assert fillOrder.publicFillOrder(orderID, fix(1), "43", sender=tester.k2) == 0 # The second users corresponding shares were used to fulfil this order assert firstShareToken.balanceOf(tester.a2) == fix(1) assert secondShareToken.balanceOf(tester.a2) == 0 assert thirdShareToken.balanceOf(tester.a2) == 0 assert orders.getAmount(orderID) == 0 assert orders.getPrice(orderID) == 0 assert orders.getOrderCreator(orderID) == longToHexString(0) assert orders.getOrderMoneyEscrowed(orderID) == 0 assert orders.getOrderSharesEscrowed(orderID) == 0 assert orders.getBetterOrderId(orderID) == longTo32Bytes(0) assert orders.getWorseOrderId(orderID) == longTo32Bytes(0)
def test_orderBidSorting(where, orderType, hints, contractsFixture, market): orders = contractsFixture.contracts['Orders'] ordersFetcher = contractsFixture.contracts['OrdersFetcher'] # setup pre-existing orders worstPrice = 6000 if orderType == BID else 6600 bestPrice = 6600 if orderType == BID else 6000 worstOrderId = orders.saveOrder(orderType, market.address, fix('1'), worstPrice, tester.a0, YES, worstPrice, 0, longTo32Bytes(0), longTo32Bytes(0), "0") bestOrderId = orders.saveOrder(orderType, market.address, fix('1'), bestPrice, tester.a0, YES, bestPrice, 0, longTo32Bytes(0), longTo32Bytes(0), "0") # validate that our setup went smoothly assert orders.getBestOrderId(orderType, market.address, YES) == bestOrderId assert orders.getWorstOrderId(orderType, market.address, YES) == worstOrderId assert orders.getWorseOrderId(bestOrderId) == worstOrderId assert orders.getWorseOrderId(worstOrderId) == longTo32Bytes(0) assert orders.getBetterOrderId(worstOrderId) == bestOrderId assert orders.getBetterOrderId(bestOrderId) == longTo32Bytes(0) # insert our new order if where == 'best': orderPrice = 6700 if orderType == BID else 5900 betterOrderId = longTo32Bytes(0) worseOrderId = bestOrderId if hints else longTo32Bytes(0) if where == 'middle': orderPrice = 6300 betterOrderId = bestOrderId if hints else longTo32Bytes(0) worseOrderId = worstOrderId if hints else longTo32Bytes(0) if where == 'worst': orderPrice = 5900 if orderType == BID else 6700 betterOrderId = worstOrderId if hints else longTo32Bytes(0) worseOrderId = longTo32Bytes(0) insertedOrder = orders.saveOrder(orderType, market.address, fix('1'), orderPrice, tester.a0, YES, orderPrice, 0, betterOrderId, worseOrderId, "0") # validate the new order was inserted correctly assert orders.getBetterOrderId(insertedOrder) == longTo32Bytes(0) if where == 'best' else bestOrderId assert orders.getWorseOrderId(insertedOrder) == longTo32Bytes(0) if where == 'worst' else worstOrderId assert orders.getBestOrderId(orderType, market.address, YES) == insertedOrder if where == 'best' else bestOrderId assert orders.getWorstOrderId(orderType, market.address, YES) == insertedOrder if where == 'worst' else worstOrderId
def test_exceptions(contractsFixture, cash, market): createOrder = contractsFixture.contracts['CreateOrder'] cancelOrder = contractsFixture.contracts['CancelOrder'] orderType = BID fxpAmount = fix(1) fxpPrice = 6000 outcomeID = YES tradeGroupID = "42" marketInitialCash = cash.balanceOf(market.address) orderID = createOrder.publicCreateOrder(orderType, fxpAmount, fxpPrice, market.address, outcomeID, longTo32Bytes(0), longTo32Bytes(0), tradeGroupID, sender=tester.k1, value = fix('10000')) assert(orderID != bytearray(32)), "Order ID should be non-zero" # cancelOrder exceptions with raises(TransactionFailed): cancelOrder.cancelOrder(longTo32Bytes(0), sender=tester.k1) with raises(TransactionFailed): cancelOrder.cancelOrder(longTo32Bytes(1), sender=tester.k1) with raises(TransactionFailed): cancelOrder.cancelOrder(orderID, sender=tester.k2) assert(cancelOrder.cancelOrder(orderID, sender=tester.k1) == 1), "cancelOrder should succeed" with raises(TransactionFailed): cancelOrder.cancelOrder(orderID, sender=tester.k1)
def test_publicCreateOrder_ask(contractsFixture, cash, market): orders = contractsFixture.contracts['Orders'] createOrder = contractsFixture.contracts['CreateOrder'] orderID = createOrder.publicCreateOrder(ASK, fix(1), 4000, market.address, 0, longTo32Bytes(0), longTo32Bytes(0), "7", value = fix(1, 6000)) assert orders.getAmount(orderID) == fix(1) assert orders.getPrice(orderID) == 4000 assert orders.getOrderCreator(orderID) == bytesToHexString(tester.a0) assert orders.getOrderMoneyEscrowed(orderID) == fix(1, 6000) assert orders.getOrderSharesEscrowed(orderID) == 0 assert orders.getBetterOrderId(orderID) == bytearray(32) assert orders.getWorseOrderId(orderID) == bytearray(32) assert cash.balanceOf(market.address) == fix(1, 6000)
def test_ask_withSharesIgnored(contractsFixture, universe, cash, market): orders = contractsFixture.contracts['Orders'] createOrder = contractsFixture.contracts['CreateOrder'] fillOrder = contractsFixture.contracts['FillOrder'] completeSets = contractsFixture.contracts['CompleteSets'] yesShareToken = contractsFixture.applySignature('ShareToken', market.getShareToken(YES)) noShareToken = contractsFixture.applySignature('ShareToken', market.getShareToken(NO)) # buy fix(2) complete sets assert completeSets.publicBuyCompleteSets(market.address, fix(2), sender=tester.k1, value=fix( 2, market.getNumTicks())) assert cash.balanceOf(tester.a1) == fix('0') assert yesShareToken.balanceOf(tester.a1) == fix(2) assert noShareToken.balanceOf(tester.a1) == fix(2) orderID = None # Even though we have no shares available to cover this order if we indicate that we do not want to use them we'll need to provide sufficient ETH to cover the order with raises(TransactionFailed): createOrder.publicCreateOrder(BID, fix(1), 5000, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), "42", True, sender=tester.k1) orderCreatedLog = { 'creator': bytesToHexString(tester.a1), 'shareToken': yesShareToken.address, 'tradeGroupId': stringToBytes("42"), } with AssertLog(contractsFixture, "OrderCreated", orderCreatedLog): orderID = createOrder.publicCreateOrder(BID, fix(1), 5000, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), "42", True, sender=tester.k1, value=fix('5000')) assert cash.balanceOf(tester.a1) == fix('0') assert yesShareToken.balanceOf(tester.a1) == fix(2) assert noShareToken.balanceOf(tester.a1) == fix(2) # validate the order contains expected results assert orderID != bytearray(32), "Order ID should be non-zero" assert orders.getAmount(orderID) == fix(1) assert orders.getPrice(orderID) == 5000 assert orders.getOrderCreator(orderID) == bytesToHexString(tester.a1) assert orders.getOrderMoneyEscrowed(orderID) == fix('5000') assert orders.getOrderSharesEscrowed(orderID) == 0
def test_simple_trades_and_fees(long, contractsFixture, cash, market, universe): ZeroXTrade = contractsFixture.contracts['ZeroXTrade'] zeroXExchange = contractsFixture.contracts["ZeroXExchange"] simulateTrade = contractsFixture.contracts["SimulateTrade"] account0 = contractsFixture.accounts[0] senderPrivateKey0 = contractsFixture.privateKeys[0] account1 = contractsFixture.accounts[1] senderPrivateKey1 = contractsFixture.privateKeys[1] expirationTime = contractsFixture.contracts['Time'].getTimestamp() + 10000 salt = 5 tradeGroupID = longTo32Bytes(42) fingerprint = longTo32Bytes(11) direction = LONG if long else SHORT outcome = YES amount = fix(1) price = 40 fillOnly = False numTicks = market.getNumTicks() longPrice = price shortPrice = numTicks - longPrice cost = amount * (longPrice if long else shortPrice) cash.faucet(cost) rawZeroXOrderData, orderHash = ZeroXTrade.createZeroXOrder(direction, amount, price, market.address, outcome, expirationTime, salt, sender=account0) signature = signOrder(orderHash, senderPrivateKey0) orders = [rawZeroXOrderData] signatures = [signature] (sharesFilled, tokensDepleted, sharesDepleted, settlementFees, numFills) = simulateTrade.simulateZeroXTrade(orders, amount, fillOnly, sender=account1) fillPrice = (shortPrice if long else longPrice) cost = amount * fillPrice assert sharesFilled == amount assert tokensDepleted == cost assert sharesDepleted == 0 assert settlementFees == 0 assert numFills == 1 cash.faucet(cost, sender=account1) assert ZeroXTrade.trade(amount, fingerprint, tradeGroupID, 0, 10, orders, signatures, sender=account1, value=150000) == 0 rawZeroXOrderData, orderHash = ZeroXTrade.createZeroXOrder( SHORT if long else LONG, amount, price, market.address, outcome, expirationTime, salt, sender=account0) signature = signOrder(orderHash, senderPrivateKey0) orders = [rawZeroXOrderData] signatures = [signature] (sharesFilled, tokensDepleted, sharesDepleted, settlementFees, numFills) = simulateTrade.simulateZeroXTrade(orders, amount, fillOnly, sender=account1) assert simulateTrade.getNumberOfAvaialableShares(LONG if long else SHORT, market.address, outcome, account1) == fix(1) expectedValue = fix(1) * (shortPrice if long else longPrice) expectedReporterFees = expectedValue / universe.getOrCacheReportingFeeDivisor( ) expectedMarketCreatorFees = expectedValue / market.getMarketCreatorSettlementFeeDivisor( ) expectedSettlementFees = expectedReporterFees + expectedMarketCreatorFees assert sharesFilled == fix(1) assert tokensDepleted == 0 assert sharesDepleted == fix(1) assert settlementFees == expectedSettlementFees assert numFills == 1
def test_create_bid_with_shares_fill_with_shares(contractsFixture, cash, market, universe): completeSets = contractsFixture.contracts['CompleteSets'] createOrder = contractsFixture.contracts['CreateOrder'] fillOrder = contractsFixture.contracts['FillOrder'] yesShareToken = contractsFixture.applySignature('ShareToken', market.getShareToken(YES)) noShareToken = contractsFixture.applySignature('ShareToken', market.getShareToken(NO)) totalProceeds = fix('12', market.getNumTicks()) marketCreatorFee = totalProceeds / market.getMarketCreatorSettlementFeeDivisor( ) reporterFee = totalProceeds / universe.getOrCacheReportingFeeDivisor() completeSetFees = marketCreatorFee + reporterFee # 1. buy complete sets with both accounts assert completeSets.publicBuyCompleteSets(market.address, fix(12), sender=tester.k1, value=fix( '12', market.getNumTicks())) assert completeSets.publicBuyCompleteSets(market.address, fix(12), sender=tester.k2, value=fix( '12', market.getNumTicks())) assert cash.balanceOf(tester.a1) == fix('0') assert cash.balanceOf(tester.a2) == fix('0') assert yesShareToken.balanceOf(tester.a2) == fix(12) assert yesShareToken.balanceOf(tester.a1) == fix(12) assert noShareToken.balanceOf(tester.a1) == fix(12) assert noShareToken.balanceOf(tester.a2) == fix(12) # 2. create BID order for YES with NO shares escrowed assert noShareToken.approve(createOrder.address, fix(12), sender=tester.k1) orderID = createOrder.publicCreateOrder(BID, fix(12), 6000, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), "42", sender=tester.k1) assert orderID assert cash.balanceOf(tester.a1) == fix('0') assert yesShareToken.balanceOf(tester.a1) == fix(12) assert noShareToken.balanceOf(tester.a1) == 0 # 3. fill BID order for YES with shares of YES initialMakerETH = contractsFixture.chain.head_state.get_balance(tester.a1) initialFillerETH = contractsFixture.chain.head_state.get_balance(tester.a2) assert yesShareToken.approve(fillOrder.address, fix(12), sender=tester.k2) orderFilledLog = { 'marketCreatorFees': marketCreatorFee, 'reporterFees': reporterFee, } with AssertLog(contractsFixture, 'OrderFilled', orderFilledLog): leftoverInOrder = fillOrder.publicFillOrder(orderID, fix(12), sender=tester.k2) assert leftoverInOrder == 0 creatorFee = completeSetFees * 0.4 fillerFee = completeSetFees * 0.6 creatorPayment = fix('12', '4000') - long(creatorFee) fillerPayment = fix('12', '6000') - long(fillerFee) assert cash.balanceOf(tester.a1) == 0 assert cash.balanceOf(tester.a2) == 0 assert contractsFixture.chain.head_state.get_balance( tester.a1) == initialMakerETH + long(creatorPayment) assert contractsFixture.chain.head_state.get_balance( tester.a2) == initialFillerETH + long(fillerPayment) assert yesShareToken.balanceOf(tester.a1) == fix(12) assert yesShareToken.balanceOf(tester.a2) == 0 assert noShareToken.balanceOf(tester.a1) == 0 assert noShareToken.balanceOf(tester.a2) == fix(12)
def test_fees(contractsFixture, cash, market, universe): ZeroXTrade = contractsFixture.contracts['ZeroXTrade'] zeroXExchange = contractsFixture.contracts["ZeroXExchange"] simulateTrade = contractsFixture.contracts["SimulateTrade"] cash = contractsFixture.contracts["Cash"] shareToken = contractsFixture.contracts["ShareToken"] expirationTime = contractsFixture.contracts['Time'].getTimestamp() + 10000 direction = SHORT outcome = YES amount = fix(1) price = 40 salt = 5 tradeGroupID = longTo32Bytes(42) fillOnly = False makerAccount = contractsFixture.accounts[1] makerPrivKey = contractsFixture.privateKeys[1] fillerAccount = contractsFixture.accounts[0] expectedValue = amount * (market.getNumTicks() - price) expectedReporterFees = expectedValue / universe.getOrCacheReportingFeeDivisor( ) expectedMarketCreatorFees = expectedValue / market.getMarketCreatorSettlementFeeDivisor( ) expectedSettlementFees = expectedReporterFees + expectedMarketCreatorFees # Buy and distribute complete sets cash.faucet(amount * market.getNumTicks(), sender=makerAccount) shareToken.publicBuyCompleteSets(market.address, amount, sender=makerAccount) shareToken.safeTransferFrom(makerAccount, fillerAccount, shareToken.getTokenId(market.address, 0), amount, "", sender=makerAccount) shareToken.safeTransferFrom(makerAccount, fillerAccount, shareToken.getTokenId(market.address, NO), amount, "", sender=makerAccount) # Make order rawZeroXOrderData, orderHash = ZeroXTrade.createZeroXOrder( direction, amount, price, market.address, outcome, expirationTime, salt, sender=makerAccount) signature = signOrder(orderHash, makerPrivKey) orders = [rawZeroXOrderData] signatures = [signature] simulate_then_trade(contractsFixture, market, outcome, direction, orders, signatures, amount, fillOnly, fillerAccount, expectedFees=expectedSettlementFees)
def simulate_then_trade(contractsFixture, market, outcome, orderDirection, orders, signatures, fillAmount, fillOnly, fillerAccount, expectedFees=0): ZeroXTrade = contractsFixture.contracts['ZeroXTrade'] zeroXExchange = contractsFixture.contracts["ZeroXExchange"] simulateTrade = contractsFixture.contracts["SimulateTrade"] shareToken = contractsFixture.contracts["ShareToken"] cash = contractsFixture.contracts["Cash"] shareTokenOutcome = outcome if orderDirection == LONG else ((outcome + 1) % 3) tradeGroupID = longTo32Bytes(42) fingerprint = longTo32Bytes(11) (sharesFilled, tokensDepleted, sharesDepleted, settlementFees, numFills) = simulateTrade.simulateZeroXTrade(orders, fillAmount, fillOnly, sender=fillerAccount) cash.faucet(tokensDepleted, sender=fillerAccount) initialCashBalance = cash.balanceOf(fillerAccount) initialShareBalance = shareToken.balanceOfMarketOutcome( market.address, shareTokenOutcome, fillerAccount) expectedAmountRemaining = fillAmount - sharesFilled # Self trades will take the full order in terms of amount remaining makerAccount = orders[0][0] expectedAmountRemaining = expectedAmountRemaining if fillerAccount != makerAccount else 0 assert ZeroXTrade.trade(fillAmount, fingerprint, tradeGroupID, 0, 10, orders, signatures, sender=fillerAccount, value=150000 * len(orders)) == expectedAmountRemaining if (tokensDepleted > 0): assert tokensDepleted == initialCashBalance - cash.balanceOf( fillerAccount) if (sharesDepleted > 0): assert sharesDepleted == initialShareBalance - shareToken.balanceOfMarketOutcome( market.address, shareTokenOutcome, fillerAccount) expectedSharesFilled = 0 expectedNumFills = 0 orderEventLogs = contractsFixture.contracts["AugurTrading"].getLogs( "OrderEvent") for log in orderEventLogs: if log.args.eventType == 2: # Fill Event expectedSharesFilled += log.args.uint256Data[6] expectedNumFills += 1 assert sharesFilled == expectedSharesFilled assert settlementFees == expectedFees assert numFills == expectedNumFills
def test_create_ask_with_shares_fill_with_shares(contractsFixture, cash, market): completeSets = contractsFixture.contracts['CompleteSets'] createOrder = contractsFixture.contracts['CreateOrder'] fillOrder = contractsFixture.contracts['FillOrder'] yesShareToken = contractsFixture.applySignature('ShareToken', market.getShareToken(YES)) noShareToken = contractsFixture.applySignature('ShareToken', market.getShareToken(NO)) completeSetFees = fix('12', '0.02') * market.getNumTicks() # 1. both accounts buy a complete set assert completeSets.publicBuyCompleteSets(market.address, fix(12), sender=tester.k1, value=fix( '12', market.getNumTicks())) assert completeSets.publicBuyCompleteSets(market.address, fix(12), sender=tester.k2, value=fix( '12', market.getNumTicks())) assert yesShareToken.balanceOf(tester.a1) == fix(12) assert yesShareToken.balanceOf(tester.a2) == fix(12) assert noShareToken.balanceOf(tester.a1) == fix(12) assert noShareToken.balanceOf(tester.a2) == fix(12) # 2. create ASK order for YES with YES shares for escrow assert yesShareToken.approve(createOrder.address, fix(12), sender=tester.k1) askOrderID = createOrder.publicCreateOrder(ASK, fix(12), 6000, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), "42", sender=tester.k1) assert askOrderID assert cash.balanceOf(tester.a1) == 0 assert yesShareToken.balanceOf(tester.a1) == 0 assert noShareToken.balanceOf(tester.a1) == fix(12) # 3. fill ASK order for YES with NO shares initialMakerETH = contractsFixture.chain.head_state.get_balance(tester.a1) initialFillerETH = contractsFixture.chain.head_state.get_balance(tester.a2) assert noShareToken.approve(fillOrder.address, fix(12), sender=tester.k2) amountRemaining = fillOrder.publicFillOrder(askOrderID, fix(12), sender=tester.k2) creatorFee = completeSetFees * 0.6 fillerFee = completeSetFees * 0.4 assert amountRemaining == 0 assert cash.balanceOf(tester.a1) == 0 assert cash.balanceOf(tester.a2) == 0 assert contractsFixture.chain.head_state.get_balance( tester.a1) == initialMakerETH + fix('12', '6000') - long(creatorFee) assert contractsFixture.chain.head_state.get_balance( tester.a2) == initialFillerETH + fix('12', '4000') - long(fillerFee) assert yesShareToken.balanceOf(tester.a1) == 0 assert yesShareToken.balanceOf(tester.a2) == fix(12) assert noShareToken.balanceOf(tester.a1) == fix(12) assert noShareToken.balanceOf(tester.a2) == 0
def test_repro_shares_depleted_case(contractsFixture, cash, market, universe): ZeroXTrade = contractsFixture.contracts['ZeroXTrade'] zeroXExchange = contractsFixture.contracts["ZeroXExchange"] simulateTrade = contractsFixture.contracts["SimulateTrade"] account0 = contractsFixture.accounts[0] senderPrivateKey0 = contractsFixture.privateKeys[0] account1 = contractsFixture.accounts[1] senderPrivateKey1 = contractsFixture.privateKeys[1] expirationTime = contractsFixture.contracts['Time'].getTimestamp() + 10000 salt = 5 tradeGroupID = longTo32Bytes(42) fingerprint = longTo32Bytes(11) direction = LONG outcome = YES amount = fix(1) price = 10 fillOnly = False numTicks = market.getNumTicks() longPrice = price shortPrice = numTicks - longPrice cost = amount * longPrice cash.faucet(cost) rawZeroXOrderData, orderHash = ZeroXTrade.createZeroXOrder(direction, amount, price, market.address, outcome, expirationTime, salt, sender=account0) signature = signOrder(orderHash, senderPrivateKey0) orders = [rawZeroXOrderData] signatures = [signature] cost = amount * shortPrice cash.faucet(cost, sender=account1) assert ZeroXTrade.trade(amount, fingerprint, tradeGroupID, 0, 10, orders, signatures, sender=account1, value=150000) == 0 rawZeroXOrderData, orderHash = ZeroXTrade.createZeroXOrder(direction, amount, price, market.address, NO, expirationTime, salt, sender=account0) signature = signOrder(orderHash, senderPrivateKey0) orders = [rawZeroXOrderData] signatures = [signature] (sharesFilled, tokensDepleted, sharesDepleted, settlementFees, numFills) = simulateTrade.simulateZeroXTrade(orders, amount, fillOnly, sender=account1) assert simulateTrade.getNumberOfAvaialableShares(SHORT, market.address, NO, account1) == fix(1) assert sharesFilled == fix(1) assert tokensDepleted == 0 assert sharesDepleted == fix(1) assert numFills == 1
def test_redeem_shares_in_yesNo_market(afterMkrShutdown, kitchenSinkFixture, universe, cash, market): shareToken = kitchenSinkFixture.contracts["ShareToken"] expectedValue = 1 * market.getNumTicks() expectedReporterFees = expectedValue / universe.getOrCacheReportingFeeDivisor( ) expectedMarketCreatorFees = expectedValue / market.getMarketCreatorSettlementFeeDivisor( ) expectedSettlementFees = expectedReporterFees + expectedMarketCreatorFees expectedPayout = expectedValue - expectedSettlementFees if (afterMkrShutdown): kitchenSinkFixture.MKRShutdown() assert universe.getOpenInterestInAttoCash() == 0 # get YES shares with a1 acquireLongShares(kitchenSinkFixture, cash, market, YES, 1, shareToken.address, sender=kitchenSinkFixture.accounts[1]) assert universe.getOpenInterestInAttoCash() == 1 * market.getNumTicks() # get NO shares with a2 acquireShortShareSet(kitchenSinkFixture, cash, market, YES, 1, shareToken.address, sender=kitchenSinkFixture.accounts[2]) assert universe.getOpenInterestInAttoCash() == 2 * market.getNumTicks() finalizeMarket(kitchenSinkFixture, market, [0, 0, 10**2]) tradingProceedsClaimedLog = { 'market': market.address, 'numPayoutTokens': expectedPayout, 'numShares': 1, 'sender': kitchenSinkFixture.accounts[1], 'fees': 2, } daiVat = kitchenSinkFixture.contracts['DaiVat'] disputeWindow = universe.getOrCreateNextDisputeWindow(False) originalDisputeWindowBalance = cash.balanceOf(disputeWindow) originalMarketCreatorBalance = cash.balanceOf(market.getOwner()) # redeem shares with a1 with AssertLog(kitchenSinkFixture, "TradingProceedsClaimed", tradingProceedsClaimedLog): shareToken.claimTradingProceeds(market.address, kitchenSinkFixture.accounts[1], longTo32Bytes(11)) # redeem shares with a2 shareToken.claimTradingProceeds(market.address, kitchenSinkFixture.accounts[2], longTo32Bytes(11)) newDisputeWindowBalance = cash.balanceOf( disputeWindow) + daiVat.dai(disputeWindow) / 10**27 assert newDisputeWindowBalance == expectedReporterFees + originalDisputeWindowBalance if afterMkrShutdown: newMarketCreatorBalanceFromFees = ( daiVat.dai(market.getOwner()) - 10**46) / 10**27 # - 10**46 is subtracting winnings to get fees else: newMarketCreatorBalanceFromFees = cash.balanceOf(market.getOwner()) assert newMarketCreatorBalanceFromFees == int( expectedMarketCreatorFees) + originalMarketCreatorBalance # assert a1 ends up with cash (minus fees) and a2 does not if afterMkrShutdown: assert daiVat.dai( kitchenSinkFixture.accounts[1]) / 10**27 == expectedPayout else: assert cash.balanceOf(kitchenSinkFixture.accounts[1]) == expectedPayout assert shareToken.balanceOfMarketOutcome( market.address, YES, kitchenSinkFixture.accounts[1]) == 0 assert shareToken.balanceOfMarketOutcome( market.address, YES, kitchenSinkFixture.accounts[2]) == 0 assert shareToken.balanceOfMarketOutcome( market.address, NO, kitchenSinkFixture.accounts[1]) == 0 assert shareToken.balanceOfMarketOutcome( market.address, NO, kitchenSinkFixture.accounts[2]) == 0
def test_orderCreation(hints, localFixture, categoricalMarket): createOrder = localFixture.contracts['CreateOrder'] for i in range(3900, 4003): createOrder.publicCreateOrder(BID, fix(1), i, categoricalMarket.address, 1, longTo32Bytes(0), longTo32Bytes(0), "7", value=fix(1, i)) worseOrderId = createOrder.publicCreateOrder(BID, fix(1), 4004, categoricalMarket.address, 1, longTo32Bytes(0), longTo32Bytes(0), "7", value=fix(1, 4004)) betterOrderId = createOrder.publicCreateOrder(BID, fix(1), 4006, categoricalMarket.address, 1, longTo32Bytes(0), longTo32Bytes(0), "7", value=fix(1, 4006)) for i in range(4007, 4107): createOrder.publicCreateOrder(BID, fix(1), i, categoricalMarket.address, 1, longTo32Bytes(0), longTo32Bytes(0), "7", value=fix(1, i)) if not hints: with PrintGasUsed(localFixture, "CreateOrder:publicCreateOrder NO Hints", CREATE_ORDER): orderID = createOrder.publicCreateOrder(BID, fix(1), 4005, categoricalMarket.address, 1, longTo32Bytes(0), longTo32Bytes(0), "7", value=fix(1, 4005)) else: with PrintGasUsed(localFixture, "CreateOrder:publicCreateOrder HINTS", CREATE_ORDER): orderID = createOrder.publicCreateOrder(BID, fix(1), 4005, categoricalMarket.address, 1, betterOrderId, worseOrderId, "7", value=fix(1, 4005))
def test_take_best_order_with_shares_escrowed_buy_with_shares_categorical( contractsFixture, cash, categoricalMarket, universe): market = categoricalMarket zeroXTradeToken = contractsFixture.contracts['ZeroXTradeToken'] completeSets = contractsFixture.contracts['CompleteSets'] expirationTime = contractsFixture.contracts['Time'].getTimestamp() + 10000 salt = 5 tradeGroupID = longTo32Bytes(42) firstShareToken = contractsFixture.applySignature('ShareToken', market.getShareToken(0)) secondShareToken = contractsFixture.applySignature('ShareToken', market.getShareToken(1)) thirdShareToken = contractsFixture.applySignature('ShareToken', market.getShareToken(2)) # buy complete sets for both users numTicks = market.getNumTicks() with BuyWithCash(cash, fix('1', numTicks), contractsFixture.accounts[1], "buy complete set"): assert completeSets.publicBuyCompleteSets( market.address, fix(1), sender=contractsFixture.accounts[1]) with BuyWithCash(cash, fix('1', numTicks), contractsFixture.accounts[2], "buy complete set"): assert completeSets.publicBuyCompleteSets( market.address, fix(1), sender=contractsFixture.accounts[2]) assert firstShareToken.balanceOf( contractsFixture.accounts[1]) == firstShareToken.balanceOf( contractsFixture.accounts[2]) == fix(1) assert secondShareToken.balanceOf( contractsFixture.accounts[1]) == secondShareToken.balanceOf( contractsFixture.accounts[2]) == fix(1) assert thirdShareToken.balanceOf( contractsFixture.accounts[1]) == thirdShareToken.balanceOf( contractsFixture.accounts[2]) == fix(1) # create signed order rawZeroXOrderData, orderHash = zeroXTradeToken.createZeroXOrder( ASK, fix(1), 60, market.address, 0, nullAddress, expirationTime, salt, sender=contractsFixture.accounts[1]) signature = signOrder(orderHash, contractsFixture.privateKeys[1]) # fill order with shares and see payouts occur orders = [rawZeroXOrderData] signatures = [signature] totalProceeds = fix(1, numTicks) totalProceeds -= fix( 1, numTicks) / market.getMarketCreatorSettlementFeeDivisor() totalProceeds -= fix(1, numTicks) / universe.getOrCacheReportingFeeDivisor() expectedTester1Payout = totalProceeds * 60 / numTicks expectedTester2Payout = totalProceeds * (numTicks - 60) / numTicks with TokenDelta(cash, expectedTester1Payout, contractsFixture.accounts[1], "Tester 1 Cash delta wrong"): with TokenDelta(cash, expectedTester2Payout, contractsFixture.accounts[2], "Tester 2 Cash delta wrong"): assert zeroXTradeToken.trade( fix(1), nullAddress, tradeGroupID, orders, signatures, sender=contractsFixture.accounts[2]) == 0 assert firstShareToken.balanceOf(contractsFixture.accounts[1]) == 0 assert secondShareToken.balanceOf(contractsFixture.accounts[1]) == fix(1) assert thirdShareToken.balanceOf(contractsFixture.accounts[1]) == fix(1) assert firstShareToken.balanceOf(contractsFixture.accounts[2]) == fix(1) assert secondShareToken.balanceOf(contractsFixture.accounts[2]) == 0 assert thirdShareToken.balanceOf(contractsFixture.accounts[2]) == 0
def test_correct_order_for_same_price(contractsFixture, cash, market): createOrder = contractsFixture.contracts['CreateOrder'] orders = contractsFixture.contracts['Orders'] tradeGroupID = longTo32Bytes(42) nullAddress = longTo32Bytes(0) assert orders.getBestOrderId(BID, market.address, 1) == nullAddress with BuyWithCash(cash, fix('1', '3001'), tester.k1, "create order 1"): orderID1 = createOrder.publicCreateOrder(BID, fix(1), 3001, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), tradeGroupID, False, sender=tester.k1) with BuyWithCash(cash, fix('1', '3000'), tester.k1, "create order 2"): orderID2 = createOrder.publicCreateOrder(BID, fix(1), 3000, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), tradeGroupID, False, sender=tester.k1) with BuyWithCash(cash, fix('2', '3000'), tester.k1, "create order 3"): orderID3 = createOrder.publicCreateOrder(BID, fix(2), 3000, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), tradeGroupID, False, sender=tester.k1) with BuyWithCash(cash, fix('3', '3000'), tester.k1, "create order 4"): orderID4 = createOrder.publicCreateOrder(BID, fix(3), 3000, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), tradeGroupID, False, sender=tester.k1) with BuyWithCash(cash, fix('1', '2999'), tester.k1, "create order 5"): orderID5 = createOrder.publicCreateOrder(BID, fix(1), 2999, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), tradeGroupID, False, sender=tester.k1) with BuyWithCash(cash, fix('4', '3000'), tester.k1, "create order 6"): orderID6 = createOrder.publicCreateOrder(BID, fix(4), 3000, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), tradeGroupID, False, sender=tester.k1) assert orders.getWorseOrderId(orderID1) == orderID2 assert orders.getWorseOrderId(orderID2) == orderID3 assert orders.getWorseOrderId(orderID3) == orderID4 assert orders.getWorseOrderId(orderID4) == orderID6 assert orders.getWorseOrderId(orderID6) == orderID5 assert orders.getWorseOrderId(orderID5) == longTo32Bytes(0) assert orders.getBetterOrderId(orderID2) == orderID1 assert orders.getBetterOrderId(orderID3) == orderID2 assert orders.getBetterOrderId(orderID4) == orderID3 assert orders.getBetterOrderId(orderID5) == orderID6 assert orders.getBetterOrderId(orderID6) == orderID4 assert orders.getBetterOrderId(orderID1) == longTo32Bytes(0)
def test_two_asks_on_books_buy_full_and_partial(contractsFixture, cash, market): zeroXTradeToken = contractsFixture.contracts['ZeroXTradeToken'] expirationTime = contractsFixture.contracts['Time'].getTimestamp() + 10000 salt = 5 tradeGroupID = longTo32Bytes(42) yesShareToken = contractsFixture.applySignature("ShareToken", market.getShareToken(YES)) noShareToken = contractsFixture.applySignature("ShareToken", market.getShareToken(NO)) # create signed order 1 cash.faucet(fix('1', '40'), sender=contractsFixture.accounts[1]) rawZeroXOrderData1, orderHash1 = zeroXTradeToken.createZeroXOrder( ASK, fix(1), 60, market.address, YES, nullAddress, expirationTime, salt, sender=contractsFixture.accounts[1]) signature1 = signOrder(orderHash1, contractsFixture.privateKeys[1]) # create signed order 2 cash.faucet(fix('4', '40'), sender=contractsFixture.accounts[3]) rawZeroXOrderData2, orderHash2 = zeroXTradeToken.createZeroXOrder( ASK, fix(4), 60, market.address, YES, nullAddress, expirationTime, salt, sender=contractsFixture.accounts[3]) signature2 = signOrder(orderHash2, contractsFixture.privateKeys[3]) orders = [rawZeroXOrderData1, rawZeroXOrderData2] signatures = [signature1, signature2] # fill signed orders cash.faucet(fix('3', '60'), sender=contractsFixture.accounts[2]) with TokenDelta(noShareToken, fix(1), contractsFixture.accounts[1], "Creator Shares not received"): with TokenDelta(noShareToken, fix(2), contractsFixture.accounts[3], "Creator Shares not received"): with TokenDelta(yesShareToken, fix(3), contractsFixture.accounts[2], "Taker Shares not received"): with TokenDelta(cash, -fix(1, 40), contractsFixture.accounts[1], "Creator cash not taken"): with TokenDelta(cash, -fix(2, 40), contractsFixture.accounts[3], "Creator cash not taken"): with TokenDelta(cash, -fix(3, 60), contractsFixture.accounts[2], "Taker cash not taken"): assert zeroXTradeToken.trade( fix(3), nullAddress, tradeGroupID, orders, signatures, sender=contractsFixture.accounts[2]) == 0
def test_one_ask_on_books_buy_partial_order(contractsFixture, cash, market, universe): zeroXTradeToken = contractsFixture.contracts['ZeroXTradeToken'] expirationTime = contractsFixture.contracts['Time'].getTimestamp() + 10000 salt = 5 tradeGroupID = longTo32Bytes(42) yesShareToken = contractsFixture.applySignature("ShareToken", market.getShareToken(YES)) noShareToken = contractsFixture.applySignature("ShareToken", market.getShareToken(NO)) # create signed order sender = contractsFixture.accounts[1] senderPrivateKey = contractsFixture.privateKeys[1] cash.faucet(fix('4', '40'), sender=sender) rawZeroXOrderData, orderHash = zeroXTradeToken.createZeroXOrder( ASK, fix(4), 60, market.address, YES, nullAddress, expirationTime, salt, sender=sender) signature = signOrder(orderHash, senderPrivateKey) # fill signed order orderEventLog = { "eventType": 2, "addressData": [ nullAddress, contractsFixture.accounts[1], contractsFixture.accounts[2] ], "uint256Data": [ 60, 0, YES, 0, 0, 0, fix(2), contractsFixture.contracts['Time'].getTimestamp(), 0, 0 ], } orders = [rawZeroXOrderData] signatures = [signature] assert cash.faucet(fix(2, 60), sender=contractsFixture.accounts[2]) with AssertLog(contractsFixture, "OrderEvent", orderEventLog): with TokenDelta(noShareToken, fix(2), sender, "Creator Shares not received"): with TokenDelta(yesShareToken, fix(2), contractsFixture.accounts[2], "Taker Shares not received"): with TokenDelta(cash, -fix(2, 40), sender, "Creator cash not taken"): with TokenDelta(cash, -fix(2, 60), contractsFixture.accounts[2], "Taker cash not taken"): assert zeroXTradeToken.trade( fix(2), nullAddress, tradeGroupID, orders, signatures, sender=contractsFixture.accounts[2]) == 0
def test_basic_trading(contractsFixture, cash, market, universe): zeroXTradeToken = contractsFixture.contracts['ZeroXTradeToken'] expirationTime = contractsFixture.contracts['Time'].getTimestamp() + 10000 salt = 5 # First we'll create a signed order rawZeroXOrderData, orderHash = zeroXTradeToken.createZeroXOrder( BID, fix(2), 60, market.address, YES, nullAddress, expirationTime, salt) signature = signOrder(orderHash, contractsFixture.privateKeys[0]) zeroXExchange = contractsFixture.applySignature("ZeroXExchange", zeroXTradeToken.exchange()) assert zeroXExchange.isValidSignature(orderHash, contractsFixture.accounts[0], signature) fillAmount = fix(1) affiliateAddress = nullAddress tradeGroupId = longTo32Bytes(42) orders = [rawZeroXOrderData] signatures = [signature] yesShareToken = contractsFixture.applySignature("ShareToken", market.getShareToken(YES)) noShareToken = contractsFixture.applySignature("ShareToken", market.getShareToken(NO)) # Lets take the order as another user and confirm assets are traded assert cash.faucet(fix(1, 60)) assert cash.faucet(fix(1, 40), sender=contractsFixture.accounts[1]) with TokenDelta(yesShareToken, fix(1), contractsFixture.accounts[0], "Tester 0 Shares not received"): with TokenDelta(noShareToken, fix(1), contractsFixture.accounts[1], "Tester 1 Shares not received"): with TokenDelta(cash, -fix(1, 60), contractsFixture.accounts[0], "Tester 0 cash not taken"): with TokenDelta(cash, -fix(1, 40), contractsFixture.accounts[1], "Tester 1 cash not taken"): with PrintGasUsed(contractsFixture, "zeroXTradeToken.trade", 0): amountRemaining = zeroXTradeToken.trade( fillAmount, affiliateAddress, tradeGroupId, orders, signatures, sender=contractsFixture.accounts[1]) assert amountRemaining == 0 # Another user can fill the rest. We'll also ask to fill more than is available and see that we get back the remaining amount desired assert cash.faucet(fix(1, 60)) assert cash.faucet(fix(1, 40), sender=contractsFixture.accounts[2]) amountRemaining = zeroXTradeToken.trade( fillAmount + 1, affiliateAddress, tradeGroupId, orders, signatures, sender=contractsFixture.accounts[2]) assert amountRemaining == 1 # The order is completely filled so further attempts to take it will not actuall result in any trade occuring assert cash.faucet(fix(1, 60)) assert cash.faucet(fix(1, 40), sender=contractsFixture.accounts[1]) with TokenDelta(yesShareToken, 0, contractsFixture.accounts[0], "Tester 0 Shares not received"): with TokenDelta(noShareToken, 0, contractsFixture.accounts[1], "Tester 1 Shares not received"): with TokenDelta(cash, 0, contractsFixture.accounts[0], "Tester 0 cash not taken"): with TokenDelta(cash, 0, contractsFixture.accounts[1], "Tester 1 cash not taken"): zeroXTradeToken.trade(fillAmount, affiliateAddress, tradeGroupId, orders, signatures, sender=contractsFixture.accounts[1])
def test_binary_and_claim(contractsFixture, cash, market, universe): createOrder = contractsFixture.contracts["CreateOrder"] fillOrder = contractsFixture.contracts["FillOrder"] profitLoss = contractsFixture.contracts["ProfitLoss"] shareToken = contractsFixture.getShareToken() augurTrading = contractsFixture.contracts['AugurTrading'] test_data = [ { "direction": SHORT, "outcome": YES, "quantity": 10, "price": .65, "position": -10, "avgPrice": .65, "realizedPL": 0, "frozenFunds": 3.5 }, { "direction": LONG, "outcome": YES, "quantity": 3, "price": .58, "position": -7, "avgPrice": .65, "realizedPL": .193, # .21 - .017 from fees "frozenFunds": 2.45 }, { "direction": SHORT, "outcome": YES, "quantity": 13, "price": .62, "position": -20, "avgPrice": .6305, "realizedPL": .193, "frozenFunds": 7.39 }, { "direction": LONG, "outcome": YES, "quantity": 10, "price": .5, "position": -10, "avgPrice": .6305, "realizedPL": 1.448, "frozenFunds": 3.695 }, { "direction": LONG, "outcome": YES, "quantity": 7, "price": .15, "position": -3, "avgPrice": .6305, "realizedPL": 4.8015, "frozenFunds": 1.1085 } ] process_trades(contractsFixture, test_data, cash, market, createOrder, fillOrder, profitLoss) contractsFixture.contracts["Time"].setTimestamp(market.getEndTime() + 1) market.doInitialReport([0, 0, market.getNumTicks()], "", 0) disputeWindow = contractsFixture.applySignature('DisputeWindow', market.getDisputeWindow()) contractsFixture.contracts["Time"].setTimestamp( disputeWindow.getEndTime() + 1) assert market.finalize() # Claim proceeds augurTrading.claimTradingProceeds(market.address, contractsFixture.accounts[1], longTo32Bytes(11)) augurTrading.claimTradingProceeds(market.address, contractsFixture.accounts[2], longTo32Bytes(11)) assert profitLoss.getNetPosition(market.address, contractsFixture.accounts[1], YES) == 0 assert profitLoss.getAvgPrice(market.address, contractsFixture.accounts[1], YES) == 0 assert roughlyEqual( profitLoss.getRealizedProfit(market.address, contractsFixture.accounts[1], YES), -3894 * 10**18) assert profitLoss.getFrozenFunds(market.address, contractsFixture.accounts[1], YES) == 0 assert profitLoss.getNetPosition(market.address, contractsFixture.accounts[2], YES) == 0 assert profitLoss.getAvgPrice(market.address, contractsFixture.accounts[2], YES) == 0 assert roughlyEqual( profitLoss.getRealizedProfit(market.address, contractsFixture.accounts[2], YES), 3693 * 10**18) assert profitLoss.getFrozenFunds(market.address, contractsFixture.accounts[2], YES) == 0
def test_cancelWithSharesInEscrowAsk(contractsFixture, cash, market, universe): completeSets = contractsFixture.contracts['CompleteSets'] createOrder = contractsFixture.contracts['CreateOrder'] cancelOrder = contractsFixture.contracts['CancelOrder'] orders = contractsFixture.contracts['Orders'] yesShareToken = contractsFixture.applySignature('ShareToken', market.getShareToken(YES)) noShareToken = contractsFixture.applySignature('ShareToken', market.getShareToken(NO)) totalProceeds = fix('12', market.getNumTicks()) marketCreatorFee = totalProceeds / market.getMarketCreatorSettlementFeeDivisor( ) reporterFee = totalProceeds / universe.getOrCacheReportingFeeDivisor() completeSetFees = marketCreatorFee + reporterFee # buy complete sets with BuyWithCash(cash, fix('12', market.getNumTicks()), tester.k1, "buy complete set"): assert completeSets.publicBuyCompleteSets(market.address, fix(12), sender=tester.k1) assert cash.balanceOf(tester.a1) == fix('0') assert yesShareToken.balanceOf(tester.a1) == fix(12) assert noShareToken.balanceOf(tester.a1) == fix(12) creatorInitialShares = yesShareToken.balanceOf(tester.a1) marketInitialCash = cash.balanceOf(market.address) marketInitialYesShares = yesShareToken.totalSupply() marketInitialNoShares = noShareToken.totalSupply() # create ASK order for YES with YES shares escrowed assert noShareToken.approve(createOrder.address, fix(12), sender=tester.k1) orderID = createOrder.publicCreateOrder(ASK, fix(12), 6000, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), longTo32Bytes(42), False, nullAddress, sender=tester.k1) assert orderID assert cash.balanceOf(tester.a1) == fix('0') assert yesShareToken.balanceOf(tester.a1) == 0 assert noShareToken.balanceOf(tester.a1) == fix(12) # now cancel the order assert (cancelOrder.cancelOrder( orderID, sender=tester.k1) == 1), "cancelOrder should succeed" assert orders.getAmount(orderID) == 0 assert orders.getPrice(orderID) == 0 assert orders.getOrderCreator(orderID) == longToHexString(0) assert orders.getOrderMoneyEscrowed(orderID) == 0 assert orders.getOrderSharesEscrowed(orderID) == 0 assert orders.getBetterOrderId(orderID) == longTo32Bytes(0) assert orders.getWorseOrderId(orderID) == longTo32Bytes(0) assert ( marketInitialCash == cash.balanceOf(market.address) ), "Market's cash balance should be the same as before the order was placed" assert (creatorInitialShares == yesShareToken.balanceOf( tester.a1)), "Maker's shares should be unchanged" assert (marketInitialYesShares == yesShareToken.totalSupply() ), "Market's yes shares should be unchanged" assert marketInitialNoShares == noShareToken.totalSupply( ), "Market's no shares should be unchanged"
def test_cancelBid(contractsFixture, cash, market, universe): createOrder = contractsFixture.contracts['CreateOrder'] cancelOrder = contractsFixture.contracts['CancelOrder'] orders = contractsFixture.contracts['Orders'] orderType = BID amount = fix(1) fxpPrice = 6000 outcomeID = YES tradeGroupID = longTo32Bytes(42) yesShareToken = contractsFixture.applySignature('ShareToken', market.getShareToken(YES)) noShareToken = contractsFixture.applySignature('ShareToken', market.getShareToken(NO)) creatorInitialShares = yesShareToken.balanceOf(tester.a1) marketInitialCash = cash.balanceOf(market.address) marketInitialYesShares = yesShareToken.totalSupply() marketInitialNoShares = noShareToken.totalSupply() with BuyWithCash(cash, fix(fxpPrice), tester.k1, "The sender didn't get cost deducted for create order"): orderID = createOrder.publicCreateOrder(orderType, amount, fxpPrice, market.address, outcomeID, longTo32Bytes(0), longTo32Bytes(0), tradeGroupID, False, nullAddress, sender=tester.k1) assert orderID, "Order ID should be non-zero" assert orders.getOrderCreator(orderID), "Order should have an owner" orderCanceledLog = { 'orderId': orderID, 'shareToken': yesShareToken.address, 'sender': bytesToHexString(tester.a1), 'orderType': orderType, 'sharesRefund': 0, 'tokenRefund': fix('1', '6000'), } with AssertLog(contractsFixture, 'OrderCanceled', orderCanceledLog): assert (cancelOrder.cancelOrder( orderID, sender=tester.k1) == 1), "cancelOrder should succeed" assert orders.getAmount(orderID) == 0 assert orders.getPrice(orderID) == 0 assert orders.getOrderCreator(orderID) == longToHexString(0) assert orders.getOrderMoneyEscrowed(orderID) == 0 assert orders.getOrderSharesEscrowed(orderID) == 0 assert orders.getBetterOrderId(orderID) == longTo32Bytes(0) assert orders.getWorseOrderId(orderID) == longTo32Bytes(0) assert (cash.balanceOf( tester.a1) == fix('6000')), "Maker's cash balance should be order size" assert ( marketInitialCash == cash.balanceOf(market.address) ), "Market's cash balance should be the same as before the order was placed" assert (creatorInitialShares == yesShareToken.balanceOf( tester.a1)), "Maker's shares should be unchanged" assert (marketInitialYesShares == yesShareToken.totalSupply() ), "Market's yes shares should be unchanged" assert marketInitialNoShares == noShareToken.totalSupply( ), "Market's no shares should be unchanged"
def test_saveOrder(contractsFixture, market): if contractsFixture.paraAugur: return orders = contractsFixture.contracts['Orders'] uints = [fix(10), 5000, NO, 0, fix(10)] bytes32s = [ longTo32Bytes(0), longTo32Bytes(0), stringToBytes("1"), stringToBytes("0") ] orderId1 = orders.testSaveOrder(uints, bytes32s, BID, market.address, contractsFixture.accounts[1], nullAddress) assert (orderId1 != bytearray(32)), "saveOrder wasn't executed successfully" uints = [fix(10), 5000, NO, fix('10', '5000'), 0] bytes32s = [ longTo32Bytes(0), longTo32Bytes(0), stringToBytes("1"), stringToBytes("0") ] orderId2 = orders.testSaveOrder(uints, bytes32s, ASK, market.address, contractsFixture.accounts[2], nullAddress) assert (orderId2 != bytearray(32)), "saveOrder wasn't executed successfully" assert (orders.getAmount(orderId1) == fix(10) ), "amount for order1 should be set to 10" assert (orders.getAmount(orderId2) == fix(10) ), "amount for order2 should be set to 10" assert (orders.getPrice(orderId1) == 5000 ), "price for order1 should be set to 5000 wei" assert (orders.getPrice(orderId2) == 5000 ), "price for order2 should be set to 5000 wei" assert (orders.getOrderCreator(orderId1) == contractsFixture.accounts[1] ), "orderOwner for order1 should be contractsFixture.accounts[1]" assert (orders.getOrderCreator(orderId2) == contractsFixture.accounts[2] ), "orderOwner for order2 should be contractsFixture.accounts[2]" assert orders.getOrderMoneyEscrowed( orderId1) == 0, "money escrowed should be 0" assert orders.getOrderMoneyEscrowed(orderId2) == fix( '10', '5000'), "money escrowed should be 50000 ETH" assert orders.getOrderSharesEscrowed(orderId1) == fix( 10), "shares escrowed should be fix(10)" assert orders.getOrderSharesEscrowed( orderId2) == 0, "shares escrowed should be 0" assert orders.getBetterOrderId(orderId1) == longTo32Bytes( 0), "better order id should be 0" assert orders.getBetterOrderId(orderId2) == longTo32Bytes( 0), "better order id should be 0" assert orders.getWorseOrderId(orderId1) == longTo32Bytes( 0), "worse order id should be 0" assert orders.getWorseOrderId(orderId2) == longTo32Bytes( 0), "worse order id should be 0" assert (orders.testRemoveOrder(orderId1) == 1), "Remove order 1" assert (orders.testRemoveOrder(orderId2) == 1), "Remove order 2"
def test_parametrized(type, outcome, displayPrice, orderSize, creatorYesShares, creatorNoShares, creatorCost, fillSize, fillerYesShares, fillerNoShares, fillerCost, expectMakeRaise, expectedMakerYesShares, expectedMakerNoShares, expectedMakerPayout, expectTakeRaise, expectedFillerYesShares, expectedFillerNoShares, expectedFillerPayout, contractsFixture, cash, market): fixture = contractsFixture # TODO: add support for wider range markets displayPrice = int(float(displayPrice) * market.getNumTicks()) assert displayPrice < market.getNumTicks() assert displayPrice > 0 orderSize = fix(orderSize) creatorYesShares = fix(creatorYesShares) creatorNoShares = fix(creatorNoShares) creatorCost = fix(creatorCost, market.getNumTicks()) fillSize = fix(fillSize) fillerYesShares = fix(fillerYesShares) fillerNoShares = fix(fillerNoShares) fillerCost = fix(fillerCost, market.getNumTicks()) expectedMakerYesShares = fix(expectedMakerYesShares) expectedMakerNoShares = fix(expectedMakerNoShares) expectedMakerPayout = fix(expectedMakerPayout, market.getNumTicks()) expectedFillerYesShares = fix(expectedFillerYesShares) expectedFillerNoShares = fix(expectedFillerNoShares) expectedFillerPayout = fix(expectedFillerPayout, market.getNumTicks()) creatorAddress = tester.a1 creatorKey = tester.k1 fillerAddress = tester.a2 fillerKey = tester.k2 completeSets = fixture.contracts['CompleteSets'] createOrder = fixture.contracts['CreateOrder'] fillOrder = fixture.contracts['FillOrder'] yesShareToken = fixture.applySignature('ShareToken', market.getShareToken(YES)) noShareToken = fixture.applySignature('ShareToken', market.getShareToken(NO)) def acquireShares(outcome, amount, approvalAddress, sender): if amount == 0: return assert completeSets.publicBuyCompleteSets(market.address, amount, sender=sender, value=amount * market.getNumTicks()) if outcome == YES: assert yesShareToken.approve(approvalAddress, amount, sender=sender) assert noShareToken.transfer(0, amount, sender=sender) if outcome == NO: assert yesShareToken.transfer(0, amount, sender=sender) assert noShareToken.approve(approvalAddress, amount, sender=sender) # create order acquireShares(YES, creatorYesShares, createOrder.address, sender=creatorKey) acquireShares(NO, creatorNoShares, createOrder.address, sender=creatorKey) with raises( TransactionFailed) if expectMakeRaise else placeholder_context(): orderID = createOrder.publicCreateOrder(type, orderSize, displayPrice, market.address, outcome, longTo32Bytes(0), longTo32Bytes(0), "42", sender=creatorKey, value=creatorCost) # fill order acquireShares(YES, fillerYesShares, fillOrder.address, sender=fillerKey) acquireShares(NO, fillerNoShares, fillOrder.address, sender=fillerKey) initialMakerETH = fixture.chain.head_state.get_balance(creatorAddress) initialFillerETH = fixture.chain.head_state.get_balance(fillerAddress) with raises( TransactionFailed) if expectTakeRaise else placeholder_context(): fillOrder.publicFillOrder(orderID, fillSize, sender=fillerKey, value=fillerCost) # assert final state assert cash.balanceOf(creatorAddress) == 0 assert cash.balanceOf(fillerAddress) == 0 assert fixture.chain.head_state.get_balance( creatorAddress) == initialMakerETH + expectedMakerPayout assert fixture.chain.head_state.get_balance( fillerAddress) == initialFillerETH + expectedFillerPayout - fillerCost assert yesShareToken.balanceOf(creatorAddress) == expectedMakerYesShares assert yesShareToken.balanceOf(fillerAddress) == expectedFillerYesShares assert noShareToken.balanceOf(creatorAddress) == expectedMakerNoShares assert noShareToken.balanceOf(fillerAddress) == expectedFillerNoShares
def process_trades(contractsFixture, trade_data, cash, market, createOrder, fillOrder, profitLoss, minPrice=0, displayRange=1): for trade in trade_data: onChainLongPrice = int( round((trade['price'] - minPrice) * market.getNumTicks() / displayRange)) onChainShortPrice = int(round(market.getNumTicks() - onChainLongPrice)) direction = BID if trade['direction'] == SHORT else ASK longCost = trade['quantity'] * onChainLongPrice shortCost = trade['quantity'] * onChainShortPrice creatorCost = longCost if direction == BID else shortCost fillerCost = longCost if direction == ASK else shortCost assert cash.faucet(creatorCost, sender=contractsFixture.accounts[1]) orderID = createOrder.publicCreateOrder( direction, trade['quantity'], onChainLongPrice, market.address, trade['outcome'], longTo32Bytes(0), longTo32Bytes(0), longTo32Bytes(42), nullAddress, sender=contractsFixture.accounts[1]) timestamp = contractsFixture.contracts["Augur"].getTimestamp() profitLossChangedLog = { "outcome": trade['outcome'], "timestamp": timestamp, } assert cash.faucet(fillerCost, sender=contractsFixture.accounts[2]) with AssertLog(contractsFixture, "ProfitLossChanged", profitLossChangedLog, skip=0 if direction == BID else 1): fillOrder.publicFillOrder(orderID, trade['quantity'], longTo32Bytes(42), longTo32Bytes(11), sender=contractsFixture.accounts[2]) avgPrice = (trade['avgPrice'] - minPrice) * market.getNumTicks() / displayRange * 10**18 realizedProfit = trade['realizedPL'] * market.getNumTicks( ) / displayRange * 10**18 frozenFunds = trade['frozenFunds'] * market.getNumTicks( ) / displayRange * 10**18 assert profitLoss.getNetPosition(market.address, contractsFixture.accounts[2], trade['outcome']) == trade['position'] assert roughlyEqual( profitLoss.getAvgPrice(market.address, contractsFixture.accounts[2], trade['outcome']), avgPrice) assert roughlyEqual( profitLoss.getRealizedProfit(market.address, contractsFixture.accounts[2], trade['outcome']), realizedProfit) assert roughlyEqual( profitLoss.getFrozenFunds(market.address, contractsFixture.accounts[2], trade['outcome']), frozenFunds)
def test_createOrder_failure(contractsFixture, universe, cash, market): orders = contractsFixture.contracts['Orders'] createOrder = contractsFixture.contracts['CreateOrder'] fillOrder = contractsFixture.contracts['FillOrder'] completeSets = contractsFixture.contracts['CompleteSets'] yesShareToken = contractsFixture.applySignature('ShareToken', market.getShareToken(YES)) noShareToken = contractsFixture.applySignature('ShareToken', market.getShareToken(NO)) with raises(TransactionFailed): createOrder.createOrder(tester.a1, ASK, fix(1), 4000, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), "42", sender=tester.k1) # createOrder exceptions (pre-escrowFunds) with raises(TransactionFailed): createOrder.publicCreateOrder(3, fix(1), 4000, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), "42", sender=tester.k1) # escrowFundsForBid exceptions with raises(TransactionFailed): createOrder.publicCreateOrder(BID, fix(1), 4000, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), "42", sender=tester.k1) with raises(TransactionFailed): createOrder.publicCreateOrder(BID, fix(1), 4000, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), "42", sender=tester.k1) # escrowFundsForAsk exceptions with raises(TransactionFailed): createOrder.publicCreateOrder(ASK, 1, 1, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), "42", sender=tester.k1) with raises(TransactionFailed): createOrder.publicCreateOrder(ASK, fix(1), 4000, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), "42", sender=tester.k1) assert completeSets.publicBuyCompleteSets(market.address, fix(12), sender=tester.k1, value=fix( '12', market.getNumTicks())) with raises(TransactionFailed): createOrder.publicCreateOrder(ASK, fix(1), 12000, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), "42", sender=tester.k1) assert yesShareToken.approve( createOrder.address, fix(12), sender=tester.k1 ) == 1, "Approve createOrder contract to spend shares from the user's account (account 1)" assert yesShareToken.allowance(tester.a1, createOrder.address) == fix( 12 ), "CreateOrder contract's allowance should be equal to the amount approved" with raises(TransactionFailed): createOrder.publicCreateOrder(ASK, fix(1), 4000, tester.a1, YES, longTo32Bytes(0), longTo32Bytes(0), "42", sender=tester.k1) assert createOrder.publicCreateOrder( ASK, fix(1), 4000, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), "42", sender=tester.k1) != 0, "Order ID should be non-zero" # createOrder exceptions (post-escrowFunds) with raises(TransactionFailed): createOrder.publicCreateOrder(ASK, fix(1), 4000, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), "42", sender=tester.k1)
def test_walkOrderList_asks(contractsFixture, market): if contractsFixture.paraAugur: return orders = contractsFixture.contracts['Orders'] outcomeID = 1 order = { "orderID": longTo32Bytes(8), "type": ASK, "amount": fix('1'), "price": 6000, "sender": contractsFixture.accounts[0], "outcome": outcomeID, "moneyEscrowed": fix('6000'), "sharesEscrowed": 0, "betterOrderID": longTo32Bytes(0), "worseOrderID": longTo32Bytes(0), "tradeGroupID": stringToBytes("0"), } uints = [ order["amount"], order["price"], order["outcome"], order["moneyEscrowed"], order["sharesEscrowed"] ] bytes32s = [ order["betterOrderID"], order["worseOrderID"], order["tradeGroupID"], stringToBytes("0") ] orderId8 = orders.testSaveOrder(uints, bytes32s, order["type"], market.address, order["sender"]) assert (orderId8 != bytearray(32)), "Save order" bestOrderID = orders.getBestOrderId(ASK, market.address, outcomeID, nullAddress) worstOrderID = orders.getWorstOrderId(ASK, market.address, outcomeID, nullAddress) assert (bestOrderID == orderId8) assert (worstOrderID == orderId8) # walk down order list starting from bestOrderID assert (orders.descendOrderList( ASK, 6000, bestOrderID) == [orderId8, longTo32Bytes(0)]) assert (orders.descendOrderList( ASK, 5900, bestOrderID) == [longTo32Bytes(0), orderId8]) assert (orders.descendOrderList( ASK, 6100, bestOrderID) == [orderId8, longTo32Bytes(0)]) assert (orders.descendOrderList( ASK, 5800, bestOrderID) == [longTo32Bytes(0), orderId8]) # walk up order list starting from worstOrderID assert (orders.ascendOrderList( ASK, 6000, worstOrderID) == [orderId8, longTo32Bytes(0)]) assert (orders.ascendOrderList( ASK, 5900, worstOrderID) == [longTo32Bytes(0), orderId8]) assert (orders.ascendOrderList( ASK, 6100, worstOrderID) == [orderId8, longTo32Bytes(0)]) assert (orders.ascendOrderList( ASK, 5800, worstOrderID) == [longTo32Bytes(0), orderId8]) order = { "orderID": longTo32Bytes(9), "type": ASK, "amount": fix('1'), "price": 5900, "sender": contractsFixture.accounts[0], "outcome": outcomeID, "moneyEscrowed": fix('5900'), "sharesEscrowed": 0, "betterOrderID": longTo32Bytes(0), "worseOrderID": longTo32Bytes(0), "tradeGroupID": stringToBytes("0"), } uints = [ order["amount"], order["price"], order["outcome"], order["moneyEscrowed"], order["sharesEscrowed"] ] bytes32s = [ order["betterOrderID"], order["worseOrderID"], order["tradeGroupID"], stringToBytes("0") ] orderId9 = orders.testSaveOrder(uints, bytes32s, order["type"], market.address, order["sender"]) assert (orderId9 != bytearray(32)), "Save order" bestOrderID = orders.getBestOrderId(ASK, market.address, outcomeID, nullAddress) worstOrderID = orders.getWorstOrderId(ASK, market.address, outcomeID, nullAddress) assert (bestOrderID == orderId9) assert (worstOrderID == orderId8) # walk down order list starting from bestOrderID assert (orders.descendOrderList( ASK, 6000, bestOrderID) == [orderId8, longTo32Bytes(0)]) assert (orders.descendOrderList(ASK, 5900, bestOrderID) == [orderId9, orderId8]) assert (orders.descendOrderList( ASK, 6100, bestOrderID) == [orderId8, longTo32Bytes(0)]) assert (orders.descendOrderList( ASK, 5800, bestOrderID) == [longTo32Bytes(0), orderId9]) assert (orders.descendOrderList(ASK, 5950, bestOrderID) == [orderId9, orderId8]) # walk up order list starting from worstOrderID assert (orders.ascendOrderList( ASK, 6000, worstOrderID) == [orderId8, longTo32Bytes(0)]) assert (orders.ascendOrderList(ASK, 5900, worstOrderID) == [orderId9, orderId8]) assert (orders.ascendOrderList( ASK, 6100, worstOrderID) == [orderId8, longTo32Bytes(0)]) assert (orders.ascendOrderList( ASK, 5800, worstOrderID) == [longTo32Bytes(0), orderId9]) assert (orders.ascendOrderList(ASK, 5950, bestOrderID) == [orderId9, orderId8]) order = { "orderID": longTo32Bytes(10), "type": ASK, "amount": fix('1'), "price": 5950, "sender": contractsFixture.accounts[0], "outcome": outcomeID, "moneyEscrowed": fix('5950'), "sharesEscrowed": 0, "betterOrderID": longTo32Bytes(0), "worseOrderID": longTo32Bytes(0), "tradeGroupID": stringToBytes("0"), } uints = [ order["amount"], order["price"], order["outcome"], order["moneyEscrowed"], order["sharesEscrowed"] ] bytes32s = [ order["betterOrderID"], order["worseOrderID"], order["tradeGroupID"], stringToBytes("0") ] orderId10 = orders.testSaveOrder(uints, bytes32s, order["type"], market.address, order["sender"]) assert (orderId10 != bytearray(32)), "Save order" bestOrderID = orders.getBestOrderId(ASK, market.address, outcomeID, nullAddress) worstOrderID = orders.getWorstOrderId(ASK, market.address, outcomeID, nullAddress) assert (bestOrderID == orderId9) assert (worstOrderID == orderId8) # walk down order list starting from bestOrderID assert (orders.descendOrderList( ASK, 6000, bestOrderID) == [orderId8, longTo32Bytes(0)]) assert (orders.descendOrderList(ASK, 5900, bestOrderID) == [orderId9, orderId10]) assert (orders.descendOrderList( ASK, 6100, bestOrderID) == [orderId8, longTo32Bytes(0)]) assert (orders.descendOrderList( ASK, 5800, bestOrderID) == [longTo32Bytes(0), orderId9]) # walk up order list starting from worstOrderID assert (orders.ascendOrderList( ASK, 6000, worstOrderID) == [orderId8, longTo32Bytes(0)]) assert (orders.ascendOrderList(ASK, 5900, worstOrderID) == [orderId9, orderId10]) assert (orders.ascendOrderList( ASK, 6100, worstOrderID) == [orderId8, longTo32Bytes(0)]) assert (orders.ascendOrderList( ASK, 5800, worstOrderID) == [longTo32Bytes(0), orderId9]) assert (orders.testRemoveOrder(orderId8) == 1), "Remove order 8" assert (orders.testRemoveOrder(orderId9) == 1), "Remove order 9" assert (orders.testRemoveOrder(orderId10) == 1), "Remove order 10"
def test_orderBidSorting(where, orderType, hints, contractsFixture, market): if contractsFixture.paraAugur: return orders = contractsFixture.contracts['Orders'] # setup pre-existing orders worstPrice = 6000 if orderType == BID else 6600 bestPrice = 6600 if orderType == BID else 6000 uints = [fix('1'), worstPrice, YES, worstPrice, 0] bytes32s = [ longTo32Bytes(0), longTo32Bytes(0), stringToBytes("0"), stringToBytes("0") ] worstOrderId = orders.testSaveOrder(uints, bytes32s, orderType, market.address, contractsFixture.accounts[0], nullAddress) uints = [fix('1'), bestPrice, YES, bestPrice, 0] bytes32s = [ longTo32Bytes(0), longTo32Bytes(0), stringToBytes("0"), stringToBytes("0") ] bestOrderId = orders.testSaveOrder(uints, bytes32s, orderType, market.address, contractsFixture.accounts[0], nullAddress) # validate that our setup went smoothly assert orders.getBestOrderId(orderType, market.address, YES, nullAddress) == bestOrderId assert orders.getWorstOrderId(orderType, market.address, YES, nullAddress) == worstOrderId assert orders.getWorseOrderId(bestOrderId) == worstOrderId assert orders.getWorseOrderId(worstOrderId) == longTo32Bytes(0) assert orders.getBetterOrderId(worstOrderId) == bestOrderId assert orders.getBetterOrderId(bestOrderId) == longTo32Bytes(0) # insert our new order if where == 'best': orderPrice = 6700 if orderType == BID else 5900 betterOrderId = longTo32Bytes(0) worseOrderId = bestOrderId if hints else longTo32Bytes(0) if where == 'middle': orderPrice = 6300 betterOrderId = bestOrderId if hints else longTo32Bytes(0) worseOrderId = worstOrderId if hints else longTo32Bytes(0) if where == 'worst': orderPrice = 5900 if orderType == BID else 6700 betterOrderId = worstOrderId if hints else longTo32Bytes(0) worseOrderId = longTo32Bytes(0) uints = [fix('1'), orderPrice, YES, orderPrice, 0] bytes32s = [ betterOrderId, worseOrderId, stringToBytes("0"), stringToBytes("0") ] insertedOrder = orders.testSaveOrder(uints, bytes32s, orderType, market.address, contractsFixture.accounts[0], nullAddress) # validate the new order was inserted correctly assert orders.getBetterOrderId(insertedOrder) == longTo32Bytes( 0) if where == 'best' else bestOrderId assert orders.getWorseOrderId(insertedOrder) == longTo32Bytes( 0) if where == 'worst' else worstOrderId assert orders.getBestOrderId( orderType, market.address, YES, nullAddress) == insertedOrder if where == 'best' else bestOrderId assert orders.getWorstOrderId( orderType, market.address, YES, nullAddress) == insertedOrder if where == 'worst' else worstOrderId
def process_trades(contractsFixture, trade_data, cash, market, createOrder, fillOrder, profitLoss, minPrice=0, displayRange=1): for trade in trade_data: onChainLongPrice = int( round((trade['price'] - minPrice) * market.getNumTicks() / displayRange)) onChainShortPrice = int(round(market.getNumTicks() - onChainLongPrice)) direction = BID if trade['direction'] == SHORT else ASK longCost = trade['quantity'] * onChainLongPrice shortCost = trade['quantity'] * onChainShortPrice creatorCost = longCost if direction == BID else shortCost fillerCost = longCost if direction == ASK else shortCost assert cash.faucet(creatorCost, sender=tester.k1) orderID = createOrder.publicCreateOrder(direction, trade['quantity'], onChainLongPrice, market.address, trade['outcome'], longTo32Bytes(0), longTo32Bytes(0), longTo32Bytes(42), False, nullAddress, sender=tester.k1) avgPrice = int( round((trade['avgPrice'] - minPrice) * market.getNumTicks() / displayRange)) realizedProfit = int( round(trade['realizedPL'] * market.getNumTicks() / displayRange)) frozenFunds = int( round(trade['frozenFunds'] * market.getNumTicks() / displayRange)) timestamp = contractsFixture.contracts["Augur"].getTimestamp() profitLossChangedLog = { "outcome": trade['outcome'], "netPosition": trade['position'], "avgPrice": avgPrice, "realizedProfit": realizedProfit, "frozenFunds": frozenFunds, "timestamp": timestamp, } assert cash.faucet(fillerCost, sender=tester.k2) with AssertLog(contractsFixture, "ProfitLossChanged", profitLossChangedLog, skip=0 if direction == BID else 1): fillOrder.publicFillOrder(orderID, trade['quantity'], longTo32Bytes(42), False, nullAddress, sender=tester.k2) assert profitLoss.getNetPosition(market.address, tester.a2, trade['outcome']) == trade['position'] assert profitLoss.getAvgPrice(market.address, tester.a2, trade['outcome']) == avgPrice assert profitLoss.getRealizedProfit(market.address, tester.a2, trade['outcome']) == realizedProfit assert profitLoss.getFrozenFunds(market.address, tester.a2, trade['outcome']) == frozenFunds
def test_fees_from_trades(finalized, invalid, contractsFixture, cash, market, universe): zeroXTradeToken = contractsFixture.contracts['ZeroXTradeToken'] completeSets = contractsFixture.contracts['CompleteSets'] expirationTime = contractsFixture.contracts['Time'].getTimestamp() + 10000 salt = 5 tradeGroupID = longTo32Bytes(42) completeSets = contractsFixture.contracts['CompleteSets'] firstShareToken = contractsFixture.applySignature('ShareToken', market.getShareToken(0)) secondShareToken = contractsFixture.applySignature('ShareToken', market.getShareToken(1)) if finalized: if invalid: contractsFixture.contracts["Time"].setTimestamp( market.getDesignatedReportingEndTime() + 1) market.doInitialReport([market.getNumTicks(), 0, 0], "", 0) else: proceedToNextRound(contractsFixture, market) disputeWindow = contractsFixture.applySignature( 'DisputeWindow', market.getDisputeWindow()) contractsFixture.contracts["Time"].setTimestamp( disputeWindow.getEndTime() + 1) assert market.finalize() # buy complete sets for both users numTicks = market.getNumTicks() with BuyWithCash(cash, fix('1', numTicks), contractsFixture.accounts[1], "buy complete set"): assert completeSets.publicBuyCompleteSets( market.address, fix(1), sender=contractsFixture.accounts[1]) with BuyWithCash(cash, fix('1', numTicks), contractsFixture.accounts[2], "buy complete set"): assert completeSets.publicBuyCompleteSets( market.address, fix(1), sender=contractsFixture.accounts[2]) assert firstShareToken.balanceOf( contractsFixture.accounts[1]) == firstShareToken.balanceOf( contractsFixture.accounts[2]) == fix(1) assert secondShareToken.balanceOf( contractsFixture.accounts[1]) == secondShareToken.balanceOf( contractsFixture.accounts[2]) == fix(1) # create order with shares rawZeroXOrderData, orderHash = zeroXTradeToken.createZeroXOrder( ASK, fix(1), 60, market.address, 0, nullAddress, expirationTime, salt, sender=contractsFixture.accounts[1]) signature = signOrder(orderHash, contractsFixture.privateKeys[1]) orders = [rawZeroXOrderData] signatures = [signature] expectedAffiliateFees = fix(100) / 400 cash.faucet(fix(60), sender=contractsFixture.accounts[2]) # Trade and specify an affiliate address. if finalized: if invalid: nextDisputeWindowAddress = universe.getOrCreateNextDisputeWindow( False) totalFees = fix(100) / 50 # Market fees + reporting fees with TokenDelta(cash, totalFees, nextDisputeWindowAddress, "Dispute Window did not recieve the correct fees"): assert zeroXTradeToken.trade( fix(1), contractsFixture.accounts[3], tradeGroupID, orders, signatures, sender=contractsFixture.accounts[2]) == 0 else: with TokenDelta(cash, expectedAffiliateFees, contractsFixture.accounts[3], "Affiliate did not recieve the correct fees"): assert zeroXTradeToken.trade( fix(1), contractsFixture.accounts[3], tradeGroupID, orders, signatures, sender=contractsFixture.accounts[2]) == 0 else: assert zeroXTradeToken.trade(fix(1), contractsFixture.accounts[3], tradeGroupID, orders, signatures, sender=contractsFixture.accounts[2]) == 0 assert firstShareToken.balanceOf(contractsFixture.accounts[1]) == 0 assert secondShareToken.balanceOf(contractsFixture.accounts[1]) == fix(1) # The second user sold the complete set they ended up holding from this transaction, which extracts fees assert firstShareToken.balanceOf(contractsFixture.accounts[2]) == fix(1) assert secondShareToken.balanceOf(contractsFixture.accounts[2]) == fix(0) if not finalized: # We can confirm that the 3rd test account has an affiliate fee balance of 25% of the market creator fee 1% taken from the 1 ETH order assert market.affiliateFeesAttoCash( contractsFixture.accounts[3]) == expectedAffiliateFees # The affiliate can withdraw their fees only after the market is finalized as valid with raises(TransactionFailed): market.withdrawAffiliateFees(contractsFixture.accounts[3]) if invalid: contractsFixture.contracts["Time"].setTimestamp( market.getDesignatedReportingEndTime() + 1) market.doInitialReport([market.getNumTicks(), 0, 0], "", 0) else: proceedToNextRound(contractsFixture, market) disputeWindow = contractsFixture.applySignature( 'DisputeWindow', market.getDisputeWindow()) contractsFixture.contracts["Time"].setTimestamp( disputeWindow.getEndTime() + 1) totalCollectedFees = market.marketCreatorFeesAttoCash( ) + market.totalAffiliateFeesAttoCash() + market.validityBondAttoCash( ) nextDisputeWindowAddress = universe.getOrCreateNextDisputeWindow(False) nextDisputeWindowBalanceBeforeFinalization = cash.balanceOf( universe.getOrCreateNextDisputeWindow(False)) assert market.finalize() if invalid: with raises(TransactionFailed): market.withdrawAffiliateFees(contractsFixture.accounts[3]) assert cash.balanceOf( universe.getOrCreateNextDisputeWindow(False) ) == nextDisputeWindowBalanceBeforeFinalization + totalCollectedFees else: with TokenDelta(cash, expectedAffiliateFees, contractsFixture.accounts[3], "Affiliate did not recieve the correct fees"): market.withdrawAffiliateFees(contractsFixture.accounts[3]) # No more fees can be withdrawn if not invalid: with TokenDelta(cash, 0, contractsFixture.accounts[3], "Affiliate double received fees"): market.withdrawAffiliateFees(contractsFixture.accounts[3])
def test_publicCreateOrder_List_Logic(contractsFixture, cash, market): orders = contractsFixture.contracts['Orders'] createOrder = contractsFixture.contracts['CreateOrder'] orderID_10 = createOrder.publicCreateOrder(BID, fix(1), 4010, market.address, 1, longTo32Bytes(0), longTo32Bytes(0), "1", value=fix(1, 4010)) orderID_8 = createOrder.publicCreateOrder(BID, fix(1), 4008, market.address, 1, longTo32Bytes(0), longTo32Bytes(0), "2", value=fix(1, 4008)) orderID_6 = createOrder.publicCreateOrder(BID, fix(1), 4006, market.address, 1, longTo32Bytes(0), longTo32Bytes(0), "3", value=fix(1, 4006)) orderID_2 = createOrder.publicCreateOrder(BID, fix(1), 4002, market.address, 1, longTo32Bytes(0), longTo32Bytes(0), "4", value=fix(1, 4002)) orderID_1 = createOrder.publicCreateOrder(BID, fix(1), 4001, market.address, 1, longTo32Bytes(0), longTo32Bytes(0), "5", value=fix(1, 4001)) orderID_7 = createOrder.publicCreateOrder(BID, fix(1), 4007, market.address, 1, orderID_10, orderID_1, "6", value=fix(1, 4007)) assert orderID_7 assert orders.getBetterOrderId(orderID_7) == orderID_8 assert orders.getWorseOrderId(orderID_7) == orderID_6 orderID_5 = createOrder.publicCreateOrder(BID, fix(1), 4005, market.address, 1, orderID_6, orderID_1, "7", value=fix(1, 4005)) assert orderID_5 assert orders.getBetterOrderId(orderID_5) == orderID_6 assert orders.getWorseOrderId(orderID_5) == orderID_2 orderID_3 = createOrder.publicCreateOrder(BID, fix(1), 4003, market.address, 1, orderID_5, orderID_2, "8", value=fix(1, 4003)) assert orderID_3 assert orders.getBetterOrderId(orderID_3) == orderID_5 assert orders.getWorseOrderId(orderID_3) == orderID_2
def execute(fixture, snapshot, universe, market, orderType, orderSize, orderPrice, orderOutcome, creatorLongShares, creatorShortShares, creatorTokens, fillerLongShares, fillerShortShares, fillerTokens, expectedMakerLongShares, expectedMakerShortShares, expectedMakerTokens, expectedFillerLongShares, expectedFillerShortShares, expectedFillerTokens, numTicks): def acquireLongShares(outcome, amount, approvalAddress, sender): if amount == 0: return shareToken = fixture.applySignature('ShareToken', market.getShareToken(outcome)) completeSets = fixture.contracts['CompleteSets'] createOrder = fixture.contracts['CreateOrder'] fillOrder = fixture.contracts['FillOrder'] ethRequired = amount * numTicks assert completeSets.publicBuyCompleteSets(market.address, amount, sender = sender, value = ethRequired) for otherOutcome in range(0, market.getNumberOfOutcomes()): if otherOutcome == outcome: continue otherShareToken = fixture.applySignature('ShareToken', market.getShareToken(otherOutcome)) assert otherShareToken.transfer(0, amount, sender = sender) def acquireShortShareSet(outcome, amount, approvalAddress, sender): if amount == 0: return shareToken = fixture.applySignature('ShareToken', market.getShareToken(outcome)) completeSets = fixture.contracts['CompleteSets'] createOrder = fixture.contracts['CreateOrder'] fillOrder = fixture.contracts['FillOrder'] ethRequired = amount * numTicks assert completeSets.publicBuyCompleteSets(market.address, amount, sender = sender, value = ethRequired) assert shareToken.transfer(0, amount, sender = sender) for otherOutcome in range(0, market.getNumberOfOutcomes()): if otherOutcome == outcome: continue otherShareToken = fixture.applySignature('ShareToken', market.getShareToken(otherOutcome)) fixture.resetToSnapshot(snapshot) legacyReputationToken = fixture.contracts['LegacyReputationToken'] legacyReputationToken.faucet(long(11 * 10**6 * 10**18)) fixture.chain.head_state.timestamp += 15000 orders = fixture.contracts['Orders'] createOrder = fixture.contracts['CreateOrder'] fillOrder = fixture.contracts['FillOrder'] completeSets = fixture.contracts['CompleteSets'] creatorAddress = tester.a1 fillerAddress = tester.a2 creatorKey = tester.k1 fillerKey = tester.k2 # Set creator/filler balances creatorBalance = fixture.chain.head_state.get_balance(creatorAddress) fillerBalance = fixture.chain.head_state.get_balance(fillerAddress) # Acquire shares for creator creatorEthRequiredLong = 0 if creatorLongShares == 0 else creatorLongShares * numTicks creatorEthRequiredShort = 0 if creatorShortShares == 0 else creatorShortShares * numTicks acquireLongShares(orderOutcome, creatorLongShares, createOrder.address, sender = creatorKey) acquireShortShareSet(orderOutcome, creatorShortShares, createOrder.address, sender = creatorKey) assert fixture.chain.head_state.get_balance(creatorAddress) == creatorBalance - creatorEthRequiredLong - creatorEthRequiredShort assert fixture.chain.head_state.get_balance(fillerAddress) == fillerBalance creatorBalance = fixture.chain.head_state.get_balance(creatorAddress) fillerBalance = fixture.chain.head_state.get_balance(fillerAddress) # Create order orderId = createOrder.publicCreateOrder(orderType, orderSize, orderPrice, market.address, orderOutcome, longTo32Bytes(0), longTo32Bytes(0), "42", sender = creatorKey, value = creatorTokens) assert fixture.chain.head_state.get_balance(creatorAddress) == creatorBalance - creatorTokens assert fixture.chain.head_state.get_balance(fillerAddress) == fillerBalance creatorBalance = fixture.chain.head_state.get_balance(creatorAddress) fillerBalance = fixture.chain.head_state.get_balance(fillerAddress) # Validate order assert orders.getAmount(orderId) == orderSize assert orders.getPrice(orderId) == orderPrice assert orders.getOrderCreator(orderId) == bytesToHexString(creatorAddress) assert orders.getOrderMoneyEscrowed(orderId) == creatorTokens assert orders.getOrderSharesEscrowed(orderId) == creatorLongShares or creatorShortShares # Acquire shares for filler fillerEthRequiredLong = 0 if fillerLongShares == 0 else fillerLongShares * numTicks fillerEthRequiredShort = 0 if fillerShortShares == 0 else fillerShortShares * numTicks acquireLongShares(orderOutcome, fillerLongShares, fillOrder.address, sender = fillerKey) acquireShortShareSet(orderOutcome, fillerShortShares, fillOrder.address, sender = fillerKey) assert fixture.chain.head_state.get_balance(creatorAddress) == creatorBalance assert fixture.chain.head_state.get_balance(fillerAddress) == fillerBalance - fillerEthRequiredLong - fillerEthRequiredShort creatorBalance = fixture.chain.head_state.get_balance(creatorAddress) fillerBalance = fixture.chain.head_state.get_balance(fillerAddress) # Fill order remaining = fillOrder.publicFillOrder(orderId, orderSize, "42", sender = fillerKey, value = fillerTokens) assert not remaining # Assert final state assert fixture.chain.head_state.get_balance(creatorAddress) == creatorBalance + expectedMakerTokens assert fixture.chain.head_state.get_balance(fillerAddress) == fillerBalance - fillerTokens + expectedFillerTokens for outcome in range(0, market.getNumberOfOutcomes()): shareToken = fixture.applySignature('ShareToken', market.getShareToken(outcome)) if outcome == orderOutcome: assert shareToken.balanceOf(creatorAddress) == expectedMakerLongShares assert shareToken.balanceOf(fillerAddress) == expectedFillerLongShares else: assert shareToken.balanceOf(creatorAddress) == expectedMakerShortShares assert shareToken.balanceOf(fillerAddress) == expectedFillerShortShares
def test_frozen_funds(contractsFixture, cash, market, universe): createOrder = contractsFixture.contracts["CreateOrder"] fillOrder = contractsFixture.contracts["FillOrder"] profitLoss = contractsFixture.contracts["ProfitLoss"] orders = contractsFixture.contracts["Orders"] cancelOrder = contractsFixture.contracts["CancelOrder"] amount = fix(1) price = 10 cost = fix(10) outcome = 1 # Create Order profitLossChangedLog = { "outcome": outcome, "netPosition": 0, "avgPrice": 0, "realizedProfit": 0, "frozenFunds": cost, } assert cash.faucet(cost) with AssertLog(contractsFixture, "ProfitLossChanged", profitLossChangedLog): orderID = createOrder.publicCreateOrder(BID, amount, price, market.address, outcome, longTo32Bytes(0), longTo32Bytes(0), longTo32Bytes(42), False, nullAddress) assert profitLoss.getFrozenFunds(market.address, tester.a0, outcome) == cost # Change order price newPrice = 9 newCost = fix(9) profitLossChangedLog = { "outcome": outcome, "netPosition": 0, "avgPrice": 0, "realizedProfit": 0, "frozenFunds": newCost, } with AssertLog(contractsFixture, "ProfitLossChanged", profitLossChangedLog): orders.setOrderPrice(orderID, newPrice, longTo32Bytes(0), longTo32Bytes(0)) assert profitLoss.getFrozenFunds(market.address, tester.a0, outcome) == newCost # Cancel Order profitLossChangedLog = { "outcome": outcome, "netPosition": 0, "avgPrice": 0, "realizedProfit": 0, "frozenFunds": 0, } with AssertLog(contractsFixture, "ProfitLossChanged", profitLossChangedLog): orderID = cancelOrder.cancelOrder(orderID) assert profitLoss.getFrozenFunds(market.address, tester.a0, outcome) == 0 # Create Order orderID = createOrder.publicCreateOrder(BID, amount, price, market.address, outcome, longTo32Bytes(0), longTo32Bytes(0), longTo32Bytes(42), False, nullAddress) # Fill Order profitLossChangedLog = { "outcome": outcome, "netPosition": amount, "avgPrice": 10, "realizedProfit": 0, "frozenFunds": cost, } fillerCost = (market.getNumTicks() - price) * amount assert cash.faucet(fillerCost, sender=tester.k2) with AssertLog(contractsFixture, "ProfitLossChanged", profitLossChangedLog, skip=1): fillOrder.publicFillOrder(orderID, amount, longTo32Bytes(42), False, nullAddress, sender=tester.k2) assert profitLoss.getFrozenFunds(market.address, tester.a0, outcome) == cost # Create new Order newOutcome = 2 assert cash.faucet(cost) orderID = createOrder.publicCreateOrder(BID, amount, price, market.address, newOutcome, longTo32Bytes(0), longTo32Bytes(0), longTo32Bytes(42), False, nullAddress) # Fill own Order. This should make FF 0 profitLossChangedLog = { "outcome": newOutcome, "netPosition": 0, "avgPrice": 0, "realizedProfit": 0, "frozenFunds": 0, } fillerCost = (market.getNumTicks() - price) * amount assert cash.faucet(fillerCost) with AssertLog(contractsFixture, "ProfitLossChanged", profitLossChangedLog, skip=2): fillOrder.publicFillOrder(orderID, amount, longTo32Bytes(42), False, nullAddress) assert profitLoss.getFrozenFunds(market.address, tester.a0, newOutcome) == 0
def test_no_orphans_when_same_price(contractsFixture, cash, market, universe): createOrder = contractsFixture.contracts['CreateOrder'] orders = contractsFixture.contracts['Orders'] tradeGroupID = longTo32Bytes(42) nullAddress = longTo32Bytes(0) # create orders assert orders.getBestOrderId(BID, market.address, 1) == nullAddress with BuyWithCash(cash, fix('1', '3001'), tester.k1, "create order 1"): orderID1 = createOrder.publicCreateOrder(BID, fix(1), 3001, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), tradeGroupID, False, sender=tester.k1) with BuyWithCash(cash, fix('1', '3000'), tester.k1, "create order 2"): orderID2 = createOrder.publicCreateOrder(BID, fix(1), 3000, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), tradeGroupID, False, sender=tester.k1) with BuyWithCash(cash, fix('2', '3000'), tester.k1, "create order 3"): orderID3 = createOrder.publicCreateOrder(BID, fix(2), 3000, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), tradeGroupID, False, sender=tester.k1) with BuyWithCash(cash, fix('3', '3000'), tester.k1, "create order 4"): orderID4 = createOrder.publicCreateOrder(BID, fix(3), 3000, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), tradeGroupID, False, sender=tester.k1) assert orders.getWorseOrderId(orderID1) == orderID2 assert orders.getWorseOrderId(orderID2) == orderID3 assert orders.getWorseOrderId(orderID3) == orderID4 assert orders.getWorseOrderId(orderID4) == longTo32Bytes(0) assert orders.getBetterOrderId(orderID2) == orderID1 assert orders.getBetterOrderId(orderID3) == orderID2 assert orders.getBetterOrderId(orderID4) == orderID3 assert orders.getBetterOrderId(orderID1) == longTo32Bytes(0)
def test_walkOrderList_bids(contractsFixture, market): if contractsFixture.paraAugur: return orders = contractsFixture.contracts['Orders'] outcomeID = 1 order = { "orderID": longTo32Bytes(5), "type": BID, "amount": fix('1'), "price": 6000, "sender": contractsFixture.accounts[0], "outcome": outcomeID, "moneyEscrowed": fix('6000'), "sharesEscrowed": 0, "betterOrderID": longTo32Bytes(0), "worseOrderID": longTo32Bytes(0), "tradeGroupID": stringToBytes("0") } uints = [ order["amount"], order["price"], order["outcome"], order["moneyEscrowed"], order["sharesEscrowed"] ] bytes32s = [ order["betterOrderID"], order["worseOrderID"], order["tradeGroupID"], stringToBytes("0") ] orderId5 = orders.testSaveOrder(uints, bytes32s, order["type"], market.address, order["sender"]) assert (orderId5 != bytearray(32)), "Save order" bestOrderID = orders.getBestOrderId(BID, market.address, outcomeID, nullAddress) worstOrderID = orders.getWorstOrderId(BID, market.address, outcomeID, nullAddress) assert (bestOrderID == orderId5) assert (worstOrderID == orderId5) # walk down order list starting from bestOrderID assert (orders.descendOrderList( BID, 6000, bestOrderID) == [orderId5, longTo32Bytes(0)]) assert (orders.descendOrderList( BID, 5900, bestOrderID) == [orderId5, longTo32Bytes(0)]) assert (orders.descendOrderList( BID, 6100, bestOrderID) == [longTo32Bytes(0), orderId5]) assert (orders.descendOrderList( BID, 5800, bestOrderID) == [orderId5, longTo32Bytes(0)]) assert (orders.descendOrderList( BID, 5950, bestOrderID) == [orderId5, longTo32Bytes(0)]) # walk up order list starting from worstOrderID assert (orders.ascendOrderList( BID, 6000, worstOrderID) == [orderId5, longTo32Bytes(0)]) assert (orders.ascendOrderList( BID, 5900, worstOrderID) == [orderId5, longTo32Bytes(0)]) assert (orders.ascendOrderList( BID, 6100, worstOrderID) == [longTo32Bytes(0), orderId5]) assert (orders.ascendOrderList( BID, 5800, worstOrderID) == [orderId5, longTo32Bytes(0)]) assert (orders.ascendOrderList( BID, 5950, bestOrderID) == [orderId5, longTo32Bytes(0)]) order = { "orderID": longTo32Bytes(6), "type": BID, "amount": fix('1'), "price": 5900, "sender": contractsFixture.accounts[0], "outcome": outcomeID, "moneyEscrowed": fix('5900'), "sharesEscrowed": 0, "betterOrderID": longTo32Bytes(0), "worseOrderID": longTo32Bytes(0), "tradeGroupID": stringToBytes("0"), } uints = [ order["amount"], order["price"], order["outcome"], order["moneyEscrowed"], order["sharesEscrowed"] ] bytes32s = [ order["betterOrderID"], order["worseOrderID"], order["tradeGroupID"], stringToBytes("0") ] orderId6 = orders.testSaveOrder(uints, bytes32s, order["type"], market.address, order["sender"]) assert (orderId6 != bytearray(32)), "Save order" bestOrderID = orders.getBestOrderId(BID, market.address, outcomeID, nullAddress) worstOrderID = orders.getWorstOrderId(BID, market.address, outcomeID, nullAddress) assert (bestOrderID == orderId5) assert (worstOrderID == orderId6) # walk down order list starting from bestOrderID assert (orders.descendOrderList(BID, 6000, bestOrderID) == [orderId5, orderId6]) assert (orders.descendOrderList( BID, 5900, bestOrderID) == [orderId6, longTo32Bytes(0)]) assert (orders.descendOrderList( BID, 6100, bestOrderID) == [longTo32Bytes(0), orderId5]) assert (orders.descendOrderList( BID, 5800, bestOrderID) == [orderId6, longTo32Bytes(0)]) assert (orders.descendOrderList(BID, 5950, bestOrderID) == [orderId5, orderId6]) # walk up order list starting from worstOrderID assert (orders.ascendOrderList(BID, 6000, worstOrderID) == [orderId5, orderId6]) assert (orders.ascendOrderList( BID, 5900, worstOrderID) == [orderId6, longTo32Bytes(0)]) assert (orders.ascendOrderList( BID, 6100, worstOrderID) == [longTo32Bytes(0), orderId5]) assert (orders.ascendOrderList( BID, 5800, worstOrderID) == [orderId6, longTo32Bytes(0)]) assert (orders.ascendOrderList(BID, 5950, bestOrderID) == [orderId5, orderId6]) order = { "orderID": longTo32Bytes(7), "type": BID, "amount": fix('1'), "price": 5950, "sender": contractsFixture.accounts[0], "outcome": outcomeID, "moneyEscrowed": fix('5950'), "sharesEscrowed": 0, "betterOrderID": longTo32Bytes(0), "worseOrderID": longTo32Bytes(0), "tradeGroupID": stringToBytes("0"), } uints = [ order["amount"], order["price"], order["outcome"], order["moneyEscrowed"], order["sharesEscrowed"] ] bytes32s = [ order["betterOrderID"], order["worseOrderID"], order["tradeGroupID"], stringToBytes("0") ] orderId7 = orders.testSaveOrder(uints, bytes32s, order["type"], market.address, order["sender"]) assert (orderId7 != bytearray(32)), "Save order" bestOrderID = orders.getBestOrderId(BID, market.address, outcomeID, nullAddress) worstOrderID = orders.getWorstOrderId(BID, market.address, outcomeID, nullAddress) assert (bestOrderID == orderId5) assert (worstOrderID == orderId6) # walk down order list starting from bestOrderID assert (orders.descendOrderList(BID, 6000, bestOrderID) == [orderId5, orderId7]) assert (orders.descendOrderList( BID, 5900, bestOrderID) == [orderId6, longTo32Bytes(0)]) assert (orders.descendOrderList( BID, 6100, bestOrderID) == [longTo32Bytes(0), orderId5]) assert (orders.descendOrderList( BID, 5800, bestOrderID) == [orderId6, longTo32Bytes(0)]) # walk up order list starting from worstOrderID assert (orders.ascendOrderList(BID, 6000, worstOrderID) == [orderId5, orderId7]) assert (orders.ascendOrderList( BID, 5900, worstOrderID) == [orderId6, longTo32Bytes(0)]) assert (orders.ascendOrderList( BID, 6100, worstOrderID) == [longTo32Bytes(0), orderId5]) assert (orders.ascendOrderList( BID, 5800, worstOrderID) == [orderId6, longTo32Bytes(0)]) assert (orders.testRemoveOrder(orderId5) == 1), "Remove order 5" assert (orders.testRemoveOrder(orderId6) == 1), "Remove order 6" assert (orders.testRemoveOrder(orderId7) == 1), "Remove order 7"