def test_two_asks_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(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(3), 6000, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), tradeGroupID, sender = tester.k3, value=fix('3', '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) == 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_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_registry(localFixture, controller): key1 = 'abc'.ljust(32, '\x00') key2 = 'foo'.ljust(32, '\x00') with raises(TransactionFailed): controller.registerContract(key1, 123, garbageBytes20, garbageBytes32, sender = tester.k2) assert controller.lookup(key1, sender = tester.k2) == longToHexString(0) assert controller.addToWhitelist(tester.a1, sender = tester.k0) assert controller.registerContract(key1, 123, garbageBytes20, garbageBytes32, sender = tester.k0) assert controller.lookup(key1, sender = tester.k2) == longToHexString(123) # We can't re-upload a contract under the same registry key with raises(TransactionFailed): controller.registerContract(key1, 123, garbageBytes20, garbageBytes32, sender = tester.k0)
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_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_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_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 localSnapshot(fixture, augurInitializedWithMocksSnapshot): fixture.resetToSnapshot(augurInitializedWithMocksSnapshot) controller = fixture.contracts['Controller'] mockCash = fixture.contracts['MockCash'] mockAugur = fixture.contracts['MockAugur'] mockFeeToken = fixture.contracts['MockFeeToken'] mockFeeTokenFactory = fixture.contracts['MockFeeTokenFactory'] mockFeeTokenFactory.setCreateFeeToken(mockFeeToken.address) mockReputationToken = fixture.contracts['MockReputationToken'] controller.registerContract(stringToBytes('Cash'), mockCash.address, twentyZeros, thirtyTwoZeros) controller.registerContract(stringToBytes('Augur'), mockAugur.address, twentyZeros, thirtyTwoZeros) controller.registerContract(stringToBytes('FeeTokenFactory'), mockFeeTokenFactory.address, twentyZeros, thirtyTwoZeros) feeWindow = fixture.upload('../source/contracts/reporting/FeeWindow.sol', 'feeWindow') fixture.contracts["initializedFeeWindow"] = feeWindow feeWindow.setController(fixture.contracts["Controller"].address) mockUniverse = fixture.contracts['MockUniverse'] mockUniverse.setReputationToken(mockReputationToken.address) mockUniverse.setDisputeRoundDurationInSeconds(5040) mockUniverse.setForkingMarket(5040) mockUniverse.setForkingMarket(longToHexString(0)) mockUniverse.setIsForking(False) fixture.contracts["Time"].setTimestamp(feeWindowId) feeWindow.initialize(mockUniverse.address, feeWindowId) return fixture.createSnapshot()
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 applySignature(self, signatureName, address): assert address if type(address) is long: address = longToHexString(address) translator = ContractTranslator(ContractsFixture.signatures[signatureName]) contract = ABIContract(self.chain, translator, address) return contract
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 proceedToFork(fixture, market, universe): while (market.getForkingMarket() == longToHexString(0)): proceedToNextRound(fixture, market) for i in range(market.getNumParticipants()): reportingParticipant = fixture.applySignature("DisputeCrowdsourcer", market.getReportingParticipant(i)) reportingParticipant.fork()
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_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_fee_window_redeem_for_reporting_participant_with_balance(localFixture, initializedFeeWindow, mockUniverse, Time, mockReputationToken, mockFeeToken, constants, mockCash): attoToken = 10 ** 10 feeTokenBalance = 10 ** 2 feeWindowBalance = 10 ** 4 # buy tokens Time.setTimestamp(feeWindowId * mockUniverse.getDisputeRoundDurationInSeconds() + 1) assert initializedFeeWindow.isActive() == True assert initializedFeeWindow.buy(attoToken, sender=tester.k0) == True assert initializedFeeWindow.balanceOf(tester.a0) == attoToken # verify fee window fee stake is updated with buy assert initializedFeeWindow.getTotalFeeStake() == attoToken # set up feeTokens for user mockFeeToken.setBalanceOf(feeTokenBalance) # set up fee window cash balance mockCash.setBalanceOf(feeWindowBalance) Time.setTimestamp(feeWindowId * mockUniverse.getDisputeRoundDurationInSeconds() + constants.DISPUTE_ROUND_DURATION_SECONDS()) assert initializedFeeWindow.isOver() == True assert mockFeeToken.balanceOf(tester.a0) == feeTokenBalance assert initializedFeeWindow.redeemForReportingParticipant(sender=tester.k0) == True assert mockReputationToken.getTransferValueFor(tester.a0) == attoToken # participation tokens should have been burnt assert initializedFeeWindow.balanceOf(tester.a0) == 0 assert mockFeeToken.getFeeWindowBurnTargetValue() == bytesToHexString(tester.a0) assert mockFeeToken.getFeeWindowBurnAmountValue() == feeTokenBalance assert mockCash.getTransferValueFor(tester.a0) == feeWindowBalance * (attoToken + feeTokenBalance) / attoToken assert mockCash.getwithdrawEtherToAddressValue() == longToHexString(0) assert mockCash.getwithdrawEthertoAmountValue() == 0
def test_fee_window_redeem_for_reporting_participant_zero(localFixture, initializedFeeWindow, mockUniverse, Time, mockReputationToken, mockFeeToken, constants, mockCash): assert initializedFeeWindow.isOver() == False mockUniverse.setIsForking(False) with raises(TransactionFailed, message="fee window needs to be over or universe needs to be forking"): initializedFeeWindow.redeemForReportingParticipant() # no tokens purchased and no fee token balance mockUniverse.setIsForking(True) assert mockFeeToken.getFeeWindowBurnTargetValue() == longToHexString(0) assert mockFeeToken.getFeeWindowBurnAmountValue() == 0 assert initializedFeeWindow.totalSupply() == 0 mockFeeToken.setTotalSupply(0) assert initializedFeeWindow.redeemForReportingParticipant(sender=tester.k0) == True assert mockFeeToken.getFeeWindowBurnTargetValue() == longToHexString(0) assert mockFeeToken.getFeeWindowBurnAmountValue() == 0 assert initializedFeeWindow.totalSupply() == 0 assert mockReputationToken.getTransferValueFor(tester.a0) == 0
def test_reputation_token_creation(localFixture, mockUniverse): reputationToken = localFixture.upload('../source/contracts/reporting/ReputationToken.sol', 'reputationToken') reputationToken.setController(localFixture.contracts['Controller'].address) with raises(TransactionFailed, message="universe has to have address"): reputationToken.initialize(longToHexString(0)) assert reputationToken.initialize(mockUniverse.address) assert reputationToken.getTypeName() == stringToBytes('ReputationToken') assert reputationToken.getUniverse() == mockUniverse.address
def test_universe_creation(localFixture, mockReputationToken, mockReputationTokenFactory, mockUniverse, mockUniverseFactory, mockAugur): universe = localFixture.upload('../source/contracts/reporting/Universe.sol', 'newUniverse') with raises(TransactionFailed, message="reputation token can not be address 0"): universe.initialize(mockUniverse.address, stringToBytes("5")) mockReputationTokenFactory.setCreateReputationTokenValue(mockReputationToken.address) universe.setController(localFixture.contracts['Controller'].address) assert universe.initialize(mockUniverse.address, stringToBytes("5")) assert universe.getReputationToken() == mockReputationToken.address assert universe.getParentUniverse() == mockUniverse.address assert universe.getParentPayoutDistributionHash() == stringToBytes("5") assert universe.getForkingMarket() == longToHexString(0) assert universe.getForkEndTime() == 0 assert universe.getTypeName() == stringToBytes('Universe') assert universe.getForkEndTime() == 0 assert universe.getChildUniverse("5") == longToHexString(0)
def localSnapshot(fixture, augurInitializedWithMocksSnapshot): fixture.resetToSnapshot(augurInitializedWithMocksSnapshot) controller = fixture.contracts['Controller'] mockCash = fixture.contracts['MockCash'] mockAugur = fixture.contracts['MockAugur'] mockInitialReporter = fixture.contracts['MockInitialReporter'] mockDisputeCrowdsourcer = fixture.contracts['MockDisputeCrowdsourcer'] mockShareTokenFactory = fixture.contracts['MockShareTokenFactory'] mockInitialReporterFactory = fixture.contracts['MockInitialReporterFactory'] mockDisputeCrowdsourcerFactory = fixture.contracts['MockDisputeCrowdsourcerFactory'] mockShareToken = fixture.contracts['MockShareToken'] # pre populate share tokens for max of 8 possible outcomes for index in range(8): item = fixture.uploadAndAddToController('solidity_test_helpers/MockShareToken.sol', 'newMockShareToken' + str(index)); mockShareTokenFactory.pushCreateShareToken(item.address) controller.registerContract(stringToBytes('Cash'), mockCash.address, twentyZeros, thirtyTwoZeros) controller.registerContract(stringToBytes('ShareTokenFactory'), mockShareTokenFactory.address, twentyZeros, thirtyTwoZeros) controller.registerContract(stringToBytes('InitialReporterFactory'), mockInitialReporterFactory.address, twentyZeros, thirtyTwoZeros) controller.registerContract(stringToBytes('DisputeCrowdsourcerFactory'), mockDisputeCrowdsourcerFactory.address, twentyZeros, thirtyTwoZeros) mockShareTokenFactory.resetCreateShareToken() mockReputationToken = fixture.contracts['MockReputationToken'] mockUniverse = fixture.contracts['MockUniverse'] mockUniverse.setReputationToken(mockReputationToken.address) mockFeeWindow = fixture.contracts['MockFeeWindow'] mockFeeWindow.setReputationToken(mockReputationToken.address) mockFeeWindow.setUniverse(mockUniverse.address) mockNextFeeWindow = fixture.upload('solidity_test_helpers/MockFeeWindow.sol', 'mockNextFeeWindow') mockNextFeeWindow.setReputationToken(mockReputationToken.address) mockNextFeeWindow.setUniverse(mockUniverse.address) mockInitialReporterFactory.setInitialReporter(mockInitialReporter.address) mockDisputeCrowdsourcerFactory.setDisputeCrowdsourcer(mockDisputeCrowdsourcer.address) constants = fixture.contracts['Constants'] market = fixture.upload('../source/contracts/reporting/Market.sol', 'market') fixture.contracts["initializedMarket"] = market contractMap = fixture.upload('../source/contracts/libraries/collections/Map.sol', 'Map') endTime = fixture.contracts["Time"].getTimestamp() + constants.DESIGNATED_REPORTING_DURATION_SECONDS() market.setController(fixture.contracts["Controller"].address) mockUniverse.setForkingMarket(longToHexString(0)) mockUniverse.setOrCacheDesignatedReportNoShowBond(100) mockReputationToken.setBalanceOf(100) mockUniverse.setOrCacheTargetReporterGasCosts(15) mockUniverse.setOrCacheValidityBond(12) mockUniverse.setNextFeeWindow(mockNextFeeWindow.address) mockFeeWindow.setEndTime(fixture.contracts["Time"].getTimestamp() + constants.DESIGNATED_REPORTING_DURATION_SECONDS()) mockNextFeeWindow.setEndTime(mockFeeWindow.getEndTime() + constants.DESIGNATED_REPORTING_DURATION_SECONDS()) assert market.initialize(mockUniverse.address, endTime, 16, mockCash.address, tester.a1, tester.a2, 5, numTicks, value=100) return fixture.createSnapshot()
def test_getContractDetails(controller): key = stringToBytes('lookup key') address = garbageAddress commitHash = garbageBytes20 fileHash = garbageBytes32 assert controller.getContractDetails(key, sender = tester.k2) == [ longToHexString(0), twentyZeros, thirtyTwoZeros ] assert controller.registerContract(key, address, commitHash, fileHash, sender = tester.k0) assert controller.getContractDetails(key, sender = tester.k2) == [ address, commitHash, fileHash ]
def test_recordFillOrder(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" # orderID, fill, money, shares with raises(TransactionFailed): orders.recordFillOrder(orderId1, fix(11), "0") with raises(TransactionFailed): orders.recordFillOrder(orderId1, 0, fix('1')) with raises(TransactionFailed): orders.recordFillOrder(orderId1, fix(10), fix('1')) # fully fill assert(orders.recordFillOrder(orderId1, fix(10), 0) == 1), "fillOrder wasn't executed successfully" # prove all 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) # test partial fill assert(orders.recordFillOrder(orderId2, 0, fix('3', '5000')) == 1), "fillOrder wasn't executed successfully" # confirm partial fill assert orders.getAmount(orderId2) == fix('7') assert orders.getPrice(orderId2) == 5000 assert orders.getOrderCreator(orderId2) == bytesToHexString(tester.a2) assert orders.getOrderMoneyEscrowed(orderId2) == fix('7', '5000') assert orders.getOrderSharesEscrowed(orderId2) == 0 assert orders.getBetterOrderId(orderId2) == longTo32Bytes(0) assert orders.getWorseOrderId(orderId2) == longTo32Bytes(0) # fill rest of order2 assert(orders.recordFillOrder(orderId2, 0, fix('7', '5000')) == 1), "fillOrder wasn't executed successfully" 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)
def test_forking(localFixture, universe, market, categoricalMarket, cash, reputationToken): # Let's do some initial disputes for the categorical market proceedToNextRound(localFixture, categoricalMarket, tester.k1, moveTimeForward = False) # Get to a fork testers = [tester.k0, tester.k1, tester.k2, tester.k3] testerIndex = 1 while (market.getForkingMarket() == longToHexString(0)): proceedToNextRound(localFixture, market, testers[testerIndex], True) testerIndex += 1 testerIndex = testerIndex % len(testers) # Have the participants fork and create new child universes reportingParticipant = localFixture.applySignature("DisputeCrowdsourcer", market.getReportingParticipant(0)) ReportingParticipantDisavowedLog = { "universe": universe.address, "market": market.address, "reportingParticipant": reportingParticipant.address, } with AssertLog(localFixture, "ReportingParticipantDisavowed", ReportingParticipantDisavowedLog): reportingParticipant.fork() for i in range(1, market.getNumParticipants()): reportingParticipant = localFixture.applySignature("DisputeCrowdsourcer", market.getReportingParticipant(i)) reportingParticipant.fork() # Finalize the fork finalizeFork(localFixture, market, universe) categoricalDisputeCrowdsourcer = localFixture.applySignature("DisputeCrowdsourcer", categoricalMarket.getReportingParticipant(1)) # Migrate the categorical market into the winning universe. This will disavow the dispute crowdsourcer on it, letting us redeem for original universe rep and eth assert categoricalMarket.migrateThroughOneFork() expectedRep = categoricalDisputeCrowdsourcer.getStake() expectedEth = getExpectedFees(localFixture, cash, categoricalDisputeCrowdsourcer, 2) with EtherDelta(expectedEth, tester.a1, localFixture.chain, "Redeeming didn't increase ETH correctly"): with TokenDelta(reputationToken, expectedRep, tester.a1, "Redeeming didn't increase REP correctly"): categoricalDisputeCrowdsourcer.redeem(tester.a1) # Now we'll redeem the forked reporting participants testers = [tester.a0, tester.a1, tester.a2, tester.a3] for i in range(market.getNumParticipants()): account = testers[i % 4] reportingParticipant = localFixture.applySignature("DisputeCrowdsourcer", market.getReportingParticipant(i)) expectedRep = reportingParticipant.getStake() expectedRep += expectedRep / localFixture.contracts["Constants"].FORK_MIGRATION_PERCENTAGE_BONUS_DIVISOR() expectedRep += reportingParticipant.getStake() / 2 expectedEth = cash.balanceOf(reportingParticipant.address) newReputationToken = localFixture.applySignature("ReputationToken", reportingParticipant.getReputationToken()) with EtherDelta(expectedEth, account, localFixture.chain, "Redeeming didn't increase ETH correctly"): with TokenDelta(newReputationToken, expectedRep, account, "Redeeming didn't increase REP correctly"): reportingParticipant.redeem(account)
def test_forkAndRedeem(localFixture, universe, market, categoricalMarket, cash, reputationToken): # Let's do some initial disputes for the categorical market proceedToNextRound(localFixture, categoricalMarket, tester.k1, moveTimeForward = False) # Get to a fork testers = [tester.k0, tester.k1, tester.k2, tester.k3] testerIndex = 1 while (market.getForkingMarket() == longToHexString(0)): proceedToNextRound(localFixture, market, testers[testerIndex], True) testerIndex += 1 testerIndex = testerIndex % len(testers) # Have the participants fork and create new child universes for i in range(market.getNumParticipants()): reportingParticipant = localFixture.applySignature("DisputeCrowdsourcer", market.getReportingParticipant(i)) # Finalize the fork finalizeFork(localFixture, market, universe) categoricalDisputeCrowdsourcer = localFixture.applySignature("DisputeCrowdsourcer", categoricalMarket.getReportingParticipant(1)) # Migrate the categorical market into the winning universe. This will disavow the dispute crowdsourcer on it, letting us redeem for original universe rep and eth assert categoricalMarket.migrateThroughOneFork() expectedRep = categoricalDisputeCrowdsourcer.getStake() expectedEth = getExpectedFees(localFixture, cash, categoricalDisputeCrowdsourcer, 2) with EtherDelta(expectedEth, tester.a1, localFixture.chain, "Redeeming didn't increase ETH correctly"): with TokenDelta(reputationToken, expectedRep, tester.a1, "Redeeming didn't increase REP correctly"): categoricalDisputeCrowdsourcer.redeem(tester.a1) noPayoutNumerators = [0] * market.getNumberOfOutcomes() noPayoutNumerators[0] = market.getNumTicks() yesPayoutNumerators = noPayoutNumerators[::-1] noUniverse = localFixture.applySignature('Universe', universe.createChildUniverse(noPayoutNumerators, False)) yesUniverse = localFixture.applySignature('Universe', universe.createChildUniverse(yesPayoutNumerators, False)) noUniverseReputationToken = localFixture.applySignature('ReputationToken', noUniverse.getReputationToken()) yesUniverseReputationToken = localFixture.applySignature('ReputationToken', yesUniverse.getReputationToken()) # Now we'll fork and redeem the reporting participants for i in range(market.getNumParticipants()): account = localFixture.testerAddress[i % 4] key = localFixture.testerKey[i % 4] reportingParticipant = localFixture.applySignature("DisputeCrowdsourcer", market.getReportingParticipant(i)) expectedRep = reportingParticipant.getStake() expectedRep += expectedRep / localFixture.contracts["Constants"].FORK_MIGRATION_PERCENTAGE_BONUS_DIVISOR() expectedRep += reportingParticipant.getStake() / 2 repToken = noUniverseReputationToken if i % 2 == 0 else yesUniverseReputationToken with TokenDelta(repToken, expectedRep, account, "Redeeming didn't increase REP correctly for " + str(i)): assert reportingParticipant.forkAndRedeem(sender=key)
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_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 proceedToNextRound(fixture, market, contributor = tester.k0, doGenerateFees = False, moveTimeForward = True, randomPayoutNumerators = False): if fixture.contracts["Controller"].getTimestamp() < market.getEndTime(): fixture.contracts["Time"].setTimestamp(market.getDesignatedReportingEndTime() + 1) feeWindow = market.getFeeWindow() payoutNumerators = [0] * market.getNumberOfOutcomes() payoutNumerators[0] = market.getNumTicks() if (feeWindow == longToHexString(0)): market.doInitialReport(payoutNumerators, False) assert market.getFeeWindow() else: feeWindow = fixture.applySignature('FeeWindow', market.getFeeWindow()) fixture.contracts["Time"].setTimestamp(feeWindow.getStartTime() + 1) # This will also use the InitialReporter which is not a DisputeCrowdsourcer, but has the called function from abstract inheritance winningReport = fixture.applySignature('DisputeCrowdsourcer', market.getWinningReportingParticipant()) winningPayoutHash = winningReport.getPayoutDistributionHash() if (randomPayoutNumerators): chosenPayoutNumerators = [0] * market.getNumberOfOutcomes() chosenPayoutNumerators[0] = randint(0, market.getNumTicks()) chosenPayoutNumerators[1] = market.getNumTicks() - chosenPayoutNumerators[0] else: firstReportWinning = market.derivePayoutDistributionHash(payoutNumerators, False) == winningPayoutHash chosenPayoutNumerators = payoutNumerators if not firstReportWinning else payoutNumerators[::-1] chosenPayoutHash = market.derivePayoutDistributionHash(chosenPayoutNumerators, False) amount = 2 * market.getParticipantStake() - 3 * market.getStakeInOutcome(chosenPayoutHash) with PrintGasUsed(fixture, "Contribute:", 0): market.contribute(chosenPayoutNumerators, False, amount, sender=contributor) assert market.getForkingMarket() or market.getFeeWindow() != feeWindow if (doGenerateFees): universe = fixture.applySignature("Universe", market.getUniverse()) generateFees(fixture, universe, market) if (moveTimeForward): feeWindow = fixture.applySignature('FeeWindow', market.getFeeWindow()) fixture.contracts["Time"].setTimestamp(feeWindow.getStartTime() + 1)
def test_rep_migration_convenience_function(localFixture, universe, market): proceedToFork(localFixture, market, universe) payoutNumerators = [1, market.getNumTicks()-1] payoutDistributionHash = market.derivePayoutDistributionHash(payoutNumerators, False) # Initially child universes don't exist assert universe.getChildUniverse(payoutDistributionHash) == longToHexString(0) # We'll use the convenience function for migrating REP instead of manually creating a child universe reputationToken = localFixture.applySignature("ReputationToken", universe.getReputationToken()) with raises(TransactionFailed): reputationToken.migrateOutByPayout(payoutNumerators, False, 0) assert reputationToken.migrateOutByPayout(payoutNumerators, False, 10) # We can see that the child universe was created newUniverse = localFixture.applySignature("Universe", universe.getChildUniverse(payoutDistributionHash)) newReputationToken = localFixture.applySignature("ReputationToken", newUniverse.getReputationToken()) bonus = 10 / localFixture.contracts["Constants"].FORK_MIGRATION_PERCENTAGE_BONUS_DIVISOR() assert newReputationToken.balanceOf(tester.a0) == 10 + bonus
def test_malicious_order_creator(contractsFixture, cash, market, universe): createOrder = contractsFixture.contracts['CreateOrder'] fillOrder = contractsFixture.contracts['FillOrder'] orders = contractsFixture.contracts['Orders'] augur = contractsFixture.contracts['Augur'] 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)) maliciousTrader = contractsFixture.upload( 'solidity_test_helpers/MaliciousTrader.sol', 'maliciousTrader') maliciousTrader.approveAugur(cash.address, augur.address) # create order with the malicious contract by escrowing shares price = 60 numTicks = market.getNumTicks() with BuyWithCash(cash, fix('1', numTicks), tester.k0, "buy complete set"): assert completeSets.publicBuyCompleteSets(market.address, fix(1)) assert firstShareToken.transfer(maliciousTrader.address, fix(1)) assert secondShareToken.transfer(maliciousTrader.address, fix(1)) assert thirdShareToken.transfer(maliciousTrader.address, fix(1)) orderID = maliciousTrader.makeOrder(createOrder.address, BID, fix(1), price, market.address, 0, longTo32Bytes(0), longTo32Bytes(0), longTo32Bytes(42), value=fix(1, price), sender=tester.k1) assert orderID # Make the fallback function fail maliciousTrader.setEvil(True) # fill order with cash with BuyWithCash(cash, fix(1, numTicks - price), tester.k2, "fill order"): assert fillOrder.publicFillOrder( orderID, fix(1), "43", False, "0x0000000000000000000000000000000000000000", 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) # The malicious contract may have just been a smart contract that has expensive and dumb fallback behavior. We do the right thing and still award them Cash in this case. assert cash.balanceOf(maliciousTrader.address) == fix(1, 40)
def test_publicFillOrder_bid(contractsFixture, cash, market, universe): createOrder = contractsFixture.contracts['CreateOrder'] fillOrder = contractsFixture.contracts['FillOrder'] orders = contractsFixture.contracts['Orders'] tradeGroupID = longTo32Bytes(42) creatorCost = fix('2', '60') fillerCost = fix('2', '40') # create order with BuyWithCash(cash, creatorCost, tester.k1, "complete set buy"): orderID = createOrder.publicCreateOrder(BID, fix(2), 60, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), tradeGroupID, False, nullAddress, sender=tester.k1) # fill best order orderEventLog = { "universe": universe.address, "market": market.address, "eventType": 3, "addressData": [ nullAddress, bytesToHexString(tester.a1), bytesToHexString(tester.a2) ], "uint256Data": [ 60, 0, YES, 0, 0, 0, fix(2), contractsFixture.contracts['Time'].getTimestamp() ], } marketVolumeChangedLog = { "market": market.address, "volume": creatorCost + fillerCost } profitLossChangedLog = { "market": market.address, "account": bytesToHexString(tester.a2), "outcome": YES, "netPosition": -fix(2), "avgPrice": 60, "realizedProfit": 0, "frozenFunds": fillerCost, } with BuyWithCash(cash, fillerCost, tester.k2, "filling order"): with AssertLog(contractsFixture, "ProfitLossChanged", profitLossChangedLog): with AssertLog(contractsFixture, "OrderEvent", orderEventLog): with AssertLog(contractsFixture, "MarketVolumeChanged", marketVolumeChangedLog): fillOrderID = fillOrder.publicFillOrder( orderID, fix(2), tradeGroupID, False, "0x0000000000000000000000000000000000000000", sender=tester.k2) assert fillOrderID == 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_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" logs = [] 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 captureFilteredLogs(contractsFixture.chain.head_state, orders, logs) captureFilteredLogs(contractsFixture.chain.head_state, contractsFixture.contracts['Augur'], logs) fillOrderID = fillOrder.publicFillOrder(orderID, fix(2), tradeGroupID, sender=tester.k2, value=fillerCost) assert len(logs) == 5 assert logs[4]["_event_type"] == "OrderFilled" assert logs[4]["filler"] == bytesToHexString(tester.a2) assert logs[4]["numCreatorShares"] == 0 assert logs[4]["numCreatorTokens"] == creatorCost assert logs[4]["numFillerShares"] == 0 assert logs[4]["numFillerTokens"] == fillerCost assert logs[4]["marketCreatorFees"] == 0 assert logs[4]["reporterFees"] == 0 assert logs[4]["shareToken"] == market.getShareToken(YES) assert logs[4]["tradeGroupId"] == stringToBytes("42") 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_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 logs = [] captureFilteredLogs(contractsFixture.chain.head_state, contractsFixture.contracts['Augur'], logs) 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 len(logs) == 8 log1 = logs[7] assert log1["_event_type"] == "OrderFilled" assert log1["filler"] == bytesToHexString(tester.a2) assert log1["numCreatorShares"] == fix(1) assert log1["numCreatorTokens"] == 0 assert log1["numFillerShares"] == fix(1) assert log1["numFillerTokens"] == 0 assert log1["marketCreatorFees"] == fix( 1, 10000) / market.getMarketCreatorSettlementFeeDivisor() assert log1["reporterFees"] == fix( 1, 10000) / universe.getOrCacheReportingFeeDivisor() assert log1["shareToken"] == market.getShareToken(YES) assert log1["tradeGroupId"] == stringToBytes("43") 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_forkAndRedeem(localFixture, universe, market, categoricalMarket, cash, reputationToken): # Let's do some initial disputes for the categorical market proceedToNextRound(localFixture, categoricalMarket, tester.k1, moveTimeForward=False) # Get to a fork testers = [tester.k0, tester.k1, tester.k2, tester.k3] testerIndex = 1 while (market.getForkingMarket() == longToHexString(0)): proceedToNextRound(localFixture, market, testers[testerIndex], True) testerIndex += 1 testerIndex = testerIndex % len(testers) # Have the participants fork and create new child universes for i in range(market.getNumParticipants()): reportingParticipant = localFixture.applySignature( "DisputeCrowdsourcer", market.getReportingParticipant(i)) # Finalize the fork finalizeFork(localFixture, market, universe) categoricalDisputeCrowdsourcer = localFixture.applySignature( "DisputeCrowdsourcer", categoricalMarket.getReportingParticipant(1)) # Migrate the categorical market into the winning universe. This will disavow the dispute crowdsourcer on it, letting us redeem for original universe rep and eth assert categoricalMarket.migrateThroughOneFork() expectedRep = categoricalDisputeCrowdsourcer.getStake() expectedEth = getExpectedFees(localFixture, cash, categoricalDisputeCrowdsourcer, 2) with EtherDelta(expectedEth, tester.a1, localFixture.chain, "Redeeming didn't increase ETH correctly"): with TokenDelta(reputationToken, expectedRep, tester.a1, "Redeeming didn't increase REP correctly"): categoricalDisputeCrowdsourcer.redeem(tester.a1) noPayoutNumerators = [0] * market.getNumberOfOutcomes() noPayoutNumerators[0] = market.getNumTicks() yesPayoutNumerators = noPayoutNumerators[::-1] noUniverse = localFixture.applySignature( 'Universe', universe.createChildUniverse(noPayoutNumerators, False)) yesUniverse = localFixture.applySignature( 'Universe', universe.createChildUniverse(yesPayoutNumerators, False)) noUniverseReputationToken = localFixture.applySignature( 'ReputationToken', noUniverse.getReputationToken()) yesUniverseReputationToken = localFixture.applySignature( 'ReputationToken', yesUniverse.getReputationToken()) # Now we'll fork and redeem the reporting participants for i in range(market.getNumParticipants()): account = localFixture.testerAddress[i % 4] key = localFixture.testerKey[i % 4] reportingParticipant = localFixture.applySignature( "DisputeCrowdsourcer", market.getReportingParticipant(i)) expectedRep = reportingParticipant.getStake() expectedRep += expectedRep / localFixture.contracts[ "Constants"].FORK_MIGRATION_PERCENTAGE_BONUS_DIVISOR() expectedRep += reportingParticipant.getStake() / 2 repToken = noUniverseReputationToken if i % 2 == 0 else yesUniverseReputationToken with TokenDelta( repToken, expectedRep, account, "Redeeming didn't increase REP correctly for " + str(i)): assert reportingParticipant.forkAndRedeem(sender=key)
def test_two_asks_on_books_buy_one_full_then_create(contractsFixture, cash, market, universe): createOrder = contractsFixture.contracts['CreateOrder'] trade = contractsFixture.contracts['Trade'] fillOrder = contractsFixture.contracts['FillOrder'] orders = contractsFixture.contracts['Orders'] tradeGroupID = 42L logs = [] # create order 1 orderID1 = createOrder.publicCreateOrder(ASK, 12, fix('0.6'), market.address, YES, longTo32Bytes(0), longTo32Bytes(0), tradeGroupID, sender=tester.k1, value=fix('12', '0.4')) # create order 2 orderID2 = createOrder.publicCreateOrder(ASK, 7, fix('0.7'), market.address, YES, longTo32Bytes(0), longTo32Bytes(0), tradeGroupID, sender=tester.k3, value=fix('7', '0.4')) # fill/create captureFilteredLogs(contractsFixture.chain.head_state, orders, logs) captureFilteredLogs(contractsFixture.chain.head_state, contractsFixture.contracts['Augur'], logs) fillOrderID = trade.publicBuy(market.address, YES, 15, fix('0.6'), tradeGroupID, sender=tester.k2, value=fix('15', '0.6')) assert len(logs) == 6 log1 = logs[4] log2 = logs[5] assert log1["_event_type"] == "OrderFilled" assert log1["filler"] == bytesToHexString(tester.a2) assert log1["numCreatorShares"] == 0 assert log1["numCreatorTokens"] == fix('12', '0.4') assert log1["numFillerShares"] == 0 assert log1["numFillerTokens"] == fix('12', '0.6') assert log1["settlementFees"] == 0 assert log1["shareToken"] == market.getShareToken(YES) assert log1["tradeGroupId"] == 42 assert log2["_event_type"] == "OrderCreated" assert log2['creator'] == bytesToHexString(tester.a2) assert log2["orderId"] == fillOrderID assert log2["shareToken"] == market.getShareToken(YES) assert log2["tradeGroupId"] == 42 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) == 7 assert orders.getPrice(orderID2) == fix('0.7') assert orders.getOrderCreator(orderID2) == bytesToHexString(tester.a3) assert orders.getOrderMoneyEscrowed(orderID2) == fix('7', '0.3') assert orders.getOrderSharesEscrowed(orderID2) == 0 assert orders.getBetterOrderId(orderID2) == longTo32Bytes(0) assert orders.getWorseOrderId(orderID2) == longTo32Bytes(0) assert orders.getAmount(fillOrderID) == 3 assert orders.getPrice(fillOrderID) == fix('0.6') assert orders.getOrderCreator(fillOrderID) == bytesToHexString(tester.a2) assert orders.getOrderMoneyEscrowed(fillOrderID) == fix('3', '0.6') assert orders.getOrderSharesEscrowed(fillOrderID) == 0 assert orders.getBetterOrderId(fillOrderID) == longTo32Bytes(0) assert orders.getWorseOrderId(fillOrderID) == longTo32Bytes(0)
def test_cancelAsk(escapeHatch, contractsFixture, cash, market): createOrder = contractsFixture.contracts['CreateOrder'] cancelOrder = contractsFixture.contracts['CancelOrder'] orders = contractsFixture.contracts['Orders'] orderType = ASK fxpAmount = fix(1) fxpPrice = 6000 outcomeID = 1 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 != bytearray(32)), "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', '4000'), "ETH should be deducted from the creator balance" if (escapeHatch): controller = contractsFixture.contracts['Controller'] controller.emergencyStop() 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_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"
from pytest import fixture, raises from utils import longTo32Bytes, longToHexString KEY1 = "1" KEY2 = "2" KEY3 = "3" KEY4 = "4" NULL_VALUE = longTo32Bytes(0) VALUE1 = longTo32Bytes(1) VALUE2 = longTo32Bytes(2) VALUE3 = longTo32Bytes(3) VALUE4 = longTo32Bytes(4) NULL_ADDRESS = longToHexString(0) ADDRESS = longToHexString(1) def test_map(testerContractsFixture): mapTester = testerContractsFixture.contracts['MapHelper'] # Initially the map has no data assert mapTester.getCount() == 0 assert mapTester.getValueOrZero(KEY1) == NULL_VALUE assert not mapTester.contains(KEY1) with raises(TransactionFailed): mapTester.get(KEY1) # Add a value assert mapTester.add(KEY1, VALUE1)
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_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 = 42L logs = [] # create order 1 orderID1 = createOrder.publicCreateOrder(BID, 4, fix('0.6'), market.address, YES, longTo32Bytes(0), longTo32Bytes(0), tradeGroupID, sender=tester.k1, value=fix('4', '0.6')) # create order 2 orderID2 = createOrder.publicCreateOrder(BID, 1, fix('0.6'), market.address, YES, longTo32Bytes(0), longTo32Bytes(0), tradeGroupID, sender=tester.k3, value=fix('1', '0.6')) # fill best order captureFilteredLogs(contractsFixture.chain.head_state, orders, logs) captureFilteredLogs(contractsFixture.chain.head_state, contractsFixture.contracts['Augur'], logs) fillOrderID = trade.publicSell(market.address, YES, 5, fix('0.6'), tradeGroupID, sender=tester.k2, value=fix('5', '0.4')) assert len(logs) == 10 log1 = logs[4] log2 = logs[9] assert log1["_event_type"] == "OrderFilled" assert log1["filler"] == bytesToHexString(tester.a2) assert log1["numCreatorShares"] == 0 assert log1["numCreatorTokens"] == fix('4', '0.6') assert log1["numFillerShares"] == 0 assert log1["numFillerTokens"] == fix('4', '0.4') assert log1["settlementFees"] == 0 assert log1["shareToken"] == market.getShareToken(YES) assert log1["tradeGroupId"] == 42 assert log2["_event_type"] == "OrderFilled" assert log2["filler"] == bytesToHexString(tester.a2) assert log2["numCreatorShares"] == 0 assert log2["numCreatorTokens"] == fix('1', '0.6') assert log2["numFillerShares"] == 0 assert log2["numFillerTokens"] == fix('1', '0.4') assert log2["settlementFees"] == 0 assert log2["shareToken"] == market.getShareToken(YES) assert log2["tradeGroupId"] == 42 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_two_bids_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" logs = [] # create order 1 orderID1 = createOrder.publicCreateOrder(BID, fix(12), 6000, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), tradeGroupID, sender=tester.k1, value=fix('12', '6000')) # create order 2 orderID2 = createOrder.publicCreateOrder(BID, fix(7), 6000, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), tradeGroupID, sender=tester.k3, value=fix('7', '6000')) # fill best order captureFilteredLogs(contractsFixture.chain.head_state, orders, logs) captureFilteredLogs(contractsFixture.chain.head_state, contractsFixture.contracts['Augur'], logs) fillOrderID = trade.publicSell(market.address, YES, fix(15), 6000, tradeGroupID, sender=tester.k2, value=fix('15', '4000')) assert len(logs) == 10 log1 = logs[4] log2 = logs[9] assert log1["_event_type"] == "OrderFilled" assert log1["filler"] == bytesToHexString(tester.a2) assert log1["numCreatorShares"] == 0 assert log1["numCreatorTokens"] == fix('12', '6000') assert log1["numFillerShares"] == 0 assert log1["numFillerTokens"] == fix('12', '4000') assert log1["marketCreatorFees"] == 0 assert log1["reporterFees"] == 0 assert log1["shareToken"] == market.getShareToken(YES) assert log1["tradeGroupId"] == stringToBytes("42") assert log2["_event_type"] == "OrderFilled" assert log2["filler"] == bytesToHexString(tester.a2) assert log2["numCreatorShares"] == 0 assert log2["numCreatorTokens"] == fix('3', '6000') assert log2["numFillerShares"] == 0 assert log2["numFillerTokens"] == fix('3', '4000') assert log2["marketCreatorFees"] == 0 assert log2["reporterFees"] == 0 assert log2["shareToken"] == market.getShareToken(YES) assert log2["tradeGroupId"] == stringToBytes("42") 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', '6000') assert orders.getOrderSharesEscrowed(orderID2) == 0 assert orders.getBetterOrderId(orderID2) == longTo32Bytes(0) assert orders.getWorseOrderId(orderID2) == longTo32Bytes(0) assert fillOrderID == longTo32Bytes(1)
def test_market_creation(localFixture, mockUniverse, mockFeeWindow, mockCash, chain, constants, mockMarket, mockReputationToken, mockShareToken, mockShareTokenFactory): fee = 16 oneEther = 10 ** 18 endTime = localFixture.contracts["Time"].getTimestamp() + constants.DESIGNATED_REPORTING_DURATION_SECONDS() market = localFixture.upload('../source/contracts/reporting/Market.sol', 'newMarket') market.setController(localFixture.contracts["Controller"].address) with raises(TransactionFailed, message="outcomes has to be greater than 1"): market.initialize(mockUniverse.address, endTime, fee, mockCash.address, tester.a1, tester.a1, 1, numTicks) with raises(TransactionFailed, message="outcomes has to be less than 9"): market.initialize(mockUniverse.address, endTime, fee, mockCash.address, tester.a1, tester.a1, 9, numTicks) with raises(TransactionFailed, message="numTicks needs to be divisable by outcomes"): market.initialize(mockUniverse.address, endTime, fee, mockCash.address, tester.a1, tester.a1, 7, numTicks) with raises(TransactionFailed, message="fee per eth can not be greater than max fee per eth in attoEth"): market.initialize(mockUniverse.address, endTime, oneEther / 2 + 1, mockCash.address, tester.a1, tester.a1, 5, numTicks) with raises(TransactionFailed, message="creator address can not be 0"): market.initialize(mockUniverse.address, endTime, fee, mockCash.address, longToHexString(0), tester.a1, 5, numTicks) with raises(TransactionFailed, message="designated reporter address can not be 0"): market.initialize(mockUniverse.address, endTime, fee, mockCash.address, tester.a1, longToHexString(0), 5, numTicks) mockUniverse.setForkingMarket(mockMarket.address) with raises(TransactionFailed, message="forking market address has to be 0"): market.initialize(mockUniverse.address, endTime, fee, mockCash.address, tester.a1, tester.a1, 5, numTicks) mockUniverse.setForkingMarket(longToHexString(0)) mockReputationToken.setBalanceOf(0) mockUniverse.setOrCacheDesignatedReportNoShowBond(100) with raises(TransactionFailed, message="reporting window reputation token does not have enough balance"): market.initialize(mockUniverse.address, endTime, fee, mockCash.address, tester.a1, tester.a1, 5, numTicks) badCash = localFixture.upload('../source/contracts/trading/Cash.sol', 'uncontrolledCash') with raises(TransactionFailed, message="the denomination token must be a valid cash implementation"): market.initialize(mockUniverse.address, endTime, fee, badCash.address, tester.a1, tester.a1, 5, numTicks, value=100) mockReputationToken.setBalanceOf(100) mockUniverse.setOrCacheTargetReporterGasCosts(15) mockUniverse.setOrCacheValidityBond(12) with raises(TransactionFailed, message="refund is not over 0"): market.initialize(mockUniverse.address, endTime, fee, mockCash.address, tester.a1, tester.a1, 5, numTicks, value=0) mockShareTokenFactory.resetCreateShareToken() assert market.initialize(mockUniverse.address, endTime, fee, mockCash.address, tester.a1, tester.a1, 5, numTicks, value=100) assert mockShareTokenFactory.getCreateShareTokenMarketValue() == market.address assert mockShareTokenFactory.getCreateShareTokenOutcomeValue() == 5 - 1 # mock logs the last outcome assert market.getTypeName() == stringToBytes("Market") assert market.getUniverse() == mockUniverse.address assert market.getUniverse() == mockUniverse.address assert market.getDesignatedReporter() == bytesToHexString(tester.a1) assert market.getNumberOfOutcomes() == 5 assert market.getEndTime() == endTime assert market.getNumTicks() == numTicks assert market.getDenominationToken() == mockCash.address assert market.getMarketCreatorSettlementFeeDivisor() == oneEther / 16 assert mockShareTokenFactory.getCreateShareTokenCounter() == 5 assert mockShareTokenFactory.getCreateShareToken(0) == market.getShareToken(0) assert mockShareTokenFactory.getCreateShareToken(1) == market.getShareToken(1) assert mockShareTokenFactory.getCreateShareToken(2) == market.getShareToken(2) assert mockShareTokenFactory.getCreateShareToken(3) == market.getShareToken(3) assert mockShareTokenFactory.getCreateShareToken(4) == market.getShareToken(4) assert mockUniverse.getOrCacheValidityBondWallCalled() == True
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() with BuyWithCash(cash, fix('1', numTicks), tester.k1, "buy complete set"): assert completeSets.publicBuyCompleteSets(market.address, fix(1), sender=tester.k1) with BuyWithCash(cash, fix('1', numTicks), tester.k2, "buy complete set"): assert completeSets.publicBuyCompleteSets(market.address, fix(1), sender=tester.k2) 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 = 60 orderID = createOrder.publicCreateOrder(ASK, fix(1), price, market.address, 0, longTo32Bytes(0), longTo32Bytes(0), longTo32Bytes(42), False, nullAddress, sender=tester.k1) assert orderID # fill order with shares assert fillOrder.publicFillOrder( orderID, fix(1), "43", False, "0x0000000000000000000000000000000000000000", 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_cancelBid(contractsFixture, cash, market, universe): createOrder = contractsFixture.contracts['CreateOrder'] cancelOrder = contractsFixture.contracts['CancelOrder'] orders = contractsFixture.contracts['Orders'] orderType = BID amount = fix(1) fxpPrice = 60 outcomeID = YES tradeGroupID = longTo32Bytes(42) yesShareToken = contractsFixture.applySignature('ShareToken', market.getShareToken(YES)) noShareToken = contractsFixture.applySignature('ShareToken', market.getShareToken(NO)) creatorInitialShares = yesShareToken.balanceOf( contractsFixture.accounts[1]) marketInitialCash = cash.balanceOf(market.address) marketInitialYesShares = yesShareToken.totalSupply() marketInitialNoShares = noShareToken.totalSupply() with BuyWithCash(cash, fix(fxpPrice), contractsFixture.accounts[1], "The sender didn't get cost deducted for create order"): orderID = createOrder.publicCreateOrder( orderType, amount, fxpPrice, market.address, outcomeID, longTo32Bytes(0), longTo32Bytes(0), tradeGroupID, nullAddress, sender=contractsFixture.accounts[1]) assert orderID, "Order ID should be non-zero" assert orders.getOrderCreator(orderID), "Order should have an owner" orderEventLog = { "universe": universe.address, "market": market.address, "eventType": 1, "addressData": [nullAddress, contractsFixture.accounts[1], nullAddress], "uint256Data": [ 0, 0, 0, fix('1', '60'), 0, 0, 0, contractsFixture.contracts['Time'].getTimestamp(), 0, 0 ], } with AssertLog(contractsFixture, 'OrderEvent', orderEventLog): assert (cancelOrder.cancelOrder( orderID, sender=contractsFixture.accounts[1]) == 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(contractsFixture.accounts[1]) == fix('60') ), "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( contractsFixture.accounts[1])), "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 proceedToNextRound(fixture, market, contributor=None, doGenerateFees=False, moveTimeForward=True, randomPayoutNumerators=False, description=""): contributor = contributor or fixture.accounts[0] if fixture.contracts["Augur"].getTimestamp() < market.getEndTime(): fixture.contracts["Time"].setTimestamp( market.getDesignatedReportingEndTime() + 1) disputeWindow = market.getDisputeWindow() payoutNumerators = [0] * market.getNumberOfOutcomes() payoutNumerators[1] = market.getNumTicks() if (disputeWindow == longToHexString(0)): market.doInitialReport(payoutNumerators, "", 0) assert market.getDisputeWindow() else: disputeWindow = fixture.applySignature('DisputeWindow', market.getDisputeWindow()) if market.getDisputePacingOn(): fixture.contracts["Time"].setTimestamp( disputeWindow.getStartTime() + 1) # This will also use the InitialReporter which is not a DisputeCrowdsourcer, but has the called function from abstract inheritance winningReport = fixture.applySignature( 'DisputeCrowdsourcer', market.getWinningReportingParticipant()) winningPayoutHash = winningReport.getPayoutDistributionHash() chosenPayoutNumerators = [0] * market.getNumberOfOutcomes() chosenPayoutNumerators[1] = market.getNumTicks() if (randomPayoutNumerators): chosenPayoutNumerators[1] = randint(0, market.getNumTicks()) chosenPayoutNumerators[2] = market.getNumTicks( ) - chosenPayoutNumerators[1] else: firstReportWinning = market.derivePayoutDistributionHash( payoutNumerators) == winningPayoutHash if firstReportWinning: chosenPayoutNumerators[1] = 0 chosenPayoutNumerators[2] = market.getNumTicks() chosenPayoutHash = market.derivePayoutDistributionHash( chosenPayoutNumerators) amount = 2 * market.getParticipantStake( ) - 3 * market.getStakeInOutcome(chosenPayoutHash) with PrintGasUsed(fixture, "Contribute:", 0): market.contribute(chosenPayoutNumerators, amount, description, sender=contributor) assert market.getForkingMarket( ) or market.getDisputeWindow() != disputeWindow if (doGenerateFees): universe = fixture.applySignature("Universe", market.getUniverse()) generateFees(fixture, universe, market) if (moveTimeForward): disputeWindow = fixture.applySignature('DisputeWindow', market.getDisputeWindow()) fixture.contracts["Time"].setTimestamp(disputeWindow.getStartTime() + 1)
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 logs = [] price = 6000 numTicks = market.getNumTicks() captureFilteredLogs(contractsFixture.chain.head_state, contractsFixture.contracts['Augur'], logs) 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 len(logs) == 8 log1 = logs[7] assert log1["_event_type"] == "OrderFilled" assert log1["filler"] == bytesToHexString(tester.a2) assert log1["numCreatorShares"] == 0 assert log1["numCreatorTokens"] == fix(1, price) assert log1["numFillerShares"] == 0 assert log1["numFillerTokens"] == fix(1, numTicks - price) assert log1["marketCreatorFees"] == 0 assert log1["reporterFees"] == 0 assert log1["shareToken"] == market.getShareToken(0) assert log1["tradeGroupId"] == stringToBytes("43") 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_forking(localFixture, universe, market, categoricalMarket, cash, reputationToken): # Let's do some initial disputes for the categorical market proceedToNextRound(localFixture, categoricalMarket, tester.k1, moveTimeForward=False) # Get to a fork testers = [tester.k0, tester.k1, tester.k2, tester.k3] testerIndex = 1 while (market.getForkingMarket() == longToHexString(0)): proceedToNextRound(localFixture, market, testers[testerIndex], True) testerIndex += 1 testerIndex = testerIndex % len(testers) # Have the participants fork and create new child universes for i in range(market.getNumParticipants()): reportingParticipant = localFixture.applySignature( "DisputeCrowdsourcer", market.getReportingParticipant(i)) with PrintGasUsed(localFixture, "Fork:", 0): reportingParticipant.fork(startgas=long(6.7 * 10**6)) # Finalize the fork finalizeFork(localFixture, market, universe) categoricalDisputeCrowdsourcer = localFixture.applySignature( "DisputeCrowdsourcer", categoricalMarket.getReportingParticipant(1)) # Migrate the categorical market into the winning universe. This will disavow the dispute crowdsourcer on it, letting us redeem for original universe rep and eth assert categoricalMarket.migrateThroughOneFork() expectedRep = categoricalDisputeCrowdsourcer.getStake() expectedEth = getExpectedFees(localFixture, cash, categoricalDisputeCrowdsourcer, 2) with EtherDelta(expectedEth, tester.a1, localFixture.chain, "Redeeming didn't increase ETH correctly"): with TokenDelta(reputationToken, expectedRep, tester.a1, "Redeeming didn't increase REP correctly"): categoricalDisputeCrowdsourcer.redeem(tester.a1, startgas=long(6.7 * 10**6)) # Now we'll redeem the forked reporting participants testers = [tester.a0, tester.a1, tester.a2, tester.a3] for i in range(market.getNumParticipants()): account = testers[i % 4] reportingParticipant = localFixture.applySignature( "DisputeCrowdsourcer", market.getReportingParticipant(i)) expectedRep = reportingParticipant.getStake() expectedRep += expectedRep / localFixture.contracts[ "Constants"].FORK_MIGRATION_PERCENTAGE_BONUS_DIVISOR() expectedRep += reportingParticipant.getStake() / 2 expectedEth = cash.balanceOf(reportingParticipant.address) newReputationToken = localFixture.applySignature( "ReputationToken", reportingParticipant.getReputationToken()) with EtherDelta(expectedEth, account, localFixture.chain, "Redeeming didn't increase ETH correctly"): with TokenDelta(newReputationToken, expectedRep, account, "Redeeming didn't increase REP correctly"): reportingParticipant.redeem(account, startgas=long(6.7 * 10**6))
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 logs = [] price = 6000 captureFilteredLogs(contractsFixture.chain.head_state, contractsFixture.contracts['Augur'], logs) 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 len(logs) == 10 log1 = logs[9] assert log1["_event_type"] == "OrderFilled" assert log1["filler"] == bytesToHexString(tester.a2) assert log1["numCreatorShares"] == fix(1) assert log1["numCreatorTokens"] == 0 assert log1["numFillerShares"] == fix(1) assert log1["numFillerTokens"] == 0 assert log1["marketCreatorFees"] == fix( 1, numTicks) / market.getMarketCreatorSettlementFeeDivisor() assert log1["reporterFees"] == fix( 1, numTicks) / universe.getOrCacheReportingFeeDivisor() assert log1["shareToken"] == market.getShareToken(0) assert log1["tradeGroupId"] == stringToBytes("43") 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_cancelWithSharesInEscrow(contractsFixture, cash, market, universe): shareToken = contractsFixture.contracts['ShareToken'] createOrder = contractsFixture.contracts['CreateOrder'] cancelOrder = contractsFixture.contracts['CancelOrder'] orders = contractsFixture.contracts['Orders'] 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()), contractsFixture.accounts[1], "buy complete set"): assert shareToken.publicBuyCompleteSets( market.address, fix(12), sender=contractsFixture.accounts[1]) assert cash.balanceOf(contractsFixture.accounts[1]) == fix('0') assert shareToken.balanceOfMarketOutcome( market.address, YES, contractsFixture.accounts[1]) == fix(12) assert shareToken.balanceOfMarketOutcome( market.address, NO, contractsFixture.accounts[1]) == fix(12) creatorInitialShares = shareToken.balanceOfMarketOutcome( market.address, YES, contractsFixture.accounts[1]) marketInitialCash = cash.balanceOf(market.address) marketInitialYesShares = shareToken.totalSupplyForMarketOutcome( market.address, YES) marketInitialNoShares = shareToken.totalSupplyForMarketOutcome( market.address, NO) # create BID order for YES with NO shares escrowed orderID = createOrder.publicCreateOrder( BID, fix(12), 60, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), longTo32Bytes(42), nullAddress, sender=contractsFixture.accounts[1]) assert orderID assert cash.balanceOf(contractsFixture.accounts[1]) == fix('0') assert shareToken.balanceOfMarketOutcome( market.address, YES, contractsFixture.accounts[1]) == fix(12) assert shareToken.balanceOfMarketOutcome(market.address, NO, contractsFixture.accounts[1]) == 0 # now cancel the order assert (cancelOrder.cancelOrder(orderID, sender=contractsFixture.accounts[1]) == 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 == shareToken.balanceOfMarketOutcome( market.address, YES, contractsFixture.accounts[1])), "Maker's shares should be unchanged" assert (marketInitialYesShares == shareToken.totalSupplyForMarketOutcome( market.address, YES)), "Market's yes shares should be unchanged" assert marketInitialNoShares == shareToken.totalSupplyForMarketOutcome( market.address, NO), "Market's no shares should be unchanged"
def localSnapshot(fixture, augurInitializedWithMocksSnapshot): fixture.resetToSnapshot(augurInitializedWithMocksSnapshot) augur = fixture.contracts['Augur'] mockCash = fixture.contracts['MockCash'] mockAugur = fixture.contracts['MockAugur'] mockInitialReporter = fixture.contracts['MockInitialReporter'] mockDisputeCrowdsourcer = fixture.contracts['MockDisputeCrowdsourcer'] mockShareTokenFactory = fixture.contracts['MockShareTokenFactory'] mockInitialReporterFactory = fixture.contracts[ 'MockInitialReporterFactory'] mockDisputeCrowdsourcerFactory = fixture.contracts[ 'MockDisputeCrowdsourcerFactory'] mockShareToken = fixture.contracts['MockShareToken'] # pre populate share tokens for max of 8 possible outcomes for index in range(8): item = fixture.uploadAndAddToAugur( 'solidity_test_helpers/MockShareToken.sol', 'newMockShareToken' + str(index)) mockShareTokenFactory.pushCreateShareToken(item.address) augur.registerContract(stringToBytes('Cash'), mockCash.address) augur.registerContract(stringToBytes('ShareTokenFactory'), mockShareTokenFactory.address) augur.registerContract(stringToBytes('InitialReporterFactory'), mockInitialReporterFactory.address) augur.registerContract(stringToBytes('DisputeCrowdsourcerFactory'), mockDisputeCrowdsourcerFactory.address) mockShareTokenFactory.resetCreateShareToken() mockReputationToken = fixture.contracts['MockReputationToken'] mockUniverse = fixture.contracts['MockUniverse'] mockUniverse.setReputationToken(mockReputationToken.address) mockDisputeWindow = fixture.contracts['MockDisputeWindow'] mockDisputeWindow.setReputationToken(mockReputationToken.address) mockDisputeWindow.setUniverse(mockUniverse.address) mockNextDisputeWindow = fixture.upload( 'solidity_test_helpers/MockDisputeWindow.sol', 'mockNextDisputeWindow') mockNextDisputeWindow.setReputationToken(mockReputationToken.address) mockNextDisputeWindow.setUniverse(mockUniverse.address) mockInitialReporterFactory.setInitialReporter(mockInitialReporter.address) mockDisputeCrowdsourcerFactory.setDisputeCrowdsourcer( mockDisputeCrowdsourcer.address) constants = fixture.contracts['Constants'] market = fixture.upload('../source/contracts/reporting/Market.sol', 'market') fixture.contracts["initializedMarket"] = market contractMap = fixture.upload( '../source/contracts/libraries/collections/Map.sol', 'Map') endTime = fixture.contracts["Time"].getTimestamp( ) + constants.DESIGNATED_REPORTING_DURATION_SECONDS() mockUniverse.setForkingMarket(longToHexString(0)) mockUniverse.setOrCacheDesignatedReportNoShowBond(100) mockReputationToken.setBalanceOf(100) mockUniverse.setOrCacheTargetReporterGasCosts(15) mockUniverse.setOrCacheValidityBond(12) mockUniverse.setNextDisputeWindow(mockNextDisputeWindow.address) mockDisputeWindow.setEndTime( fixture.contracts["Time"].getTimestamp() + constants.DESIGNATED_REPORTING_DURATION_SECONDS()) mockNextDisputeWindow.setEndTime( mockDisputeWindow.getEndTime() + constants.DESIGNATED_REPORTING_DURATION_SECONDS()) assert market.initialize(mockUniverse.address, endTime, 16, tester.a1, tester.a2, 5, numTicks, value=100) return fixture.createSnapshot()