def test_live_dai(accounts):

    me = accounts.at("0x7495B77b15fCb52fbb7BCB7380335d819ce4c04B", force=True)
    ygov = accounts.at("0xFEB4acf3df3cDEA7399794D0869ef76A6EfAff52", force=True)
    usdc_vault = Contract("0x5f18C75AbDAe578b483E5F43f12a39cF75b973a9", owner=ygov)
    sharerV4 = Contract("0xc491599b9a20c3a2f0a85697ee6d9434efa9f503")
    idleusdc = Contract("0x2E1ad896D3082C52A5AE7Af307131DE7a37a46a0", owner=ygov)
    stratFarmer = Contract("0xFc403fd9E7A916eC38437807704e92236cA1f7A5", owner=me)
    keeper = "0x7495B77b15fCb52fbb7BCB7380335d819ce4c04B"
    masterchef = "0xd7fa57069E4767ddE13aD7970A562c43f03f8365"
    reward = "0xf33121A2209609cAdc7349AcC9c40E41CE21c730"
    router = "0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D"
    pid = 2
    tx = stratFarmer.cloneStrategy(
        usdc_vault, me, sharerV4, keeper, masterchef, reward, router, pid, {"from": me}
    )
    strategy = StrategyLegacy.at(tx.events["Cloned"]["clone"])
    # Remove idleusdc to replace it with farmer strat
    usdc_vault.updateStrategyDebtRatio(idleusdc, 0)
    # Add strategy to vault
    usdc_vault.addStrategy(strategy, 500, 0, 1000)
    # Remove funds from idleusdc
    idleusdc.harvest()
    strategy.harvest({"from": me})
    # Get initial deposit
    initialDeposit = strategy.estimatedTotalAssets()
    for i in range(15):
        waitBlock = random.randint(10, 20)
        # print(f'\n----wait {waitBlock} blocks----')
        chain.mine(waitBlock)
        strategy.harvest({"from": me})
        chain.sleep(waitBlock * 13)

    strategy.harvest({"from": me})
    # check strategy made a profit
    assert strategy.estimatedTotalAssets() > initialDeposit

    # Assume farm is over,lets exit the farm
    # Set emergencyexit
    strategy.setEmergencyExit({"from": me})
    # Call harvest to get funds out
    strategy.harvest({"from": me})
    # Check if the funds got out successfully
    assert strategy.estimatedTotalAssets() == 0

    # Lets add back idleusdc farming to vault
    usdc_vault.updateStrategyDebtRatio(idleusdc, 500)
    # we should harvest and get back the tvl on idleusdc
    idleusdc.harvest({"from": ygov})
    assert idleusdc.estimatedTotalAssets() > 0
def test_unbond_reward(a, staking, deployer, alice, bob, worker, alpha):
    alice_stake_amt = 10**18
    bob_stake_amt = 3 * 10**18

    # setup stake
    staking.stake(alice_stake_amt, {'from': alice})
    staking.stake(bob_stake_amt, {'from': bob})

    ####################################################################################
    print('===============================================')
    print('1. unbond -> reward (before 7 days) -> withdraw. still get reward')

    staking.unbond(alice_stake_amt // 4, {'from': alice})

    reward_amt = 4 * 10**18

    staking.reward(reward_amt, {'from': worker})  # reward before 7 days

    chain.sleep(7 * 86400)

    prevAliceBal = alpha.balanceOf(alice)

    staking.withdraw({'from': alice})

    curAliceBal = alpha.balanceOf(alice)

    assert curAliceBal - prevAliceBal == alice_stake_amt // 4 * \
        2, 'incorrect withdraw amount (should get reward)'

    ####################################################################################
    print('===============================================')
    print('2. unbond -> reward (after 7 days) -> withdraw. still get reward')

    staking.unbond(alice_stake_amt // 4, {'from': alice})

    reward_amt = 75 * 10**17

    chain.sleep(7 * 86400 + 10)

    staking.reward(reward_amt, {'from': worker})  # reward after 7 days

    prevAliceBal = alpha.balanceOf(alice)

    staking.withdraw({'from': alice})

    curAliceBal = alpha.balanceOf(alice)

    assert curAliceBal - prevAliceBal == alice_stake_amt // 4 * \
        4, 'incorrect withdraw amount (should get reward)'
def test_strategy_rebalance(
    vault,
    strategy,
    pool,
    tokens,
    router,
    getPositions,
    gov,
    user,
    keeper,
    buy,
    big,
    PassiveStrategy,
):
    strategy = gov.deploy(PassiveStrategy, vault, 2400, 1200, 0, 0, 200000, 600, keeper)
    vault.setStrategy(strategy, {"from": gov})

    # Mint some liquidity
    vault.deposit(1e16, 1e18, 0, 0, user, {"from": user})
    strategy.rebalance({"from": keeper})

    # Do a swap to move the price
    qty = 1e16 * [100, 1][buy] * [1, 100][big]
    router.swap(pool, buy, qty, {"from": gov})

    # fast forward 1 day
    chain.sleep(86400)

    # Store totals
    total0, total1 = vault.getTotalAmounts()
    totalSupply = vault.totalSupply()

    # Rebalance
    tx = strategy.rebalance({"from": keeper})

    # Check ranges are set correctly
    tick = pool.slot0()[1]
    tickFloor = tick // 60 * 60
    assert vault.baseLower() == tickFloor - 2400
    assert vault.baseUpper() == tickFloor + 60 + 2400
    if buy:
        assert vault.limitLower() == tickFloor + 60
        assert vault.limitUpper() == tickFloor + 60 + 1200
    else:
        assert vault.limitLower() == tickFloor - 1200
        assert vault.limitUpper() == tickFloor

    assert strategy.lastTimestamp() == tx.timestamp
    assert strategy.lastTick() == tick
Esempio n. 4
0
def test_finalize_batch_auction_successful(batch_auction, batch_auction_token):

    token_buyer = accounts[2]
    eth_to_transfer = 100 * TENPOW18

    with reverts("BatchAuction: Auction has not finished yet"):
        batch_auction.finalize({"from": accounts[0]})

    with reverts("BatchAuction: Value must be higher than 0"):
        batch_auction.commitEth(token_buyer, True, {
            "from": token_buyer,
            "value": 0
        })

    with reverts("BatchAuction: Sender must be operator"):
        batch_auction.finalize({"from": accounts[9]})

    with reverts("BatchAuction: Payment currency is not a token"):
        batch_auction.commitTokens(eth_to_transfer, True,
                                   {"from": token_buyer})

    batch_auction.commitEth(token_buyer, True, {
        "from": token_buyer,
        "value": eth_to_transfer
    })

    finalized = batch_auction.marketStatus()[3]

    assert finalized == False
    assert batch_auction.auctionSuccessful({"from": accounts[0]}) == True

    chain.sleep(AUCTION_TIME + 100)
    chain.mine()
    batch_auction.finalize({"from": accounts[0]})

    with reverts("BatchAuction: Auction has already finalized"):
        batch_auction.finalize({"from": accounts[0]})

    batch_token_before_withdraw = batch_auction_token.balanceOf(token_buyer)

    batch_auction.withdrawTokens({"from": token_buyer})

    batch_token_after_withdraw = batch_auction_token.balanceOf(token_buyer)
    ######### Total auction tokens as there is only one buy #########
    assert batch_token_after_withdraw - batch_token_before_withdraw == AUCTION_TOKENS

    assert batch_auction.tokensClaimable(accounts[8]) == 0
    with reverts("BatchAuction: No tokens to claim"):
        batch_auction.withdrawTokens(token_buyer, {"from": token_buyer})
Esempio n. 5
0
File: conftest.py Progetto: d9k/et
    def deploy(
        eth_to_ldo_rate,
        vesting_cliff_delay,
        vesting_end_delay,
        offer_expiration_delay,
        ldo_purchasers,
        allocations_total
    ):
        (executor, vote_id) = deploy_and_start_dao_vote(
            {'from': ldo_holder},
            eth_to_ldo_rate=eth_to_ldo_rate,
            vesting_cliff_delay=vesting_cliff_delay,
            vesting_end_delay=vesting_end_delay,
            offer_expiration_delay=offer_expiration_delay,
            ldo_purchasers=ldo_purchasers,
            allocations_total=allocations_total
        )

        print(f'vote id: {vote_id}')

        # together these accounts hold 15% of LDO total supply
        ldo_holders = [
            '0x3e40d73eb977dc6a537af587d48316fee66e9c8c',
            '0xb8d83908aab38a159f3da47a59d84db8e1838712',
            '0xa2dfc431297aee387c05beef507e5335e684fbcd'
        ]

        for holder_addr in ldo_holders:
            print('voting from acct:', holder_addr)
            accounts[0].transfer(holder_addr, '0.1 ether')
            account = accounts.at(holder_addr, force=True)
            dao_voting.vote(vote_id, True, False, {'from': account})

        # wait for the vote to end
        chain.sleep(3 * 60 * 60 * 24)
        chain.mine()

        assert dao_voting.canExecute(vote_id)
        dao_voting.executeVote(vote_id, {'from': accounts[0]})

        print(f'vote executed')

        total_ldo_assignment = sum([ p[1] for p in ldo_purchasers ])
        assert ldo_token.balanceOf(executor) == total_ldo_assignment

        ldo_assign_role = dao_token_manager.ASSIGN_ROLE()
        assert dao_acl.hasPermission(executor, dao_token_manager, ldo_assign_role)

        return executor
Esempio n. 6
0
def test_dutch_auction_claim_not_enough(dutch_auction):
    token_buyer = accounts[2]
    eth_to_transfer = 0.01 * TENPOW18

    dutch_auction.commitEth(token_buyer, True, {
        "from": token_buyer,
        "value": eth_to_transfer
    })
    chain.sleep(AUCTION_TIME + 100)
    chain.mine()
    dutch_auction.finalize({"from": accounts[0]})
    dutch_auction.withdrawTokens({'from': token_buyer})

    with reverts("DutchAuction: auction already finalized"):
        dutch_auction.finalize({"from": accounts[0]})
Esempio n. 7
0
def test_frames_crowdsale_purchaseEth_ended(frames_crowdsale, frame_token):
    tokenOwner = accounts[4]
    frames = 2
    chain.sleep(60000)
    (frame_eth, live) = frames_crowdsale.frameEthBonus(tokenOwner,
                                                       {'from': tokenOwner})
    eth_to_transfer = frames * frame_eth
    with reverts("Sale ended"):
        tx = frames_crowdsale.buyFramesEth({
            'from': tokenOwner,
            'value': eth_to_transfer
        })

    with reverts("Sale ended"):
        tx = tokenOwner.transfer(frames_crowdsale, eth_to_transfer)
Esempio n. 8
0
def test_crowdsale_withdraw_tokens_goal_not_reached(crowdsale, mintable_token, buy_token_multiple_times_goal_not_reached):
    chain.sleep(CROWDSALE_TIME)
    claimer1 = accounts[1]
    claimer2 = accounts[2]
    
    claimer1_eth_balance_before_withdraw = claimer1.balance()
    claimer1_commitments_before_withdraw = crowdsale.commitments(claimer1)
    claimer2_commitments_before_withdraw = crowdsale.commitments(claimer2)
    claimer2_eth_balance_before_withdraw = claimer2.balance()
    chain.sleep(CROWDSALE_TIME)
    crowdsale.withdrawTokens(claimer1, {"from": claimer1})
    crowdsale.withdrawTokens(claimer2, {"from": claimer1})
    assert crowdsale.commitments(claimer1) == 0
    assert claimer1_eth_balance_before_withdraw + claimer1_commitments_before_withdraw == claimer1.balance()
    assert claimer2_eth_balance_before_withdraw + claimer2_commitments_before_withdraw == claimer2.balance()
Esempio n. 9
0
def test_depositTokensAfterContractExpired(pool_liquidity_02, token_1, token_2):
    chain.sleep(POOL_LAUNCH_DEADLINE + POOL_LAUNCH_WINDOW)

    token_1.mint(accounts[0], TOKENS_TO_MINT, {'from': accounts[0]})

    deposit_amount = TOKENS_TO_MINT
    token_1.approve(pool_liquidity_02, deposit_amount, {"from": accounts[0]})
    with reverts("PoolLiquidity02: Contract has expired"):    
        pool_liquidity_02.depositToken1(deposit_amount, {"from": accounts[0]})

    token_2.mint(accounts[0], TOKENS_TO_MINT, {'from': accounts[0]})

    token_2.approve(pool_liquidity_02, deposit_amount, {"from": accounts[0]})
    with reverts("PoolLiquidity02: Contract has expired"):    
        pool_liquidity_02.depositToken2(deposit_amount, {"from": accounts[0]})
def test_rewards_genesis_staking(staked_nft, staking_genesis):

    chain.sleep(10000)

    print("stakers struct[balance]=", staking_genesis.stakers(accounts[2])[0])
    print("stakers struct[lastRewardPoints]=",
          staking_genesis.stakers(accounts[2])[1])
    print("stakers struct[lastRewardEarned]=",
          staking_genesis.stakers(accounts[2])[2])
    print("stakers struct[rewardsReleased]=",
          staking_genesis.stakers(accounts[2])[3])
    rewardsOwing = staking_genesis.rewardsOwing(accounts[2])

    print("rewardsOwing--->", rewardsOwing)
    print("total reward points -->", staking_genesis.rewardsPerTokenPoints())
Esempio n. 11
0
def test_withdraw_after_expire(alice, bob, worker, alpha, staking):
    alice_stake_amt = 10**18
    bob_stake_amt = 3 * 10**18

    staking.stake(alice_stake_amt, {'from': alice})
    staking.stake(bob_stake_amt, {'from': bob})

    prev_status, prev_share, prev_unbondtime, prev_unbondshare = staking.users(
        alice)
    staking.unbond(prev_share, {'from': alice})

    chain.sleep(8 * 86400 + 1)

    with brownie.reverts('withdraw/already-expired'):
        staking.withdraw({'from': alice})
Esempio n. 12
0
def test_apply_new_fee(FeeGovernorContract, FeeGovernorProxyContract,
                       accounts):

    assert FeeGovernorContract.future_admin_fee() == 2e8

    with reverts():
        tx1 = FeeGovernorContract.apply_new_admin_fee({'from': accounts[0]})

    chain.sleep(259200)

    tx2 = FeeGovernorContract.apply_new_admin_fee({'from': accounts[0]})

    assert tx2.events['newAdminFeeApplied']['new_admin_fee'] == 2e8
    assert FeeGovernorContract.admin_fee() == 2e8
    assert FeeGovernorProxyContract.get_admin_fee() == 2e8
def test_borrow_token_transfer_increments_yshares(
    vault, yvault, strategy, token, token_whale, borrow_token, borrow_whale, gov
):
    token.approve(vault, 2 ** 256 - 1, {"from": token_whale})
    vault.deposit(500_000 * (10 ** token.decimals()), {"from": token_whale})

    chain.sleep(1)
    strategy.harvest({"from": gov})
    initialBalance = yvault.balanceOf(strategy)

    amount = 1_000 * (10 ** borrow_token.decimals())
    borrow_token.transfer(strategy, amount, {"from": borrow_whale})

    strategy.harvest({"from": gov})
    assert yvault.balanceOf(strategy) > initialBalance
Esempio n. 14
0
def test_exit_no_penalty(eps, eps_staker, alice):
    initial = eps.balanceOf(alice)
    eps_staker.stake(10000, False, {'from': alice})
    tx = eps_staker.mint(alice, 30000, {'from': alice})
    locked_until = (tx.timestamp // 604800 + 13) * 604800
    chain.sleep(604800)
    chain.mine()
    eps_staker.mint(alice, 60000, {'from': alice})

    chain.mine(timestamp=locked_until + 604801)
    eps_staker.exit({'from': alice})
    assert eps.balanceOf(alice) == initial + 90000
    assert eps_staker.earnedBalances(alice) == [0, []]
    assert eps_staker.unlockedBalance(alice) == 0
    assert eps_staker.totalSupply() == 0
def test_live_dai(accounts):

    me = accounts.at("0x7495B77b15fCb52fbb7BCB7380335d819ce4c04B", force=True)
    ygov = accounts.at("0xFEB4acf3df3cDEA7399794D0869ef76A6EfAff52", force=True)
    dai_vault = Contract("0x19D3364A399d251E894aC732651be8B0E4e85001", owner=ygov)
    sharerV4 = Contract("0xc491599b9a20c3a2f0a85697ee6d9434efa9f503")
    iblevcomp = Contract("0x77b7CD137Dd9d94e7056f78308D7F65D2Ce68910", owner=ygov)
    keeper = "0x7495B77b15fCb52fbb7BCB7380335d819ce4c04B"
    masterchef = "0xd7fa57069E4767ddE13aD7970A562c43f03f8365"
    reward = "0xf33121A2209609cAdc7349AcC9c40E41CE21c730"
    router = "0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D"
    pid = 3
    strategy = StrategyLegacy.deploy(
        dai_vault, masterchef, reward, router, pid, {"from": me},
    )
    # Remove iblevcomp to replace it with farmer strat
    dai_vault.updateStrategyDebtRatio(iblevcomp, 0)
    # Add strategy to vault
    dai_vault.addStrategy(strategy, 5.5 * 100, 0, 1000)
    # Remove funds from iblevcomp
    iblevcomp.harvest()
    strategy.harvest({"from": me})
    # Get initial deposit
    initialDeposit = strategy.estimatedTotalAssets()
    for i in range(15):
        waitBlock = random.randint(10, 50)
        # print(f'\n----wait {waitBlock} blocks----')
        chain.mine(waitBlock)
        strategy.harvest({"from": me})
        chain.sleep(waitBlock * 13)

    strategy.harvest()
    # check strategy made a profit
    assert strategy.estimatedTotalAssets() > initialDeposit

    # Assume farm is over,lets exit the farm
    # Set emergencyexit
    strategy.setEmergencyExit({"from": me})
    # Call harvest to get funds out
    strategy.harvest({"from": me})
    # Check if the funds got out successfully
    assert strategy.estimatedTotalAssets() == 0

    # Lets add back iblev farming to vault
    dai_vault.updateStrategyDebtRatio(iblevcomp, 5.5 * 100)
    # we should harvest and get back the tvl on iblev
    iblevcomp.harvest({"from": ygov})
    assert iblevcomp.estimatedTotalAssets() > 0
def test_one_farm(accounts, creatures, land, farm):
    logging.info('1 farming for account {}-{}'.format(0, accounts[0]))
    my_crtrs = creatures.getUsersTokens(accounts[0])
    logging.info('my_crtrs={}'.format(my_crtrs))
    my_lands = land.getUsersTokens(accounts[0])
    logging.info('my_lands={}'.format(my_lands))
    res = creatures.getTypeAndRarity(my_crtrs[0])
    logging.info(
        '!!!!!!!!!!!!!!1 creatures.getTypeAndRarity({}) {}, uri={}'.format(
            my_crtrs[0], res, creatures.tokenURI(my_crtrs[0])))

    for i in my_crtrs:
        is_enable_f = farm.isFarmingAllowedForCreature(i)
        logging.info(
            '***************** farm.isFarmingAllowedForCreature({})= {}'.
            format(i, is_enable_f))
        assert is_enable_f == True
    allowed_for_f = farm.getFarmingAllowedCreatures(accounts[0])
    logging.info(allowed_for_f)
    assert set(my_crtrs) == set(allowed_for_f)

    # logging.info('amulets for type ({}) {}, uri={}'.format(
    #     res[0],
    #     farm.getCreatureAmulets(0)
    # ))

    tx = farm.farmDeploy(my_crtrs[0], my_lands[0], {'from': accounts[0]})
    logging.info(tx.events)
    logging.info(
        'Time machine running.....+168 hours...................................'
    )
    chain.sleep(3600 * 168)
    chain.mine()
    logging.info('Chain time {}'.format(chain.time()))
    logging.info(land.ownerOf(my_lands[0]))
    logging.info(creatures.ownerOf(my_crtrs[0]))
    assert land.ownerOf(my_lands[0]) == farm.address
    assert creatures.ownerOf(my_crtrs[0]) == farm.address
    my_eggs = farm.getUsersTokens(accounts[0])
    logging.info('my_eggs: {}'.format(my_eggs))
    logging.info('egg={}, farmingRec= {}'.format(
        my_eggs[0], farm.getFarmingById(my_eggs[0])))
    tx = farm.harvest(my_eggs[0], {'from': accounts[0]})
    logging.info(tx.events['Harvest'])
    logging.info(tx.events)
    logging.info('After farming egg={}, farmingRec= {}'.format(
        my_eggs[0], farm.getFarmingById(my_eggs[0])))
    assert creatures.ownerOf(farm.getFarmingById(my_eggs[0])[0]) == accounts[0]
def test_deploy(
    yvDAI,
    yvSUSD,
    strategy,
    gov,
    dai,
    dai_whale,
    susd,
    susd_whale,
    vdsusd,
    RELATIVE_APPROX,
):
    dai.approve(yvDAI, 2**256 - 1, {"from": dai_whale})
    yvDAI.deposit(Wei("100_000 ether"), {"from": dai_whale})

    # TODO: can we remove this sushi woes?
    susdEth = Contract("0xF1F85b2C54a2bD284B1cf4141D64fD171Bd85539")
    susdEth.sync({"from": gov})
    daiEth = Contract("0xC3D03e4F041Fd4cD388c549Ee2A29a9E5075882f")
    daiEth.sync({"from": gov})

    strategy.harvest({"from": gov})

    # After first investment sleep for a month
    chain.sleep(60 * 60 * 24 * 30)
    chain.mine(1)

    # Send some profit to yvault
    susd.transfer(
        yvSUSD,
        yvDAI.strategies(strategy).dict()["totalDebt"] * 0.05,
        {"from": susd_whale},
    )

    yvDAI.revokeStrategy(strategy, {"from": gov})
    tx = strategy.harvest({"from": gov})

    assert tx.events["Harvested"]["profit"] > 0
    assert tx.events["Harvested"]["debtPayment"] >= Wei("10 ether")

    data = yvDAI.strategies(strategy).dict()
    assert data["totalLoss"] == 0
    assert data["totalDebt"] == 0
    assert data["debtRatio"] == 0
    assert pytest.approx(yvSUSD.balanceOf(strategy) / 1e18,
                         rel=RELATIVE_APPROX) == 0
    assert pytest.approx(vdsusd.balanceOf(strategy) / 1e18,
                         rel=RELATIVE_APPROX) == 0
Esempio n. 18
0
def hyperbolic_auction(DutchSwapHyperbolic, auction_token):
    
    startDate = chain.time() +10
    endDate = startDate + AUCTION_TIME
    wallet = accounts[1]
    funder = accounts[0]

    hyperbolic_auction = DutchSwapHyperbolic.deploy({'from': accounts[0]})
    tx = auction_token.approve(hyperbolic_auction, AUCTION_TOKENS, {'from':funder})

    hyperbolic_auction.initDutchAuction(funder, auction_token, AUCTION_TOKENS, startDate, endDate,ETH_ADDRESS, AUCTION_RESERVE, wallet, {"from": accounts[0]})
    # assert hyperbolic_auction.clearingPrice( {'from': accounts[0]}) == AUCTION_START_PRICE

    # Move the chain to the moment the auction begins
    chain.sleep(10)
    return hyperbolic_auction
Esempio n. 19
0
 def la_lambda():
   (executor, vote_id) = deploy_and_start_easy_track_vote(
       {'from': fx_ballot_maker}, # TODO: ACL
       ballot_maker=fx_ballot_maker,
       ballot_time=fx_ballot_time,
       objections_threshold=fx_objections_threshold,
       stub=fx_stub
   )
   print(f'vote id: {vote_id}')
   # TODO: определить аккаунты, которые будут голосовать
   # Wait for the vote to end
   chain.sleep(3 * 60 * 60 * 24)
   chain.mine()
   print(f'vote executed')
   # Ret
   return executor
Esempio n. 20
0
def test_recover_unsold_tokens_should_transfer_all_tokens_after_exparation(
        executor, dao_agent, ldo_token):
    chain = Chain()

    expiration_delay = executor.offer_expires_at() - chain.time()
    chain.sleep(expiration_delay + 3600)
    chain.mine()

    executor_balance = ldo_token.balanceOf(executor)
    dao_agent_balance = ldo_token.balanceOf(dao_agent)

    executor.recover_unsold_tokens()

    assert ldo_token.balanceOf(executor) == 0
    assert ldo_token.balanceOf(
        dao_agent) == dao_agent_balance + executor_balance
def test_revoke(gov, vault, strategy, token, whale, amount):
    scale = 10**token.decimals()
    # Deposit to the vault
    token.approve(vault, 2**256 - 1, {"from": whale})
    vault.deposit(amount, {"from": whale})
    # assert token.balanceOf(vault.address) == amount
    strategy.harvest({"from": gov})

    chain.sleep(86400)
    chain.mine(1)

    vault.revokeStrategy(strategy, {"from": gov})
    strategy.harvest({"from": gov})

    assert vault.totalDebt() == 0
    assert vault.totalAssets() == token.balanceOf(vault)
Esempio n. 22
0
def frames_crowdsale(DreamFramesCrowdsale, frame_token, price_feed,
                     bonus_list):
    wallet = accounts[9]
    startDate = chain.time() + 10
    endDate = startDate + 50000

    frames_crowdsale = DreamFramesCrowdsale.deploy({"from": accounts[0]})
    frames_crowdsale.init(frame_token, price_feed, wallet, startDate, endDate,
                          PRODUCER_PCT, FRAME_USD, BONUS, BONUS_ON_LIST,
                          HARDCAP_USD, SOFTCAP_USD, {"from": accounts[0]})
    tx = frames_crowdsale.addOperator(accounts[1], {"from": accounts[0]})
    assert 'OperatorAdded' in tx.events
    tx = frame_token.setMinter(frames_crowdsale, {"from": accounts[0]})
    tx = frames_crowdsale.setBonusList(bonus_list, {"from": accounts[0]})
    chain.sleep(15)
    return frames_crowdsale
Esempio n. 23
0
def test_simulation_after_upgrade_crv_setts(settID):
    # Upgrade crv setts kkk
    badger = connect_badger(badger_config.prod_json)
    txFilename = queue_upgrade_crv_sett(badger, settID)
    # Sleep 2 days to pass timelock delay period.
    chain.sleep(2*days(2))
    badger.governance_execute_transaction(txFilename)
    sett = interface.ISett("0x6dEf55d2e18486B9dDfaA075bc4e4EE0B28c1545")

    snap = SnapshotManager(badger, settID)
    simulation = SimulationManager(badger, snap, settID)

    simulation.provision()
    # Randomize 30 actions.
    simulation.randomize(30)
    simulation.run()
    def invariant_relative_gauge_weight(self):
        """
        Validate the relative gauge weights.
        """
        chain.sleep(WEEK)

        total_weight = sum(
            self._gauge_weight(idx) * weight
            for idx, weight in enumerate(self.type_weights))

        for gauge, weight, idx in [(i["contract"], i["weight"], i["type"])
                                   for i in self.gauges]:
            self.controller.checkpoint_gauge(gauge)
            expected = 10**18 * self.type_weights[idx] * weight // total_weight

            assert self.controller.gauge_relative_weight(gauge) == expected
def test_revoke_strategy_from_strategy(token, vault, strategy, gov,
                                       token_whale, RELATIVE_APPROX):
    amount = 50_000 * (10**token.decimals())
    # Deposit to the vault and harvest
    token.approve(vault.address, amount, {"from": token_whale})
    vault.deposit(amount, {"from": token_whale})

    chain.sleep(1)
    strategy.harvest({"from": gov})
    assert pytest.approx(strategy.estimatedTotalAssets(),
                         rel=RELATIVE_APPROX) == amount

    strategy.setEmergencyExit({"from": gov})
    strategy.harvest({"from": gov})
    assert pytest.approx(token.balanceOf(vault.address),
                         rel=RELATIVE_APPROX) == amount
Esempio n. 26
0
def test_emergency_exit(token, vault, strategy, token_whale, strategist,
                        RELATIVE_APPROX):
    # Deposit to the vault
    token.approve(vault, 2**256 - 1, {"from": token_whale})
    vault.deposit(500_000 * (10**token.decimals()), {"from": token_whale})
    amount = 500_000 * (10**token.decimals())

    chain.sleep(1)
    strategy.harvest({"from": strategist})
    assert pytest.approx(strategy.estimatedTotalAssets(),
                         rel=RELATIVE_APPROX) == amount

    # set emergency and exit
    strategy.setEmergencyExit({"from": strategist})
    strategy.harvest({"from": strategist})
    assert strategy.estimatedTotalAssets() < amount
Esempio n. 27
0
 def create(fee):
     tokenA = create_token("TA", "TokenA")
     tokenB = create_token("TB", "TokenB")
     for u in users:
         tokenA.mint(u, 1e50)
         tokenB.mint(u, 1e50)
     tx = uni_factory.createPool(tokenA, tokenB, fee, {"from": accounts[0]})
     pool = UniswapV3Core.interface.IUniswapV3Pool(tx.new_contracts[0])
     pool.initialize(10**(1 / 2) * (1 << 96), {"from": accounts[0]})
     pool.increaseObservationCardinalityNext(20, {"from": accounts[0]})
     spacing = pool.tickSpacing()
     tick = 887271 // spacing * spacing
     mock_router.mintAmounts(pool, 1e18, 1e18, -tick, tick)
     chain.sleep(20000)
     return Pool(pool, TestERC20.at(pool.token0()),
                 TestERC20.at(pool.token1()), fee)
def test_scalability(accounts, gauges, gauge_controller, mock_lp_token, minter,
                     st_actions):

    # handle actions is a deque, so we can rotate it to ensure each gauge has multiple actions
    st_actions = deque(st_actions)

    # convert accounts to a deque so we can rotate it to evenly spread actions across accounts
    action_accounts = deque(accounts)

    # for voting we use a seperate deque that only rotates once per test round
    # this way accounts never vote too often
    last_voted = deque(accounts)

    balances = {i: [0] * len(accounts) for i in gauges}

    for i in range(TEST_ROUNDS):
        print(f"Round {i}")
        # rotate voting account and actions
        last_voted.rotate()
        st_actions.rotate()

        # sleep just over a day between each round
        chain.sleep(86401)

        for gauge, action in zip(gauges, st_actions):
            action = ActionEnum.get_action(action)

            action_accounts.rotate()
            acct = action_accounts[0]
            idx = list(accounts).index(acct)

            if action == ActionEnum.vote:
                gauge_controller.vote_for_gauge_weights(
                    gauge, 100, {'from': last_voted[0]})

            elif action == ActionEnum.deposit:
                mock_lp_token.approve(gauge, 10**17, {'from': acct})
                gauge.deposit(10**17, {'from': acct})
                balances[gauge][idx] += 10**17

            elif action == ActionEnum.withdraw:
                amount = balances[gauge][idx]
                gauge.withdraw(amount, {'from': acct})
                balances[gauge][idx] = 0

            elif action == ActionEnum.mint:
                minter.mint(gauge, {'from': acct})
Esempio n. 29
0
def test_simulation_after_upgrade_crv_setts(settID):
    # Upgrade crv strategy
    badger = connect_badger(badger_config.prod_json)
    """
    TODO Get the Implementation before upgrade
    """

    txFilename = queue_upgrade_crv_strat(badger, settID)
    # Sleep 2 days to pass timelock delay period.
    chain.sleep(2 * days(2))
    badger.governance_execute_transaction(txFilename)
    """
    TODO assert tht implementation has changed
    """

    ## Object representing the sett we want and the mode we're in
    thisSettConfig = {"id": settID, "mode": "test"}

    ## Get badger so we can get info in sett and strats
    badger = badger_single_sett(thisSettConfig)

    ## We now have the want, we can mint some
    deployer = badger.deployer

    ## Mints token for us
    distribute_from_whales(deployer)

    snap = SnapshotManager(badger, settID)
    simulation = SimulationManager(badger, snap, settID)

    simulation.provision()
    # Randomize 30 actions.
    simulation.randomize(30)
    simulation.run()

    assert_deposit_withdraw_single_user_flow(thisSettConfig)
    assert_single_user_harvest_flow(thisSettConfig)
    assert_migrate_single_user(thisSettConfig)
    assert_withdraw_other(thisSettConfig)
    assert_single_user_harvest_flow_remove_fees(thisSettConfig)

    assert_strategy_action_permissions(thisSettConfig)
    assert_strategy_config_permissions(thisSettConfig)
    assert_strategy_pausing_permissions(thisSettConfig)
    assert_sett_pausing_permissions(thisSettConfig)
    assert_sett_config_permissions(thisSettConfig)
    assert_controller_permissions(thisSettConfig)
Esempio n. 30
0
def test_finalize_abi_batch_auction(init_market_abi, batch_auction_init,
                                    batch_auction_token_2):
    token_buyer = accounts[2]
    eth_to_transfer = 100 * TENPOW18
    batch_token_before_withdraw = batch_auction_token_2.balanceOf(token_buyer)
    #  assert batch_auction_init.operator() == accounts[0]

    with reverts("BatchAuction: Auction has not finished yet"):
        batch_auction_init.finalize({"from": accounts[0]})

    with reverts("BatchAuction: Value must be higher than 0"):
        batch_auction_init.commitEth(token_buyer, True, {
            "from": token_buyer,
            "value": 0
        })

    with reverts("BatchAuction: Sender must be operator"):
        batch_auction_init.finalize({"from": accounts[9]})

    with reverts("BatchAuction: Payment currency is not a token"):
        batch_auction_init.commitTokens(eth_to_transfer, True,
                                        {"from": token_buyer})

    # token_buyer.transfer(batch_auction_init, eth_to_transfer)
    tx = batch_auction_init.commitEth(token_buyer, True, {
        "from": token_buyer,
        "value": eth_to_transfer
    })

    finalized = batch_auction_init.marketStatus()[3]

    assert finalized == False

    assert batch_auction_init.auctionSuccessful({"from": accounts[0]}) == True

    chain.sleep(AUCTION_TIME + 100)
    chain.mine()
    batch_auction_init.finalize({"from": accounts[0]})

    with reverts("BatchAuction: Auction has already finalized"):
        batch_auction_init.finalize({"from": accounts[0]})

    batch_auction_init.withdrawTokens({"from": token_buyer})

    batch_token_after_withdraw = batch_auction_token_2.balanceOf(token_buyer)
    ######### Total auction tokens as there is only one buy #########
    assert batch_token_after_withdraw - batch_token_before_withdraw == AUCTION_TOKENS