コード例 #1
0
def doBondWithdraw(fixture, bond, bonus, market, universe, reputationToken, destinationUniverse, testerAddress, testerKey):
    disputeUniverse = fixture.applySignature("Universe", universe.getOrCreateChildUniverse(bond.getDisputedPayoutDistributionHash()))
    destinationReputationToken = fixture.applySignature("ReputationToken", destinationUniverse.getReputationToken())
    bondRemainingToBePaid = bond.getBondRemainingToBePaidOut()
    bondAmount = bondRemainingToBePaid / 2
    amountRequiredForBondPayouts = market.getExtraDisputeBondRemainingToBePaidOut()
    amountInMigrationPool = disputeUniverse.getRepAvailableForExtraBondPayouts()
    bonusDivisor = fixture.contracts["Constants"].FORK_MIGRATION_PERCENTAGE_BONUS_DIVISOR()

    amountDirectlyMigrated = reputationToken.balanceOf(bond.address)
    if (bonus):
        amountDirectlyMigrated = amountDirectlyMigrated + (amountDirectlyMigrated / bonusDivisor)

    amountNeededForExtraPayout = bondRemainingToBePaid - amountDirectlyMigrated
    expectedAmountPulledFromDestinationPool = amountInMigrationPool * amountNeededForExtraPayout / amountRequiredForBondPayouts
    expectedAmountPulledFromDestinationPool = min(amountNeededForExtraPayout, expectedAmountPulledFromDestinationPool)

    assert bond.withdrawToUniverse(destinationUniverse.address, sender=testerKey)
    balanceInDestinationUniverse = destinationReputationToken.balanceOf(testerAddress)
    assert balanceInDestinationUniverse == amountDirectlyMigrated + expectedAmountPulledFromDestinationPool

    newBondRemainingToBePaid = bond.getBondRemainingToBePaidOut()
    assert newBondRemainingToBePaid == bondRemainingToBePaid - balanceInDestinationUniverse
    assert market.getExtraDisputeBondRemainingToBePaidOut() == amountRequiredForBondPayouts - (bondAmount - newBondRemainingToBePaid)
    assert disputeUniverse.getRepAvailableForExtraBondPayouts() == amountInMigrationPool - expectedAmountPulledFromDestinationPool
コード例 #2
0
def proceedToNextRound(fixture,
                       market,
                       contributor=tester.k0,
                       doGenerateFees=False,
                       moveTimeForward=True,
                       randomPayoutNumerators=False,
                       description=""):
    if fixture.contracts["Controller"].getTimestamp() < market.getEndTime():
        fixture.contracts["Time"].setTimestamp(
            market.getDesignatedReportingEndTime() + 1)

    feeWindow = market.getFeeWindow()

    payoutNumerators = [0] * market.getNumberOfOutcomes()
    payoutNumerators[0] = market.getNumTicks()

    if (feeWindow == longToHexString(0)):
        market.doInitialReport(payoutNumerators, False, "")
        assert market.getFeeWindow()
    else:
        feeWindow = fixture.applySignature('FeeWindow', market.getFeeWindow())
        if market.getDisputePacingOn():
            fixture.contracts["Time"].setTimestamp(feeWindow.getStartTime() +
                                                   1)
        # This will also use the InitialReporter which is not a DisputeCrowdsourcer, but has the called function from abstract inheritance
        winningReport = fixture.applySignature(
            'DisputeCrowdsourcer', market.getWinningReportingParticipant())
        winningPayoutHash = winningReport.getPayoutDistributionHash()

        if (randomPayoutNumerators):
            chosenPayoutNumerators = [0] * market.getNumberOfOutcomes()
            chosenPayoutNumerators[0] = randint(0, market.getNumTicks())
            chosenPayoutNumerators[1] = market.getNumTicks(
            ) - chosenPayoutNumerators[0]
        else:
            firstReportWinning = market.derivePayoutDistributionHash(
                payoutNumerators, False) == winningPayoutHash
            chosenPayoutNumerators = payoutNumerators if not firstReportWinning else payoutNumerators[::
                                                                                                      -1]

        chosenPayoutHash = market.derivePayoutDistributionHash(
            chosenPayoutNumerators, False)
        amount = 2 * market.getParticipantStake(
        ) - 3 * market.getStakeInOutcome(chosenPayoutHash)
        with PrintGasUsed(fixture, "Contribute:", 0):
            market.contribute(chosenPayoutNumerators,
                              False,
                              amount,
                              description,
                              sender=contributor)
        assert market.getForkingMarket() or market.getFeeWindow() != feeWindow

    if (doGenerateFees):
        universe = fixture.applySignature("Universe", market.getUniverse())
        generateFees(fixture, universe, market)

    if (moveTimeForward):
        feeWindow = fixture.applySignature('FeeWindow', market.getFeeWindow())
        fixture.contracts["Time"].setTimestamp(feeWindow.getStartTime() + 1)
コード例 #3
0
def finalizeFork(fixture, market, universe, finalizeByMigration = True):
    reputationToken = fixture.applySignature('ReputationToken', universe.getReputationToken())

    # The universe forks and there is now a universe where NO and YES are the respective outcomes of each
    noPayoutNumerators = [0] * market.getNumberOfOutcomes()
    noPayoutNumerators[0] = market.getNumTicks()
    noPayoutHash = market.derivePayoutDistributionHash(noPayoutNumerators, False)
    yesPayoutNumerators = noPayoutNumerators[::-1]
    yesPayoutHash = market.derivePayoutDistributionHash(yesPayoutNumerators, False)
    noUniverse =  fixture.applySignature('Universe', universe.getChildUniverse(noPayoutHash))
    yesUniverse =  fixture.applySignature('Universe', universe.getChildUniverse(yesPayoutHash))
    noUniverseReputationToken = fixture.applySignature('ReputationToken', noUniverse.getReputationToken())
    yesUniverseReputationToken = fixture.applySignature('ReputationToken', yesUniverse.getReputationToken())
    assert noUniverse.address != universe.address
    assert yesUniverse.address != universe.address
    assert yesUniverse.address != noUniverse.address
    assert noUniverseReputationToken.address != yesUniverseReputationToken.address

    # Attempting to finalize the fork now will not succeed as no REP has been migrated and not enough time has passed
    with raises(TransactionFailed):
        market.finalizeFork()

    # A Tester moves some of their REP to the YES universe
    amount = 10 ** 6 * 10 ** 18
    bonus = amount / fixture.contracts["Constants"].FORK_MIGRATION_PERCENTAGE_BONUS_DIVISOR()
    reputationToken.migrateOut(yesUniverseReputationToken.address, amount)
    assert yesUniverseReputationToken.balanceOf(tester.a0) == amount + bonus

    # Attempting to finalize the fork now will not succeed as a majority or REP has not yet migrated and fork end time has not been reached
    with raises(TransactionFailed):
        market.finalizeFork()

    if (finalizeByMigration):
        # Tester 0 moves more than 50% of REP
        amount = reputationToken.balanceOf(tester.a0) - 20
        bonus = amount / fixture.contracts["Constants"].FORK_MIGRATION_PERCENTAGE_BONUS_DIVISOR()
        reputationToken.migrateOut(noUniverseReputationToken.address, amount)
        assert reputationToken.balanceOf(tester.a0) == 20
        assert noUniverseReputationToken.balanceOf(tester.a0) == amount + bonus
        assert market.getWinningPayoutDistributionHash() == noUniverse.getParentPayoutDistributionHash()
    else:
        # Time marches on past the fork end time
        fixture.contracts["Time"].setTimestamp(universe.getForkEndTime() + 1)
        assert market.finalize()
        assert market.getWinningPayoutDistributionHash() == yesUniverse.getParentPayoutDistributionHash()

    # if the fork finalized by migration we're still in the 60 day fork window and can still get a bonus for migrating. If the fork is past the fork period we can no longer get the 5% bonus
    amount = 20
    amountAdded = amount
    if finalizeByMigration:
        bonus = amount / fixture.contracts["Constants"].FORK_MIGRATION_PERCENTAGE_BONUS_DIVISOR()
        amountAdded += bonus

    with TokenDelta(yesUniverseReputationToken, amountAdded, tester.a0, "reputation migration bonus did not work correctly"):
        reputationToken.migrateOut(yesUniverseReputationToken.address, amount)

    assert market.finalizeFork()
コード例 #4
0
ファイル: test_gas_costs.py プロジェクト: MicrohexHQ/augur
def localSnapshot(fixture, kitchenSinkSnapshot):
    fixture.resetToSnapshot(kitchenSinkSnapshot)
    universe = fixture.applySignature(None, kitchenSinkSnapshot['universe'].address, kitchenSinkSnapshot['universe'].abi)
    market = fixture.applySignature(None, kitchenSinkSnapshot['yesNoMarket'].address, kitchenSinkSnapshot['yesNoMarket'].abi)
    # Give some REP to testers to make things interesting
    reputationToken = fixture.applySignature('ReputationToken', universe.getReputationToken())
    for testAccount in [fixture.accounts[1], fixture.accounts[2], fixture.accounts[3]]:
        reputationToken.transfer(testAccount, 1 * 10**6 * 10**18)

    return fixture.createSnapshot()
コード例 #5
0
    def acquireShortShareSet(outcome, amount, approvalAddress, sender):
        if amount == 0: return

        shareToken = fixture.applySignature('ShareToken', market.getShareToken(outcome))
        completeSets = fixture.contracts['CompleteSets']
        createOrder = fixture.contracts['CreateOrder']
        fillOrder = fixture.contracts['FillOrder']

        ethRequired = amount * numTicks
        assert completeSets.publicBuyCompleteSets(market.address, amount, sender = sender, value = ethRequired)
        assert shareToken.transfer(0, amount, sender = sender)
        for otherOutcome in range(0, market.getNumberOfOutcomes()):
            if otherOutcome == outcome: continue
            otherShareToken = fixture.applySignature('ShareToken', market.getShareToken(otherOutcome))
コード例 #6
0
def localSnapshot(fixture, kitchenSinkSnapshot):
    fixture.resetToSnapshot(kitchenSinkSnapshot)
    universe = ABIContract(fixture.chain,
                           kitchenSinkSnapshot['universe'].translator,
                           kitchenSinkSnapshot['universe'].address)
    market = ABIContract(fixture.chain,
                         kitchenSinkSnapshot['binaryMarket'].translator,
                         kitchenSinkSnapshot['binaryMarket'].address)
    categoricalMarket = ABIContract(
        fixture.chain, kitchenSinkSnapshot['categoricalMarket'].translator,
        kitchenSinkSnapshot['categoricalMarket'].address)
    scalarMarket = ABIContract(fixture.chain,
                               kitchenSinkSnapshot['scalarMarket'].translator,
                               kitchenSinkSnapshot['scalarMarket'].address)
    cash = ABIContract(fixture.chain, kitchenSinkSnapshot['cash'].translator,
                       kitchenSinkSnapshot['cash'].address)
    completeSets = fixture.contracts['CompleteSets']
    mailbox = fixture.applySignature('Mailbox',
                                     market.getMarketCreatorMailbox())

    # Generate the fees in our initial reporting window
    cost = 1000 * market.getNumTicks()
    marketCreatorFees = cost / market.getMarketCreatorSettlementFeeDivisor()
    completeSets.publicBuyCompleteSets(market.address,
                                       1000,
                                       sender=tester.k1,
                                       value=cost)
    with TokenDelta(
            cash, marketCreatorFees, mailbox.address,
            "The market creator mailbox didn't get their share of fees from complete set sale"
    ):
        completeSets.publicSellCompleteSets(market.address,
                                            1000,
                                            sender=tester.k1)
    with EtherDelta(
            marketCreatorFees, market.getOwner(), fixture.chain,
            "The market creator did not get their fees when withdrawing ETH from the mailbox"
    ):
        assert mailbox.withdrawEther()
    fees = cash.balanceOf(market.getReportingWindow())
    reporterFees = cost / universe.getOrCacheReportingFeeDivisor()
    assert fees == reporterFees

    # Distribute REP
    reputationToken = fixture.applySignature('ReputationToken',
                                             universe.getReputationToken())
    for testAccount in [tester.a1, tester.a2, tester.a3, tester.a4, tester.a5]:
        reputationToken.transfer(testAccount, 1 * 10**6 * 10**18)

    return fixture.createSnapshot()
コード例 #7
0
def getExpectedFees(fixture, cash, reportingParticipant, expectedRounds):
    stake = reportingParticipant.getStake()
    feeWindow = fixture.applySignature("FeeWindow", reportingParticipant.getFeeWindow())
    universe = fixture.applySignature("Universe", feeWindow.getUniverse())
    feeToken = fixture.applySignature("FeeToken", feeWindow.getFeeToken())
    expectedFees = 0
    rounds = 0
    while feeToken.balanceOf(reportingParticipant.address) > 0:
        rounds += 1
        expectedFees += cash.balanceOf(feeWindow.address) * stake / feeToken.totalSupply()
        feeWindow = fixture.applySignature("FeeWindow", universe.getOrCreateFeeWindowBefore(feeWindow.address))
        feeToken = fixture.applySignature("FeeToken", feeWindow.getFeeToken())
    assert expectedRounds == rounds, "Had fees from " + str(rounds) + " rounds instead of " + str(expectedRounds)
    assert expectedFees > 0, "No fees. Tests should just use 0 if this is the expected case"
    return expectedFees
コード例 #8
0
def getExpectedFees(fixture, cash, reportingParticipant, expectedRounds):
    stake = reportingParticipant.getStake()
    feeWindow = fixture.applySignature("FeeWindow", reportingParticipant.getFeeWindow())
    universe = fixture.applySignature("Universe", feeWindow.getUniverse())
    feeToken = fixture.applySignature("FeeToken", feeWindow.getFeeToken())
    expectedFees = 0
    rounds = 0
    while feeToken.balanceOf(reportingParticipant.address) > 0:
        rounds += 1
        expectedFees += cash.balanceOf(feeWindow.address) * stake / feeToken.totalSupply()
        feeWindow = fixture.applySignature("FeeWindow", universe.getOrCreateFeeWindowBefore(feeWindow.address))
        feeToken = fixture.applySignature("FeeToken", feeWindow.getFeeToken())
    assert expectedRounds == rounds, "Had fees from " + str(rounds) + " rounds instead of " + str(expectedRounds)
    assert expectedFees > 0, "No fees. Tests should just use 0 if this is the expected case"
    return expectedFees
コード例 #9
0
def localSnapshot(fixture, controllerSnapshot):
    fixture.resetToSnapshot(controllerSnapshot)

    # Upload a token
    fixture.uploadAndAddToController(
        "solidity_test_helpers/StandardTokenHelper.sol")

    # Upload Cash
    cash = fixture.uploadAndAddToController(
        "../source/contracts/trading/Cash.sol")
    cash.setController(fixture.contracts['Controller'].address)

    # Upload the mailbox
    name = "Mailbox"
    targetName = "MailboxTarget"
    fixture.uploadAndAddToController(
        "../source/contracts/libraries/Mailbox.sol", targetName, name)
    fixture.uploadAndAddToController(
        "../source/contracts/libraries/Delegator.sol",
        name,
        "delegator",
        constructorArgs=[
            fixture.contracts['Controller'].address,
            stringToBytes(targetName)
        ])
    fixture.contracts[name] = fixture.applySignature(
        name, fixture.contracts[name].address)
    fixture.contracts[name].initialize(tester.a0)
    return fixture.createSnapshot()
コード例 #10
0
def localSnapshot(fixture, kitchenSinkSnapshot):
    fixture.resetToSnapshot(kitchenSinkSnapshot)

    universe = kitchenSinkSnapshot['universe']
    market = kitchenSinkSnapshot['yesNoMarket']
    categoricalMarket = kitchenSinkSnapshot['categoricalMarket']
    scalarMarket = kitchenSinkSnapshot['scalarMarket']

    # Skip to Designated Reporting
    fixture.contracts["Time"].setTimestamp(market.getEndTime() + 1)

    # Distribute REP
    reputationToken = fixture.applySignature('ReputationToken',
                                             universe.getReputationToken())
    for testAccount in [
            fixture.accounts[1], fixture.accounts[2], fixture.accounts[3]
    ]:
        reputationToken.transfer(testAccount, 1 * 10**6 * 10**18)

    # Designated Report on the markets
    designatedReportCost = universe.getOrCacheDesignatedReportStake()
    with TokenDelta(
            reputationToken, 0, fixture.accounts[0],
            "Doing the designated report didn't deduct REP correctly or didn't award the no show bond"
    ):
        market.doInitialReport([0, market.getNumTicks(), 0], "", 0)
        categoricalMarket.doInitialReport(
            [0, categoricalMarket.getNumTicks(), 0, 0], "", 0)
        scalarMarket.doInitialReport([0, scalarMarket.getNumTicks(), 0], "", 0)

    return fixture.createSnapshot()
コード例 #11
0
def proceedToFork(fixture, market, universe):
    while (market.getForkingMarket() == longToHexString(0)):
        proceedToNextRound(fixture, market)

    for i in range(market.getNumParticipants()):
        reportingParticipant = fixture.applySignature("DisputeCrowdsourcer", market.getReportingParticipant(i))
        reportingParticipant.fork()
コード例 #12
0
def generateFees(fixture, universe, market):
    completeSets = fixture.contracts['CompleteSets']
    cash = fixture.contracts['Cash']
    mailbox = fixture.applySignature('Mailbox',
                                     market.getMarketCreatorMailbox())
    assert mailbox.withdrawEther()

    cost = 1000 * market.getNumTicks()
    marketCreatorFees = cost / market.getMarketCreatorSettlementFeeDivisor()
    completeSets.publicBuyCompleteSets(market.address,
                                       1000,
                                       sender=tester.k1,
                                       value=cost)
    with TokenDelta(
            cash, marketCreatorFees, mailbox.address,
            "The market creator mailbox didn't get their share of fees from complete set sale"
    ):
        completeSets.publicSellCompleteSets(market.address,
                                            1000,
                                            sender=tester.k1)
    with EtherDelta(
            marketCreatorFees, market.getOwner(), fixture.chain,
            "The market creator did not get their fees when withdrawing ETH from the mailbox"
    ):
        assert mailbox.withdrawEther()
    fees = cash.balanceOf(universe.getNextFeeWindow())
    reporterFees = cost / universe.getOrCacheReportingFeeDivisor()
    assert fees == reporterFees, "Cash balance of window higher by: " + str(
        fees - reporterFees)
コード例 #13
0
def proceedToFork(fixture, market, universe):    
    while (market.getForkingMarket() == longToHexString(0)):
        proceedToNextRound(fixture, market)

    for i in range(market.getNumParticipants()):
        reportingParticipant = fixture.applySignature("DisputeCrowdsourcer", market.getReportingParticipant(i))
        reportingParticipant.fork()
コード例 #14
0
def localSnapshot(fixture, baseSnapshot):
    fixture.resetToSnapshot(baseSnapshot)
    fixture.uploadAugur()
    fixture.uploadAndAddToAugur("solidity_test_helpers/DelegatorHelper.sol")
    delegatorHelperFactory = fixture.uploadAndAddToAugur("solidity_test_helpers/DelegatorHelperFactory.sol")
    delegatorHelperAddress = delegatorHelperFactory.createDelegatorHelper(fixture.contracts['Augur'].address)
    fixture.contracts["Clone"] = fixture.applySignature("DelegatorHelper", delegatorHelperAddress)
    return fixture.createSnapshot()
コード例 #15
0
def prepare_finalize_market(fixture, market, payoutNumerators):
    # set timestamp to after market end
    fixture.contracts["Time"].setTimestamp(market.getEndTime() + 1)
    # have kitchenSinkFixture.accounts[0] submit designated report
    market.doInitialReport(payoutNumerators, "", 0)
    # set timestamp to after designated dispute end
    disputeWindow = fixture.applySignature('DisputeWindow', market.getDisputeWindow())
    fixture.contracts["Time"].setTimestamp(disputeWindow.getEndTime() + 1)
コード例 #16
0
def localFixture(fixture, localSnapshot, kitchenSinkSnapshot):
    fixture.resetToSnapshot(localSnapshot)

    market = ABIContract(fixture.chain,
                         kitchenSinkSnapshot['binaryMarket'].translator,
                         kitchenSinkSnapshot['binaryMarket'].address)
    categoricalMarket = ABIContract(
        fixture.chain, kitchenSinkSnapshot['categoricalMarket'].translator,
        kitchenSinkSnapshot['categoricalMarket'].address)
    scalarMarket = ABIContract(fixture.chain,
                               kitchenSinkSnapshot['scalarMarket'].translator,
                               kitchenSinkSnapshot['scalarMarket'].address)
    universe = ABIContract(fixture.chain,
                           kitchenSinkSnapshot['universe'].translator,
                           kitchenSinkSnapshot['universe'].address)
    reputationToken = fixture.applySignature('ReputationToken',
                                             universe.getReputationToken())
    reportingWindow = fixture.applySignature('ReportingWindow',
                                             market.getReportingWindow())

    # Skip to Designated Reporting
    fixture.chain.head_state.timestamp = market.getEndTime() + 1

    # Designated Report on each market
    designatedReportCost = universe.getOrCacheDesignatedReportStake()
    totalDesignatedReportCostInWindow = designatedReportCost * 3
    with TokenDelta(
            reputationToken, 0, tester.a0,
            "Doing the designated report didn't deduct REP correctly or didn't award the no show bond"
    ):
        with StakeDelta(
                designatedReportCost, totalDesignatedReportCostInWindow, 0,
                market, reportingWindow,
                "Doing the designated report din't adjust stake accounting correctly"
        ):
            fixture.designatedReport(market, [0, market.getNumTicks()],
                                     tester.k0)
            fixture.designatedReport(
                categoricalMarket,
                [0, 0, categoricalMarket.getNumTicks()], tester.k0)
            fixture.designatedReport(scalarMarket,
                                     [0, scalarMarket.getNumTicks()],
                                     tester.k0)

    return fixture
コード例 #17
0
def localSnapshot(fixture, controllerSnapshot):
    fixture.resetToSnapshot(controllerSnapshot)
    fixture.uploadAugur()
    name = "DelegatorHelper"
    targetName = "DelegatorHelperTarget"
    fixture.uploadAndAddToController("solidity_test_helpers/DelegatorHelper.sol", targetName, name)
    fixture.uploadAndAddToController("../source/contracts/libraries/Delegator.sol", name, "delegator", constructorArgs=[fixture.contracts['Controller'].address, stringToBytes(targetName)])
    fixture.contracts[name] = fixture.applySignature(name, fixture.contracts[name].address)
    return fixture.createSnapshot()
コード例 #18
0
def reportingSnapshot(fixture, kitchenSinkSnapshot):
    fixture.resetToSnapshot(kitchenSinkSnapshot)
    # Give some REP to testers to make things interesting
    universe = ABIContract(fixture.chain, kitchenSinkSnapshot['universe'].translator, kitchenSinkSnapshot['universe'].address)
    reputationToken = fixture.applySignature('ReputationToken', universe.getReputationToken())
    for testAccount in [tester.a1, tester.a2, tester.a3]:
        reputationToken.transfer(testAccount, 1 * 10**6 * 10**18)

    return fixture.createSnapshot()
コード例 #19
0
def localSnapshot(fixture, controllerSnapshot):
    fixture.resetToSnapshot(controllerSnapshot)
    fixture.uploadAugurLite()
    name = "DelegatorHelper"
    targetName = "DelegatorHelperTarget"
    fixture.uploadAndAddToController("solidity_test_helpers/DelegatorHelper.sol", targetName, name)
    fixture.uploadAndAddToController("../source/contracts/libraries/Delegator.sol", name, "delegator", constructorArgs=[fixture.contracts['Controller'].address, stringToBytes(targetName)])
    fixture.contracts[name] = fixture.applySignature(name, fixture.contracts[name].address)
    return fixture.createSnapshot()
コード例 #20
0
def finalizeMarket(fixture, market, payoutNumerators, invalid=False):
    # set timestamp to after market end
    fixture.contracts["Time"].setTimestamp(market.getEndTime() + 1)
    # have tester.a0 submit designated report
    market.doInitialReport(payoutNumerators, invalid, "")
    # set timestamp to after designated dispute end
    feeWindow = fixture.applySignature('FeeWindow', market.getFeeWindow())
    fixture.contracts["Time"].setTimestamp(feeWindow.getEndTime() + 1)
    # finalize the market
    assert market.finalize()
コード例 #21
0
ファイル: test_auction.py プロジェクト: zackster/augur
def localSnapshot(fixture, kitchenSinkSnapshot):
    fixture.resetToSnapshot(kitchenSinkSnapshot)
    universe = ABIContract(fixture.chain, kitchenSinkSnapshot['universe'].translator, kitchenSinkSnapshot['universe'].address)

    # Distribute REP
    reputationToken = fixture.applySignature('ReputationToken', universe.getReputationToken())
    for testAccount in [tester.a1, tester.a2, tester.a3]:
        reputationToken.transfer(testAccount, 1 * 10**6 * 10**18)

    return fixture.createSnapshot()
コード例 #22
0
def finalizeMarket(fixture, market, payoutNumerators, invalid=False):
    # set timestamp to after market end
    fixture.contracts["Time"].setTimestamp(market.getEndTime() + 1)
    # have tester.a0 submit designated report
    market.doInitialReport(payoutNumerators, invalid)
    # set timestamp to after designated dispute end
    feeWindow = fixture.applySignature('FeeWindow', market.getFeeWindow())
    fixture.contracts["Time"].setTimestamp(feeWindow.getEndTime() + 1)
    # finalize the market
    assert market.finalize()
    # set timestamp to 3 days later (waiting period)
    fixture.contracts["Time"].incrementTimestamp(long(timedelta(days = 3, seconds = 1).total_seconds()))
コード例 #23
0
def finalizeMarket(fixture, market, payoutNumerators):
    # set timestamp to after market end
    fixture.contracts["Time"].setTimestamp(market.getEndTime() + 1)
    # have tester.a0 submit designated report
    market.doInitialReport(payoutNumerators, False)
    # set timestamp to after designated dispute end
    feeWindow = fixture.applySignature('FeeWindow', market.getFeeWindow())
    fixture.contracts["Time"].setTimestamp(feeWindow.getEndTime() + 1)
    # finalize the market
    assert market.finalize()
    # set timestamp to 3 days later (waiting period)
    fixture.contracts["Time"].incrementTimestamp(long(timedelta(days = 3, seconds = 1).total_seconds()))
コード例 #24
0
def proceedToNextRound(fixture, market, contributor = tester.k0, doGenerateFees = False, moveTimeForward = True, randomPayoutNumerators = False):
    if fixture.contracts["Controller"].getTimestamp() < market.getEndTime():
        fixture.contracts["Time"].setTimestamp(market.getDesignatedReportingEndTime() + 1)

    feeWindow = market.getFeeWindow()

    payoutNumerators = [0] * market.getNumberOfOutcomes()
    payoutNumerators[0] = market.getNumTicks()

    if (feeWindow == longToHexString(0)):
        market.doInitialReport(payoutNumerators, False)
        assert market.getFeeWindow()
    else:
        feeWindow = fixture.applySignature('FeeWindow', market.getFeeWindow())
        fixture.contracts["Time"].setTimestamp(feeWindow.getStartTime() + 1)
        # This will also use the InitialReporter which is not a DisputeCrowdsourcer, but has the called function from abstract inheritance
        winningReport = fixture.applySignature('DisputeCrowdsourcer', market.getWinningReportingParticipant())
        winningPayoutHash = winningReport.getPayoutDistributionHash()

        if (randomPayoutNumerators):
            chosenPayoutNumerators = [0] * market.getNumberOfOutcomes()
            chosenPayoutNumerators[0] = randint(0, market.getNumTicks())
            chosenPayoutNumerators[1] = market.getNumTicks() - chosenPayoutNumerators[0]
        else:
            firstReportWinning = market.derivePayoutDistributionHash(payoutNumerators, False) == winningPayoutHash
            chosenPayoutNumerators = payoutNumerators if not firstReportWinning else payoutNumerators[::-1]

        chosenPayoutHash = market.derivePayoutDistributionHash(chosenPayoutNumerators, False)
        amount = 2 * market.getParticipantStake() - 3 * market.getStakeInOutcome(chosenPayoutHash)
        with PrintGasUsed(fixture, "Contribute:", 0):
            market.contribute(chosenPayoutNumerators, False, amount, sender=contributor)
        assert market.getForkingMarket() or market.getFeeWindow() != feeWindow

    if (doGenerateFees):
        universe = fixture.applySignature("Universe", market.getUniverse())
        generateFees(fixture, universe, market)

    if (moveTimeForward):
        feeWindow = fixture.applySignature('FeeWindow', market.getFeeWindow())
        fixture.contracts["Time"].setTimestamp(feeWindow.getStartTime() + 1)
コード例 #25
0
def localSnapshot(fixture, kitchenSinkSnapshot):
    fixture.resetToSnapshot(kitchenSinkSnapshot)
    universe = fixture.applySignature(None, kitchenSinkSnapshot['universe'].address, kitchenSinkSnapshot['universe'].abi)
    fixture.markets = [
        fixture.createReasonableCategoricalMarket(universe, 2),
        fixture.createReasonableCategoricalMarket(universe, 3),
        fixture.createReasonableCategoricalMarket(universe, 4),
        fixture.createReasonableCategoricalMarket(universe, 5),
        fixture.createReasonableCategoricalMarket(universe, 6),
        fixture.createReasonableCategoricalMarket(universe, 7),
    ]

    return fixture.createSnapshot()
コード例 #26
0
ファイル: test_auction.py プロジェクト: peachbits/augur
def localSnapshot(fixture, kitchenSinkSnapshot):
    fixture.resetToSnapshot(kitchenSinkSnapshot)
    universe = kitchenSinkSnapshot['universe']

    # Distribute REP
    reputationToken = fixture.applySignature('ReputationToken',
                                             universe.getReputationToken())
    for testAccount in [
            fixture.accounts[1], fixture.accounts[2], fixture.accounts[3]
    ]:
        reputationToken.transfer(testAccount, 1 * 10**6 * 10**18)

    return fixture.createSnapshot()
コード例 #27
0
def generateFees(fixture, universe, market):
    completeSets = fixture.contracts['CompleteSets']
    cash = fixture.contracts['Cash']
    mailbox = fixture.applySignature('Mailbox', market.getMarketCreatorMailbox())
    assert mailbox.withdrawEther()

    cost = 1000 * market.getNumTicks()
    marketCreatorFees = cost / market.getMarketCreatorSettlementFeeDivisor()
    completeSets.publicBuyCompleteSets(market.address, 1000, sender = tester.k1, value = cost)
    with TokenDelta(cash, marketCreatorFees, mailbox.address, "The market creator mailbox didn't get their share of fees from complete set sale"):
        completeSets.publicSellCompleteSets(market.address, 1000, sender=tester.k1)
    with EtherDelta(marketCreatorFees, market.getOwner(), fixture.chain, "The market creator did not get their fees when withdrawing ETH from the mailbox"):
        assert mailbox.withdrawEther()
    fees = cash.balanceOf(universe.getNextFeeWindow())
    reporterFees = cost / universe.getOrCacheReportingFeeDivisor()
    assert fees == reporterFees, "Cash balance of window higher by: " + str(fees - reporterFees)
コード例 #28
0
ファイル: test_mailbox.py プロジェクト: Arbitrage0/augur-core
def localSnapshot(fixture, controllerSnapshot):
    fixture.resetToSnapshot(controllerSnapshot)

    fixture.uploadAugur()

    # Upload a token
    fixture.uploadAndAddToController("solidity_test_helpers/StandardTokenHelper.sol")

    # Upload Cash
    cash = fixture.uploadAndAddToController("../source/contracts/trading/Cash.sol")
    cash.setController(fixture.contracts['Controller'].address)

    # Upload the mailbox
    name = "Mailbox"
    targetName = "MailboxTarget"
    fixture.uploadAndAddToController("../source/contracts/reporting/Mailbox.sol", targetName, name)
    fixture.uploadAndAddToController("../source/contracts/libraries/Delegator.sol", name, "delegator", constructorArgs=[fixture.contracts['Controller'].address, stringToBytes(targetName)])
    fixture.contracts[name] = fixture.applySignature(name, fixture.contracts[name].address)
    fixture.contracts[name].initialize(tester.a0)
    return fixture.createSnapshot()
コード例 #29
0
def localSnapshot(fixture, kitchenSinkSnapshot):
    fixture.resetToSnapshot(kitchenSinkSnapshot)
    universe = ABIContract(fixture.chain, kitchenSinkSnapshot['universe'].translator, kitchenSinkSnapshot['universe'].address)
    market = ABIContract(fixture.chain, kitchenSinkSnapshot['yesNoMarket'].translator, kitchenSinkSnapshot['yesNoMarket'].address)
    categoricalMarket = ABIContract(fixture.chain, kitchenSinkSnapshot['categoricalMarket'].translator, kitchenSinkSnapshot['categoricalMarket'].address)
    scalarMarket = ABIContract(fixture.chain, kitchenSinkSnapshot['scalarMarket'].translator, kitchenSinkSnapshot['scalarMarket'].address)

    # Skip to Designated Reporting
    fixture.contracts["Time"].setTimestamp(market.getEndTime() + 1)

    # Distribute REP
    reputationToken = fixture.applySignature('ReputationToken', universe.getReputationToken())
    for testAccount in [tester.a1, tester.a2, tester.a3]:
        reputationToken.transfer(testAccount, 1 * 10**6 * 10**18)

    # Designated Report on the markets
    designatedReportCost = universe.getOrCacheDesignatedReportStake()
    with TokenDelta(reputationToken, 0, tester.a0, "Doing the designated report didn't deduct REP correctly or didn't award the no show bond"):
        market.doInitialReport([market.getNumTicks(), 0], False, "")
        categoricalMarket.doInitialReport([categoricalMarket.getNumTicks(), 0, 0], False, "")
        scalarMarket.doInitialReport([scalarMarket.getNumTicks(), 0], False, "")

    return fixture.createSnapshot()
コード例 #30
0
def localSnapshot(fixture, kitchenSinkSnapshot):
    fixture.resetToSnapshot(kitchenSinkSnapshot)
    universe = ABIContract(fixture.chain, kitchenSinkSnapshot['universe'].translator, kitchenSinkSnapshot['universe'].address)
    market = ABIContract(fixture.chain, kitchenSinkSnapshot['yesNoMarket'].translator, kitchenSinkSnapshot['yesNoMarket'].address)
    categoricalMarket = ABIContract(fixture.chain, kitchenSinkSnapshot['categoricalMarket'].translator, kitchenSinkSnapshot['categoricalMarket'].address)
    scalarMarket = ABIContract(fixture.chain, kitchenSinkSnapshot['scalarMarket'].translator, kitchenSinkSnapshot['scalarMarket'].address)

    # Skip to Designated Reporting
    fixture.contracts["Time"].setTimestamp(market.getEndTime() + 1)

    # Distribute REP
    reputationToken = fixture.applySignature('ReputationToken', universe.getReputationToken())
    for testAccount in [tester.a1, tester.a2, tester.a3]:
        reputationToken.transfer(testAccount, 1 * 10**6 * 10**18)

    # Designated Report on the markets
    designatedReportCost = universe.getOrCacheDesignatedReportStake()
    with TokenDelta(reputationToken, 0, tester.a0, "Doing the designated report didn't deduct REP correctly or didn't award the no show bond"):
        market.doInitialReport([market.getNumTicks(), 0], False)
        categoricalMarket.doInitialReport([categoricalMarket.getNumTicks(), 0, 0], False)
        scalarMarket.doInitialReport([scalarMarket.getNumTicks(), 0], False)

    return fixture.createSnapshot()
コード例 #31
0
def localSnapshot(fixture, controllerSnapshot):
    fixture.resetToSnapshot(controllerSnapshot)

    fixture.uploadAugur()

    # Upload a token
    fixture.uploadAndAddToController(
        "solidity_test_helpers/StandardTokenHelper.sol")

    # Upload Cash
    cash = fixture.uploadAndAddToController(
        "../source/contracts/trading/Cash.sol")
    cash.setController(fixture.contracts['Controller'].address)

    # Upload the mailbox
    fixture.uploadAndAddToController(
        "../source/contracts/reporting/Mailbox.sol")
    mailboxFactory = fixture.uploadAndAddToController(
        "../source/contracts/factories/MailboxFactory.sol")
    mailboxAddress = mailboxFactory.createMailbox(
        fixture.contracts["Controller"].address, tester.a0, 0)
    fixture.contracts["Mailbox"] = fixture.applySignature(
        "Mailbox", mailboxAddress)
    return fixture.createSnapshot()
コード例 #32
0
def finalizeFork(fixture, market, universe, finalizeByMigration=True):
    reputationToken = fixture.applySignature('ReputationToken',
                                             universe.getReputationToken())

    # The universe forks and there is now a universe where NO and YES are the respective outcomes of each
    noPayoutNumerators = [0] * market.getNumberOfOutcomes()
    noPayoutNumerators[1] = market.getNumTicks()
    yesPayoutNumerators = [0] * market.getNumberOfOutcomes()
    yesPayoutNumerators[2] = market.getNumTicks()
    noUniverse = fixture.applySignature(
        'Universe', universe.createChildUniverse(noPayoutNumerators))
    yesUniverse = fixture.applySignature(
        'Universe', universe.createChildUniverse(yesPayoutNumerators))
    noUniverseReputationToken = fixture.applySignature(
        'ReputationToken', noUniverse.getReputationToken())
    yesUniverseReputationToken = fixture.applySignature(
        'ReputationToken', yesUniverse.getReputationToken())
    assert noUniverse.address != universe.address
    assert yesUniverse.address != universe.address
    assert yesUniverse.address != noUniverse.address
    assert noUniverseReputationToken.address != yesUniverseReputationToken.address

    # Attempting to finalize the fork now will not succeed as no REP has been migrated and not enough time has passed
    with raises(TransactionFailed):
        market.finalizeFork()

    # A Tester moves some of their REP to the YES universe
    amount = 10**6 * 10**18

    with raises(TransactionFailed):
        reputationToken.migrateOut(yesUniverseReputationToken.address, 0)

    with TokenDelta(yesUniverseReputationToken, amount, tester.a0,
                    "Yes REP token balance was no correct"):
        reputationToken.migrateOut(yesUniverseReputationToken.address, amount)

    # Attempting to finalize the fork now will not succeed as a majority or REP has not yet migrated and fork end time has not been reached
    with raises(TransactionFailed):
        market.finalizeFork()

    if (finalizeByMigration):
        # Tester 0 moves more than 50% of REP
        amount = reputationToken.balanceOf(tester.a0) - 20
        with TokenDelta(noUniverseReputationToken, amount, tester.a0,
                        "No REP token balance was no correct"):
            reputationToken.migrateOut(noUniverseReputationToken.address,
                                       amount)
        assert reputationToken.balanceOf(tester.a0) == 20
        assert market.getWinningPayoutDistributionHash(
        ) == noUniverse.getParentPayoutDistributionHash()
    else:
        # Time marches on past the fork end time
        fixture.contracts["Time"].setTimestamp(universe.getForkEndTime() + 1)
        assert market.finalize()
        assert market.getWinningPayoutDistributionHash(
        ) == yesUniverse.getParentPayoutDistributionHash()
        # If the fork is past the fork period we can not migrate
        with raises(TransactionFailed):
            reputationToken.migrateOut(yesUniverseReputationToken.address, 1)

    # Finalize fork cannot be called again
    with raises(TransactionFailed):
        market.finalizeFork()
コード例 #33
0
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.contracts['ShareToken']
        createOrder = fixture.contracts['CreateOrder']
        fillOrder = fixture.contracts['FillOrder']

        ethRequired = amount * numTicks
        fixture.contracts['Cash'].faucet(ethRequired, sender=sender)
        assert shareToken.publicBuyCompleteSets(market.address,
                                                amount,
                                                sender=sender)
        for otherOutcome in range(0, market.getNumberOfOutcomes()):
            if otherOutcome == outcome: continue
            shareToken.safeTransferFrom(sender,
                                        fixture.accounts[8],
                                        shareToken.getTokenId(
                                            market.address, otherOutcome),
                                        amount,
                                        "",
                                        sender=sender)

    def acquireShortShareSet(outcome, amount, approvalAddress, sender):
        if amount == 0: return

        shareToken = fixture.contracts['ShareToken']
        createOrder = fixture.contracts['CreateOrder']
        fillOrder = fixture.contracts['FillOrder']

        ethRequired = amount * numTicks
        fixture.contracts['Cash'].faucet(ethRequired, sender=sender)
        assert shareToken.publicBuyCompleteSets(market.address,
                                                amount,
                                                sender=sender)
        shareToken.safeTransferFrom(sender,
                                    fixture.accounts[8],
                                    shareToken.getTokenId(
                                        market.address, outcome),
                                    amount,
                                    "",
                                    sender=sender)

    fixture.resetToSnapshot(snapshot)

    legacyReputationToken = fixture.contracts['LegacyReputationToken']
    legacyReputationToken.faucet(11 * 10**6 * 10**18)
    fixture.contracts['Time'].incrementTimestamp(15000)

    orders = fixture.contracts['Orders']
    createOrder = fixture.contracts['CreateOrder']
    fillOrder = fixture.contracts['FillOrder']
    shareToken = fixture.contracts['ShareToken']
    shareToken = fixture.contracts['ShareToken']

    account1 = fixture.accounts[1]
    account2 = fixture.accounts[2]

    creatorAddress = account1
    fillerAddress = account2
    creatorKey = account1
    fillerKey = account2

    # 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)

    # Create order
    fixture.contracts['Cash'].faucet(creatorTokens, sender=creatorKey)
    orderId = createOrder.publicCreateOrder(orderType,
                                            orderSize,
                                            orderPrice,
                                            market.address,
                                            orderOutcome,
                                            longTo32Bytes(0),
                                            longTo32Bytes(0),
                                            longTo32Bytes(42),
                                            nullAddress,
                                            sender=creatorKey)

    # Validate order
    assert orders.getAmount(orderId) == orderSize
    assert orders.getPrice(orderId) == orderPrice
    assert orders.getOrderCreator(orderId) == 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)

    # Move time and sweep interest
    assert fixture.contracts['Time'].incrementTimestamp(50000)
    assert universe.sweepInterest()

    # Fill order
    fixture.contracts['Cash'].faucet(fillerTokens, sender=fillerKey)
    remaining = fillOrder.publicFillOrder(orderId,
                                          orderSize,
                                          longTo32Bytes(42),
                                          longTo32Bytes(11),
                                          sender=fillerKey)
    assert not remaining

    # Move time and sweep interest
    assert fixture.contracts['Time'].incrementTimestamp(50000)
    assert universe.sweepInterest()

    # Assert final state of positions
    assert fixture.contracts['Cash'].balanceOf(creatorAddress) == int(
        expectedMakerTokens)
    assert fixture.contracts['Cash'].balanceOf(fillerAddress) == int(
        expectedFillerTokens)
    for outcome in range(0, market.getNumberOfOutcomes()):
        if outcome == orderOutcome:
            assert shareToken.balanceOfMarketOutcome(
                market.address, outcome,
                creatorAddress) == expectedMakerLongShares
            assert shareToken.balanceOfMarketOutcome(
                market.address, outcome,
                fillerAddress) == expectedFillerLongShares
        else:
            assert shareToken.balanceOfMarketOutcome(
                market.address, outcome,
                creatorAddress) == expectedMakerShortShares
            assert shareToken.balanceOfMarketOutcome(
                market.address, outcome,
                fillerAddress) == expectedFillerShortShares

    # Finalize and claim proceeds
    fixture.contracts["Time"].setTimestamp(market.getEndTime() + 1)
    payoutNumerators = [0, 0, market.getNumTicks()
                        ] if market.getNumberOfOutcomes() == 3 else [
                            0, 0, 0, market.getNumTicks()
                        ]
    market.doInitialReport(payoutNumerators, "", 0)
    disputeWindow = fixture.applySignature('DisputeWindow',
                                           market.getDisputeWindow())
    fixture.contracts["Time"].setTimestamp(disputeWindow.getEndTime() + 1)
    assert market.finalize()

    shareToken = fixture.contracts['ShareToken']
    assert shareToken.claimTradingProceeds(market.address, account1,
                                           longTo32Bytes(11))
    assert shareToken.claimTradingProceeds(market.address, account2,
                                           longTo32Bytes(11))
コード例 #34
0
def execute(fixture, snapshot, universe, market, orderType, orderSize, orderPrice, orderOutcome, creatorLongShares, creatorShortShares, creatorTokens, fillerLongShares, fillerShortShares, fillerTokens, expectedMakerLongShares, expectedMakerShortShares, expectedMakerTokens, expectedFillerLongShares, expectedFillerShortShares, expectedFillerTokens, numTicks):
    def acquireLongShares(outcome, amount, approvalAddress, sender):
        if amount == 0: return

        shareToken = fixture.applySignature('ShareToken', market.getShareToken(outcome))
        completeSets = fixture.contracts['CompleteSets']
        createOrder = fixture.contracts['CreateOrder']
        fillOrder = fixture.contracts['FillOrder']

        ethRequired = amount * numTicks
        assert completeSets.publicBuyCompleteSets(market.address, amount, sender = sender, value = ethRequired)
        for otherOutcome in range(0, market.getNumberOfOutcomes()):
            if otherOutcome == outcome: continue
            otherShareToken = fixture.applySignature('ShareToken', market.getShareToken(otherOutcome))
            assert otherShareToken.transfer(0, amount, sender = sender)

    def acquireShortShareSet(outcome, amount, approvalAddress, sender):
        if amount == 0: return

        shareToken = fixture.applySignature('ShareToken', market.getShareToken(outcome))
        completeSets = fixture.contracts['CompleteSets']
        createOrder = fixture.contracts['CreateOrder']
        fillOrder = fixture.contracts['FillOrder']

        ethRequired = amount * numTicks
        assert completeSets.publicBuyCompleteSets(market.address, amount, sender = sender, value = ethRequired)
        assert shareToken.transfer(0, amount, sender = sender)
        for otherOutcome in range(0, market.getNumberOfOutcomes()):
            if otherOutcome == outcome: continue
            otherShareToken = fixture.applySignature('ShareToken', market.getShareToken(otherOutcome))

    fixture.resetToSnapshot(snapshot)

    legacyReputationToken = fixture.contracts['LegacyReputationToken']
    legacyReputationToken.faucet(long(11 * 10**6 * 10**18))
    fixture.chain.head_state.timestamp += 15000

    orders = fixture.contracts['Orders']
    createOrder = fixture.contracts['CreateOrder']
    fillOrder = fixture.contracts['FillOrder']
    completeSets = fixture.contracts['CompleteSets']

    creatorAddress = tester.a1
    fillerAddress = tester.a2
    creatorKey = tester.k1
    fillerKey = tester.k2

    # Set creator/filler balances
    creatorBalance = fixture.chain.head_state.get_balance(creatorAddress)
    fillerBalance = fixture.chain.head_state.get_balance(fillerAddress)

    # Acquire shares for creator
    creatorEthRequiredLong = 0 if creatorLongShares == 0 else creatorLongShares * numTicks
    creatorEthRequiredShort = 0 if creatorShortShares == 0 else creatorShortShares * numTicks
    acquireLongShares(orderOutcome, creatorLongShares, createOrder.address, sender = creatorKey)
    acquireShortShareSet(orderOutcome, creatorShortShares, createOrder.address, sender = creatorKey)
    assert fixture.chain.head_state.get_balance(creatorAddress) == creatorBalance - creatorEthRequiredLong - creatorEthRequiredShort
    assert fixture.chain.head_state.get_balance(fillerAddress) == fillerBalance

    creatorBalance = fixture.chain.head_state.get_balance(creatorAddress)
    fillerBalance = fixture.chain.head_state.get_balance(fillerAddress)

    # Create order
    orderId = createOrder.publicCreateOrder(orderType, orderSize, orderPrice, market.address, orderOutcome, longTo32Bytes(0), longTo32Bytes(0), "42", sender = creatorKey, value = creatorTokens)
    assert fixture.chain.head_state.get_balance(creatorAddress) == creatorBalance - creatorTokens
    assert fixture.chain.head_state.get_balance(fillerAddress) == fillerBalance

    creatorBalance = fixture.chain.head_state.get_balance(creatorAddress)
    fillerBalance = fixture.chain.head_state.get_balance(fillerAddress)

    # Validate order
    assert orders.getAmount(orderId) == orderSize
    assert orders.getPrice(orderId) == orderPrice
    assert orders.getOrderCreator(orderId) == bytesToHexString(creatorAddress)
    assert orders.getOrderMoneyEscrowed(orderId) == creatorTokens
    assert orders.getOrderSharesEscrowed(orderId) == creatorLongShares or creatorShortShares

    # Acquire shares for filler
    fillerEthRequiredLong = 0 if fillerLongShares == 0 else fillerLongShares * numTicks
    fillerEthRequiredShort = 0 if fillerShortShares == 0 else fillerShortShares * numTicks
    acquireLongShares(orderOutcome, fillerLongShares, fillOrder.address, sender = fillerKey)
    acquireShortShareSet(orderOutcome, fillerShortShares, fillOrder.address, sender = fillerKey)
    assert fixture.chain.head_state.get_balance(creatorAddress) == creatorBalance
    assert fixture.chain.head_state.get_balance(fillerAddress) == fillerBalance - fillerEthRequiredLong - fillerEthRequiredShort

    creatorBalance = fixture.chain.head_state.get_balance(creatorAddress)
    fillerBalance = fixture.chain.head_state.get_balance(fillerAddress)

    # Fill order
    remaining = fillOrder.publicFillOrder(orderId, orderSize, "42", sender = fillerKey, value = fillerTokens)
    assert not remaining

    # Assert final state
    assert fixture.chain.head_state.get_balance(creatorAddress) == creatorBalance + expectedMakerTokens
    assert fixture.chain.head_state.get_balance(fillerAddress) == fillerBalance - fillerTokens + expectedFillerTokens
    for outcome in range(0, market.getNumberOfOutcomes()):
        shareToken = fixture.applySignature('ShareToken', market.getShareToken(outcome))
        if outcome == orderOutcome:
            assert shareToken.balanceOf(creatorAddress) == expectedMakerLongShares
            assert shareToken.balanceOf(fillerAddress) == expectedFillerLongShares
        else:
            assert shareToken.balanceOf(creatorAddress) == expectedMakerShortShares
            assert shareToken.balanceOf(fillerAddress) == expectedFillerShortShares
コード例 #35
0
ファイル: test_wcl_fuzzy.py プロジェクト: peachbits/augur
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'].faucet(ethRequired, sender=sender)
        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(fixture.accounts[8], 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'].faucet(ethRequired, sender=sender)
        assert completeSets.publicBuyCompleteSets(market.address, amount, sender = sender)
        assert shareToken.transfer(fixture.accounts[8], 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(11 * 10**6 * 10**18)
    fixture.contracts['Time'].incrementTimestamp(15000)

    orders = fixture.contracts['Orders']
    createOrder = fixture.contracts['CreateOrder']
    fillOrder = fixture.contracts['FillOrder']
    completeSets = fixture.contracts['CompleteSets']

    account1 = fixture.accounts[1]
    account2 = fixture.accounts[2]

    creatorAddress = account1
    fillerAddress = account2
    creatorKey = account1
    fillerKey = account2

    # 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)

    # Create order
    fixture.contracts['Cash'].faucet(creatorTokens, sender=creatorKey)
    try:
        orderId = createOrder.publicCreateOrder(orderType, orderSize, orderPrice, market.address, orderOutcome, longTo32Bytes(0), longTo32Bytes(0), longTo32Bytes(42), False, nullAddress, sender = creatorKey)
    except Exception:
        import pdb;pdb.set_trace()
        raise

    # Validate order
    assert orders.getAmount(orderId) == orderSize
    assert orders.getPrice(orderId) == orderPrice
    assert orders.getOrderCreator(orderId) == 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)

    # Fill order
    fixture.contracts['Cash'].faucet(fillerTokens, sender=fillerKey)
    remaining = fillOrder.publicFillOrder(orderId, orderSize, longTo32Bytes(42), False, "0x0000000000000000000000000000000000000000", sender = fillerKey)
    assert not remaining

    # Assert final state
    assert fixture.contracts['Cash'].balanceOf(creatorAddress) == int(expectedMakerTokens)
    assert fixture.contracts['Cash'].balanceOf(fillerAddress) == int(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
コード例 #36
0
def finalizeFork(fixture, market, universe, finalizeByMigration = True):
    reputationToken = fixture.applySignature('ReputationToken', universe.getReputationToken())

    # The universe forks and there is now a universe where NO and YES are the respective outcomes of each
    noPayoutNumerators = [0] * market.getNumberOfOutcomes()
    noPayoutNumerators[0] = market.getNumTicks()
    yesPayoutNumerators = noPayoutNumerators[::-1]
    noUniverse =  fixture.applySignature('Universe', universe.createChildUniverse(noPayoutNumerators, False))
    yesUniverse =  fixture.applySignature('Universe', universe.createChildUniverse(yesPayoutNumerators, False))
    noUniverseReputationToken = fixture.applySignature('ReputationToken', noUniverse.getReputationToken())
    yesUniverseReputationToken = fixture.applySignature('ReputationToken', yesUniverse.getReputationToken())
    assert noUniverse.address != universe.address
    assert yesUniverse.address != universe.address
    assert yesUniverse.address != noUniverse.address
    assert noUniverseReputationToken.address != yesUniverseReputationToken.address

    # Attempting to finalize the fork now will not succeed as no REP has been migrated and not enough time has passed
    with raises(TransactionFailed):
        market.finalizeFork()

    # A Tester moves some of their REP to the YES universe
    amount = 10 ** 6 * 10 ** 18
    bonus = amount / fixture.contracts["Constants"].FORK_MIGRATION_PERCENTAGE_BONUS_DIVISOR()

    with raises(TransactionFailed):
        reputationToken.migrateOut(yesUniverseReputationToken.address, 0)

    with TokenDelta(yesUniverseReputationToken, amount + bonus, tester.a0, "Yes REP token balance was no correct"):
        reputationToken.migrateOut(yesUniverseReputationToken.address, amount)

    # Attempting to finalize the fork now will not succeed as a majority or REP has not yet migrated and fork end time has not been reached
    with raises(TransactionFailed):
        market.finalizeFork()

    if (finalizeByMigration):
        # Tester 0 moves more than 50% of REP
        amount = reputationToken.balanceOf(tester.a0) - 20
        bonus = amount / fixture.contracts["Constants"].FORK_MIGRATION_PERCENTAGE_BONUS_DIVISOR()
        with TokenDelta(noUniverseReputationToken, amount + bonus, tester.a0, "No REP token balance was no correct"):
            reputationToken.migrateOut(noUniverseReputationToken.address, amount)
        assert reputationToken.balanceOf(tester.a0) == 20
        assert market.getWinningPayoutDistributionHash() == noUniverse.getParentPayoutDistributionHash()
    else:
        # Time marches on past the fork end time
        fixture.contracts["Time"].setTimestamp(universe.getForkEndTime() + 1)
        assert market.finalize()
        assert market.getWinningPayoutDistributionHash() == yesUniverse.getParentPayoutDistributionHash()

    # if the fork finalized by migration we're still in the 60 day fork window and can still get a bonus for migrating. If the fork is past the fork period we can no longer get the 5% bonus
    amount = 20
    amountAdded = amount
    if finalizeByMigration:
        bonus = amount / fixture.contracts["Constants"].FORK_MIGRATION_PERCENTAGE_BONUS_DIVISOR()
        amountAdded += bonus

    with TokenDelta(yesUniverseReputationToken, amountAdded, tester.a0, "reputation migration bonus did not work correctly"):
        reputationToken.migrateOut(yesUniverseReputationToken.address, amount)

    # Finalize fork cannot be called again
    with raises(TransactionFailed):
        market.finalizeFork()