def test_ask_withPartialShares(contractsFixture, universe, cash, market): orders = contractsFixture.contracts['Orders'] createOrder = contractsFixture.contracts['CreateOrder'] fillOrder = contractsFixture.contracts['FillOrder'] completeSets = contractsFixture.contracts['CompleteSets'] yesShareToken = contractsFixture.applySignature('ShareToken', market.getShareToken(YES)) noShareToken = contractsFixture.applySignature('ShareToken', market.getShareToken(NO)) # buy fix(2) complete sets assert completeSets.publicBuyCompleteSets(market.address, fix(2), sender = tester.k1, value= fix(2, market.getNumTicks())) assert cash.balanceOf(tester.a1) == fix('0') assert yesShareToken.balanceOf(tester.a1) == fix(2) assert noShareToken.balanceOf(tester.a1) == fix(2) orderID = None orderCreatedLog = { 'creator': bytesToHexString(tester.a1), 'shareToken': yesShareToken.address, 'tradeGroupId': stringToBytes("42"), } with AssertLog(contractsFixture, "OrderCreated", orderCreatedLog): orderID = createOrder.publicCreateOrder(ASK, fix(3), 4000, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), "42", sender=tester.k1, value=fix('6000')) assert cash.balanceOf(tester.a1) == fix('0') assert yesShareToken.balanceOf(tester.a1) == 0 assert noShareToken.balanceOf(tester.a1) == fix(2) # validate the order contains expected results assert orderID != bytearray(32), "Order ID should be non-zero" assert orders.getAmount(orderID) == fix(3) assert orders.getPrice(orderID) == 4000 assert orders.getOrderCreator(orderID) == bytesToHexString(tester.a1) assert orders.getOrderMoneyEscrowed(orderID) == fix('6000') assert orders.getOrderSharesEscrowed(orderID) == fix(2)
def test_saveOrder(contractsFixture, market): orders = contractsFixture.contracts['Orders'] orderId1 = orders.saveOrder(BID, market.address, fix(10), 5000, tester.a1, NO, 0, fix(10), longTo32Bytes(0), longTo32Bytes(0), "1") assert(orderId1 != bytearray(32)), "saveOrder wasn't executed successfully" orderId2 = orders.saveOrder(ASK, market.address, fix(10), 5000, tester.a2, NO, fix('10', '5000'), 0, longTo32Bytes(0), longTo32Bytes(0), "1") assert(orderId2 != bytearray(32)), "saveOrder wasn't executed successfully" assert(orders.getAmount(orderId1) == fix(10)), "amount for order1 should be set to 10" assert(orders.getAmount(orderId2) == fix(10)), "amount for order2 should be set to 10" assert(orders.getPrice(orderId1) == 5000), "price for order1 should be set to 5000 wei" assert(orders.getPrice(orderId2) == 5000), "price for order2 should be set to 5000 wei" assert(orders.getOrderCreator(orderId1) == bytesToHexString(tester.a1)), "orderOwner for order1 should be tester.a1" assert(orders.getOrderCreator(orderId2) == bytesToHexString(tester.a2)), "orderOwner for order2 should be tester.a2" assert orders.getOrderMoneyEscrowed(orderId1) == 0, "money escrowed should be 0" assert orders.getOrderMoneyEscrowed(orderId2) == fix('10', '5000'), "money escrowed should be 50000 ETH" assert orders.getOrderSharesEscrowed(orderId1) == fix(10), "shares escrowed should be fix(10)" assert orders.getOrderSharesEscrowed(orderId2) == 0, "shares escrowed should be 0" assert orders.getBetterOrderId(orderId1) == longTo32Bytes(0), "better order id should be 0" assert orders.getBetterOrderId(orderId2) == longTo32Bytes(0), "better order id should be 0" assert orders.getWorseOrderId(orderId1) == longTo32Bytes(0), "worse order id should be 0" assert orders.getWorseOrderId(orderId2) == longTo32Bytes(0), "worse order id should be 0" assert(orders.removeOrder(orderId1) == 1), "Remove order 1" assert(orders.removeOrder(orderId2) == 1), "Remove order 2"
def test_fee_window_logging(contractsFixture, market, categoricalMarket, scalarMarket, universe): feeWindow = contractsFixture.applySignature('FeeWindow', universe.getOrCreateCurrentFeeWindow()) contractsFixture.contracts["Time"].setTimestamp(feeWindow.getStartTime() + 1) assert feeWindow.buy(100) tokensTransferredLog = { 'from': bytesToHexString(tester.a0), 'to': bytesToHexString(tester.a1), 'token': feeWindow.address, 'universe': universe.address, 'tokenType': 3, 'value': 8 } with AssertLog(contractsFixture, "TokensTransferred", tokensTransferredLog): assert feeWindow.transfer(tester.a1, 8) assert feeWindow.approve(tester.a2, 12) tokensTransferredLog = { 'from': bytesToHexString(tester.a0), 'to': bytesToHexString(tester.a1), 'token': feeWindow.address, 'universe': universe.address, 'tokenType': 3, 'value': 12 } with AssertLog(contractsFixture, "TokensTransferred", tokensTransferredLog): assert feeWindow.transferFrom(tester.a0, tester.a1, 12, sender=tester.k2)
def test_publicCreateOrder_bid2(contractsFixture, cash, market, universe): orders = contractsFixture.contracts['Orders'] createOrder = contractsFixture.contracts['CreateOrder'] orderType = BID amount = fix(1) fxpPrice = 4000 outcome = 0 tradeGroupID = "42" marketInitialCash = cash.balanceOf(market.address) creatorInitialETH = contractsFixture.chain.head_state.get_balance(tester.a1) orderID = None shareToken = contractsFixture.getShareToken(market, 0) orderCreatedLog = { 'creator': bytesToHexString(tester.a1), 'shareToken': shareToken.address, 'tradeGroupId': stringToBytes("42"), } with AssertLog(contractsFixture, "OrderCreated", orderCreatedLog): orderID = createOrder.publicCreateOrder(orderType, amount, fxpPrice, market.address, outcome, longTo32Bytes(0), longTo32Bytes(0), tradeGroupID, sender=tester.k1, value = fix('1', '4000')) assert orderID != bytearray(32), "Order ID should be non-zero" assert orders.getAmount(orderID) == amount assert orders.getPrice(orderID) == fxpPrice assert orders.getOrderCreator(orderID) == bytesToHexString(tester.a1) assert orders.getOrderMoneyEscrowed(orderID) == fix(1, 4000) assert orders.getOrderSharesEscrowed(orderID) == 0 assert cash.balanceOf(tester.a1) == 0 assert contractsFixture.chain.head_state.get_balance(tester.a1) == creatorInitialETH - long(4000 * 10**18) assert cash.balanceOf(market.address) - marketInitialCash == 4000 * 10**18
def test_fee_window_redeem_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.k1) == True assert initializedFeeWindow.balanceOf(tester.a1) == 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) assert mockReputationToken.getTransferValueFor(tester.a1) == 0 Time.setTimestamp(feeWindowId * mockUniverse.getDisputeRoundDurationInSeconds() + constants.DISPUTE_ROUND_DURATION_SECONDS()) assert initializedFeeWindow.isOver() == True assert mockFeeToken.balanceOf(tester.a1) == feeTokenBalance assert initializedFeeWindow.redeem(tester.a1) == True assert mockReputationToken.getTransferValueFor(tester.a1) == attoToken assert initializedFeeWindow.balanceOf(tester.a1) == 0 assert mockFeeToken.getFeeWindowBurnTargetValue() == bytesToHexString(tester.a1) assert mockFeeToken.getFeeWindowBurnAmountValue() == feeTokenBalance assert mockCash.getTransferValueFor(tester.a1) == 0 assert mockCash.getwithdrawEtherToAddressValue() == bytesToHexString(tester.a1) assert mockCash.getwithdrawEthertoAmountValue() == feeWindowBalance * (attoToken + feeTokenBalance) / attoToken
def test_one_bid_on_books_buy_excess_order(contractsFixture, cash, market, universe): createOrder = contractsFixture.contracts['CreateOrder'] trade = contractsFixture.contracts['Trade'] fillOrder = contractsFixture.contracts['FillOrder'] orders = contractsFixture.contracts['Orders'] tradeGroupID = "42" # create order orderID = createOrder.publicCreateOrder(BID, fix(4), 6000, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), tradeGroupID, sender = tester.k1, value=fix('4', '6000')) fillOrderID = None # fill best order orderFilledLog = { "filler": bytesToHexString(tester.a2), "numCreatorShares": 0, "numCreatorTokens": fix('4', '6000'), "numFillerShares": 0, "numFillerTokens": fix('4', '4000'), "marketCreatorFees": 0, "reporterFees": 0, "shareToken": market.getShareToken(YES), "tradeGroupId": stringToBytes("42"), } orderCreatedLog = { "creator": bytesToHexString(tester.a2), "shareToken": market.getShareToken(YES), "tradeGroupId": stringToBytes("42"), } with AssertLog(contractsFixture, "OrderFilled", orderFilledLog): with AssertLog(contractsFixture, "OrderCreated", orderCreatedLog): fillOrderID = trade.publicSell(market.address, YES, fix(5), 6000, "0", "0", tradeGroupID, sender = tester.k2, value=fix('5', '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) assert orders.getAmount(fillOrderID) == fix(1) assert orders.getPrice(fillOrderID) == 6000 assert orders.getOrderCreator(fillOrderID) == bytesToHexString(tester.a2) assert orders.getOrderMoneyEscrowed(fillOrderID) == fix('1', '4000') assert orders.getOrderSharesEscrowed(fillOrderID) == 0 assert orders.getBetterOrderId(fillOrderID) == longTo32Bytes(0) assert orders.getWorseOrderId(fillOrderID) == longTo32Bytes(0)
def test_one_bid_on_books_buy_partial_order(useTrade, contractsFixture, cash, market, universe): createOrder = contractsFixture.contracts['CreateOrder'] trade = contractsFixture.contracts['Trade'] fillOrder = contractsFixture.contracts['FillOrder'] orders = contractsFixture.contracts['Orders'] tradeGroupID = "42" # create order orderID = createOrder.publicCreateOrder(BID, fix(2), 6000, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), tradeGroupID, sender = tester.k1, value=fix('2', '6000')) # fill best order fillOrderID = None if useTrade: fillOrderID = trade.publicTrade(1, market.address, YES, fix(1), 6000, "0", "0", tradeGroupID, sender = tester.k2, value=fix('1', '4000')) else: fillOrderID = trade.publicSell(market.address, YES, fix(1), 6000, "0", "0", tradeGroupID, sender = tester.k2, value=fix('1', '4000')) assert orders.getAmount(orderID) == fix(1) assert orders.getPrice(orderID) == 6000 assert orders.getOrderCreator(orderID) == bytesToHexString(tester.a1) assert orders.getOrderMoneyEscrowed(orderID) == fix('1', '6000') assert orders.getOrderSharesEscrowed(orderID) == 0 assert orders.getBetterOrderId(orderID) == longTo32Bytes(0) assert orders.getWorseOrderId(orderID) == longTo32Bytes(0) assert fillOrderID == longTo32Bytes(1)
def test_two_asks_on_books_buy_full_and_partial(contractsFixture, cash, market, universe): createOrder = contractsFixture.contracts['CreateOrder'] trade = contractsFixture.contracts['Trade'] fillOrder = contractsFixture.contracts['FillOrder'] orders = contractsFixture.contracts['Orders'] tradeGroupID = "42" # create order 1 orderID1 = createOrder.publicCreateOrder(ASK, fix(12), 6000, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), tradeGroupID, sender = tester.k1, value=fix('12', '4000')) # create order 2 orderID2 = createOrder.publicCreateOrder(ASK, fix(7), 6000, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), tradeGroupID, sender = tester.k3, value=fix('7', '4000')) # fill best order fillOrderID = trade.publicBuy(market.address, YES, fix(15), 6000, "0", "0", tradeGroupID, sender = tester.k2, value=fix('15', '6000')) assert orders.getAmount(orderID1) == 0 assert orders.getPrice(orderID1) == 0 assert orders.getOrderCreator(orderID1) == longToHexString(0) assert orders.getOrderMoneyEscrowed(orderID1) == 0 assert orders.getOrderSharesEscrowed(orderID1) == 0 assert orders.getBetterOrderId(orderID1) == longTo32Bytes(0) assert orders.getWorseOrderId(orderID1) == longTo32Bytes(0) assert orders.getAmount(orderID2) == fix(4) assert orders.getPrice(orderID2) == 6000 assert orders.getOrderCreator(orderID2) == bytesToHexString(tester.a3) assert orders.getOrderMoneyEscrowed(orderID2) == fix('4', '4000') assert orders.getOrderSharesEscrowed(orderID2) == 0 assert orders.getBetterOrderId(orderID2) == longTo32Bytes(0) assert orders.getWorseOrderId(orderID2) == longTo32Bytes(0) assert fillOrderID == longTo32Bytes(1)
def test_one_ask_on_books_buy_excess_order(contractsFixture, cash, market, universe): createOrder = contractsFixture.contracts['CreateOrder'] trade = contractsFixture.contracts['Trade'] fillOrder = contractsFixture.contracts['FillOrder'] orders = contractsFixture.contracts['Orders'] tradeGroupID = "42" # create order orderID = createOrder.publicCreateOrder(ASK, fix(12), 6000, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), tradeGroupID, sender = tester.k1, value=fix('12', '4000')) # fill best order fillOrderID = trade.publicBuy(market.address, YES, fix(15), 6000, "0", "0", tradeGroupID, sender = tester.k2, value=fix('15', '6000')) assert orders.getAmount(orderID) == 0 assert orders.getPrice(orderID) == 0 assert orders.getOrderCreator(orderID) == longToHexString(0) assert orders.getOrderMoneyEscrowed(orderID) == 0 assert orders.getOrderSharesEscrowed(orderID) == 0 assert orders.getBetterOrderId(orderID) == longTo32Bytes(0) assert orders.getWorseOrderId(orderID) == longTo32Bytes(0) assert orders.getAmount(fillOrderID) == fix(3) assert orders.getPrice(fillOrderID) == 6000 assert orders.getOrderCreator(fillOrderID) == bytesToHexString(tester.a2) assert orders.getOrderMoneyEscrowed(fillOrderID) == fix('3', '6000') assert orders.getOrderSharesEscrowed(fillOrderID) == 0 assert orders.getBetterOrderId(fillOrderID) == longTo32Bytes(0) assert orders.getWorseOrderId(fillOrderID) == longTo32Bytes(0)
def test_contribute(localFixture, initializedMarket, mockNextFeeWindow, mockInitialReporter, mockDisputeCrowdsourcer, mockDisputeCrowdsourcerFactory): # We can't contribute until there is an initial report to dispute with raises(TransactionFailed, message="can't contribute until there is an initial report to dispute"): initializedMarket.contribute([0, 0, 0, 0, initializedMarket.getNumTicks()], False, 1) localFixture.contracts["Time"].setTimestamp(initializedMarket.getEndTime() + 1) assert initializedMarket.doInitialReport([initializedMarket.getNumTicks(), 0, 0, 0, 0], False, sender=tester.k1) # We can't contribute till the window begins with raises(TransactionFailed, message="can't contribute until the window begins"): initializedMarket.contribute([0, 0, 0, 0, initializedMarket.getNumTicks()], False, 1) mockNextFeeWindow.setIsActive(True) winningPayoutHash = initializedMarket.derivePayoutDistributionHash([initializedMarket.getNumTicks(), 0, 0, 0, 0], False) mockInitialReporter.setPayoutDistributionHash(winningPayoutHash) # We can't contribute to the current winning outcome with raises(TransactionFailed, message="can't contribute to current winning outcome"): initializedMarket.contribute([initializedMarket.getNumTicks(), 0, 0, 0, 0], False, 1) assert initializedMarket.contribute([0, 0, 0, 0, initializedMarket.getNumTicks()], False, 1) assert mockDisputeCrowdsourcer.contributeWasCalled() == True assert mockDisputeCrowdsourcer.getContributeParticipant() == bytesToHexString(tester.a0) assert mockDisputeCrowdsourcer.getContributeAmount() == 1
def upload(self, relativeFilePath, lookupKey = None, signatureKey = None, constructorArgs=[]): resolvedPath = resolveRelativePath(relativeFilePath) if self.coverageMode: resolvedPath = resolvedPath.replace("tests", "coverageEnv").replace("source/", "coverageEnv/") lookupKey = lookupKey if lookupKey else path.splitext(path.basename(resolvedPath))[0] signatureKey = signatureKey if signatureKey else lookupKey if lookupKey in self.contracts: return(self.contracts[lookupKey]) compiledCode = self.getCompiledCode(resolvedPath) # abstract contracts have a 0-length array for bytecode if len(compiledCode) == 0: if ("libraries" in relativeFilePath or lookupKey.startswith("I") or lookupKey.startswith("Base")): pass#print "Skipping upload of " + lookupKey + " because it had no bytecode (likely a abstract class/interface)." else: raise Exception("Contract: " + lookupKey + " has no bytecode, but this is not expected. It probably doesn't implement all its abstract methods") return None if signatureKey not in ContractsFixture.signatures: ContractsFixture.signatures[signatureKey] = self.generateSignature(resolvedPath) signature = ContractsFixture.signatures[signatureKey] contractTranslator = ContractTranslator(signature) if len(constructorArgs) > 0: compiledCode += contractTranslator.encode_constructor_arguments(constructorArgs) contractAddress = bytesToHexString(self.chain.contract(compiledCode, language='evm')) contract = ABIContract(self.chain, contractTranslator, contractAddress) self.contracts[lookupKey] = contract 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 test_setController(controlled): with raises(TransactionFailed): controlled.setController(tester.a1, sender=tester.k1) assert controlled.setController(tester.a1, sender=tester.k0) assert controlled.getController() == bytesToHexString(tester.a1) with raises(TransactionFailed): controlled.setController(tester.a2, sender=tester.k0)
def localSnapshot(fixture, baseSnapshot): fixture.resetToSnapshot(baseSnapshot) controller = fixture.upload('../source/contracts/Controller.sol') assert fixture.contracts['Controller'].owner() == bytesToHexString(tester.a0) fixture.upload('solidity_test_helpers/ControllerUser.sol') fixture.uploadAugur() return fixture.createSnapshot()
def test_crowdsourcer_transfer(contractsFixture, market, universe): proceedToNextRound(contractsFixture, market) proceedToNextRound(contractsFixture, market) proceedToNextRound(contractsFixture, market) crowdsourcer = contractsFixture.applySignature("DisputeCrowdsourcer", market.getWinningReportingParticipant()) crowdsourcerTokenTransferLog = { 'from': bytesToHexString(tester.a0), 'to': bytesToHexString(tester.a1), 'token': crowdsourcer.address, 'universe': universe.address, 'tokenType': 2, 'value': 0, } with AssertLog(contractsFixture, "TokensTransferred", crowdsourcerTokenTransferLog): assert crowdsourcer.transfer(tester.a1, 0)
def test_initialReport_methods(localFixture, universe, market, cash, constants): reputationToken = localFixture.applySignature("ReputationToken", universe.getReputationToken()) # proceed to the initial reporting period proceedToInitialReporting(localFixture, market) # do an initial report as someone other than the designated reporter assert market.doInitialReport([0, market.getNumTicks()], False, sender=tester.k1) # the market is now assigned a fee window newFeeWindowAddress = market.getFeeWindow() assert newFeeWindowAddress feeWindow = localFixture.applySignature('FeeWindow', newFeeWindowAddress) # time marches on and the market can be finalized localFixture.contracts["Time"].setTimestamp(feeWindow.getEndTime() + 1) assert market.finalize() # We can see that the market reports the designated reporter did not show assert not market.designatedReporterShowed() # Let's get a reference to the Initial Reporter bond and transfer it to the original designated reporter account initialReporter = localFixture.applySignature("InitialReporter", market.getInitialReporter()) transferLog = { "universe": universe.address, "market": market.address, "from": bytesToHexString(tester.a1), "to": initialReporter.getDesignatedReporter(), } with AssertLog(localFixture, "InitialReporterTransferred", transferLog): assert initialReporter.transferOwnership(initialReporter.getDesignatedReporter(), sender=tester.k1) # Transfering to the owner is a noop assert initialReporter.transferOwnership(initialReporter.getDesignatedReporter()) # The market still correctly indicates the designated reporter did not show up assert not market.designatedReporterShowed() # confirm we cannot call protected methods on the initial reporter which only the market may use with raises(TransactionFailed): initialReporter.report(tester.a0, "", [], False) with raises(TransactionFailed): initialReporter.resetReportTimestamp() with raises(TransactionFailed): initialReporter.migrateREP() # When we redeem the initialReporter it goes to the correct party as well expectedRep = initialReporter.getStake() owner = initialReporter.getOwner() expectedGasBond = 2 * constants.GAS_TO_REPORT() * constants.DEFAULT_REPORTING_GAS_PRICE() with EtherDelta(expectedGasBond, owner, localFixture.chain, "Initial reporter did not get the reporting gas cost bond"): with TokenDelta(reputationToken, expectedRep, owner, "Redeeming didn't refund REP"): assert initialReporter.redeem(owner)
def test_one_round_crowdsourcer_fees(localFixture, universe, market, cash, reputationToken): feeWindow = localFixture.applySignature('FeeWindow', market.getFeeWindow()) constants = localFixture.contracts["Constants"] # We'll make the window active localFixture.contracts["Time"].setTimestamp(feeWindow.getStartTime() + 1) # generate some fees generateFees(localFixture, universe, market) # We'll have testers push markets into the next round by funding dispute crowdsourcers amount = 2 * market.getParticipantStake() with TokenDelta(reputationToken, -amount, tester.a1, "Disputing did not reduce REP balance correctly"): assert market.contribute([0, market.getNumTicks()], False, amount, sender=tester.k1) newFeeWindowAddress = market.getFeeWindow() assert newFeeWindowAddress != feeWindow.address # fast forward time to the fee new window and generate additional fees feeWindow = localFixture.applySignature('FeeWindow', newFeeWindowAddress) localFixture.contracts["Time"].setTimestamp(feeWindow.getStartTime() + 1) # Fast forward time until the new fee window is over and we can redeem our winning stake, and dispute bond tokens and receive fees localFixture.contracts["Time"].setTimestamp(feeWindow.getEndTime() + 1) assert market.finalize() initialReporter = localFixture.applySignature('InitialReporter', market.getReportingParticipant(0)) marketDisputeCrowdsourcer = localFixture.applySignature('DisputeCrowdsourcer', market.getReportingParticipant(1)) # The dispute crowdsourcer contributor locked in REP for 2 rounds, as did the Initial Reporter expectedTotalFees = cash.balanceOf(feeWindow.address) + cash.balanceOf(universe.getOrCreateFeeWindowBefore(feeWindow.address)) expectedFees = expectedTotalFees * 2 / 3 expectedRep = market.getParticipantStake() assert expectedRep == long(marketDisputeCrowdsourcer.getStake() + marketDisputeCrowdsourcer.getStake() / 2) disputeCrowdsourcerRedeemedLog = { "reporter": bytesToHexString(tester.a1), "disputeCrowdsourcer": marketDisputeCrowdsourcer.address, "amountRedeemed": marketDisputeCrowdsourcer.getStake(), "repReceived": expectedRep, "reportingFeesReceived": expectedFees, "payoutNumerators": [0, market.getNumTicks()], "universe": universe.address, "market": market.address } with AssertLog(localFixture, "DisputeCrowdsourcerRedeemed", disputeCrowdsourcerRedeemedLog): with TokenDelta(reputationToken, expectedRep, tester.a1, "Redeeming didn't refund REP"): with EtherDelta(expectedFees, tester.a1, localFixture.chain, "Redeeming didn't increase ETH correctly"): assert marketDisputeCrowdsourcer.redeem(tester.a1, sender=tester.k1) # The initial reporter gets fees even though they were not correct. They do not get their REP back though expectedFees = cash.balanceOf(feeWindow.address) + cash.balanceOf(universe.getOrCreateFeeWindowBefore(feeWindow.address)) with TokenDelta(reputationToken, 0, tester.a0, "Redeeming didn't refund REP"): with EtherDelta(expectedFees, tester.a0, localFixture.chain, "Redeeming didn't increase ETH correctly"): assert initialReporter.redeem(tester.a0)
def test_reputation_token_logging(contractsFixture, universe): reputationToken = contractsFixture.applySignature("ReputationToken", universe.getReputationToken()) tokensTransferredLog = { 'from': bytesToHexString(tester.a0), 'to': bytesToHexString(tester.a1), 'token': reputationToken.address, 'universe': universe.address, 'tokenType': 0, 'value': 8, } with AssertLog(contractsFixture, 'TokensTransferred', tokensTransferredLog): assert reputationToken.transfer(tester.a1, 8) assert reputationToken.approve(tester.a2, 12) tokensTransferredLog['value'] = 12 with AssertLog(contractsFixture, 'TokensTransferred', tokensTransferredLog): assert reputationToken.transferFrom(tester.a0, tester.a1, 12, sender=tester.k2)
def test_transfering_ownership(contractsFixture, universe, market): transferLog = { "universe": universe.address, "market": market.address, "from": bytesToHexString(tester.a0), "to": bytesToHexString(tester.a1), } with AssertLog(contractsFixture, "MarketTransferred", transferLog): assert market.transferOwnership(tester.a1) mailbox = contractsFixture.applySignature('Mailbox', market.getMarketCreatorMailbox()) transferLog = { "universe": universe.address, "market": market.address, "from": bytesToHexString(tester.a0), "to": bytesToHexString(tester.a1), } with AssertLog(contractsFixture, "MarketMailboxTransferred", transferLog): assert mailbox.transferOwnership(tester.a1)
def test_fee_token(contractsFixture, universe): feeWindow = contractsFixture.applySignature('FeeWindow', universe.getOrCreateCurrentFeeWindow()) feeToken = contractsFixture.applySignature("FeeToken", feeWindow.getFeeToken()) feeTokenTransferLog = { 'from': bytesToHexString(tester.a0), 'to': bytesToHexString(tester.a1), 'token': feeToken.address, 'universe': universe.address, 'tokenType': 4, 'value': 0, } with AssertLog(contractsFixture, "TokensTransferred", feeTokenTransferLog): assert feeToken.transfer(tester.a1, 0) with raises(TransactionFailed): feeToken.feeWindowBurn(tester.a0, 1) with raises(TransactionFailed): feeToken.mintForReportingParticipant(tester.a0, 1)
def test_approve(contractsFixture, market): shareToken = contractsFixture.applySignature('ShareToken', market.getShareToken()) shareToken.createShares(tester.a0, 7, sender=tester.k0) assert(shareToken.allowance(tester.a0, tester.a1) == 0), "initial allowance is 0" approvalLog = { "owner": bytesToHexString(tester.a0), "spender": bytesToHexString(tester.a1), "value": 10 } with AssertLog(contractsFixture, "Approval", approvalLog, contract=shareToken): assert shareToken.approve(tester.a1, 10, sender=tester.k0) assert(shareToken.allowance(tester.a0, tester.a1) == 10), "allowance is 10 after approval" transferLog = { "from": bytesToHexString(tester.a0), "to": bytesToHexString(tester.a1), "value": 7 } tokensTransferredLog = { "token": shareToken.address, "from": bytesToHexString(tester.a0), "to": bytesToHexString(tester.a1), "universe": market.getUniverse(), "tokenType": 1, "market": market.address, "value": 7 } with AssertLog(contractsFixture, "Transfer", transferLog, contract=shareToken): with AssertLog(contractsFixture, "TokensTransferred", tokensTransferredLog): assert shareToken.transferFrom(tester.a0, tester.a1, 7, sender=tester.k1)
def test_transfer(contractsFixture, market): shareToken = contractsFixture.applySignature('ShareToken', market.getShareToken()) shareToken.createShares(tester.a0, 7, sender=tester.k0) initialTotalSupply = shareToken.totalSupply() initialBalance0 = shareToken.balanceOf(tester.a0) initialBalance1 = shareToken.balanceOf(tester.a1) with raises(TransactionFailed): shareToken.transfer(tester.a0, 11, sender=tester.k0) with raises(TransactionFailed): shareToken.transfer(tester.a0, 5, sender = tester.k1) transferLog = { "_event_type": "Transfer", "from": bytesToHexString(tester.a0), "to": bytesToHexString(tester.a1), "value": 5, } tokensTransferredLog = { "_event_type": "TokensTransferred", "token": shareToken.address, "from": bytesToHexString(tester.a0), "to": bytesToHexString(tester.a1), "universe": market.getUniverse(), "tokenType": 1, "market": market.address, "value": 5 } with AssertLog(contractsFixture, "Transfer", transferLog, contract=shareToken): with AssertLog(contractsFixture, "TokensTransferred", tokensTransferredLog): assert shareToken.transfer(tester.a1, 5, sender=tester.k0) afterTransferBalance0 = shareToken.balanceOf(tester.a0) afterTransferBalance1 = shareToken.balanceOf(tester.a1) assert(initialBalance0 - 5 == afterTransferBalance0), "Decrease in address 1's balance should equal amount transferred" assert(initialBalance1 + 5 == afterTransferBalance1), "Increase in address 2's balance should equal amount transferred" assert(shareToken.totalSupply() == initialTotalSupply), "Total supply should be unchanged"
def test_universe_rep_price_oracle(localFixture, populatedUniverse, mockReputationToken, mockShareToken): controller = localFixture.contracts['Controller'] repPriceOracle = localFixture.uploadAndAddToController("../source/contracts/reporting/RepPriceOracle.sol", 'repPriceOracle') controller.registerContract(stringToBytes('RepPriceOracle'), repPriceOracle.address, twentyZeros, thirtyTwoZeros) mockReputationToken.setTotalSupply(0) assert populatedUniverse.getRepMarketCapInAttoeth() == 0 mockReputationToken.setTotalSupply(1) assert repPriceOracle.setRepPriceInAttoEth(100) assert populatedUniverse.getRepMarketCapInAttoeth() == 100 mockReputationToken.setTotalSupply(12) assert populatedUniverse.getRepMarketCapInAttoeth() == 1200 assert repPriceOracle.transferOwnership(tester.a1) assert repPriceOracle.getOwner() == bytesToHexString(tester.a1)
def test_two_bids_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 = "42" # 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), 5000, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), tradeGroupID, sender = tester.k3, value=fix('7', '5000')) # fill/create fillOrderID = trade.publicSell(market.address, YES, fix(15), 6000, "0", "0", tradeGroupID, sender = tester.k2, value=fix('15', '4000')) assert orders.getAmount(orderID1) == 0 assert orders.getPrice(orderID1) == 0 assert orders.getOrderCreator(orderID1) == longToHexString(0) assert orders.getOrderMoneyEscrowed(orderID1) == 0 assert orders.getOrderSharesEscrowed(orderID1) == 0 assert orders.getBetterOrderId(orderID1) == longTo32Bytes(0) assert orders.getWorseOrderId(orderID1) == longTo32Bytes(0) assert orders.getAmount(orderID2) == fix(7) assert orders.getPrice(orderID2) == 5000 assert orders.getOrderCreator(orderID2) == bytesToHexString(tester.a3) assert orders.getOrderMoneyEscrowed(orderID2) == fix('7', '5000') assert orders.getOrderSharesEscrowed(orderID2) == 0 assert orders.getBetterOrderId(orderID2) == longTo32Bytes(0) assert orders.getWorseOrderId(orderID2) == longTo32Bytes(0) assert orders.getAmount(fillOrderID) == fix(3) assert orders.getPrice(fillOrderID) == 6000 assert orders.getOrderCreator(fillOrderID) == bytesToHexString(tester.a2) assert orders.getOrderMoneyEscrowed(fillOrderID) == fix('3', '4000') assert orders.getOrderSharesEscrowed(fillOrderID) == 0 assert orders.getBetterOrderId(fillOrderID) == longTo32Bytes(0) assert orders.getWorseOrderId(fillOrderID) == longTo32Bytes(0)
def test_publicCreateOrder_ask(contractsFixture, cash, market): orders = contractsFixture.contracts['Orders'] createOrder = contractsFixture.contracts['CreateOrder'] orderID = createOrder.publicCreateOrder(ASK, fix(1), 4000, market.address, 0, longTo32Bytes(0), longTo32Bytes(0), "7", value = fix(1, 6000)) assert orders.getAmount(orderID) == fix(1) assert orders.getPrice(orderID) == 4000 assert orders.getOrderCreator(orderID) == bytesToHexString(tester.a0) assert orders.getOrderMoneyEscrowed(orderID) == fix(1, 6000) assert orders.getOrderSharesEscrowed(orderID) == 0 assert orders.getBetterOrderId(orderID) == bytearray(32) assert orders.getWorseOrderId(orderID) == bytearray(32) assert cash.balanceOf(market.address) == fix(1, 6000)
def test_redeem_shares_in_binary_market(kitchenSinkFixture, universe, cash, market): claimTradingProceeds = kitchenSinkFixture.contracts['ClaimTradingProceeds'] yesShareToken = kitchenSinkFixture.applySignature('ShareToken', market.getShareToken(YES)) noShareToken = kitchenSinkFixture.applySignature('ShareToken', market.getShareToken(NO)) expectedValue = 1 * market.getNumTicks() expectedReporterFees = expectedValue / universe.getOrCacheReportingFeeDivisor() expectedMarketCreatorFees = expectedValue / market.getMarketCreatorSettlementFeeDivisor() expectedSettlementFees = expectedReporterFees + expectedMarketCreatorFees expectedPayout = long(expectedValue - expectedSettlementFees) assert universe.getOpenInterestInAttoEth() == 0 # get YES shares with a1 acquireLongShares(kitchenSinkFixture, cash, market, YES, 1, claimTradingProceeds.address, sender = tester.k1) assert universe.getOpenInterestInAttoEth() == 1 * market.getNumTicks() # get NO shares with a2 acquireShortShareSet(kitchenSinkFixture, cash, market, YES, 1, claimTradingProceeds.address, sender = tester.k2) assert universe.getOpenInterestInAttoEth() == 2 * market.getNumTicks() finalizeMarket(kitchenSinkFixture, market, [0,10**4]) initialLongHolderETH = kitchenSinkFixture.chain.head_state.get_balance(tester.a1) initialShortHolderETH = kitchenSinkFixture.chain.head_state.get_balance(tester.a2) tradingProceedsClaimedLog = { 'market': market.address, 'shareToken': yesShareToken.address, 'numPayoutTokens': expectedPayout, 'numShares': 1, 'sender': bytesToHexString(tester.a1), 'finalTokenBalance': initialLongHolderETH + expectedPayout, } with TokenDelta(cash, expectedMarketCreatorFees, market.getMarketCreatorMailbox(), "Market creator fees not paid"): with TokenDelta(cash, expectedReporterFees, universe.getOrCreateNextFeeWindow(), "Reporter fees not paid"): # redeem shares with a1 with AssertLog(kitchenSinkFixture, "TradingProceedsClaimed", tradingProceedsClaimedLog): claimTradingProceeds.claimTradingProceeds(market.address, tester.a1) # redeem shares with a2 claimTradingProceeds.claimTradingProceeds(market.address, tester.a2) # assert a1 ends up with cash (minus fees) and a2 does not assert kitchenSinkFixture.chain.head_state.get_balance(tester.a1) == initialLongHolderETH + expectedPayout assert kitchenSinkFixture.chain.head_state.get_balance(tester.a2) == initialShortHolderETH assert yesShareToken.balanceOf(tester.a1) == 0 assert yesShareToken.balanceOf(tester.a2) == 0 assert noShareToken.balanceOf(tester.a1) == 0 assert noShareToken.balanceOf(tester.a2) == 0 assert universe.getOpenInterestInAttoEth() == 1 * market.getNumTicks() # The corresponding share for tester2's complete set has not been redeemed
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_fee_window_buy(localFixture, initializedFeeWindow, Time, mockReputationToken, mockUniverse): with raises(TransactionFailed, message="atto token needs to be greater than 0"): initializedFeeWindow.buy(0) attoToken = 10 ** 10 assert initializedFeeWindow.isActive() == False with raises(TransactionFailed, message="fee window needs to be active to buy"): initializedFeeWindow.buy(attoToken) Time.setTimestamp(feeWindowId * mockUniverse.getDisputeRoundDurationInSeconds() + 1) assert initializedFeeWindow.isActive() == True user_balance = initializedFeeWindow.balanceOf(tester.a0) assert initializedFeeWindow.buy(attoToken, sender=tester.k0) == True assert mockReputationToken.getTrustedTransferSourceValue() == bytesToHexString(tester.a0) assert mockReputationToken.getTrustedTransferDestinationValue() == initializedFeeWindow.address assert mockReputationToken.getTrustedTransferAttotokensValue() == attoToken assert initializedFeeWindow.balanceOf(tester.a0) == user_balance + attoToken
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_designatedReportHappyPath(localFixture, universe, market): # proceed to the designated reporting period proceedToDesignatedReporting(localFixture, market) # an address that is not the designated reporter cannot report with raises(TransactionFailed): market.doInitialReport([0, market.getNumTicks()], False, sender=tester.k1) # Reporting with an invalid number of outcomes should fail with raises(TransactionFailed): market.doInitialReport([0, 0, market.getNumTicks()], False) # do an initial report as the designated reporter initialReportLog = { "universe": universe.address, "reporter": bytesToHexString(tester.a0), "market": market.address, "amountStaked": universe.getInitialReportMinValue(), "isDesignatedReporter": True, "payoutNumerators": [0, market.getNumTicks()], "invalid": False } with AssertLog(localFixture, "InitialReportSubmitted", initialReportLog): assert market.doInitialReport([0, market.getNumTicks()], False) with raises(TransactionFailed, message="Cannot initial report twice"): assert market.doInitialReport([0, market.getNumTicks()], False) # the market is now assigned a fee window newFeeWindowAddress = market.getFeeWindow() assert newFeeWindowAddress feeWindow = localFixture.applySignature('FeeWindow', newFeeWindowAddress) # time marches on and the market can be finalized localFixture.contracts["Time"].setTimestamp(feeWindow.getEndTime() + 1) marketFinalizedLog = { "universe": universe.address, "market": market.address } with AssertLog(localFixture, "MarketFinalized", marketFinalizedLog): assert market.finalize() with raises(TransactionFailed, message="Cannot finalize twice"): market.finalize()
def controllerSnapshot(fixture, baseSnapshot): fixture.resetToSnapshot(baseSnapshot) controller = fixture.upload('../source/contracts/Controller.sol') assert fixture.contracts['Controller'].owner() == bytesToHexString( tester.a0) return fixture.createSnapshot()
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_initialReport_methods(localFixture, universe, market, cash, constants): reputationToken = localFixture.applySignature( "ReputationToken", universe.getReputationToken()) # proceed to the initial reporting period proceedToInitialReporting(localFixture, market) # do an initial report as someone other than the designated reporter assert market.doInitialReport([0, market.getNumTicks()], False, sender=tester.k1) # the market is now assigned a fee window newFeeWindowAddress = market.getFeeWindow() assert newFeeWindowAddress feeWindow = localFixture.applySignature('FeeWindow', newFeeWindowAddress) # time marches on and the market can be finalized localFixture.contracts["Time"].setTimestamp(feeWindow.getEndTime() + 1) assert market.finalize() # We can see that the market reports the designated reporter did not show assert not market.designatedReporterShowed() # Let's get a reference to the Initial Reporter bond and transfer it to the original designated reporter account initialReporter = localFixture.applySignature("InitialReporter", market.getInitialReporter()) transferLog = { "universe": universe.address, "market": market.address, "from": bytesToHexString(tester.a1), "to": initialReporter.getDesignatedReporter(), } with AssertLog(localFixture, "InitialReporterTransferred", transferLog): assert initialReporter.transferOwnership( initialReporter.getDesignatedReporter(), sender=tester.k1) # Transfering to the owner is a noop assert initialReporter.transferOwnership( initialReporter.getDesignatedReporter()) # The market still correctly indicates the designated reporter did not show up assert not market.designatedReporterShowed() # confirm we cannot call protected methods on the initial reporter which only the market may use with raises(TransactionFailed): initialReporter.report(tester.a0, "", [], False) with raises(TransactionFailed): initialReporter.resetReportTimestamp() with raises(TransactionFailed): initialReporter.migrateREP() # When we redeem the initialReporter it goes to the correct party as well expectedRep = initialReporter.getStake() owner = initialReporter.getOwner() expectedGasBond = 2 * constants.GAS_TO_REPORT( ) * constants.DEFAULT_REPORTING_GAS_PRICE() with EtherDelta( expectedGasBond, owner, localFixture.chain, "Initial reporter did not get the reporting gas cost bond"): with TokenDelta(reputationToken, expectedRep, owner, "Redeeming didn't refund REP"): assert initialReporter.redeem(owner)
def test_cancelBid(escapeHatch, 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" if (escapeHatch): controller = contractsFixture.contracts['Controller'] controller.emergencyStop() 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_initial_report_and_participation_fee_collection( localFixture, universe, market, categoricalMarket, scalarMarket, cash, reputationToken): feeWindow = localFixture.applySignature('FeeWindow', market.getFeeWindow()) constants = localFixture.contracts["Constants"] # We cannot purchase participation tokens yet since the window isn't active with raises(TransactionFailed): feeWindow.buy(1) # generate some fees generateFees(localFixture, universe, market) # We'll make the window active then purchase some participation tokens localFixture.contracts["Time"].setTimestamp(feeWindow.getStartTime() + 1) feeWindowAmount = 100 with TokenDelta(reputationToken, -feeWindowAmount, tester.a0, "Buying participation tokens didn't deduct REP correctly"): with TokenDelta( feeWindow, feeWindowAmount, tester.a0, "Buying participation tokens didn't increase participation token balance correctly" ): assert feeWindow.buy(feeWindowAmount) # As other testers we'll buy some more assert feeWindow.buy(feeWindowAmount, sender=tester.k1) assert feeWindow.buy(feeWindowAmount, sender=tester.k2) assert feeWindow.buy(feeWindowAmount, sender=tester.k3) # We can't redeem the participation tokens yet since the window isn't over with raises(TransactionFailed): feeWindow.redeem(False) # Now end the window and finalize localFixture.contracts["Time"].setTimestamp(feeWindow.getEndTime() + 1) assert market.finalize() assert categoricalMarket.finalize() assert scalarMarket.finalize() marketInitialReport = localFixture.applySignature( 'InitialReporter', market.getInitialReporter()) categoricalInitialReport = localFixture.applySignature( 'InitialReporter', categoricalMarket.getInitialReporter()) scalarInitialReport = localFixture.applySignature( 'InitialReporter', scalarMarket.getInitialReporter()) reporterFees = 1000 * market.getNumTicks( ) / universe.getOrCacheReportingFeeDivisor() totalStake = feeWindow.getTotalFeeStake() assert cash.balanceOf(feeWindow.address) == reporterFees expectedParticipationFees = reporterFees * feeWindowAmount / totalStake # Cashing out Participation tokens will awards fees proportional to the total winning stake in the window with TokenDelta(reputationToken, feeWindowAmount, tester.a0, "Redeeming participation tokens didn't refund REP"): with TokenDelta( feeWindow, -feeWindowAmount, tester.a0, "Redeeming participation tokens didn't decrease participation token balance correctly" ): with EtherDelta( expectedParticipationFees, tester.a0, localFixture.chain, "Redeeming participation tokens didn't increase ETH correctly" ): assert feeWindow.redeem(tester.a0) with TokenDelta(reputationToken, feeWindowAmount, tester.a1, "Redeeming participation tokens didn't refund REP"): with TokenDelta( feeWindow, -feeWindowAmount, tester.a1, "Redeeming participation tokens didn't decrease participation token balance correctly" ): with EtherDelta( expectedParticipationFees, tester.a1, localFixture.chain, "Redeeming participation tokens didn't increase ETH correctly" ): assert feeWindow.redeem(tester.a1) with TokenDelta(reputationToken, feeWindowAmount, tester.a2, "Redeeming participation tokens didn't refund REP"): with TokenDelta( feeWindow, -feeWindowAmount, tester.a2, "Redeeming participation tokens didn't decrease participation token balance correctly" ): with EtherDelta( expectedParticipationFees, tester.a2, localFixture.chain, "Redeeming participation tokens didn't increase ETH correctly" ): assert feeWindow.redeem(tester.a2) marketStake = marketInitialReport.getStake() expectedFees = reporterFees * marketStake / totalStake initialReporterRedeemedLog = { "reporter": bytesToHexString(tester.a0), "amountRedeemed": marketStake, "repReceived": marketStake, "reportingFeesReceived": expectedFees, "payoutNumerators": [market.getNumTicks(), 0], "universe": universe.address, "market": market.address } with AssertLog(localFixture, "InitialReporterRedeemed", initialReporterRedeemedLog): with TokenDelta(reputationToken, marketStake, tester.a0, "Redeeming didn't refund REP"): with EtherDelta(expectedFees, tester.a0, localFixture.chain, "Redeeming didn't increase ETH correctly"): assert marketInitialReport.redeem(tester.a0) categoricalMarketStake = categoricalInitialReport.getStake() expectedFees = reporterFees * categoricalMarketStake / totalStake with TokenDelta(reputationToken, categoricalMarketStake, tester.a0, "Redeeming didn't refund REP"): with EtherDelta(expectedFees, tester.a0, localFixture.chain, "Redeeming didn't increase ETH correctly"): assert categoricalInitialReport.redeem(tester.a0)
def test_transferOwnership(controller): with raises(TransactionFailed): controller.transferOwnership(tester.a1, sender=tester.k2) assert controller.transferOwnership(tester.a1, sender=tester.k0) assert controller.owner() == bytesToHexString(tester.a1)
def test_redeem_shares_in_yesNo_market(kitchenSinkFixture, universe, cash, market): claimTradingProceeds = kitchenSinkFixture.contracts['ClaimTradingProceeds'] yesShareToken = kitchenSinkFixture.applySignature( 'ShareToken', market.getShareToken(YES)) noShareToken = kitchenSinkFixture.applySignature('ShareToken', market.getShareToken(NO)) expectedValue = 1 * market.getNumTicks() expectedReporterFees = expectedValue / universe.getOrCacheReportingFeeDivisor( ) expectedMarketCreatorFees = expectedValue / market.getMarketCreatorSettlementFeeDivisor( ) expectedSettlementFees = expectedReporterFees + expectedMarketCreatorFees expectedPayout = long(expectedValue - expectedSettlementFees) assert universe.getOpenInterestInAttoEth() == 0 # get YES shares with a1 acquireLongShares(kitchenSinkFixture, cash, market, YES, 1, claimTradingProceeds.address, sender=tester.k1) assert universe.getOpenInterestInAttoEth() == 1 * market.getNumTicks() # get NO shares with a2 acquireShortShareSet(kitchenSinkFixture, cash, market, YES, 1, claimTradingProceeds.address, sender=tester.k2) assert universe.getOpenInterestInAttoEth() == 2 * market.getNumTicks() finalizeMarket(kitchenSinkFixture, market, [0, 10**4]) initialLongHolderETH = kitchenSinkFixture.chain.head_state.get_balance( tester.a1) initialShortHolderETH = kitchenSinkFixture.chain.head_state.get_balance( tester.a2) tradingProceedsClaimedLog = { 'market': market.address, 'shareToken': yesShareToken.address, 'numPayoutTokens': expectedPayout, 'numShares': 1, 'sender': bytesToHexString(tester.a1), 'finalTokenBalance': initialLongHolderETH + expectedPayout, } with TokenDelta(cash, expectedMarketCreatorFees, market.getMarketCreatorMailbox(), "Market creator fees not paid"): with TokenDelta(cash, expectedReporterFees, universe.getOrCreateNextFeeWindow(), "Reporter fees not paid"): # redeem shares with a1 with AssertLog(kitchenSinkFixture, "TradingProceedsClaimed", tradingProceedsClaimedLog): claimTradingProceeds.claimTradingProceeds( market.address, tester.a1) # redeem shares with a2 claimTradingProceeds.claimTradingProceeds(market.address, tester.a2) # assert a1 ends up with cash (minus fees) and a2 does not assert kitchenSinkFixture.chain.head_state.get_balance( tester.a1) == initialLongHolderETH + expectedPayout assert kitchenSinkFixture.chain.head_state.get_balance( tester.a2) == initialShortHolderETH assert yesShareToken.balanceOf(tester.a1) == 0 assert yesShareToken.balanceOf(tester.a2) == 0 assert noShareToken.balanceOf(tester.a1) == 0 assert noShareToken.balanceOf(tester.a2) == 0
def controllerSnapshot(fixture, baseSnapshot): fixture.resetToSnapshot(baseSnapshot) controller = fixture.upload('solidity_test_helpers/TestController.sol', lookupKey="Controller") assert fixture.contracts['Controller'].owner() == bytesToHexString(tester.a0) return fixture.createSnapshot()
def test_ask_withSharesIgnored(contractsFixture, cash, market): orders = contractsFixture.contracts['Orders'] createOrder = contractsFixture.contracts['CreateOrder'] completeSets = contractsFixture.contracts['CompleteSets'] yesShareToken = contractsFixture.applySignature('ShareToken', market.getShareToken(YES)) noShareToken = contractsFixture.applySignature('ShareToken', market.getShareToken(NO)) # buy fix(2) complete sets with BuyWithCash(cash, fix(2, market.getNumTicks()), tester.k1, "buy complete set"): assert completeSets.publicBuyCompleteSets(market.address, fix(2), sender=tester.k1) assert cash.balanceOf(tester.a1) == fix('0') assert yesShareToken.balanceOf(tester.a1) == fix(2) assert noShareToken.balanceOf(tester.a1) == fix(2) orderID = None # Even though we have no shares available to cover this order if we indicate that we do not want to use them we'll need to provide sufficient ETH to cover the order with raises(TransactionFailed): createOrder.publicCreateOrder(BID, fix(1), 50, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), longTo32Bytes(42), True, nullAddress, sender=tester.k1) orderCreatedEventLog = { "eventType": 0, "addressData": [nullAddress, bytesToHexString(tester.a1), nullAddress], "uint256Data": [ 50, fix(1), YES, 0, 0, 0, 0, contractsFixture.contracts['Time'].getTimestamp() ], } with BuyWithCash(cash, fix('50'), tester.k1, "create order"): with AssertLog(contractsFixture, "OrderEvent", orderCreatedEventLog): orderID = createOrder.publicCreateOrder(BID, fix(1), 50, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), longTo32Bytes(42), True, nullAddress, sender=tester.k1) assert cash.balanceOf(tester.a1) == fix('0') assert yesShareToken.balanceOf(tester.a1) == fix(2) assert noShareToken.balanceOf(tester.a1) == fix(2) # validate the order contains expected results assert orderID != bytearray(32), "Order ID should be non-zero" assert orders.getAmount(orderID) == fix(1) assert orders.getPrice(orderID) == 50 assert orders.getOrderCreator(orderID) == bytesToHexString(tester.a1) assert orders.getOrderMoneyEscrowed(orderID) == fix('50') assert orders.getOrderSharesEscrowed(orderID) == 0
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_ask_withSharesIgnored(contractsFixture, universe, cash, market): orders = contractsFixture.contracts['Orders'] createOrder = contractsFixture.contracts['CreateOrder'] fillOrder = contractsFixture.contracts['FillOrder'] completeSets = contractsFixture.contracts['CompleteSets'] yesShareToken = contractsFixture.applySignature('ShareToken', market.getShareToken(YES)) noShareToken = contractsFixture.applySignature('ShareToken', market.getShareToken(NO)) # buy fix(2) complete sets assert completeSets.publicBuyCompleteSets(market.address, fix(2), sender=tester.k1, value=fix( 2, market.getNumTicks())) assert cash.balanceOf(tester.a1) == fix('0') assert yesShareToken.balanceOf(tester.a1) == fix(2) assert noShareToken.balanceOf(tester.a1) == fix(2) orderID = None # Even though we have no shares available to cover this order if we indicate that we do not want to use them we'll need to provide sufficient ETH to cover the order with raises(TransactionFailed): createOrder.publicCreateOrder(BID, fix(1), 5000, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), "42", True, sender=tester.k1) orderCreatedLog = { 'creator': bytesToHexString(tester.a1), 'shareToken': yesShareToken.address, 'tradeGroupId': stringToBytes("42"), } with AssertLog(contractsFixture, "OrderCreated", orderCreatedLog): orderID = createOrder.publicCreateOrder(BID, fix(1), 5000, market.address, YES, longTo32Bytes(0), longTo32Bytes(0), "42", True, sender=tester.k1, value=fix('5000')) assert cash.balanceOf(tester.a1) == fix('0') assert yesShareToken.balanceOf(tester.a1) == fix(2) assert noShareToken.balanceOf(tester.a1) == fix(2) # validate the order contains expected results assert orderID != bytearray(32), "Order ID should be non-zero" assert orders.getAmount(orderID) == fix(1) assert orders.getPrice(orderID) == 5000 assert orders.getOrderCreator(orderID) == bytesToHexString(tester.a1) assert orders.getOrderMoneyEscrowed(orderID) == fix('5000') assert orders.getOrderSharesEscrowed(orderID) == 0
def test_token_fee_collection(localFixture, universe, market, categoricalMarket, scalarMarket, cash, reputationToken, reportingWindow): # We'll progress past the designated dispute phase and finalize all the markets localFixture.chain.head_state.timestamp = market.getEndTime( ) + localFixture.contracts[ "Constants"].DESIGNATED_REPORTING_DURATION_SECONDS() + 1 assert market.tryFinalize() assert categoricalMarket.tryFinalize() assert scalarMarket.tryFinalize() # We can't redeem the stake used to do the designated report for fees yet since the window is not yet over marketDesignatedStake = localFixture.getStakeToken( market, [0, market.getNumTicks()]) categoricalMarketDesignatedStake = localFixture.getStakeToken( categoricalMarket, [0, 0, categoricalMarket.getNumTicks()]) scalarMarketDesignatedStake = localFixture.getStakeToken( scalarMarket, [0, scalarMarket.getNumTicks()]) with raises(TransactionFailed): marketDesignatedStake.redeemWinningTokens(False) # If we forgo fees we can redeem however. We'll do this for the scalar market. Note that the market total stake isn't decreased. Market total stake only decreases once it is finalized at which point it can no longer migrate so the value doesn't matter scalarStake = scalarMarketDesignatedStake.balanceOf(tester.a0) with TokenDelta(reputationToken, scalarStake, tester.a0, "Forgoing fees resulting in an incorrect REP refund"): with EtherDelta(0, tester.a0, localFixture.chain, "Forgoing fees gave fees incorrectly"): with StakeDelta( 0, -scalarStake, -scalarStake, scalarMarket, reportingWindow, "Forgoing fees incorrectly updated stake accounting"): assert scalarMarketDesignatedStake.redeemWinningTokens(True) # We cannot purchase participation tokens yet since the window isn't active participationToken = localFixture.applySignature( "ParticipationToken", reportingWindow.getParticipationToken()) with raises(TransactionFailed): participationToken.buy(1) # We'll progress to the start of the window and purchase some participation tokens localFixture.chain.head_state.timestamp = reportingWindow.getStartTime( ) + 1 participationTokenAmount = 100 with TokenDelta(reputationToken, -participationTokenAmount, tester.a0, "Buying participation tokens didn't deduct REP correctly"): with TokenDelta( participationToken, participationTokenAmount, tester.a0, "Buying participation tokens didn't increase participation token balance correctly" ): with StakeDelta( 0, participationTokenAmount, participationTokenAmount, market, reportingWindow, "Buying participation tokens din't adjust stake accounting correctly" ): assert participationToken.buy(participationTokenAmount) # As other testers we'll buy some more with StakeDelta( 0, participationTokenAmount * 3, participationTokenAmount * 3, market, reportingWindow, "Buying participation tokens din't adjust stake accounting correctly" ): with TokenDelta( participationToken, participationTokenAmount, tester.a1, "Buying participation tokens didn't increase participation token balance correctly" ): assert participationToken.buy(participationTokenAmount, sender=tester.k1) with TokenDelta( participationToken, participationTokenAmount, tester.a2, "Buying participation tokens didn't increase participation token balance correctly" ): assert participationToken.buy(participationTokenAmount, sender=tester.k2) with TokenDelta( participationToken, participationTokenAmount, tester.a3, "Buying participation tokens didn't increase participation token balance correctly" ): assert participationToken.buy(participationTokenAmount, sender=tester.k3) # We can't redeem the participation tokens for fees yet since the window isn't over with raises(TransactionFailed): participationToken.redeem(False) # We can redeem them to just get back REP. We'll have tester 3 do this participationValue = participationToken.balanceOf(tester.a3) with TokenDelta(reputationToken, participationValue, tester.a3, "Forgoing fees resulting in an incorrect REP refund"): with TokenDelta( participationToken, -participationTokenAmount, tester.a3, "Redeeming participation tokens didn't decrease participation token balance correctly" ): with EtherDelta(0, tester.a0, localFixture.chain, "Forgoing fees gave fees incorrectly"): with StakeDelta( 0, -participationValue, -participationValue, market, reportingWindow, "Forgoing fees incorrectly updated stake accounting"): assert participationToken.redeem(True, sender=tester.k3) # Fast forward time until the window is over and we can redeem our winning stake and participation tokens and receive fees localFixture.chain.head_state.timestamp = reportingWindow.getEndTime() + 1 reporterFees = 1000 * market.getNumTicks( ) / universe.getReportingFeeDivisor() totalWinningStake = reportingWindow.getTotalWinningStake() assert cash.balanceOf(reportingWindow.address) == reporterFees expectedParticipationFees = reporterFees * participationTokenAmount / totalWinningStake # Cashing out Participation tokens or Stake tokens will awards fees proportional to the total winning stake in the window with TokenDelta( participationToken, -participationTokenAmount, tester.a0, "Redeeming participation tokens didn't decrease participation token balance correctly" ): with EtherDelta( expectedParticipationFees, tester.a0, localFixture.chain, "Redeeming participation tokens didn't increase ETH correctly" ): assert participationToken.redeem(False) with TokenDelta( participationToken, -participationTokenAmount, tester.a1, "Redeeming participation tokens didn't decrease participation token balance correctly" ): with EtherDelta( expectedParticipationFees, tester.a1, localFixture.chain, "Redeeming participation tokens didn't increase ETH correctly" ): assert participationToken.redeem(False, sender=tester.k1) with TokenDelta( participationToken, -participationTokenAmount, tester.a2, "Redeeming participation tokens didn't decrease participation token balance correctly" ): with EtherDelta( expectedParticipationFees, tester.a2, localFixture.chain, "Redeeming participation tokens didn't increase ETH correctly" ): assert participationToken.redeem(False, sender=tester.k2) logs = [] captureFilteredLogs(localFixture.chain.head_state, localFixture.contracts['Augur'], logs) marketStake = marketDesignatedStake.balanceOf(tester.a0) expectedFees = reporterFees * marketStake / totalWinningStake + 1 # Rounding error with EtherDelta(expectedFees, tester.a0, localFixture.chain, "Redeeming Stake tokens didn't increase ETH correctly"): with TokenDelta( marketDesignatedStake, -marketStake, tester.a0, "Redeeming Stake tokens didn't decrease Stake token balance correctly" ): assert marketDesignatedStake.redeemWinningTokens(False) # Confirm redeeming stake tokens logs appropriately assert len(logs) == 3 assert logs[2]['_event_type'] == 'WinningTokensRedeemed' assert logs[2]['reporter'] == bytesToHexString(tester.a0) assert logs[2]['reportingFeesReceived'] == expectedFees assert logs[2]['stakeToken'] == marketDesignatedStake.address assert logs[2]['market'] == market.address assert logs[2]['amountRedeemed'] == marketStake assert logs[2]['payoutNumerators'] == [0, market.getNumTicks()] categoricalMarketStake = categoricalMarketDesignatedStake.balanceOf( tester.a0) expectedFees = reporterFees * categoricalMarketStake / totalWinningStake + 1 # Rounding error with EtherDelta(expectedFees, tester.a0, localFixture.chain, "Redeeming Stake tokens didn't increase ETH correctly"): with TokenDelta( categoricalMarketDesignatedStake, -categoricalMarketStake, tester.a0, "Redeeming Stake tokens didn't decrease Stake token balance correctly" ): assert categoricalMarketDesignatedStake.redeemWinningTokens(False)
def test_redeem_shares_in_binary_market(kitchenSinkFixture, universe, cash, market): claimTradingProceeds = kitchenSinkFixture.contracts['ClaimTradingProceeds'] yesShareToken = kitchenSinkFixture.applySignature( 'ShareToken', market.getShareToken(YES)) noShareToken = kitchenSinkFixture.applySignature('ShareToken', market.getShareToken(NO)) expectedValue = 1 * market.getNumTicks() expectedReporterFees = expectedValue / universe.getOrCacheReportingFeeDivisor( ) expectedMarketCreatorFees = expectedValue / market.getMarketCreatorSettlementFeeDivisor( ) expectedSettlementFees = expectedReporterFees + expectedMarketCreatorFees expectedPayout = long(expectedValue - expectedSettlementFees) assert universe.getOpenInterestInAttoEth() == 0 # get YES shares with a1 acquireLongShares(kitchenSinkFixture, cash, market, YES, 1, claimTradingProceeds.address, sender=tester.k1) assert universe.getOpenInterestInAttoEth() == 1 * market.getNumTicks() # get NO shares with a2 acquireShortShareSet(kitchenSinkFixture, cash, market, YES, 1, claimTradingProceeds.address, sender=tester.k2) assert universe.getOpenInterestInAttoEth() == 2 * market.getNumTicks() finalizeMarket(kitchenSinkFixture, market, [0, 10**4]) logs = [] captureFilteredLogs(kitchenSinkFixture.chain.head_state, kitchenSinkFixture.contracts['Augur'], logs) with TokenDelta(cash, expectedMarketCreatorFees, market.getMarketCreatorMailbox(), "Market creator fees not paid"): with TokenDelta(cash, expectedReporterFees, market.getReportingWindow(), "Reporter fees not paid"): # redeem shares with a1 initialLongHolderETH = kitchenSinkFixture.chain.head_state.get_balance( tester.a1) claimTradingProceeds.claimTradingProceeds(market.address, sender=tester.k1) # redeem shares with a2 initialShortHolderETH = kitchenSinkFixture.chain.head_state.get_balance( tester.a2) claimTradingProceeds.claimTradingProceeds(market.address, sender=tester.k2) # Confirm claim proceeds logging works correctly assert len(logs) == 4 assert logs[1]['_event_type'] == 'TradingProceedsClaimed' assert logs[1]['market'] == market.address assert logs[1]['shareToken'] == yesShareToken.address assert logs[1]['numPayoutTokens'] == expectedPayout assert logs[1]['numShares'] == 1 assert logs[1]['sender'] == bytesToHexString(tester.a1) assert logs[1][ 'finalTokenBalance'] == initialLongHolderETH + expectedPayout # assert a1 ends up with cash (minus fees) and a2 does not assert kitchenSinkFixture.chain.head_state.get_balance( tester.a1) == initialLongHolderETH + expectedPayout assert kitchenSinkFixture.chain.head_state.get_balance( tester.a2) == initialShortHolderETH assert yesShareToken.balanceOf(tester.a1) == 0 assert yesShareToken.balanceOf(tester.a2) == 0 assert noShareToken.balanceOf(tester.a1) == 0 assert noShareToken.balanceOf(tester.a2) == 0 assert universe.getOpenInterestInAttoEth() == 1 * market.getNumTicks( ) # The corresponding share for tester2's complete set has not been redeemed
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_one_round_crowdsourcer_fees(localFixture, universe, market, cash, reputationToken): feeWindow = localFixture.applySignature('FeeWindow', market.getFeeWindow()) constants = localFixture.contracts["Constants"] # We'll make the window active localFixture.contracts["Time"].setTimestamp(feeWindow.getStartTime() + 1) # generate some fees generateFees(localFixture, universe, market) # We'll have testers push markets into the next round by funding dispute crowdsourcers amount = 2 * market.getParticipantStake() with TokenDelta(reputationToken, -amount, tester.a1, "Disputing did not reduce REP balance correctly"): assert market.contribute([0, market.getNumTicks()], False, amount, "", sender=tester.k1) newFeeWindowAddress = market.getFeeWindow() assert newFeeWindowAddress != feeWindow.address # fast forward time to the fee new window and generate additional fees feeWindow = localFixture.applySignature('FeeWindow', newFeeWindowAddress) localFixture.contracts["Time"].setTimestamp(feeWindow.getStartTime() + 1) # Fast forward time until the new fee window is over and we can redeem our winning stake, and dispute bond tokens and receive fees localFixture.contracts["Time"].setTimestamp(feeWindow.getEndTime() + 1) assert market.finalize() initialReporter = localFixture.applySignature( 'InitialReporter', market.getReportingParticipant(0)) marketDisputeCrowdsourcer = localFixture.applySignature( 'DisputeCrowdsourcer', market.getReportingParticipant(1)) # The dispute crowdsourcer contributor locked in REP for 2 rounds, as did the Initial Reporter expectedTotalFees = cash.balanceOf(feeWindow.address) + cash.balanceOf( universe.getOrCreateFeeWindowBefore(feeWindow.address)) expectedFees = expectedTotalFees * 2 / 3 expectedRep = market.getParticipantStake() assert expectedRep == long(marketDisputeCrowdsourcer.getStake() + marketDisputeCrowdsourcer.getStake() / 2) disputeCrowdsourcerRedeemedLog = { "reporter": bytesToHexString(tester.a1), "disputeCrowdsourcer": marketDisputeCrowdsourcer.address, "amountRedeemed": marketDisputeCrowdsourcer.getStake(), "repReceived": expectedRep, "reportingFeesReceived": expectedFees, "payoutNumerators": [0, market.getNumTicks()], "universe": universe.address, "market": market.address } with AssertLog(localFixture, "DisputeCrowdsourcerRedeemed", disputeCrowdsourcerRedeemedLog): with TokenDelta(reputationToken, expectedRep, tester.a1, "Redeeming didn't refund REP"): with EtherDelta(expectedFees, tester.a1, localFixture.chain, "Redeeming didn't increase ETH correctly"): assert marketDisputeCrowdsourcer.redeem(tester.a1, sender=tester.k1) # The initial reporter gets fees even though they were not correct. They do not get their REP back though expectedFees = cash.balanceOf(feeWindow.address) + cash.balanceOf( universe.getOrCreateFeeWindowBefore(feeWindow.address)) with TokenDelta(reputationToken, 0, tester.a0, "Redeeming didn't refund REP"): with EtherDelta(expectedFees, tester.a0, localFixture.chain, "Redeeming didn't increase ETH correctly"): assert initialReporter.redeem(tester.a0)
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_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 execute(fixture, snapshot, universe, market, orderType, orderSize, orderPrice, orderOutcome, creatorLongShares, creatorShortShares, creatorTokens, fillerLongShares, fillerShortShares, fillerTokens, expectedMakerLongShares, expectedMakerShortShares, expectedMakerTokens, expectedFillerLongShares, expectedFillerShortShares, expectedFillerTokens, numTicks): def acquireLongShares(outcome, amount, approvalAddress, sender): if amount == 0: return shareToken = fixture.applySignature('ShareToken', market.getShareToken(outcome)) completeSets = fixture.contracts['CompleteSets'] createOrder = fixture.contracts['CreateOrder'] fillOrder = fixture.contracts['FillOrder'] ethRequired = amount * numTicks fixture.contracts['Cash'].depositEther(sender=sender, value = ethRequired) assert completeSets.publicBuyCompleteSets(market.address, amount, sender = sender) for otherOutcome in range(0, market.getNumberOfOutcomes()): if otherOutcome == outcome: continue otherShareToken = fixture.applySignature('ShareToken', market.getShareToken(otherOutcome)) assert otherShareToken.transfer(1, amount, sender = sender) def acquireShortShareSet(outcome, amount, approvalAddress, sender): if amount == 0: return shareToken = fixture.applySignature('ShareToken', market.getShareToken(outcome)) completeSets = fixture.contracts['CompleteSets'] createOrder = fixture.contracts['CreateOrder'] fillOrder = fixture.contracts['FillOrder'] ethRequired = amount * numTicks fixture.contracts['Cash'].depositEther(sender=sender, value = ethRequired) assert completeSets.publicBuyCompleteSets(market.address, amount, sender = sender) assert shareToken.transfer(1, amount, sender = sender) for otherOutcome in range(0, market.getNumberOfOutcomes()): if otherOutcome == outcome: continue otherShareToken = fixture.applySignature('ShareToken', market.getShareToken(otherOutcome)) fixture.resetToSnapshot(snapshot) legacyReputationToken = fixture.contracts['LegacyReputationToken'] legacyReputationToken.faucet(long(11 * 10**6 * 10**18)) fixture.chain.head_state.timestamp += 15000 orders = fixture.contracts['Orders'] createOrder = fixture.contracts['CreateOrder'] fillOrder = fixture.contracts['FillOrder'] completeSets = fixture.contracts['CompleteSets'] creatorAddress = tester.a1 fillerAddress = tester.a2 creatorKey = tester.k1 fillerKey = tester.k2 # Set creator/filler balances creatorBalance = fixture.chain.head_state.get_balance(creatorAddress) fillerBalance = fixture.chain.head_state.get_balance(fillerAddress) # Acquire shares for creator creatorEthRequiredLong = 0 if creatorLongShares == 0 else creatorLongShares * numTicks creatorEthRequiredShort = 0 if creatorShortShares == 0 else creatorShortShares * numTicks acquireLongShares(orderOutcome, creatorLongShares, createOrder.address, sender = creatorKey) acquireShortShareSet(orderOutcome, creatorShortShares, createOrder.address, sender = creatorKey) assert fixture.chain.head_state.get_balance(creatorAddress) == creatorBalance - creatorEthRequiredLong - creatorEthRequiredShort assert fixture.chain.head_state.get_balance(fillerAddress) == fillerBalance creatorBalance = fixture.chain.head_state.get_balance(creatorAddress) fillerBalance = fixture.chain.head_state.get_balance(fillerAddress) # Create order fixture.contracts['Cash'].depositEther(sender=creatorKey, value = creatorTokens) orderId = createOrder.publicCreateOrder(orderType, orderSize, orderPrice, market.address, orderOutcome, longTo32Bytes(0), longTo32Bytes(0), "42", sender = creatorKey) assert fixture.chain.head_state.get_balance(creatorAddress) == creatorBalance - creatorTokens assert fixture.chain.head_state.get_balance(fillerAddress) == fillerBalance creatorBalance = fixture.chain.head_state.get_balance(creatorAddress) fillerBalance = fixture.chain.head_state.get_balance(fillerAddress) # Validate order assert orders.getAmount(orderId) == orderSize assert orders.getPrice(orderId) == orderPrice assert orders.getOrderCreator(orderId) == bytesToHexString(creatorAddress) assert orders.getOrderMoneyEscrowed(orderId) == creatorTokens assert orders.getOrderSharesEscrowed(orderId) == creatorLongShares or creatorShortShares # Acquire shares for filler fillerEthRequiredLong = 0 if fillerLongShares == 0 else fillerLongShares * numTicks fillerEthRequiredShort = 0 if fillerShortShares == 0 else fillerShortShares * numTicks acquireLongShares(orderOutcome, fillerLongShares, fillOrder.address, sender = fillerKey) acquireShortShareSet(orderOutcome, fillerShortShares, fillOrder.address, sender = fillerKey) assert fixture.chain.head_state.get_balance(creatorAddress) == creatorBalance assert fixture.chain.head_state.get_balance(fillerAddress) == fillerBalance - fillerEthRequiredLong - fillerEthRequiredShort creatorBalance = fixture.chain.head_state.get_balance(creatorAddress) fillerBalance = fixture.chain.head_state.get_balance(fillerAddress) # Fill order fixture.contracts['Cash'].depositEther(sender=fillerKey, value = fillerTokens) remaining = fillOrder.publicFillOrder(orderId, orderSize, "42", sender = fillerKey) assert not remaining # Assert final state assert fixture.chain.head_state.get_balance(creatorAddress) == creatorBalance assert fixture.contracts['Cash'].balanceOf(creatorAddress) == expectedMakerTokens assert fixture.chain.head_state.get_balance(fillerAddress) == fillerBalance - fillerTokens assert fixture.contracts['Cash'].balanceOf(fillerAddress) == expectedFillerTokens for outcome in range(0, market.getNumberOfOutcomes()): shareToken = fixture.applySignature('ShareToken', market.getShareToken(outcome)) if outcome == orderOutcome: assert shareToken.balanceOf(creatorAddress) == expectedMakerLongShares assert shareToken.balanceOf(fillerAddress) == expectedFillerLongShares else: assert shareToken.balanceOf(creatorAddress) == expectedMakerShortShares assert shareToken.balanceOf(fillerAddress) == expectedFillerShortShares
def test_cancelBid(contractsFixture, cash, market, universe): createOrder = contractsFixture.contracts['CreateOrder'] cancelOrder = contractsFixture.contracts['CancelOrder'] orders = contractsFixture.contracts['Orders'] orderType = BID amount = fix(1) fxpPrice = 6000 outcomeID = YES tradeGroupID = longTo32Bytes(42) yesShareToken = contractsFixture.applySignature('ShareToken', market.getShareToken(YES)) noShareToken = contractsFixture.applySignature('ShareToken', market.getShareToken(NO)) creatorInitialShares = yesShareToken.balanceOf(tester.a1) marketInitialCash = cash.balanceOf(market.address) marketInitialYesShares = yesShareToken.totalSupply() marketInitialNoShares = noShareToken.totalSupply() with BuyWithCash(cash, fix(fxpPrice), tester.k1, "The sender didn't get cost deducted for create order"): orderID = createOrder.publicCreateOrder(orderType, amount, fxpPrice, market.address, outcomeID, longTo32Bytes(0), longTo32Bytes(0), tradeGroupID, False, nullAddress, sender=tester.k1) assert orderID, "Order ID should be non-zero" assert orders.getOrderCreator(orderID), "Order should have an owner" orderCanceledLog = { 'orderId': orderID, 'shareToken': yesShareToken.address, 'sender': bytesToHexString(tester.a1), 'orderType': orderType, 'sharesRefund': 0, 'tokenRefund': fix('1', '6000'), } with AssertLog(contractsFixture, 'OrderCanceled', orderCanceledLog): assert (cancelOrder.cancelOrder( orderID, sender=tester.k1) == 1), "cancelOrder should succeed" assert orders.getAmount(orderID) == 0 assert orders.getPrice(orderID) == 0 assert orders.getOrderCreator(orderID) == longToHexString(0) assert orders.getOrderMoneyEscrowed(orderID) == 0 assert orders.getOrderSharesEscrowed(orderID) == 0 assert orders.getBetterOrderId(orderID) == longTo32Bytes(0) assert orders.getWorseOrderId(orderID) == longTo32Bytes(0) assert (cash.balanceOf( tester.a1) == fix('6000')), "Maker's cash balance should be order size" assert ( marketInitialCash == cash.balanceOf(market.address) ), "Market's cash balance should be the same as before the order was placed" assert (creatorInitialShares == yesShareToken.balanceOf( tester.a1)), "Maker's shares should be unchanged" assert (marketInitialYesShares == yesShareToken.totalSupply() ), "Market's yes shares should be unchanged" assert marketInitialNoShares == noShareToken.totalSupply( ), "Market's no shares should be unchanged"
def test_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)