def test_non_fractional_price(chain, milestone_pricing, customer, end_time):
    """We divide price correctly for integer only amount."""
    time_travel(chain, end_time - 1)

    assert milestone_pricing.call().calculatePrice(
        to_wei("0.28", "ether"),
        0,
        0,
        customer,
        0,
    ) == 2

    assert milestone_pricing.call().calculatePrice(
        to_wei("0.281", "ether"),
        0,
        0,
        customer,
        0,
    ) == 2

    assert milestone_pricing.call().calculatePrice(
        to_wei("0.4199", "ether"),
        0,
        0,
        customer,
        0,
    ) == 2

    assert milestone_pricing.call().calculatePrice(
        to_wei("0.42", "ether"),
        0,
        0,
        customer,
        0,
    ) == 3
def test_tranche_prices(chain, tranche_pricing, start_time, end_time, customer):
    """We get correct tranche prices for different dates."""

    #TODO: Instead of timetravel, buy tokens here after this line, and then copy this
    assert tranche_pricing.call().calculatePrice(
        to_wei("0.10", "ether"),
        0,
        0,
        customer,
        0,
    ) == 1

    assert tranche_pricing.call().calculatePrice(
        to_wei("0.10", "ether"),
        122,
        0,
        customer,
        0,
    ) == 1

    assert tranche_pricing.call().calculatePrice(
        to_wei("0.12", "ether"),
        123,
        0,
        customer,
        0,
    ) == 1

    assert tranche_pricing.call().calculatePrice(
        to_wei("0.39", "ether"),
        1234,
        0,
        customer,
        0,
    ) == 3
def presale_milestone_pricing(chain, presale_fund_collector, uncapped_flatprice, presale_freeze_ends_at, team_multisig):
    """Pricing used in presale tests, allowing us to set special price for presale participants."""

    week = 24 * 3600 * 7
    start_time = uncapped_flatprice.call().startsAt()
    end_time = start_time + week*4

    uncapped_flatprice.transact({"from": team_multisig}).setEndsAt(end_time)

    args = [
        [
            start_time + 0, to_wei("0.10", "ether"),
            start_time + week*1, to_wei("0.10", "ether"),
            start_time + week*2, to_wei("0.10", "ether"),
            start_time + week*3, to_wei("0.10", "ether"),
            end_time, to_wei("0", "ether"),
        ],
    ]

    tx = {
        "gas": 4000000,
        "from": team_multisig
    }
    contract, hash = chain.provider.deploy_contract('MilestonePricing', deploy_args=args, deploy_transaction=tx)
    contract.transact({"from": team_multisig}).setPreicoAddress(presale_fund_collector.address, to_wei("0.05", "ether"))

    assert contract.call().isSane(uncapped_flatprice.address)
    return contract
def test_close_early(chain: TestRPCChain, ico: Contract, customer: str, preico_starts_at, preico_ends_at, team_multisig):
    """Soft cap triggered, close crowdsale early."""

    # Close earlier than anticipated
    new_early = preico_starts_at + 1*3600
    assert new_early < preico_ends_at

    time_travel(chain, preico_starts_at + 1)
    assert ico.call().getState() == CrowdsaleState.Funding
    ico.transact({"from": customer, "value": to_wei(1, "ether")}).buy()
    ico.transact({"from": team_multisig}).setEndsAt(new_early)

    # Here we try to switch the strategy, and buy again, 1 wei for 1 token
    args = [
        1,
    ]
    tx = {
        "from": team_multisig,
    }
    pricing_strategy, hash = chain.provider.deploy_contract('FlatPricing', deploy_args=args, deploy_transaction=tx)

    ico.transact({"from": team_multisig}).setPricingStrategy(pricing_strategy.address)
    assert ico.call().pricingStrategy() == pricing_strategy.address

    ico.transact({"from": customer, "value": 1}).buy()

    # Finally, here we travel in time to situation after the early closing:
    time_travel(chain, new_early + 1)
    assert ico.call().getState() == CrowdsaleState.Failure

    with pytest.raises(TransactionFailed):
        ico.transact({"from": customer, "value": to_wei(1, "ether")}).buy()
def test_milestone_prices(chain, milestone_pricing, start_time, end_time, customer):
    """We get correct milestone prices for different dates."""

    time_travel(chain, start_time - 1)
    with pytest.raises(TransactionFailed):
        # Div by zero, crowdsale has not begin yet
        assert milestone_pricing.call().getCurrentPrice()

    time_travel(chain, start_time)
    assert milestone_pricing.call().getCurrentPrice() == to_wei("0.10", "ether")

    time_travel(chain, start_time + 1)
    assert milestone_pricing.call().getCurrentPrice() == to_wei("0.10", "ether")

    # 1 week forward
    time_travel(chain, int((datetime.datetime(2017, 4, 22, 16, 0) - datetime.datetime(1970, 1, 1)).total_seconds()))
    assert milestone_pricing.call().getCurrentPrice() == to_wei("0.12", "ether")

    # 2 week forward
    time_travel(chain, int((datetime.datetime(2017, 4, 29, 16, 0) - datetime.datetime(1970, 1, 1)).total_seconds()))
    assert milestone_pricing.call().getCurrentPrice() == to_wei("0.13", "ether")

    # 3 week forward + last second
    time_travel(chain, end_time - 1)
    assert milestone_pricing.call().getCurrentPrice() == to_wei("0.14", "ether")
def test_close_late(chain: TestRPCChain, ico: Contract, customer: str, preico_starts_at, preico_ends_at, team_multisig):
    """Extend crowdsale."""

    new_end = preico_ends_at + 1*3600
    assert new_end > preico_ends_at

    time_travel(chain, preico_starts_at + 1)
    assert ico.call().getState() == CrowdsaleState.Funding
    ico.transact({"from": customer, "value": to_wei(1, "ether")}).buy()

    ico.transact({"from": team_multisig}).setEndsAt(new_end)

    time_travel(chain, preico_ends_at + 1)
    assert ico.call().getState() == CrowdsaleState.Funding
    ico.transact({"from": customer, "value": to_wei(1, "ether")}).buy()
def test_buy_early(chain: TestRPCChain, ico: Contract, customer: str, preico_starts_at, uncapped_token):
    """Cannot buy too early."""

    time_travel(chain, preico_starts_at - 1)
    assert ico.call().getState() == CrowdsaleState.PreFunding
    with pytest.raises(TransactionFailed):
        ico.transact({"from": customer, "value": to_wei(1, "ether")}).buy()
def test_deposit_default_payabl(chain: TestRPCChain, web3: Web3, ico: Contract, uncapped_token: Contract, customer: str, preico_token_price, preico_starts_at, team_multisig):
    """Cannot just send money to the contract address and expect getting tokens.."""

    wei_value = to_wei(100, "ether")
    time_travel(chain, preico_starts_at + 1)
    with pytest.raises(TransactionFailed):
        web3.eth.sendTransaction({"from": customer, "value": wei_value, "to": ico.address})
def test_pay_twice(web3, payment_forwarder, team_multisig, customer, customer_2):
    """Pay for an address twice."""

    value = to_wei("1.0", "ether")
    customer_id = int(uuid.uuid4().hex, 16)  # Customer ids are 128-bit UUID v4

    team_multisig_begin = web3.eth.getBalance(team_multisig)
    # We pay from two distinct addresses on behalf of the same customer
    payment_forwarder.transact({"value": value, "from": customer}).pay(customer_id, customer)
    payment_forwarder.transact({"value": value, "from": customer_2}).pay(customer_id, customer)
    team_multisig_end = web3.eth.getBalance(team_multisig)

    assert team_multisig_end - team_multisig_begin > 0
    assert payment_forwarder.call().totalTransferred() == 2*value
    assert payment_forwarder.call().paymentsByCustomer(customer_id) == 2*value
    assert payment_forwarder.call().paymentsByBenefactor(customer) == 2*value
    assert payment_forwarder.call().customerCount() == 1

    # Check we properly generate an event
    events = payment_forwarder.pastEvents("PaymentForwarded").get()
    assert len(events) == 2
    e = events[-1]
    assert e["args"]["source"] == customer_2
    assert e["args"]["amount"] == value
    assert e["args"]["customerId"] == customer_id
    assert e["args"]["benefactor"] == customer
def test_buy_late_goal_reached(chain: TestRPCChain, uncapped_flatprice_goal_reached: Contract, customer: str, preico_ends_at):
    """Cannot buy after closing time when the goal was not reached."""

    time_travel(chain, preico_ends_at + 1)
    assert uncapped_flatprice_goal_reached.call().getState() == CrowdsaleState.Success
    with pytest.raises(TransactionFailed):
        uncapped_flatprice_goal_reached.transact({"from": customer, "value": to_wei(1, "ether")}).buy()
def test_buy_all(chain, crowdsale, token, finalizer, start_time, end_time, team_multisig, customer, cap, founder_allocation):
    """Buy all tokens and finalize crowdsale."""

    # Buy on first week
    time_travel(chain, start_time + 1)
    assert crowdsale.call().getState() == CrowdsaleState.Funding

    # Buy all cap
    wei_value = cap * to_wei("0.10", "ether")
    crowdsale.transact({"from": customer, "value": wei_value}).buy()
    assert crowdsale.call().isCrowdsaleFull()

    # Close the deal
    time_travel(chain, end_time + 1)
    assert crowdsale.call().getState() == CrowdsaleState.Success
    crowdsale.transact({"from": team_multisig}).finalize()
    assert crowdsale.call().getState() == CrowdsaleState.Finalized

    customer_tokens = 4000000

    # See that we counted bonus correctly
    assert finalizer.call().allocatedBonus() == 800000

    # See that bounty tokens do not count against tokens sold
    assert crowdsale.call().tokensSold() == customer_tokens
    assert token.call().totalSupply() == customer_tokens * (1 + founder_allocation)

    # See that customers get their tokens
    assert token.call().balanceOf(customer) == crowdsale.call().tokensSold()

    # See that team multisig got our bonus tokens
    assert token.call().balanceOf(team_multisig) == crowdsale.call().tokensSold() * founder_allocation

    # Token is transferable
    assert token.call().released()
def test_rebuild_failed_crowdsale(chain, original_crowdsale, token, relaunched_crowdsale, sample_data, team_multisig, customer, customer_2):
    """Rebuild a crowdsale that is not going to reach its minimum goal."""

    time_travel(chain, original_crowdsale.call().startsAt() + 1)
    assert original_crowdsale.call().getState() == CrowdsaleState.Funding
    assert relaunched_crowdsale.call().getState() == CrowdsaleState.Funding

    for data in sample_data:
        addr = data["Address"]
        wei = to_wei(data["Invested ETH"], "ether")
        original_crowdsale.transact({"from": addr, "value": wei}).buy()

    # We have a confirmation hash
    events = original_crowdsale.pastEvents("Invested").get()
    assert len(events) == 2
    e = events[-1]

    for data in sample_data:
        addr = data["Address"]
        wei = to_wei(data["Invested ETH"], "ether")
        tokens = int(data["Received tokens"])
        txid = int(data["Txid"], 16)
        relaunched_crowdsale.transact({"from": team_multisig}).setInvestorData(addr, wei, tokens, txid)

    assert original_crowdsale.call().tokensSold() == relaunched_crowdsale.call().tokensSold()
    assert original_crowdsale.call().investedAmountOf(customer) == relaunched_crowdsale.call().investedAmountOf(customer)
    assert original_crowdsale.call().investedAmountOf(customer_2) == relaunched_crowdsale.call().investedAmountOf(customer_2)

    assert token.call().balanceOf(customer) == relaunched_crowdsale.call().tokenAmountOf(customer)
    assert token.call().balanceOf(customer_2) == relaunched_crowdsale.call().tokenAmountOf(customer_2)

    time_travel(chain, original_crowdsale.call().endsAt() + 1)

    assert original_crowdsale.call().getState() == CrowdsaleState.Failure
    assert relaunched_crowdsale.call().getState() == CrowdsaleState.Failure
    relaunched_crowdsale.transact({"from": team_multisig, "value": to_wei(30, "ether")}).loadRefund()
    assert relaunched_crowdsale.call().getState() == CrowdsaleState.Refunding

    relaunched_crowdsale.transact({"from": customer}).refund()
    relaunched_crowdsale.transact({"from": customer_2}).refund()

    # No double refund
    with pytest.raises(TransactionFailed):
        relaunched_crowdsale.transact({"from": customer}).refund()

    with pytest.raises(TransactionFailed):
        original_crowdsale.transact({"from": customer}).refund()
def proxy_buyers(project, chain, web3, customer, everything_deployed, deploy_address, proxy_buyer_freeze_ends_at, presale_investor_1, presale_investor_2, presale_investor_3, presale_investor_4):
    """Simulate the presale contracts."""

    crowdsale = everything_deployed["crowdsale"]
    pricing_strategy = everything_deployed["pricing_strategy"]

    # Presale price
    default_presale_price = from_wei(2500000000000000, "ether")

    # List of presale contracts
    proxy_buyers = [
        (presale_investor_1, "9930.441837", default_presale_price),
        (presale_investor_2, "9999", default_presale_price),# 0x6d997eDcA04282950416FA380d834f360fC36eBb
    ]

    results = []
    for investor, amount, price, in proxy_buyers:
        # Create finalizer contract
        amount = Decimal(amount)

        # Dummy presale min and max arguments
        args = [
            deploy_address,
            proxy_buyer_freeze_ends_at,
            1,  # 1 wei,
            to_wei(10000, "ether"),
            to_wei(10000, "ether"),
        ]
        proxy_buyer, hash = chain.provider.deploy_contract('PreICOProxyBuyer', deploy_args=args)

        # Load presale contract with money
        assert proxy_buyer.call().getState() == 1
        proxy_buyer.transact({"value": to_wei(amount, "ether"), "from": investor}).buy()

        # Set ICO
        proxy_buyer.transact({"from": deploy_address}).setCrowdsale(crowdsale.address)

        # Set proxy buyer contract special price
        pricing_strategy.transact({"from": deploy_address}).setPreicoAddress(proxy_buyer.address, to_wei(price, "ether"))

        # Allow proxy buyer to move money in early
        crowdsale.transact({"from": deploy_address}).setEarlyParicipantWhitelist(proxy_buyer.address, True)

        results.append(proxy_buyer)

    return results
def test_buy_early_whitelisted(chain: TestRPCChain, ico: Contract, customer: str, preico_starts_at, team_multisig, uncapped_token):
    """Whitelisted participants can buy earliy."""

    time_travel(chain, preico_starts_at - 1)
    assert ico.call().getState() == CrowdsaleState.PreFunding
    ico.transact({"from": team_multisig}).setEarlyParicipantWhitelist(customer, True)
    ico.transact({"from": customer, "value": to_wei(1, "ether")}).buy()
    assert uncapped_token.call().balanceOf(customer) > 0
def milestone_pricing(chain, start_time, end_time):
    """Milestone pricing, do not set presale collection contract."""

    week = 24*3600 * 7

    args = [
        [
            start_time + 0, to_wei("0.0009", "ether"),
            start_time + week*1, to_wei("0.0009", "ether"),
            end_time, 0,
        ],
    ]

    tx = {
        "gas": 4000000
    }
    contract, hash = chain.provider.deploy_contract('MilestonePricing', deploy_args=args, deploy_transaction=tx)
    return contract
def test_presale_move_to_tranche_based_crowdsale(chain, presale_fund_collector, tranche_ico, finalizer, token, start_time, team_multisig, customer, customer_2):
    """When pre-ico contract funds are moved to the crowdsale, the pre-sale investors gets tokens with a preferred price and not the current tranche price."""

    value = to_wei(50, "ether")
    presale_fund_collector.transact({"from": customer, "value": value}).invest()

    # ICO begins, Link presale to an actual ICO
    presale_fund_collector.transact({"from": team_multisig}).setCrowdsale(tranche_ico.address)
    time_travel(chain, start_time)

    assert tranche_ico.call().getState() == CrowdsaleState.Funding

    # Load funds to ICO
    presale_fund_collector.transact().participateCrowdsaleAll()

    # Tokens received, paid by preico price
    tranche_ico.call().investedAmountOf(customer) == to_wei(50, "ether")
    token.call().balanceOf(customer) == 50 / 0.050
def test_participate_missing_customer_id(chain, crowdsale, customer, customer_id, token):
    """Cannot bypass customer id process."""

    time_travel(chain, crowdsale.call().startsAt() + 1)
    wei_value = to_wei(1, "ether")
    assert crowdsale.call().getState() == CrowdsaleState.Funding

    with pytest.raises(TransactionFailed):
        crowdsale.transact({"from": customer, "value": wei_value}).buy()
def test_halt(web3, payment_forwarder, team_multisig, customer):
    """We can stop crowdsale."""

    value = to_wei("1.0", "ether")
    customer_id = int(uuid.uuid4().hex, 16) # Customer ids are 128-bit UUID v4

    team_multisig_begin = web3.eth.getBalance(team_multisig)
    payment_forwarder.transact({"from": team_multisig}).halt()
    with pytest.raises(TransactionFailed):
        payment_forwarder.transact({"value": value, "from": customer}).pay(customer_id, customer)
def test_refund(failed_ico_ready_to_refund: Contract, web3: Web3, customer: str, customer_2: str):
    """Customers can claim their refunds."""

    assert failed_ico_ready_to_refund.call().loadedRefund() == to_wei(120, "ether")
    assert failed_ico_ready_to_refund.call().getState() == CrowdsaleState.Refunding

    # Check that the customer gets money back
    invested_amount = failed_ico_ready_to_refund.call().investedAmountOf(customer)
    begin_balance = web3.eth.getBalance(customer)
    failed_ico_ready_to_refund.transact({"from": customer}).refund()
    end_balance = web3.eth.getBalance(customer)

    eth = from_wei(end_balance - begin_balance, "ether")  # Decimal('49.999999999999954693')
    assert (end_balance - begin_balance) >= eth - TRANSACTION_COST_ETH_EPSILON

    failed_ico_ready_to_refund.transact({"from": customer_2}).refund()

    # Everything has been refunded
    assert failed_ico_ready_to_refund.call().weiRefunded() == to_wei(120, "ether")
def test_non_fractional_price(chain, tranche_pricing, customer, end_time):
    """We divide price correctly for integer only amount."""

    assert tranche_pricing.call().calculatePrice(
        to_wei("0.28", "ether"),
        0,
        0,
        customer,
        0,
    ) == 2

    assert tranche_pricing.call().calculatePrice(
        to_wei("0.281", "ether"),
        0,
        0,
        customer,
        0,
    ) == 2

    assert tranche_pricing.call().calculatePrice(
        to_wei("0.11", "ether"),
        122,
        0,
        customer,
        0,
    ) == 1

    assert tranche_pricing.call().calculatePrice(
        to_wei("0.25", "ether"),
        0,
        123,
        customer,
        0,
    ) == 2

    assert tranche_pricing.call().calculatePrice(
        to_wei("0.40", "ether"),
        0,
        1234,
        customer,
        0,
    ) == 3
Beispiel #21
0
def test_buy_one_investor(chain: TestRPCChain, web3: Web3, ico: Contract,
                          uncapped_token: Contract, customer: str,
                          preico_token_price, preico_starts_at, team_multisig):
    """Can buy when crowdsale is running."""

    original_balance = web3.eth.getBalance(team_multisig)
    wei_value = to_wei(1, "ether")
    buys_tokens = wei_value // preico_token_price
    assert buys_tokens > 0

    time_travel(chain, preico_starts_at + 1)
    assert ico.call().getState() == CrowdsaleState.Funding
    assert ico.call().investorCount() == 0
    assert ico.call().investedAmountOf(customer) == 0
    ico.transact({"from": customer, "value": wei_value}).buy()

    #
    # See everything was correctly credited
    #

    # Tokens on every account
    assert uncapped_token.call().balanceOf(customer) == buys_tokens
    assert uncapped_token.call().totalSupply() == buys_tokens
    assert ico.call().tokensSold() == buys_tokens
    assert ico.call().investorCount() == 1

    # Ether on every account
    assert ico.call().weiRaised() == wei_value
    assert ico.call().investedAmountOf(customer) == wei_value
    balance_diff = web3.eth.getBalance(team_multisig) - original_balance
    assert balance_diff == wei_value

    # Investors
    assert ico.call().investorCount() == 1

    #
    # Events
    #

    # Crowdsale
    events = ico.pastEvents("Invested").get()
    assert len(events) == 1
    e = events[0]
    assert e["args"]["investor"] == customer
    assert e["args"]["weiAmount"] == wei_value
    assert e["args"]["tokenAmount"] == buys_tokens

    # ERC-20
    events = uncapped_token.pastEvents("Transfer").get()
    assert len(events) == 1
    e = events[0]
    assert e["args"]["from"] == "0x0000000000000000000000000000000000000000"
    assert e["args"]["to"] == customer
    assert e["args"]["value"] == buys_tokens
Beispiel #22
0
def test_estimate_invest_cost(chain, web3, presale_fund_collector,
                              presale_crowdsale, preico_starts_at, customer,
                              customer_2):
    """Estimate invest gas cost."""

    value = to_wei(1, "ether")
    transaction = {"from": customer, "value": value}
    cost = presale_fund_collector.estimateGas(
        transaction=transaction).invest()  # 107459
    assert cost > 0
    assert cost < 200000
Beispiel #23
0
 def reset_to_genesis(self):
     from ethereum.tools import tester
     self.evm = tester.Chain()
     self.evm = tester.Chain(
         alloc={
             account: {
                 'balance': to_wei(1000000, 'ether')
             }
             for account in tester.accounts
         })
     self.evm.extra_accounts = {}
Beispiel #24
0
def milestone_pricing(chain, presale_fund_collector, start_time):

    week = 24*3600 * 7

    args = [
        presale_fund_collector.address,
        to_wei("0.05", "ether"),
        [
            start_time + 0, to_wei("0.10", "ether"),
            start_time + week*1, to_wei("0.12", "ether"),
            start_time + week*2, to_wei("0.13", "ether"),
            start_time + week*4, to_wei("0.13", "ether"),
        ],
    ]

    tx = {
        "gas": 4000000
    }
    contract, hash = chain.provider.deploy_contract('MilestonePricing', deploy_args=args, deploy_transaction=tx)
    return contract
Beispiel #25
0
def test_buy_early(chain: TesterChain, ico: Contract, customer: str,
                   preico_starts_at, uncapped_token):
    """Cannot buy too early."""
    # two seconds early
    time_travel(chain, preico_starts_at - 2)
    assert ico.functions.getState().call() == CrowdsaleState.PreFunding
    with pytest.raises(TransactionFailed):
        ico.functions.buy().transact({
            "from": customer,
            "value": to_wei(1, "ether")
        })
Beispiel #26
0
def test_buy_late_goal_not_reached(chain: TesterChain, ico: Contract,
                                   customer: str, preico_ends_at):
    """Cannot buy after closing time when the goal was not reached."""

    time_travel(chain, preico_ends_at + 1)
    assert ico.functions.getState().call() == CrowdsaleState.Failure
    with pytest.raises(TransactionFailed):
        ico.functions.buy().transact({
            "from": customer,
            "value": to_wei(1, "ether")
        })
def test_proxy_buy_too_much(chain, web3, customer, customer_2, team_multisig,
                            proxy_buyer, crowdsale, token):
    """Try to buy over the cap."""

    assert proxy_buyer.functions.getState().call() == 1

    with pytest.raises(TransactionFailed):
        proxy_buyer.functions.buy().transact({
            "value": to_wei(100001, "ether"),
            "from": customer
        })
Beispiel #28
0
def failed_ico(chain: TestRPCChain, web3, uncapped_flatprice: Contract, team_multisig, customer, customer_2, preico_starts_at, preico_ends_at, uncapped_flatprice_finalizer) -> Contract:
    """An ICO that did not reach a goal, but has participants.

    Both ``customer`` and ``customer_2`` had bought token.

    * customer: 50 ether
    * customer_2: 70 ether
    * total: 120 ether
    * minimum funding goal: 1200 ether

    """

    time_travel(chain, preico_starts_at + 1)

    uncapped_flatprice.transact({"from": customer, "value": to_wei(50, "ether")}).buy()
    uncapped_flatprice.transact({"from": customer_2, "value": to_wei(70, "ether")}).buy()

    # Make sure customer 1 has some token balance
    time_travel(chain, preico_ends_at + 1)
    return uncapped_flatprice
Beispiel #29
0
def milestone_pricing(chain, start_time, end_time):
    """Milestone pricing, do not set presale collection contract."""

    week = 24*3600 * 7

    args = [
        "0x0000000000000000000000000000000000000000",
        to_wei("0.00001", "ether"),
        [
            start_time + 0, to_wei("0.0009", "ether"),
            start_time + week*1, to_wei("0.0009", "ether"),
            end_time, 0,
        ],
    ]

    tx = {
        "gas": 4000000
    }
    contract, hash = chain.provider.deploy_contract('MilestonePricing', deploy_args=args, deploy_transaction=tx)
    return contract
Beispiel #30
0
def test_bitcoin_suisse(chain, ready_crowdsale, bitcoin_suisse, mysterium_pricing, team_multisig):
    """"Test BitcoinSuisse address whitelisting.

    Spec 3.2.
    """

    crowdsale = ready_crowdsale

    # Cannot transact initially
    assert crowdsale.call().getState() == CrowdsaleState.PreFunding

    with pytest.raises(TransactionFailed):
        crowdsale.transact({"from": bitcoin_suisse, "value": to_wei(10000, "ether")}).buy()

    # Now let's set rate and whitelist
    mysterium_pricing.transact({"from": team_multisig}).setConversionRate(130 * 10000)
    crowdsale.transact({"from": team_multisig}).setEarlyParicipantWhitelist(bitcoin_suisse, True)

    # Now BitcoinSuisse can execute
    crowdsale.transact({"from": bitcoin_suisse, "value": to_wei(10000, "ether")}).buy()
def test_milestone_calculate_preico_price(chain, milestone_pricing, start_time,
                                          presale_fund_collector):
    """Preico contributors get their special price."""

    # 1 week forward
    time_travel(chain, start_time + 7 * 24 * 60 * 60)

    # Pre-ico address always buys at the fixed price
    assert milestone_pricing.functions.calculatePrice(
        to_wei("0.05", "ether"), 0, 0, presale_fund_collector.address,
        0).call() == 1
def test_tranche_calculate_preico_price(chain, tranche_pricing, start_time, presale_fund_collector):
    """Preico contributors get their special price."""

    # Pre-ico address always buys at the fixed price
    assert tranche_pricing.call().calculatePrice(
        to_wei("0.05", "ether"),
        0,
        0,
        presale_fund_collector.address,
        0
    ) == 1
Beispiel #33
0
def test_hard_cap_price(crowdsale, mysterium_pricing):
    """"Soft cap prices match the specification."""

    one_point_two_chf_in_eth = to_wei(1.2/120, "ether")

    soft_cap_goal = mysterium_pricing.call().getSoftCapInWeis()

    # See we get correct price for one token
    tokens_bought = mysterium_pricing.call().calculatePrice(one_point_two_chf_in_eth, soft_cap_goal + 1, 0, '0x0000000000000000000000000000000000000000', 8)

    assert tokens_bought == 1 * 10**8
Beispiel #34
0
def private_key_hex(web3_test_provider, web3):
    """Create a static private key with some ETH balance on it."""
    # accounts = web3_test_provider.ethereum_tester.get_accounts()
    private_key_hex = "3fac35a57e1e2867290ae37d54c5de61d52644b42819ce6af0c5a9c25f4c8005"

    acc_zero = web3_test_provider.ethereum_tester.get_accounts()[0]  # Accounts with pregenerated balance
    address = web3_test_provider.ethereum_tester.add_account(private_key_hex)
    web3.eth.sendTransaction({"from": acc_zero, "to": address, "value": to_wei(1, "ether")})
    balance = web3.eth.getBalance(address)
    assert balance > 0
    return private_key_hex
Beispiel #35
0
def test_proxy_max_buyin(chain, web3, customer, customer_2, team_multisig,
                         proxy_buyer, crowdsale, token):
    """Try to buy over the cap."""

    assert proxy_buyer.call().getState() == 1

    with pytest.raises(TransactionFailed):
        proxy_buyer.transact({
            "value": to_wei(44001, "ether"),
            "from": customer
        }).investWithoutId()
Beispiel #36
0
def test_close_early(chain: TesterChain, ico: Contract, customer: str,
                     preico_starts_at, preico_ends_at, team_multisig):
    """Soft cap triggered, close crowdsale early."""

    # Close earlier than anticipated
    new_early = preico_starts_at + 1 * 3600
    assert new_early < preico_ends_at

    time_travel(chain, preico_starts_at + 1)
    assert ico.functions.getState().call() == CrowdsaleState.Funding
    ico.functions.buy().transact({
        "from": customer,
        "value": to_wei(1, "ether")
    })
    ico.functions.setEndsAt(new_early).transact({"from": team_multisig})

    # Here we try to switch the strategy, and buy again, 1 wei for 1 token
    args = [
        1,
    ]
    tx = {
        "from": team_multisig,
    }
    pricing_strategy, hash = chain.provider.deploy_contract(
        'FlatPricing', deploy_args=args, deploy_transaction=tx)

    ico.functions.setPricingStrategy(pricing_strategy.address).transact(
        {"from": team_multisig})
    assert ico.functions.pricingStrategy().call() == pricing_strategy.address

    ico.functions.buy().transact({"from": customer, "value": 1})

    # Finally, here we travel in time to situation after the early closing:
    time_travel(chain, new_early + 1)
    assert ico.functions.getState().call() == CrowdsaleState.Failure

    with pytest.raises(TransactionFailed):
        ico.functions.buy().transact({
            "from": customer,
            "value": to_wei(1, "ether")
        })
Beispiel #37
0
def test_proxy_buy_with_id(chain, web3, customer, customer_2, team_multisig, proxy_buyer, crowdsale, token):
    """Buy proxy as a customer we can link to a database entry."""

    assert proxy_buyer.call().getState() == 1

    customer_id = int(uuid.uuid4().hex, 16)  # Customer ids are 128-bit UUID v4
    proxy_buyer.transact({"value": to_wei(10000, "ether"), "from": customer}).investWithId(customer_id)

    events = proxy_buyer.pastEvents("Invested").get()
    assert len(events) == 1
    e = events[-1]
    assert e["args"]["customerId"] == customer_id
Beispiel #38
0
def claim(wallet: Wallet):
    txn = {
        'chainId': client.chain_id,
        'gas': argv.gas,
        'gasPrice': eth_utils.to_wei(argv.gas_price, "gwei"),
        'nonce': client.web3.eth.getTransactionCount(wallet.address),
        'from': wallet.address
    }
    transfer_txn = contract.functions.claim().buildTransaction(txn)
    signed_tran =  client.web3.eth.account.sign_transaction(transfer_txn, private_key=wallet.private_key)
    tran_hash = client.web3.eth.sendRawTransaction(signed_tran.rawTransaction)
    return TransactionRet(tran_hash=tran_hash, web3=client.web3)
Beispiel #39
0
def test_invest_presale_move_to_crowdsale_early_whitelisted_two(chain, web3, presale_fund_collector, presale_crowdsale_miletstoned, customer, customer_2, preico_starts_at, team_multisig, finalizer, uncapped_token):
    """Move funds to a crowdsale that has whitelisted our contract address from multiple investors."""

    value = to_wei(1, "ether")
    presale_fund_collector.functions.invest().transact({"from": customer, "value": value})
    presale_fund_collector.functions.invest().transact({"from": customer_2, "value": value})

    assert presale_crowdsale_miletstoned.functions.getState().call() == CrowdsaleState.PreFunding

    # Move funds over
    updated = participate_early(chain, web3, presale_fund_collector.address, presale_crowdsale_miletstoned.address, team_multisig)
    assert updated == 2
Beispiel #40
0
def create_dev_test_blockchain_database_with_given_transactions(base_db, tx_list: List, use_real_genesis = False):

    # sort by time
    tx_list.sort(key=lambda x: x[3])

    genesis_chain_stake = 100000000000000000

    total_required_gas = sum([(to_wei(tx_key[4], 'gwei') if len(tx_key) > 4 else to_wei(1, 'gwei'))*GAS_TX for tx_key in tx_list])

    earliest_timestamp = tx_list[0][3]
    required_total_supply = sum([x[2] for x in tx_list if x[0] == TESTNET_GENESIS_PRIVATE_KEY]) + genesis_chain_stake + total_required_gas

    if use_real_genesis:
        import_genesis_block(base_db)
    else:
        genesis_params, genesis_state = create_new_genesis_params_and_state(TESTNET_GENESIS_PRIVATE_KEY, required_total_supply, earliest_timestamp - 100000)

        # import genesis block
        TestnetChain.from_genesis(base_db, TESTNET_GENESIS_PRIVATE_KEY.public_key.to_canonical_address(), genesis_params, genesis_state)

    add_transactions_to_blockchain_db(base_db, tx_list)
Beispiel #41
0
def presale_fund_collector(chain, presale_freeze_ends_at, team_multisig) -> Contract:
    """In actual ICO, the price is doubled (for testing purposes)."""
    args = [
        team_multisig,
        presale_freeze_ends_at,
        to_wei(1, "ether")
    ]
    tx = {
        "from": team_multisig,
    }
    presale_fund_collector, hash = chain.provider.deploy_contract('PresaleFundCollector', deploy_args=args, deploy_transaction=tx)
    return presale_fund_collector
Beispiel #42
0
def test_invalid_proofs_not_enough_proofs():

    testdb = create_reward_test_blockchain_database()

    chain = TestnetChain(testdb,
                         private_keys[0].public_key.to_canonical_address(),
                         private_keys[0])
    min_time_between_blocks = chain.get_vm(
        timestamp=Timestamp(int(time.time()))).min_time_between_blocks
    tx_list = [[
        private_keys[1], private_keys[0],
        to_wei(1, 'ether'),
        int(int(time.time()) - min_time_between_blocks * 10)
    ]]

    add_transactions_to_blockchain_db(testdb, tx_list)

    chain = TestnetChain(testdb,
                         private_keys[0].public_key.to_canonical_address(),
                         private_keys[0])

    required_number_of_proofs_for_reward_type_2_proof = chain.get_consensus_db(
        timestamp=Timestamp(int(
            time.time()))).required_number_of_proofs_for_reward_type_2_proof

    node_staking_scores = []

    # First score/proof with timestamp far in future
    current_private_key = private_keys[1]
    node_staking_score = NodeStakingScore(
        recipient_node_wallet_address=private_keys[0].public_key.
        to_canonical_address(),
        score=int(1000000),
        since_block_number=0,
        timestamp=int(time.time()) - 60 * 10,
        head_hash_of_sender_chain=chain.chaindb.get_canonical_head_hash(
            current_private_key.public_key.to_canonical_address()),
        v=0,
        r=0,
        s=0,
    )
    signed_node_staking_score = node_staking_score.get_signed(
        current_private_key, TESTNET_NETWORK_ID)
    node_staking_scores.append(signed_node_staking_score)

    # Now we try to import the reward block with instance 0
    reward_chain = TestnetChain(
        testdb, private_keys[0].public_key.to_canonical_address(),
        private_keys[0])

    with pytest.raises(NotEnoughProofsOrStakeForRewardType2Proof):
        reward_chain.import_current_queue_block_with_reward(
            node_staking_scores)
def test_unhalt(web3, payment_forwarder, team_multisig, customer):
    """We can resume crowdsale."""

    value = to_wei("1.0", "ether")
    customer_id = int(uuid.uuid4().hex, 16) # Customer ids are 128-bit UUID v4

    payment_forwarder.transact({"from": team_multisig}).halt()
    payment_forwarder.transact({"from": team_multisig}).unhalt()

    assert payment_forwarder.call().customerCount() == 0
    payment_forwarder.transact({"value": value, "from": customer}).pay(customer_id, customer)
    assert payment_forwarder.call().customerCount() == 1
def presale_fund_collector(chain, presale_freeze_ends_at, team_multisig) -> Contract:
    """In actual ICO, the price is doubled (for testing purposes)."""
    args = [
        team_multisig,
        presale_freeze_ends_at,
        to_wei(1, "ether")
    ]
    tx = {
        "from": team_multisig,
    }
    presale_fund_collector, hash = chain.provider.deploy_contract('PresaleFundCollector', deploy_args=args, deploy_transaction=tx)
    return presale_fund_collector
Beispiel #45
0
def proxy_buyer(chain, uncapped_token, proxy_buyer_freeze_ends_at, team_multisig) -> Contract:
    """Token used in tests"""

    # Create finalizer contract
    args = [
        team_multisig,
        proxy_buyer_freeze_ends_at,
        1,  # 1 wei
        to_wei(100000, "ether"),
    ]
    contract, hash = chain.provider.deploy_contract('PreICOProxyBuyer', deploy_args=args)
    return contract
Beispiel #46
0
def test_pay_twice(web3, payment_forwarder, team_multisig, customer,
                   customer_2):
    """Pay for an address twice."""

    value = to_wei("1.0", "ether")
    customer_id = int(uuid.uuid4().hex, 16)  # Customer ids are 128-bit UUID v4
    event_filter = payment_forwarder.events.PaymentForwarded().createFilter(
        fromBlock=0)
    team_multisig_begin = web3.eth.getBalance(team_multisig)
    # We pay from two distinct addresses on behalf of the same customer
    checksumbyte = keccak_256(
        decode_hex(format(customer_id, 'x').zfill(32)) +
        decode_hex(format(customer[2:]).zfill(40))).digest()[:1]
    payment_forwarder.functions.pay(customer_id, customer,
                                    checksumbyte).transact({
                                        "value": value,
                                        "from": customer
                                    })

    # Here we make sure the first checkummed investment was successful
    events = event_filter.get_new_entries()
    assert len(events) == 1
    e = events[-1]
    assert e["args"]["source"] == customer
    assert e["args"]["amount"] == value
    assert e["args"]["customerId"] == customer_id
    assert e["args"]["benefactor"] == customer

    payment_forwarder.functions.payWithoutChecksum(customer_id,
                                                   customer).transact({
                                                       "value":
                                                       value,
                                                       "from":
                                                       customer_2
                                                   })
    team_multisig_end = web3.eth.getBalance(team_multisig)

    assert team_multisig_end - team_multisig_begin > 0
    assert payment_forwarder.functions.totalTransferred().call() == 2 * value
    assert payment_forwarder.functions.paymentsByCustomer(
        customer_id).call() == 2 * value
    assert payment_forwarder.functions.paymentsByBenefactor(
        customer).call() == 2 * value
    assert payment_forwarder.functions.customerCount().call() == 1

    # Check we properly generate an event
    events = event_filter.get_new_entries()
    assert len(events) == 1
    e = events[-1]
    assert e["args"]["source"] == customer_2
    assert e["args"]["amount"] == value
    assert e["args"]["customerId"] == customer_id
    assert e["args"]["benefactor"] == customer
Beispiel #47
0
def test_buy_early_whitelisted(chain: TestRPCChain, ico: Contract,
                               customer: str, preico_starts_at, team_multisig,
                               uncapped_token):
    """Whitelisted participants can buy earliy."""

    time_travel(chain, preico_starts_at - 1)
    assert ico.call().getState() == CrowdsaleState.PreFunding
    ico.transact({
        "from": team_multisig
    }).setEarlyParicipantWhitelist(customer, True)
    ico.transact({"from": customer, "value": to_wei(1, "ether")}).buy()
    assert uncapped_token.call().balanceOf(customer) > 0
def test_proxy_buy(chain, web3, customer, customer_2, team_multisig,
                   proxy_buyer, crowdsale, token):
    """Buy proxy as customer."""

    assert proxy_buyer.call().getState() == 1
    assert proxy_buyer.call().isPresale() == True

    #Change owner to customer_2, and back to team_multisig
    proxy_buyer.transact({"from": team_multisig}).transferOwnership(customer_2)
    proxy_buyer.transact({"from": customer_2}).transferOwnership(team_multisig)

    proxy_buyer.transact({
        "value": to_wei(10000, "ether"),
        "from": customer
    }).buy()
    proxy_buyer.transact({
        "value": to_wei(20000, "ether"),
        "from": customer_2
    }).buy()

    # Everything funder
    assert proxy_buyer.call().weiRaised() == to_wei(30000, "ether")
    assert web3.eth.getBalance(proxy_buyer.address) == to_wei(30000, "ether")
    assert proxy_buyer.call().balances(customer) == to_wei(10000, "ether")
    assert proxy_buyer.call().balances(customer_2) == to_wei(20000, "ether")

    # Change the owner again, in the middle, and run rest of the test as customer_2
    proxy_buyer.transact({"from": team_multisig}).transferOwnership(customer_2)

    # Move over
    assert crowdsale.call().getState() == CrowdsaleState.Funding
    proxy_buyer.transact({"from": customer_2}).setCrowdsale(crowdsale.address)
    assert proxy_buyer.call().crowdsale() == crowdsale.address
    proxy_buyer.transact({"from": customer}).buyForEverybody()
    assert web3.eth.getBalance(proxy_buyer.address) == 0

    # We got our tokens
    assert proxy_buyer.call().getState() == 2
    assert proxy_buyer.call().tokensBought() == 36000000
    assert proxy_buyer.call().getClaimAmount(customer) == 36000000 / 3 * 1
    assert proxy_buyer.call().getClaimLeft(customer) == 36000000 / 3 * 1
    assert proxy_buyer.call().getClaimAmount(customer_2) == 36000000 / 3 * 2
    assert proxy_buyer.call().getClaimLeft(customer_2) == 36000000 / 3 * 2

    # Tokens cannot be claimed before they are released
    time_travel(chain, crowdsale.call().endsAt() + 1)
    crowdsale.transact({"from": team_multisig}).finalize()
    assert token.call().released()

    # Claim tokens
    proxy_buyer.transact({"from": customer}).claimAll()
    proxy_buyer.transact({"from": customer_2}).claimAll()

    # Check investors got their tokens
    assert proxy_buyer.call().totalClaimed() == 36000000
    assert proxy_buyer.call().claimCount() == 2
    assert proxy_buyer.call().claimed(customer) == 36000000 / 3 * 1
    assert proxy_buyer.call().claimed(customer_2) == 36000000 / 3 * 2
    assert token.call().balanceOf(customer) == 36000000 / 3 * 1
    assert token.call().balanceOf(customer_2) == 36000000 / 3 * 2
def milestone_pricing(chain, presale_fund_collector, start_time, end_time,
                      team_multisig):

    week = 24 * 3600 * 7

    args = [
        [
            start_time + 0,
            to_wei("0.10", "ether"),
            start_time + week * 1,
            to_wei("0.12", "ether"),
            start_time + week * 2,
            to_wei("0.13", "ether"),
            start_time + week * 3,
            to_wei("0.14", "ether"),
            end_time,
            to_wei("0", "ether"),
        ],
    ]

    tx = {"gas": 3141592, "from": team_multisig}
    contract, hash = chain.provider.deploy_contract('MilestonePricing',
                                                    deploy_args=args,
                                                    deploy_transaction=tx)

    contract.functions.setPreicoAddress(presale_fund_collector.address,
                                        to_wei("0.05", "ether")).transact(
                                            {"from": team_multisig})
    return contract
Beispiel #50
0
def test_proxy_buy_move_funds_twice(chain, web3, customer, customer_2,
                                    team_multisig, proxy_buyer, crowdsale,
                                    token):
    """We move funds only once."""

    assert proxy_buyer.call().getState() == 1

    proxy_buyer.transact({
        "value": to_wei(10000, "ether"),
        "from": customer
    }).invest()
    proxy_buyer.transact({
        "value": to_wei(20000, "ether"),
        "from": customer_2
    }).invest()

    # Everything funder
    assert proxy_buyer.call().weiRaisedTotal() == to_wei(30000, "ether")
    assert web3.eth.getBalance(proxy_buyer.address) == to_wei(30000, "ether")
    assert proxy_buyer.call().balances(customer) == to_wei(10000, "ether")
    assert proxy_buyer.call().balances(customer_2) == to_wei(20000, "ether")

    # Move over
    assert crowdsale.call().getState() == CrowdsaleState.Funding
    proxy_buyer.transact({
        "from": team_multisig
    }).setCrowdsale(crowdsale.address)
    assert proxy_buyer.call().crowdsale() == crowdsale.address
    proxy_buyer.transact({"from": customer}).buyForEverybody()

    with pytest.raises(TransactionFailed):
        proxy_buyer.transact({"from": customer}).buyForEverybody()
Beispiel #51
0
def tranche_pricing(chain, presale_fund_collector, start_time, end_time,
                    team_multisig):

    week = 24 * 3600 * 7

    args = [
        [
            0,
            to_wei("0.10", "ether"),
            123,
            to_wei("0.12", "ether"),
            1234,
            to_wei("0.13", "ether"),
            12345,
            to_wei("0.14", "ether"),
            123456,
            to_wei("0", "ether"),
        ],
    ]

    tx = {"gas": 4000000, "from": team_multisig}
    contract, hash = chain.provider.deploy_contract('TokenTranchePricing',
                                                    deploy_args=args,
                                                    deploy_transaction=tx)

    contract.transact({
        "from": team_multisig
    }).setPreicoAddress(presale_fund_collector.address,
                        to_wei("0.05", "ether"))
    return contract
def test_kyc_participate_with_signed_address(chain, kyc_crowdsale, customer,
                                             customer_id, kyc_token,
                                             private_key, preico_starts_at,
                                             pricing, team_multisig):
    """Buy tokens with a proper KYC payload."""

    # Check KYC crowdsale is good to go
    time_travel(chain, kyc_crowdsale.call().startsAt() + 1)
    event_filter = kyc_crowdsale.events.Invested().createFilter(fromBlock=0)
    # Check the setup looks good
    assert kyc_crowdsale.functions.getState().call() == CrowdsaleState.Funding
    assert kyc_crowdsale.functions.isFinalizerSane().call()
    assert kyc_crowdsale.functions.isPricingSane().call()
    assert kyc_crowdsale.functions.beneficiary().call() == team_multisig
    assert kyc_token.functions.transferAgents(team_multisig).call() == True

    # Do a test buy for 1 ETH and check it is good token wise
    wei_value = to_wei(1, "ether")
    tokens_per_eth = pricing.functions.calculatePrice(wei_value, wei_value, 0,
                                                      customer, 18).call()
    assert tokens_per_eth == 10**18
    assert kyc_crowdsale.functions.getTokensLeft().call() >= tokens_per_eth
    assert kyc_token.functions.balanceOf(
        team_multisig).call() >= tokens_per_eth
    assert not kyc_crowdsale.functions.isBreakingCap(
        wei_value, tokens_per_eth, wei_value, tokens_per_eth).call()

    # KYC limits for this participant: 0...1 ETH
    kyc_payload = pack_kyc_pricing_dataframe(customer, customer_id, 0,
                                             1 * 10000, 1 * 10**18)
    signed_data = sign(kyc_payload, private_key)

    kyc_crowdsale.functions.buyWithKYCData(kyc_payload, signed_data["v"],
                                           signed_data["r_bytes"],
                                           signed_data["s_bytes"]).transact({
                                               "from":
                                               customer,
                                               "value":
                                               wei_value
                                           })
    # We got credited
    assert kyc_token.functions.balanceOf(customer).call() > 0
    assert kyc_crowdsale.functions.investedAmountOf(
        customer).call() == 1 * 10**18

    # We have tracked the investor id
    events = event_filter.get_all_entries()
    assert len(events) == 1
    e = events[0]
    assert e["args"]["investor"] == customer
    assert e["args"]["weiAmount"] == wei_value
    assert e["args"]["customerId"] == customer_id.int
def test_buy_one_investor(chain: TestRPCChain, web3: Web3, ico: Contract, uncapped_token: Contract, customer: str, preico_token_price, preico_starts_at, team_multisig):
    """Can buy when crowdsale is running."""

    original_balance = web3.eth.getBalance(team_multisig)
    wei_value = to_wei(1, "ether")
    buys_tokens = wei_value // preico_token_price
    assert buys_tokens > 0

    time_travel(chain, preico_starts_at + 1)
    assert ico.call().getState() == CrowdsaleState.Funding
    assert ico.call().investorCount() == 0
    assert ico.call().investedAmountOf(customer) == 0
    ico.transact({"from": customer, "value": wei_value}).buy()

    #
    # See everything was correctly credited
    #

    # Tokens on every account
    assert uncapped_token.call().balanceOf(customer) == buys_tokens
    assert uncapped_token.call().totalSupply() == buys_tokens
    assert ico.call().tokensSold() == buys_tokens
    assert ico.call().investorCount() == 1

    # Ether on every account
    assert ico.call().weiRaised() == wei_value
    assert ico.call().investedAmountOf(customer) == wei_value
    balance_diff = web3.eth.getBalance(team_multisig) - original_balance
    assert balance_diff == wei_value

    # Investors
    assert ico.call().investorCount() == 1

    #
    # Events
    #

    # Crowdsale
    events = ico.pastEvents("Invested").get()
    assert len(events) == 1
    e = events[0]
    assert e["args"]["investor"] == customer
    assert e["args"]["weiAmount"] == wei_value
    assert e["args"]["tokenAmount"] == buys_tokens

    # ERC-20
    events = uncapped_token.pastEvents("Transfer").get()
    assert len(events) == 1
    e = events[0]
    assert e["args"]["from"] == "0x0000000000000000000000000000000000000000"
    assert e["args"]["to"] == customer
    assert e["args"]["value"] == buys_tokens
Beispiel #54
0
def test_collect_policy_reward(testerchain, agent, agency, token_economics):
    _token_agent, staking_agent, policy_agent = agency
    deployer_address, beneficiary_address, author, ursula, *everybody_else = testerchain.client.accounts

    # Mock Powerup consumption (Beneficiary)
    testerchain.transacting_power = TransactingPower(
        password=INSECURE_DEVELOPMENT_PASSWORD, account=agent.beneficiary)
    testerchain.transacting_power.activate()

    _txhash = agent.deposit_as_staker(
        value=token_economics.minimum_allowed_locked,
        periods=token_economics.minimum_locked_periods)

    # User sets a worker in StakingEscrow via UserEscrow
    worker = testerchain.ursula_account(0)
    _receipt = agent.set_worker(worker_address=worker)

    testerchain.time_travel(periods=1)

    # Mock Powerup consumption (Alice)
    testerchain.transacting_power = TransactingPower(
        password=INSECURE_DEVELOPMENT_PASSWORD, account=author)
    testerchain.transacting_power.activate()

    _txhash = policy_agent.create_policy(
        policy_id=os.urandom(16),
        author_address=author,
        value=to_wei(1, 'ether'),
        periods=2,
        first_period_reward=0,
        node_addresses=[agent.contract_address])

    # Mock Powerup consumption (Beneficiary-Worker)
    testerchain.transacting_power = TransactingPower(
        password=INSECURE_DEVELOPMENT_PASSWORD, account=worker)
    testerchain.transacting_power.activate()

    _txhash = staking_agent.confirm_activity(worker_address=worker)
    testerchain.time_travel(periods=2)
    _txhash = staking_agent.confirm_activity(worker_address=worker)

    old_balance = testerchain.client.get_balance(account=agent.beneficiary)

    # Mock Powerup consumption (Beneficiary)
    testerchain.transacting_power = TransactingPower(
        password=INSECURE_DEVELOPMENT_PASSWORD, account=agent.beneficiary)
    testerchain.transacting_power.activate()

    txhash = agent.collect_policy_reward()
    assert txhash  # TODO
    assert testerchain.client.get_balance(
        account=agent.beneficiary) > old_balance
def tranche_pricing(chain, presale_fund_collector, start_time, end_time, team_multisig):

    week = 24*3600*7

    args = [
        [
            0, to_wei("0.10", "ether"),
            123, to_wei("0.12", "ether"),
            1234, to_wei("0.13", "ether"),
            12345, to_wei("0.14", "ether"),
            123456, to_wei("0", "ether"),
        ],
    ]

    tx = {
        "gas": 4000000,
        "from": team_multisig
    }
    contract, hash = chain.provider.deploy_contract('TokenTranchePricing', deploy_args=args, deploy_transaction=tx)

    contract.transact({"from": team_multisig}).setPreicoAddress(presale_fund_collector.address, to_wei("0.05", "ether"))
    return contract
def failed_ico(chain: TestRPCChain, web3, uncapped_flatprice: Contract, team_multisig, customer, customer_2, preico_starts_at, preico_ends_at, uncapped_flatprice_finalizer) -> Contract:
    """An ICO that did not reach a goal, but has participants.

    Both ``customer`` and ``customer_2`` had bought token.

    * customer: 50 ether
    * customer_2: 70 ether
    * total: 120 ether
    * minimum funding goal: 1200 ether

    """

    time_travel(chain, preico_starts_at + 1)

    uncapped_flatprice.transact({"from": customer, "value": to_wei(50, "ether")}).buy()
    uncapped_flatprice.transact({"from": customer_2, "value": to_wei(70, "ether")}).buy()

    assert not uncapped_flatprice.call().isMinimumGoalReached()

    # Make sure customer 1 has some token balance
    time_travel(chain, uncapped_flatprice.call().endsAt() + 1)
    return uncapped_flatprice
def test_milestone_calculate_preico_price(chain, milestone_pricing, start_time, presale_fund_collector):
    """Preico contributors get their special price."""

    # 1 week forward
    time_travel(chain, int((datetime.datetime(2017, 4, 22, 16, 0) - datetime.datetime(1970, 1, 1)).total_seconds()))

    # Pre-ico address always buys at the fixed price
    assert milestone_pricing.call().calculatePrice(
        to_wei("0.05", "ether"),
        0,
        0,
        presale_fund_collector.address,
        0
    ) == 1
def pricing_strategy(chain, start_time, end_time, team_multisig):

    week = 24*3600 * 7

    args = [
       to_wei(1, "ether")
    ]

    tx = {
        "from": team_multisig,
    }

    contract, hash = chain.provider.deploy_contract('FlatPricing', deploy_args=args, deploy_transaction=tx)
    return contract
def test_halt(chain: TestRPCChain, web3: Web3, ico: Contract, uncapped_token: Contract, customer: str, preico_token_price, preico_starts_at, team_multisig):
    """Cannot buy tokens during the emergency pause mode."""

    time_travel(chain, preico_starts_at + 1)
    wei_value = to_wei(1, "ether")

    ico.transact({"from": team_multisig}).halt()
    assert ico.call().halted()

    with pytest.raises(TransactionFailed):
        ico.transact({"from": customer, "value": wei_value}).buy()

    ico.transact({"from": team_multisig}).unhalt()
    assert not ico.call().halted()
    ico.transact({"from": customer, "value": wei_value}).buy()
def test_fractional_tranche_pricing(chain, presale_fund_collector, tranche_pricing, fractional_token, customer):
    """Tranche amount is calculated correctly for a token having fractions."""

    amount = tranche_pricing.call().calculatePrice(
        to_wei("0.512345678", "ether"),
        0,
        0,
        customer,
        fractional_token.call().decimals()
    )

    assert amount == 512345678
    d = decimalize_token_amount(fractional_token, amount)

    assert d == Decimal("5.12345678")

    # Make sure we get decimals right
    assert d.as_tuple() == Decimal("5.12345678").as_tuple()