Beispiel #1
0
def test_migrate_lpstrat(
    currencyLP,
    AlchemixETHStrategy,
    strategylp,
    chain,
    vaultlp,
    whaleLP,
    gov,
    strategist,
    interface,
):
    debt_ratio = 10_000
    vaultlp.addStrategy(strategylp, debt_ratio, 0, 2 ** 256 - 1, 1_000, {"from": gov})

    currencyLP.approve(vaultlp, 2 ** 256 - 1, {"from": whaleLP})
    vaultlp.deposit(Wei("100 ether"), {"from": whaleLP})
    strategylp.harvest({"from": strategist})

    chain.sleep(2592000)
    chain.mine(1)

    strategylp.harvest({"from": strategist})
    totalasset_beforemig = strategylp.estimatedTotalAssets()
    assert totalasset_beforemig > 0

    strategy2 = strategist.deploy(AlchemixETHStrategy, vaultlp)
    vaultlp.migrateStrategy(strategylp, strategy2, {"from": gov})
    # Check that we got all the funds on migration
    assert strategy2.estimatedTotalAssets() >= totalasset_beforemig
Beispiel #2
0
def test_erc20_auction_twoPurchases(erc20_auction, payment_token):

    token_buyer_a = accounts[2]
    token_buyer_b = accounts[3]
    assert erc20_auction.tokensClaimable(token_buyer_a,
                                         {'from': accounts[0]}) == 0
    assert erc20_auction.tokensClaimable(token_buyer_b,
                                         {'from': accounts[0]}) == 0

    tokens_to_transfer = 20 * TENPOW18
    tx = payment_token.transfer(token_buyer_a, tokens_to_transfer,
                                {'from': accounts[0]})
    tx = payment_token.approve(erc20_auction, tokens_to_transfer,
                               {'from': token_buyer_a})
    tx = erc20_auction.commitTokens(tokens_to_transfer,
                                    {'from': token_buyer_a})
    assert 'AddedCommitment' in tx.events
    tokens_to_transfer = 4 * tokens_to_transfer
    tx = payment_token.transfer(token_buyer_b, tokens_to_transfer,
                                {'from': accounts[0]})
    tx = payment_token.approve(erc20_auction, tokens_to_transfer,
                               {'from': token_buyer_b})
    tx = erc20_auction.commitTokens(tokens_to_transfer,
                                    {'from': token_buyer_b})
    assert 'AddedCommitment' in tx.events
    chain.sleep(AUCTION_TIME + 100)
    chain.mine()
    # AG need to double check these numbers
    assert erc20_auction.tokensClaimable(
        token_buyer_a, {'from': accounts[0]}) == AUCTION_TOKENS / 5
    assert erc20_auction.tokensClaimable(
        token_buyer_b, {'from': accounts[0]}) == 4 * AUCTION_TOKENS / 5
    def rule_swap_into_existing(self, st_acct, st_token, st_amount, st_idx):
        """
        Increase the underyling balance of an existing NFT via a cross-asset swap.
        """
        if self.active_token_ids.get(st_acct):
            idx = int(st_idx * len(self.active_token_ids[st_acct]))
            token_id = self.active_token_ids[st_acct][idx]
        else:
            token_ids = self._all_token_ids()
            idx = int(st_idx * len(token_ids))
            token_id = token_ids[idx]

        synth = Settler.at(hex(token_id % 2**160)).synth()
        idx = int(st_idx * len(TOKENS[st_token]))
        initial = TOKENS[st_token][idx]
        amount = self._mint(st_acct, initial, st_amount)

        if self.active_token_ids.get(st_acct) and TOKENS[st_token][0] != synth:
            self.swap.swap_into_synth(initial, synth, amount, 0, st_acct,
                                      token_id, {"from": st_acct})
            chain.mine(timedelta=600)
        else:
            with brownie.reverts():
                self.swap.swap_into_synth(initial, synth, amount, 0, st_acct,
                                          token_id, {"from": st_acct})
def test_basic(vault, strategy, snx, snx_whale, cySNX):

    gov = vault.governance()
    snx.approve(vault, 2**256 - 1, {"from": snx_whale})
    vault.deposit(Wei("1_000 ether"), {"from": snx_whale})

    s0 = Contract(vault.withdrawalQueue(0))
    debt_ratio = vault.strategies(s0).dict()["debtRatio"]
    assert debt_ratio > 0
    vault.updateStrategyDebtRatio(s0, 0, {"from": gov})

    # Invest only 1k SNX
    vault.addStrategy(strategy, debt_ratio, 0, Wei("1_000 ether"), 1000,
                      {"from": gov})
    strategy.harvest({"from": gov})

    # No more deposits into the strategy
    vault.updateStrategyMaxDebtPerHarvest(strategy, 0, {"from": gov})

    chain.mine(2000)
    chain.sleep(3600 * 8)
    cySNX.mint(0, {"from": gov})
    strategy.harvest({"from": gov})

    assert vault.strategies(strategy).dict()["totalGain"] > 0
    assert vault.strategies(strategy).dict()["totalLoss"] == 0

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

    assert vault.strategies(strategy).dict()["totalLoss"] == 0
    assert vault.strategies(strategy).dict()["totalDebt"] <= 1
def test_migration_via_vault(gov, vault, strategy, new_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(864000)
    chain.mine(1)

    crv = Contract(strategy.crv(), owner=gov)
    cvx = Contract(strategy.cvx(), owner=gov)
    fis = Contract(strategy.fis(), owner=gov)
    print(f"crv before: {crv.balanceOf(new_strategy)}")
    print(f"cvx before: {cvx.balanceOf(new_strategy)}")
    print(f"fis before: {fis.balanceOf(new_strategy)}")

    oldStrategyAssets = strategy.estimatedTotalAssets()
    vault.migrateStrategy(strategy, new_strategy, {"from": gov})
    assert oldStrategyAssets == new_strategy.estimatedTotalAssets()

    print(f"crv after: {crv.balanceOf(new_strategy)}")
    print(f"cvx after: {cvx.balanceOf(new_strategy)}")
    print(f"fis after: {fis.balanceOf(new_strategy)}")
Beispiel #6
0
def test_shares_balance_decrease_liquidation(
        vault, vault_user, liquidations_admin, deposit_to_terra, steth_token,
        beth_token, helpers, withdraw_from_terra, lido_oracle_report):
    deposit_to_terra(TERRA_ADDRESS, vault_user, amount=10**18)

    lido_oracle_report(steth_rebase_mult=1)
    vault.collect_rewards({'from': liquidations_admin})

    withdraw_from_terra(TERRA_ADDRESS,
                        to_address=vault_user,
                        amount=0.5 * 10**18)
    vault.withdraw(0.5 * 10**18, vault.version(), {'from': vault_user})

    chain.mine(timedelta=3600 * 28)

    vault_steth_balance_before = steth_token.balanceOf(vault)
    vault_beth_balance_before = beth_token.balanceOf(vault)

    lido_oracle_report(steth_rebase_mult=1.1)
    vault.collect_rewards({'from': liquidations_admin})

    assert beth_token.balanceOf(vault) == vault_beth_balance_before

    assert helpers.equal_with_precision(steth_token.balanceOf(vault),
                                        vault_steth_balance_before, 100)
Beispiel #7
0
def test_multi_emerg_withdraw(lp_staker, alice, bob, token, token2):
    lp_staker.addPool(token2, 0, {'from': alice})
    token2.approve(lp_staker, 2**256-1, {'from': alice})
    token2.approve(lp_staker, 2**256-1, {'from': bob})

    deposit = 10000 * 10**18
    chain.sleep(1001)
    chain.mine()
    lp_staker.deposit(1, deposit, {'from': alice})
    lp_staker.deposit(1, deposit * 2, {'from': bob})
    lp_staker.deposit(2, deposit * 3, {'from': bob})
    lp_staker.deposit(2, deposit * 4, {'from': bob})
    lp_staker.deposit(1, deposit * 5, {'from': alice})
    lp_staker.deposit(1, deposit * 6, {'from': bob})
    lp_staker.deposit(2, deposit * 7, {'from': bob})
    lp_staker.deposit(2, deposit * 8, {'from': bob})
    chain.sleep(100)
    chain.mine()

    lp_staker.emergencyWithdraw(1, {'from': alice})
    lp_staker.emergencyWithdraw(2, {'from': alice})
    lp_staker.emergencyWithdraw(1, {'from': bob})
    lp_staker.emergencyWithdraw(2, {'from': bob})

    assert token.balanceOf(alice) == 1000000 * 10**18
    assert token.balanceOf(bob) == 1000000 * 10**18
    assert token2.balanceOf(alice) == 1000000 * 10**18
    assert token2.balanceOf(bob) == 1000000 * 10**18
Beispiel #8
0
def test_profitable_harvest(accounts, dai, gov, token, vault, strategy, user,
                            user217, user8, strategist, amount, amount217,
                            amount8, RELATIVE_APPROX, chain):
    # Deposit to the vault
    token.approve(vault.address, amount, {"from": user})
    token.approve(vault.address, amount217, {"from": user217})
    vault.deposit(amount, {"from": user})
    vault.deposit(amount217, {"from": user217})
    assert token.balanceOf(vault.address) == amount + amount217

    # Harvest 1: Send funds through the strategy
    strategy.harvest()
    assert pytest.approx(strategy.estimatedTotalAssets(),
                         rel=RELATIVE_APPROX) == amount + amount217
    before_pps = vault.pricePerShare()
    # TODO: Add some code before harvest #2 to simulate earning yield
    sleepAndHarvest(10, strategy, gov, vault, dai)
    # Harvest 2: Realize profit
    strategy.harvest()
    chain.sleep(3600 * 6)  # 6 hrs needed for profits to unlock
    chain.mine(1)
    profit = token.balanceOf(vault.address)  # Profits go to vault
    assert vault.pricePerShare() >= before_pps
    # Withdraws should not fail
    vault.withdraw(amount, {"from": user})
    vault.withdraw(amount217, {"from": user217})

    # Depositors after withdraw should have a profit or gotten the original amount
    assert token.balanceOf(user) >= amount
    assert token.balanceOf(user217) >= amount217

    # Make sure it isnt less than 1 after depositors withdrew
    assert vault.pricePerShare() / 1e18 >= 1
def test_direct_transfer_with_actual_profits(
    vault, strategy, token, token_whale, borrow_token, borrow_whale, yvault, gov
):
    initialProfit = vault.strategies(strategy).dict()["totalGain"]
    assert initialProfit == 0

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

    # send some profit to yvault
    borrow_token.transfer(
        yvault, 20_000 * (10 ** borrow_token.decimals()), {"from": borrow_whale}
    )

    # sleep for a day
    chain.sleep(24 * 3600)
    chain.mine(1)

    # receive a direct transfer
    airdropAmount = 1_000 * (10 ** token.decimals())
    token.transfer(strategy, airdropAmount, {"from": token_whale})

    # sleep for another day
    chain.sleep(24 * 3600)
    chain.mine(1)

    strategy.harvest({"from": gov})
    assert (
        vault.strategies(strategy).dict()["totalGain"] > initialProfit + airdropAmount
    )
def test_hyperbolic_auction_tokens_claimable(hyperbolic_auction):
    token_buyer =  accounts[2]
    eth_to_transfer = 20 * TENPOW18
    hyperbolic_auction.commitEth(token_buyer, True, {"from": token_buyer, "value":eth_to_transfer})
    chain.sleep(AUCTION_TIME+100)
    chain.mine()
    assert hyperbolic_auction.tokensClaimable(accounts[2]) == AUCTION_TOKENS
def test_hyperbolic_auction_withdraw_tokens(hyperbolic_auction):
    token_buyer = accounts[2]
    eth_to_transfer = 100 * TENPOW18

    with reverts("HyperbolicAuction: auction has not finished yet"):
        hyperbolic_auction.withdrawTokens({'from':accounts[0]})

    hyperbolic_auction.commitEth(token_buyer, True, {"from": token_buyer, "value":eth_to_transfer})
    assert hyperbolic_auction.finalized({'from': accounts[0]}) == False

    chain.sleep(AUCTION_TIME+1)
    chain.mine()
    assert hyperbolic_auction.auctionSuccessful({'from': accounts[0]}) == True
    
    with reverts("HyperbolicAuction: not finalized"):
        hyperbolic_auction.withdrawTokens({'from':accounts[0]})
    
    with reverts("HyperbolicAuction: sender must be an operator"):
        hyperbolic_auction.finalizeAuction({'from':accounts[8]})
    
    

    hyperbolic_auction.finalizeAuction({'from':accounts[0]})
    assert hyperbolic_auction.finalized({'from': accounts[0]}) == True

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

    with reverts("HyperbolicAuction: no tokens to claim"):
        hyperbolic_auction.withdrawTokens({"from":token_buyer})
Beispiel #12
0
def test_new_farming(accounts, farming, niftsy20):
    chain.sleep(110)
    chain.mine(10)

    assert farming.getAvailableRewardAmount(
        2, niftsy20) == farming.getRewardSettings(
            niftsy20)[0][1] * farming.getERC20CollateralBalance(
                2, niftsy20) / 10000

    collateral = farming.getERC20CollateralBalance(2, niftsy20)
    logging.info('col = {}'.format(collateral))
    logging.info('avail = {}'.format(
        farming.getAvailableRewardAmount(2, niftsy20)))
    logging.info('rasch = {}'.format(
        farming.getRewardSettings(niftsy20)[0][1] *
        farming.getERC20CollateralBalance(2, niftsy20) / 10000))
    rewards = farming.rewards(2)
    farming.harvest(2, niftsy20.address, {'from': accounts[1]})
    logging.info('getERC20CollateralBalance({},{})={}'.format(
        2, niftsy20,
        Wei(farming.getERC20CollateralBalance(2, niftsy20)).to('ether')))

    assert collateral + farming.getRewardSettings(niftsy20)[0][
        1] * collateral / 10000 == farming.getERC20CollateralBalance(
            2, niftsy20)
    assert rewards[0] < farming.rewards(2)[0]
    assert farming.rewards(2)[1] == 0
Beispiel #13
0
def test_check_reward(accounts, farming, niftsy20):

    chain.sleep(1100)
    chain.mine(10)

    #logging.info('getCurrenntAPYByTokenId_1 = {}'.format(farming.getCurrenntAPYByTokenId(1, niftsy20)))
    #logging.info('getPlanAPYByTokenId1 = {}'.format(farming.getPlanAPYByTokenId(1, niftsy20)))
    #logging.info('getCurrenntAPYByTokenId_2 = {}'.format(farming.getCurrenntAPYByTokenId(2, niftsy20)))
    #logging.info('timeInStake()={}'.format(
    #    chain.time() - farming.rewards(farming.lastWrappedNFTId())[0]
    #))

    #logging.info('getERC20CollateralBalance({},{})={}'.format(
    #    2,
    #    niftsy20,
    #    farming.getERC20CollateralBalance(2, niftsy20)
    #))

    #logging.info('farming.getAvailableRewardAmount(1, niftsy20)={}'.format(
    #    Wei(farming.getAvailableRewardAmount(1, niftsy20)).to('ether')
    #))

    #logging.info('farming.getAvailableRewardAmount(2, niftsy20)={}'.format(
    #    Wei(farming.getAvailableRewardAmount(2, niftsy20)).to('ether')

    #))

    assert farming.getAvailableRewardAmount(
        1, niftsy20) == farming.getRewardSettings(
            niftsy20)[3][1] * farming.getERC20CollateralBalance(
                1, niftsy20) / 10000
Beispiel #14
0
def test_migrate(
    currency,
    AlchemixStakingStrategy,
    stakingstrategy,
    chain,
    vault,
    whale,
    gov,
    strategist,
    interface,
):
    debt_ratio = 10_000
    vault.addStrategy(
        stakingstrategy, debt_ratio, 0, 2 ** 256 - 1, 1_000, {"from": gov}
    )

    currency.approve(vault, 2 ** 256 - 1, {"from": whale})
    vault.deposit(Wei("100 ether"), {"from": whale})
    stakingstrategy.harvest({"from": strategist})

    chain.sleep(2592000)
    chain.mine(1)

    stakingstrategy.harvest({"from": strategist})
    totalasset_beforemig = stakingstrategy.estimatedTotalAssets()
    assert totalasset_beforemig > 0

    strategy2 = strategist.deploy(AlchemixStakingStrategy, vault)
    vault.migrateStrategy(stakingstrategy, strategy2, {"from": gov})
    # Check that we got all the funds on migration
    assert strategy2.estimatedTotalAssets() >= totalasset_beforemig
def test_impact(comptroller):

    chain.mine(timedelta=1200)

    comptroller.impactBatch([True], [1e18])

    comptroller.impactBatch([True], [1e18])

    roller0 = comptroller.impactRollers(0)
    roller1 = comptroller.impactRollers(1)
    roller2 = comptroller.impactRollers(2)

    print(roller0)
    print(roller1)
    print(roller2)

    comptroller.impactBatch([True], [1e18])

    roller0 = comptroller.impactRollers(0)
    roller1 = comptroller.impactRollers(1)
    roller2 = comptroller.impactRollers(2)

    print(roller0)
    print(roller1)
    print(roller2)
Beispiel #16
0
def staking_rewards(GazeLPStaking, GazeRewards, gaze_coin, lp_token,
                    weth_token, access_control):
    staking_rewards = GazeLPStaking.deploy({'from': accounts[0]})
    staking_rewards.initLPStaking(gaze_coin, lp_token, weth_token,
                                  access_control, {"from": accounts[0]})

    vault = accounts[1]
    rewards_contract = GazeRewards.deploy(gaze_coin, access_control,
                                          staking_rewards,
                                          chain.time() + 10, 0, 0,
                                          {'from': accounts[0]})

    assert gaze_coin.balanceOf(vault) > 0
    gaze_coin.approve(rewards_contract, ONE_MILLION, {"from": vault})
    rewards_contract.setVault(vault, {"from": accounts[0]})

    staking_rewards.setRewardsContract(rewards_contract, {"from": accounts[0]})
    staking_rewards.setTokensClaimable(True, {"from": accounts[0]})

    weeks = [0, 1, 2, 3, 4, 5]
    rewards = [
        70000 * TENPOW18, 60000 * TENPOW18, 50000 * TENPOW18, 50000 * TENPOW18,
        45000 * TENPOW18, 42000 * TENPOW18
    ]
    rewards_contract.setRewards(weeks, rewards)

    chain.sleep(20)
    chain.mine()

    return staking_rewards
def test_impact_roller_expected_impact(comptroller):

    cap = comptroller.oiCap()

    pressure = 1e18 / cap

    chain.mine(timedelta=ONE_BLOCK)

    comptroller.impactBatch([True], [1e18])
    chain.mine(timedelta=ONE_BLOCK)
    comptroller.impactBatch([True], [1e18])
    chain.mine(timedelta=ONE_BLOCK)
    comptroller.impactBatch([True], [1e18])
    chain.mine(timedelta=ONE_BLOCK)
    comptroller.impactBatch([True], [1e18])
    chain.mine(timedelta=ONE_BLOCK)
    comptroller.impactBatch([True], [1e18])

    assert comptroller.impactCycloid() == 5

    assert comptroller.impactRollers(1)[1] / 1e18 == approx(1 * pressure)
    assert comptroller.impactRollers(2)[1] / 1e18 == approx(2 * pressure)
    assert comptroller.impactRollers(3)[1] / 1e18 == approx(3 * pressure)
    assert comptroller.impactRollers(4)[1] / 1e18 == approx(4 * pressure)
    assert comptroller.impactRollers(5)[1] / 1e18 == approx(5 * pressure)
    assert comptroller.impactRollers(5)[0] == chain[-1].timestamp
    assert comptroller.impactRollers(6)[0] == 0
Beispiel #18
0
    def pass_and_exec_dao_vote(vote_id):
        print(f'executing vote {vote_id}')

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

        helper_acct = Helpers.accounts[0]

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

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

        assert Helpers.dao_voting.canExecute(vote_id)
        tx = Helpers.dao_voting.executeVote(vote_id, {'from': helper_acct})

        print(f'vote {vote_id} executed')
        return tx
Beispiel #19
0
def test_usd_to_btc(Settler, alice, swap, sUSD, sBTC, curve_susd, curve_sbtc,
                    usd_idx, btc_idx):
    initial = MintableForkToken(curve_susd.coins(usd_idx))
    final = MintableForkToken(curve_sbtc.coins(btc_idx))

    amount = 1_000_000 * 10**initial.decimals()
    initial._mint_for_testing(alice, amount)
    initial.approve(swap, 2**256 - 1, {"from": alice})

    tx = swap.swap_into_synth(initial, sBTC, amount, 0, {"from": alice})
    token_id = tx.events["Transfer"][-1]["token_id"]

    chain.mine(timedelta=600)
    amount = swap.token_info(token_id)["underlying_balance"]
    swap.swap_from_synth(token_id, final, amount, 0, {"from": alice})

    settler = Settler.at(hex(token_id))
    for coin in (initial, sBTC, sUSD):
        assert coin.balanceOf(swap) == 0
        assert coin.balanceOf(settler) == 0
        assert coin.balanceOf(alice) == 0

    assert final.balanceOf(swap) == 0
    assert final.balanceOf(settler) == 0
    assert final.balanceOf(alice) > 0

    assert swap.balanceOf(alice) == 0
def test_increase(vault, strategy, gov, token, token_whale, borrow_token,
                  borrow_whale, yvault):
    token.approve(vault, 2**256 - 1, {"from": token_whale})
    vault.deposit(20 * (10**token.decimals()), {"from": token_whale})
    vault.updateStrategyDebtRatio(strategy, 5_000, {"from": gov})

    chain.sleep(1)
    strategy.harvest({"from": gov})
    assert vault.strategies(
        strategy).dict()["totalDebt"] == 10 * (10**token.decimals())

    borrow_token.transfer(yvault, 200 * (10**borrow_token.decimals()),
                          {"from": borrow_whale})
    tx = strategy.harvest({"from": gov})
    chain.sleep(60 * 60 * 24 * 2)
    chain.mine(1)

    # Go all the way up to 10k
    vault.updateStrategyDebtRatio(strategy, 10_000, {"from": gov})

    chain.sleep(1)
    strategy.harvest({"from": gov})
    assert vault.strategies(
        strategy).dict()["totalDebt"] >= 20 * (10**token.decimals())
    assert vault.strategies(strategy).dict()["totalLoss"] == 0
Beispiel #21
0
def sleepAndHarvest(times, strat, gov):
    for i in range(times):
        debugStratData(strat, "Before harvest" + str(i))
        chain.sleep(2500)
        chain.mine(1)
        strat.harvest({"from": gov})
        debugStratData(strat, "After harvest" + str(i))
def test_emissions_against_other_gauge(alice, mock_lp_token, gauge_controller,
                                       liquidity_gauge, root_gauge):
    gauge_controller.add_type("Test", 10**18, {"from": alice})
    gauge_controller.add_gauge(liquidity_gauge, 0, 1, {"from": alice})
    gauge_controller.add_gauge(root_gauge, 0, 1, {"from": alice})

    # alice is the only staker in `liquidity_gauge`
    mock_lp_token.approve(liquidity_gauge, 2**256 - 1, {"from": alice})
    tx = liquidity_gauge.deposit(100000, {"from": alice})

    # sleep until the start of the next epoch week
    chain.mine(timestamp=(tx.timestamp // WEEK + 1) * WEEK)

    # 110 weeks ensures we see 2 reductions in the rate
    for i in range(1, 110):
        # checkpointing the root gauge mints all the allocated emissions for the next week
        tx = root_gauge.checkpoint()
        emissions = root_gauge.emissions(
        )  # emissions this week are delayed y a week so

        claimable = liquidity_gauge.claimable_tokens(alice, {
            "from": alice
        }).return_value

        # root gauge emissions should be equal to regular gauge claimable amount
        assert math.isclose(emissions, claimable, rel_tol=1e-6)

        # now we time travel one week, and get the claimable rewards from the regular gauge
        chain.mine(timestamp=(tx.timestamp // WEEK + 1) * WEEK)
Beispiel #23
0
def test_dutch_auction_twoPurchases(dutch_auction):

    token_buyer_a = accounts[2]
    token_buyer_b = accounts[3]
    assert dutch_auction.tokensClaimable(token_buyer_a,
                                         {'from': accounts[0]}) == 0
    assert dutch_auction.tokensClaimable(token_buyer_b,
                                         {'from': accounts[0]}) == 0
    assert dutch_auction.tokensRemaining() == AUCTION_TOKENS

    eth_to_transfer = 20 * TENPOW18
    tx = dutch_auction.commitEth({
        'from': token_buyer_a,
        'value': eth_to_transfer
    })
    assert 'AddedCommitment' in tx.events
    tx = dutch_auction.commitEth({
        'from': token_buyer_b,
        'value': 4 * eth_to_transfer
    })
    assert 'AddedCommitment' in tx.events
    chain.sleep(AUCTION_TIME + 100)
    chain.mine()

    assert dutch_auction.tokensRemaining() == 0

    # AG need to double check these numbers
    assert dutch_auction.tokensClaimable(
        token_buyer_a, {'from': accounts[0]}) == AUCTION_TOKENS / 5
    assert dutch_auction.tokensClaimable(
        token_buyer_b, {'from': accounts[0]}) == 4 * AUCTION_TOKENS / 5
Beispiel #24
0
def test_eth_to_btc(Settler, alice, swap, sBTC, sETH, curve_sbtc, curve_seth,
                    btc_idx):
    final = MintableForkToken(curve_sbtc.coins(btc_idx))

    tx = swap.swap_into_synth(ETH_ADDRESS, sBTC, alice.balance(), 0, {
        'from': alice,
        'value': alice.balance()
    })
    token_id = tx.events['Transfer'][-1]['token_id']

    chain.mine(timedelta=600)
    amount = swap.token_info(token_id)['underlying_balance']
    swap.swap_from_synth(token_id, final, amount, 0, {'from': alice})

    settler = Settler.at(hex(token_id))
    for coin in (sETH, sBTC):
        assert coin.balanceOf(swap) == 0
        assert coin.balanceOf(settler) == 0
        assert coin.balanceOf(alice) == 0

    assert swap.balance() == 0
    assert settler.balance() == 0
    assert alice.balance() == 0

    assert final.balanceOf(swap) == 0
    assert final.balanceOf(settler) == 0
    assert final.balanceOf(alice) > 0

    assert swap.balanceOf(alice) == 0
Beispiel #25
0
def test_erc20_auction_claim(erc20_auction, payment_token):
    token_buyer = accounts[2]
    tokens_to_transfer = 100 * TENPOW18

    with reverts():
        erc20_auction.withdrawTokens({'from': accounts[0]})
    tx = payment_token.transfer(token_buyer, tokens_to_transfer,
                                {'from': accounts[0]})
    tx = payment_token.approve(erc20_auction, tokens_to_transfer,
                               {'from': token_buyer})
    tx = erc20_auction.commitTokens(tokens_to_transfer, {'from': token_buyer})
    assert erc20_auction.finalised({'from': accounts[0]}) == False

    chain.sleep(AUCTION_TIME + 100)
    chain.mine()
    assert erc20_auction.auctionSuccessful({'from': accounts[0]}) == True

    erc20_auction.withdrawTokens({'from': token_buyer})

    # Check for multiple withdraws
    with reverts():
        erc20_auction.withdrawTokens({'from': token_buyer})
        erc20_auction.withdrawTokens({'from': accounts[0]})

    erc20_auction.finaliseAuction({'from': accounts[0]})
    with reverts():
        erc20_auction.finaliseAuction({'from': accounts[0]})
Beispiel #26
0
def test_btc_to_eth(Settler, alice, bob, swap, sBTC, sETH, curve_sbtc,
                    curve_seth, btc_idx):
    initial = MintableForkToken(curve_sbtc.coins(btc_idx))

    amount = 5 * 10**initial.decimals()
    initial._mint_for_testing(alice, amount)
    initial.approve(swap, 2**256 - 1, {'from': alice})
    alice.transfer(bob, alice.balance())

    tx = swap.swap_into_synth(initial, sETH, amount, 0, {'from': alice})
    token_id = tx.events['Transfer'][-1]['token_id']

    chain.mine(timedelta=600)
    amount = swap.token_info(token_id)['underlying_balance']
    swap.swap_from_synth(token_id, ETH_ADDRESS, amount, 0, {'from': alice})

    settler = Settler.at(hex(token_id))
    for coin in (initial, sETH, sBTC):
        assert coin.balanceOf(swap) == 0
        assert coin.balanceOf(settler) == 0
        assert coin.balanceOf(alice) == 0

    assert swap.balance() == 0
    assert settler.balance() == 0
    assert alice.balance() > 0

    assert swap.balanceOf(alice) == 0
    def rule_swap_into(self, st_acct, st_token, st_synth, st_idx, st_amount):
        """
        Generate a new NFT via a cross-asset swap.
        """
        idx = int(st_idx * len(TOKENS[st_token]))

        initial = TOKENS[st_token][idx]
        synth = TOKENS[st_synth][0]
        amount = self._mint(st_acct, initial, st_amount)
        if st_token == st_synth:
            # initial token and target synth come from the same asset class
            # no cross-asset swap is possible
            with brownie.reverts():
                self.swap.swap_into_synth(initial, synth, amount, 0,
                                          {"from": st_acct})
        else:
            tx = self.swap.swap_into_synth(initial, synth, amount, 0,
                                           {"from": st_acct})
            token_id = tx.events["Transfer"][-1]["token_id"]
            assert token_id != 0

            if "NewSettler" in tx.events:
                settler = tx.events["NewSettler"]["addr"]
                assert settler not in self.settlers
                self.settlers.append(settler)

            # make sure `token_id` isn't previously assigned
            assert (token_id not in list(self.active_token_ids.values()) +
                    self.used_token_ids)

            self.active_token_ids.setdefault(st_acct, []).append(token_id)
            chain.mine(timedelta=600)
def test_impact_pressure(comptroller, entry):

    entry *= 1e18

    chain.mine(timedelta=ONE_BLOCK)

    cap = comptroller.oiCap()

    _lambda = comptroller.lmbda()

    comptroller.impactBatch([True], [entry])

    impact = comptroller.viewImpact(True, 1e18)

    inverse_euler = Decimal(1) / Decimal(math.e)

    impact_1 = (Decimal(entry) / Decimal(1e18)) / \
        (Decimal(cap) / Decimal(1e18))

    impact_2 = (Decimal(1e18) / Decimal(1e18)) / (Decimal(cap) / Decimal(1e18))

    pressure = impact_1 + impact_2

    impact_factor = Decimal(_lambda / 1e18) * pressure

    expected = (Decimal(1) - (inverse_euler ** impact_factor)) * Decimal(1e18)

    assert abs(expected - impact) < 1e6
Beispiel #29
0
def get_uni_feeds(feed_owner, feed_info):

    market_obs = feed_info.market_info[0]
    market_shims = feed_info.market_info[1]
    depth_obs = feed_info.depth_info[0]
    depth_shims = feed_info.depth_info[1]

    UniswapV3MockFactory = getattr(brownie, 'UniswapV3FactoryMock')
    IUniswapV3OracleMock = getattr(interface, 'IUniswapV3OracleMock')

    uniswapv3_factory = feed_owner.deploy(UniswapV3MockFactory)

    market_token0 = "0x6B175474E89094C44Da98b954EedeAC495271d0F"
    market_token1 = WRAPPED_ETH_ADDR
    depth_token0 = "0xBB0E17EF65F82Ab018d8EDd776e8DD940327B28b"
    depth_token1 = WRAPPED_ETH_ADDR

    # TODO: place token0 and token1 into the json
    uniswapv3_factory.createPool(market_token0, market_token1)
    uniswapv3_factory.createPool(depth_token0, depth_token1)

    market_mock = IUniswapV3OracleMock(uniswapv3_factory.allPools(0))
    depth_mock = IUniswapV3OracleMock(uniswapv3_factory.allPools(1))

    market_mock.loadObservations(
        market_obs, market_shims, {'from': feed_owner})

    depth_mock.loadObservations(depth_obs, depth_shims, {'from': feed_owner})

    chain.mine(timestamp=feed_info.market_info[2]['timestamp'][0])

    return uniswapv3_factory.address, market_mock.address, depth_mock.address, market_token1   # noqa: E501
Beispiel #30
0
def test_huge_debt(vault, strategy, gov, token, token_whale):
    prev_balance = token.balanceOf(token_whale)
    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})
    lp = get_lending_pool()

    prev_debt = lp.getUserAccountData(strategy).dict()["totalDebtETH"]
    print(f"T=0 totalDebtETH: {prev_debt}")

    # After first investment sleep for aproximately a month
    chain.sleep(60 * 60 * 24 * 30)
    chain.mine(1)
    new_debt = lp.getUserAccountData(strategy).dict()["totalDebtETH"]
    print(f"T=365 totalDebtETH: {new_debt}")
    assert new_debt > prev_debt

    # Test that there is no loss until withdrawal
    strategy.harvest({"from": gov})
    assert vault.strategies(strategy).dict()["totalLoss"] == 0

    vault.withdraw(vault.balanceOf(token_whale), token_whale, 10_000,
                   {"from": token_whale})

    # we are currently in a profitable scenario so there is no loss
    print(f"diff {prev_balance-token.balanceOf(token_whale)}")
    assert token.balanceOf(token_whale) - prev_balance > 0