Example #1
0
def main():
    badger = connect_badger(badger_config.prod_json)
    console.print("\n[white]===== 🦡 Sett Status 🦡 =====[white]\n")
    for key in badger.sett_system.vaults.keys():
        sett = badger.getSett(key)

        admin = badger.getProxyAdmin(sett)
        sett_impl = admin.getProxyImplementation(sett)
        sett_admin = admin.getProxyAdmin(sett)

        sett_type = badger.getSettType(key)

        print(key, sett_type)

        table = []

        table.append(["Sett Key", key])
        table.append(["Sett Type", sett_type])
        table.append(["Sett Logic", sett_impl])
        table.append(["Sett Admin", sett_admin])

        if sett_type == "v1":
            snap = SnapshotManager(badger, key)
            state = snap.snap()
            snap.printPermissions()
            # snap.printTable(state)
            strategy = badger.getStrategy(key)
            strategy_impl = badger.devProxyAdmin.getProxyImplementation(
                strategy)
            strategy_admin = admin.getProxyAdmin(strategy)
            table.append(["Strategy Logic", strategy_impl])
            table.append(["Strategy Admin", strategy_admin])

        print(tabulate(table, ["Key", "Value"]))
Example #2
0
def tend_all(badger: BadgerSystem, skip):
    table = []
    for key, vault in badger.sett_system.vaults.items():
        if key in skip:
            continue

        strategy = badger.getStrategy(key)

        if not strategy.isTendable():
            continue

        console.print("\n[bold green]===== Tend: " + key + " =====[/bold green]\n")

        snap = SnapshotManager(badger, key)
        strategy = badger.getStrategy(key)
        keeper = accounts.at(badger.keeper)

        before = snap.snap()

        if strategy.keeper() == badger.badgerRewardsManager:
            snap.settTendViaManager(
                strategy, {"from": keeper, "gas_limit": 1000000}, confirm=False,
            )
        else:
            snap.settTend(
                {"from": keeper, "gas_limit": 1000000}, confirm=False,
            )

        tx_wait()

        if rpc.is_active():
            chain.mine()
        after = snap.snap()

        snap.printCompare(before, after)
Example #3
0
def main():
    badger = connect_badger(badger_config.prod_json)
    console.print("\n[white]===== 🦡 Sett Status 🦡 =====[white]\n")
    for key in badger.sett_system.vaults.keys():
        if key in setts_to_skip:
            continue
        sett = badger.getSett(key)

        admin = badger.getProxyAdmin(sett)
        sett_impl = admin.getProxyImplementation(sett)
        sett_admin = admin.getProxyAdmin(sett)

        sett_type = badger.getSettType(key)

        print(key, sett_type)

        table = []

        console.print("[green]=== Admin: {} Sett ===[green]".format(key))

        table.append(["Sett Key", key])

        table.append(["Sett Type", sett_type])
        table.append(["Sett Logic", sett_impl])
        table.append(["Sett Admin", sett_admin])
        print(tabulate(table, ["Key", "Value"]))

        table = []
        table.append(["PPFS", sett.getPricePerFullShare()])
        table.append(["totalSupply", sett.totalSupply()])
        table.append(["balance", sett.balance()])
        print(tabulate(table, ["Key", "Value"]))

        if sett_type == "v1":
            snap = SnapshotManager(badger, key)
            # state = snap.snap()

            # snap.printTable(state)

            if badger.hasStrategy(key):
                snap.printPermissions()
                strategy = badger.getStrategy(key)
                admin = badger.getProxyAdmin(strategy)
                strategy_impl = admin.getProxyImplementation(strategy)
                strategy_admin = admin.getProxyAdmin(strategy)

                table = []
                console.print(
                    "[green]=== Admin: {} Strategy ===[green]".format(key))
                table.append(["Strategy Logic", strategy_impl])
                table.append(["Strategy Admin", strategy_admin])

        print(tabulate(table, ["Key", "Value"]))
def single_user_harvest_flow(badger: BadgerSystem, settConfig, user):
    strategy = badger.getStrategy(settConfig["id"])
    want = interface.IERC20(registry.pancake.chefPairs.bnbBtcb)
    snap = SnapshotManager(badger, settConfig["id"])
    sett = badger.getSett(settConfig["id"])
    settKeeper = accounts.at(sett.keeper(), force=True)
    strategyKeeper = accounts.at(strategy.keeper(), force=True)
    randomUser = accounts[6]

    tendable = strategy.isTendable()

    startingBalance = want.balanceOf(user)

    depositAmount = startingBalance // 200
    assert startingBalance >= depositAmount
    assert startingBalance >= 0

    # Deposit
    want.approve(sett, MaxUint256, {"from": user})
    snap.settDeposit(depositAmount, {"from": user})

    assert want.balanceOf(sett) > 0
    print("want.balanceOf(sett)", want.balanceOf(sett))

    # Earn
    snap.settEarn({"from": settKeeper})

    if tendable:
        with brownie.reverts("onlyAuthorizedActors"):
            strategy.tend({"from": randomUser})

    numTends = 48
    timeBetweenTends = days(365) // numTends

    console.print({"numTends": numTends, "timeBetweenTends": timeBetweenTends})

    for i in range(0, numTends):
        console.print("Tend {}".format(i))
        snap.settTend({"from": strategyKeeper})
        chain.sleep(timeBetweenTends)
        chain.mine()

    with brownie.reverts("onlyAuthorizedActors"):
        strategy.harvest({"from": randomUser})

    snap.settHarvest({"from": strategyKeeper})
Example #5
0
def main():
    badger = connect_badger(badger_config.prod_json)
    console.print("\n[white]===== 🦡 Sett Status 🦡 =====[white]\n")
    for key in badger.sett_system.vaults.keys():
        snap = SnapshotManager(badger, key)
        state = snap.snap()
        snap.printPermissions()
        snap.printTable(state)
Example #6
0
def test_simulation(settConfig):
    # connect to prod deploy and run simulation
    badger = badger_single_sett(settConfig, deploy=False)
    snap = SnapshotManager(badger, settConfig["id"])
    simulation = SimulationManager(badger, snap, settConfig["id"])

    simulation.provision()
    # Randomize 30 actions.
    simulation.randomize(30)
    simulation.run()
Example #7
0
def test_deposit_withdraw_single_user_flow(settConfig):
    badger = badger_single_sett(settConfig)

    sett = badger.getSett(settConfig["id"])
    strategy = badger.getStrategy(settConfig["id"])
    want = badger.getStrategyWant(settConfig["id"])
    deployer = badger.deployer

    settKeeper = accounts.at(sett.keeper(), force=True)

    snap = SnapshotManager(badger, settConfig["id"])

    randomUser = accounts[6]

    print("== Testing == ", settConfig["id"], want.address)
    # Deposit
    assert want.balanceOf(deployer) > 0

    depositAmount = int(want.balanceOf(deployer) * 0.8)
    assert depositAmount > 0

    want.approve(sett, MaxUint256, {"from": deployer})
    snap.settDeposit(depositAmount, {"from": deployer})

    # Earn
    with brownie.reverts("onlyAuthorizedActors"):
        sett.earn({"from": randomUser})

    min = sett.min()
    max = sett.max()
    remain = max - min

    snap.settEarn({"from": settKeeper})

    chain.sleep(15)
    chain.mine(1)

    snap.settWithdraw(depositAmount // 2, {"from": deployer})

    chain.sleep(10000)
    chain.mine(1)

    snap.settWithdraw(depositAmount // 2 - 1, {"from": deployer})
Example #8
0
def harvest_all(badger: BadgerSystem, skip):
    for key, vault in badger.sett_system.vaults.items():
        if key in skip:
            continue

        console.print("\n[bold yellow]===== Harvest: " + str(key) +
                      " =====[/bold yellow]\n")

        print("Harvest: " + key)

        snap = SnapshotManager(badger, key)
        strategy = badger.getStrategy(key)
        keeper = accounts.at(badger.keeper)

        before = snap.snap()
        if strategy.keeper() == badger.badgerRewardsManager:
            snap.settHarvestViaManager(
                strategy,
                {
                    "from": keeper,
                    "gas_limit": 2000000,
                    "allow_revert": True
                },
                confirm=False,
            )
        else:
            snap.settHarvest(
                {
                    "from": keeper,
                    "gas_limit": 2000000,
                    "allow_revert": True
                },
                confirm=False,
            )

        tx_wait()

        if rpc.is_active():
            chain.mine()
        after = snap.snap()

        snap.printCompare(before, after)
def test_deposit_withdraw_single_user_flow(settId):
    badger = badger_single_sett(settId)
    controller = badger.getController(settId)
    sett = badger.getSett(settId)
    strategy = badger.getStrategy(settId)
    want = badger.getStrategyWant(settId)

    snap = SnapshotManager(badger, settId)

    deployer = badger.deployer
    randomUser = accounts[6]

    print(want, want.address, want.totalSupply(), deployer)

    # Deposit
    depositAmount = int(want.balanceOf(deployer) * 0.8)

    want.approve(sett, MaxUint256, {"from": deployer})
    snap.settDeposit(depositAmount, {"from": deployer})

    # Earn
    with brownie.reverts("onlyAuthorizedActors"):
        sett.earn({"from": randomUser})

    min = sett.min()
    max = sett.max()
    remain = max - min

    assert sett.keeper() == deployer

    snap.settEarn({"from": deployer})

    chain.sleep(15)
    chain.mine(1)

    snap.settWithdraw(depositAmount // 2, {"from": deployer})

    chain.sleep(10000)
    chain.mine(1)

    snap.settWithdrawAll({"from": deployer})
Example #10
0
def deposit_withdraw_single_user_flow(badger, sett_id, user):
    controller = badger.getController("native")
    strategy = badger.getStrategy(sett_id)
    want = interface.IERC20(strategy.want())
    snap = SnapshotManager(badger, sett_id)
    sett = badger.getSett(sett_id)
    strategist = badger.deployer
    settKeeper = accounts.at(sett.keeper(), force=True)
    randomUser = accounts[6]

    # Deposit
    assert want.balanceOf(user) > 0

    depositAmount = int(want.balanceOf(user) * 0.8)
    assert depositAmount > 0

    want.approve(sett, MaxUint256, {"from": user})
    # sett.deposit(depositAmount, {"from": deployer})
    snap.settDeposit(depositAmount, {"from": user})

    # Earn
    # with brownie.reverts("onlyAuthorizedActors"):
    #     sett.earn({"from": randomUser})

    min = sett.min()
    max = sett.max()
    remain = max - min

    # sett.earn({"from": settKeeper})
    snap.settEarn({"from": settKeeper})

    chain.sleep(15)
    chain.mine(1)

    snap.settWithdraw(depositAmount // 2, {"from": user})

    chain.sleep(10000)
    chain.mine(1)

    snap.settWithdraw(depositAmount // 2 - 1, {"from": user})
Example #11
0
def test_claw(settConfig):
    badger = badger_single_sett(settConfig, deploy=False)
    snap = SnapshotManager(badger, settConfig["id"])
    deployer = badger.deployer

    want = badger.getStrategyWant(settConfig["id"])
    sett = badger.getSett(settConfig["id"])

    depositAmount = int(want.balanceOf(deployer) * 0.8)
    assert depositAmount > 0
    want.approve(sett, MaxUint256, {"from": deployer})
    snap.settDeposit(depositAmount, {"from": deployer})
    assert want.balanceOf(deployer) > 0

    distribute_test_ether(deployer, Wei("20 ether"))
    distribute_from_whales(deployer)

    claw = deploy_claw_minimal(deployer)
    if settConfig["id"] == "native.badger":
        _manage_position(claw, "bClaw", deployer)
    if settConfig["id"] == "sushi.sushiWbtcEth":
        _manage_position(claw, "sClaw", deployer)
Example #12
0
def vault_report(badger: BadgerSystem):
    controller = badger.getController("native")

    for key, vault in badger.sett_system.vaults.items():
        strategy = badger.getStrategy(key)
        snap = SnapshotManager(badger, key)

        snap.printPermissions()

        console.print(
            {
                "want": strategy.want(),
                "token0": strategy.token0(),
                "token1": strategy.token1(),
                "path0": strategy.getTokenSwapPath(
                    registry.pancake.cake, strategy.token0()
                ),
                "path1": strategy.getTokenSwapPath(
                    registry.pancake.cake, strategy.token1()
                ),
            }
        )
def deposit_withdraw_single_user_flow(badger, settConfig, user):
    strategy = badger.getStrategy(settConfig["id"])
    want = interface.IERC20(registry.pancake.chefPairs.bnbBtcb)
    snap = SnapshotManager(badger, settConfig["id"])
    sett = badger.getSett(settConfig["id"])
    settKeeper = accounts.at(sett.keeper(), force=True)

    # Deposit
    assert want.balanceOf(user) > 0

    depositAmount = int(want.balanceOf(user) * 0.8)
    assert depositAmount > 0

    want.approve(sett, MaxUint256, {"from": user})
    snap.settDeposit(depositAmount, {"from": user})

    # Earn
    # with brownie.reverts("onlyAuthorizedActors"):
    #     sett.earn({"from": randomUser})

    min = sett.min()
    max = sett.max()
    remain = max - min

    # sett.earn({"from": settKeeper})
    snap.settEarn({"from": settKeeper})

    chain.sleep(15)
    chain.mine(1)

    snap.settWithdraw(depositAmount // 2, {"from": user})

    chain.sleep(10000)
    chain.mine(1)

    snap.settWithdrawAll({"from": user})
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()
Example #15
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)
Example #16
0
def test_simulation_after_upgrade_sushi_strategies(args):
    (strategyID, artifactName) = args
    # Upgrade crv setts kkk
    badger = connect_badger(badger_config.prod_json)
    txFilename = queue_upgrade_strategy(badger, strategyID, artifactName)
    # Sleep 2 days to pass timelock delay period.
    chain.sleep(2 * days(2))
    badger.governance_execute_transaction(txFilename)

    # NB: strategy/sett IDs align
    snap = SnapshotManager(badger, strategyID)
    simulation = SimulationManager(badger, snap, strategyID)

    simulation.provision()
    # Randomize 30 actions.
    simulation.randomize(30)
    simulation.run()
Example #17
0
def harvest_all(badger: BadgerSystem, skip):
    keeper = badger.deployer

    for key, vault in badger.sett_system.vaults.items():
        if key in skip:
            continue

        console.print("\n[bold yellow]===== Harvest: " + str(key) + " =====[/bold yellow]\n")

        print("Harvest: " + key)

        snap = SnapshotManager(badger, key)
        strategy = badger.getStrategy(key)
        keeper = accounts.at(strategy.keeper())

        before = snap.snap()
        snap.settHarvest({'from': keeper, "gas_price": gas_strategy})
        after = snap.snap()

        snap.printCompare(before, after)
Example #18
0
def earn_all(badger: BadgerSystem, skip):
    keeper = badger.deployer
    for key, vault in badger.sett_system.vaults.items():
        if key in skip:
            print("Skip ", key)
            continue
        console.print("\n[bold red]===== Earn: " + key + " =====[/bold red]\n")
        strategy = badger.getStrategy(key)
        controller = Controller.at(vault.controller())
        want = interface.IERC20(vault.token())

        # Pre safety checks
        assert want == strategy.want()
        assert strategy.controller() == controller
        assert vault.controller() == controller
        assert controller.strategies(want) == strategy

        vaultBefore = want.balanceOf(vault)
        strategyBefore = strategy.balanceOf()

        toEarn = False
        if earn_preconditions(key, vaultBefore, strategyBefore):
            print("Earn: " + key, vault, strategy)
            toEarn = True

            snap = SnapshotManager(badger, key)
            before = snap.snap()

            keeper = accounts.at(vault.keeper())
            snap.settEarn(
                {"from": keeper, "gas_limit": 2000000, "allow_revert": True},
                confirm=False,
            )

            after = snap.snap()
            snap.printCompare(before, after)
Example #19
0
def single_user_harvest_flow(badger: BadgerSystem, sett_id, user):
    controller = badger.getController("native")
    strategy = badger.getStrategy(sett_id)
    want = interface.IERC20(strategy.want())
    snap = SnapshotManager(badger, sett_id)
    sett = badger.getSett(sett_id)
    strategist = accounts.at(strategy.strategist(), force=True)

    console.log({
        "key":
        sett_id,
        "want":
        strategy.want(),
        "token0":
        strategy.token0(),
        "token1":
        strategy.token1(),
        "path0":
        strategy.getTokenSwapPath(registry.pancake.cake, strategy.token0()),
        "path1":
        strategy.getTokenSwapPath(registry.pancake.cake, strategy.token1()),
    })

    strategist = badger.deployer
    settKeeper = accounts.at(sett.keeper(), force=True)
    strategyKeeper = accounts.at(strategy.keeper(), force=True)
    randomUser = accounts[6]

    tendable = strategy.isTendable()

    startingBalance = want.balanceOf(user)

    depositAmount = startingBalance // 200
    assert startingBalance >= depositAmount
    assert startingBalance >= 0

    # Deposit
    want.approve(sett, MaxUint256, {"from": user})
    snap.settDeposit(depositAmount, {"from": user})

    assert want.balanceOf(sett) > 0
    print("want.balanceOf(sett)", want.balanceOf(sett))

    # Earn
    snap.settEarn({"from": settKeeper})

    numTends = 48
    timeBetweenTends = days(0.5) // numTends

    console.print({"numTends": numTends, "timeBetweenTends": timeBetweenTends})

    for i in range(0, numTends):
        console.print("Tend {}".format(i))
        snap.settTend({"from": strategyKeeper})
        chain.sleep(timeBetweenTends)
        chain.mine()

    snap.settHarvest({"from": strategyKeeper})

    # if tendable:
    #     snap.settTend({"from": strategyKeeper})

    # snap.settWithdraw(depositAmount // 2, {"from": user})

    # chain.sleep(days(3))
    # chain.mine()

    # snap.settHarvest({"from": strategyKeeper})
    # snap.settWithdraw(depositAmount // 2 - 1, {"from": user})

    assert False
def test_single_user_harvest_flow(settId):
    suiteName = "test_single_user_harvest_flow" + ": " + settId
    testRecorder = TestRecorder(suiteName)

    badger = badger_single_sett(settId)
    controller = badger.getController(settId)
    sett = badger.getSett(settId)
    strategy = badger.getStrategy(settId)
    want = badger.getStrategyWant(settId)

    snap = SnapshotManager(badger, settId)

    deployer = badger.deployer
    randomUser = accounts[6]

    tendable = strategy.isTendable()

    startingBalance = want.balanceOf(deployer)

    depositAmount = Wei("1 ether")
    assert startingBalance >= depositAmount

    # Deposit
    want.approve(sett, MaxUint256, {"from": deployer})
    snap.settDeposit(depositAmount, {"from": deployer})

    # Earn
    snap.settEarn(depositAmount, {"from": deployer})

    if tendable:
        with brownie.reverts("onlyAuthorizedActors"):
            strategy.tend({"from": randomUser})

        snap.settTend({"from": deployer})

    chain.sleep(days(0.5))
    chain.mine()

    if tendable:
        snap.settTend({"from": deployer})

    chain.sleep(days(1))
    chain.mine()

    with brownie.reverts("onlyAuthorizedActors"):
        strategy.harvest({"from": randomUser})

    snap.settHarvest({"from": deployer})

    chain.sleep(days(1))
    chain.mine()

    if tendable:
        snap.settTend({"from": deployer})

    chain.sleep(days(3))
    chain.mine()

    snap.settHarvest({"from": deployer})

    snap.settWithdrawAll({"from": deployer})

    endingBalance = want.balanceOf(deployer)
    assert endingBalance > startingBalance
Example #21
0
def test_single_user_harvest_flow(settConfig):
    badger = badger_single_sett(settConfig)
    depositAmount = 50 * 1e8  # renBTC decimal is 8

    # test settings
    controller = badger.getController(settConfig["id"])
    sett = badger.getSett(settConfig["id"])
    strategy = badger.getStrategy(settConfig["id"])
    want = badger.getStrategyWant(settConfig["id"])
    deployer = badger.deployer

    # production settings
    # controller = interface.IController("0x9b4efa18c0c6b4822225b81d150f3518160f8609");
    # sett = interface.ISett("0x77f07Dd580cc957109c70c7fa81aa5704f8a3572")
    # strategy = StrategyUnitProtocolRenbtc.at("0x5640d6E2F72e76FBCb5296d59EA28C7375F1fE12");
    # want = interface.IERC20("0xEB4C2781e4ebA804CE9a9803C67d0893436bB27D")
    # deployer = accounts.at("0x576cD258835C529B54722F84Bb7d4170aA932C64", force=True)
    # controllerGov = accounts.at("0xB65cef03b9B89f99517643226d76e286ee999e77", force=True)
    # ethWhale = accounts.at("0x3f5CE5FBFe3E9af3971dD833D26bA9b5C936f0bE", force=True)
    # ethWhale.transfer(deployer, "100 ether")
    # settGuestList = interface.IVipCappedGuestList("0x9FC48e61B6a75eE263ca160aCF3288A99238719E");
    # settGuestList.setGuests([deployer], [True], {"from": deployer});
    # settGuestList.setUserDepositCap(depositAmount * 2, {"from": deployer});
    # settGuestList.setTotalDepositCap(depositAmount * 10, {"from": deployer});
    # controller.setVault(want, sett, {"from": deployer});
    # controller.approveStrategy(want, strategy, {"from": controllerGov});
    # controller.setStrategy(want, strategy, {"from": deployer});

    settKeeper = accounts.at(sett.keeper(), force=True)
    strategyKeeper = accounts.at(strategy.keeper(), force=True)

    snap = SnapshotManager(badger, settConfig["id"])

    governance = strategy.governance()

    tendable = strategy.isTendable()

    distribute_from_whales(deployer)
    startingBalance = want.balanceOf(deployer)

    assert startingBalance >= depositAmount
    assert startingBalance >= 0

    # Deposit
    want.approve(sett, MaxUint256, {"from": deployer})
    # sett.deposit(depositAmount, {"from": deployer});
    snap.settDeposit(depositAmount, {"from": deployer})

    assert want.balanceOf(sett) > 0
    print("want.balanceOf(sett)", want.balanceOf(sett))

    # Earn
    # sett.earn({"from": settKeeper});
    snap.settEarn({"from": settKeeper})

    # Harvest
    chain.sleep(hours(0.1))
    chain.mine()
    # strategy.harvest({"from": strategyKeeper})
    snap.settHarvest({"from": strategyKeeper})

    # Withdraw half
    # sett.withdraw(depositAmount // 2, {"from": deployer})
    snap.settWithdraw(depositAmount // 2, {"from": deployer})

    # KeepMinRatio to maintain collateralization safe enough from liquidation
    currentRatio = strategy.currentRatio()
    safeRatio = currentRatio + 20
    strategy.setMinRatio(safeRatio, {"from": governance})
    strategy.keepMinRatio({"from": governance})
    assert strategy.currentRatio() > safeRatio

    # sugar-daddy usdp discrepancy due to accrued interest in Unit Protocol
    debtTotal = strategy.getDebtBalance()
    curveGauge = interface.ICurveGauge(
        "0x055be5DDB7A925BfEF3417FC157f53CA77cA7222")
    usdp3crvInGauge = curveGauge.balanceOf(strategy)
    curvePool = interface.ICurveFi(
        "0x42d7025938bEc20B69cBae5A77421082407f053A")
    usdpOfPool = curvePool.calc_withdraw_one_coin(usdp3crvInGauge, 0)
    sugar = (debtTotal - usdpOfPool) * 2
    usdpToken = interface.IERC20("0x1456688345527bE1f37E9e627DA0837D6f08C925")
    if sugar > 0:
        usdpToken.transfer(strategy, sugar, {"from": deployer})
        print("sugar debt=", sugar)

    # Harvest again
    chain.sleep(hours(0.1))
    chain.mine()
    # strategy.harvest({"from": strategyKeeper})
    snap.settHarvest({"from": strategyKeeper})

    # Withdraw all
    wantInSettBalance = sett.getPricePerFullShare() * sett.totalSupply() / 1e18
    print("wantInSett=", wantInSettBalance)
    print("wantInStrategy=", strategy.balanceOfPool())
    print("pricePerFullShare=", sett.getPricePerFullShare())
    wantToWithdraw = sett.balanceOf(
        deployer) * sett.getPricePerFullShare() / 1e18
    print("wantToWithdraw=", wantToWithdraw)
    assert wantToWithdraw <= wantInSettBalance

    sugarWithdrawAll = (strategy.getDebtBalance() -
                        strategy.balanceOfPool()) * 2
    if sugarWithdrawAll > 0:
        usdpToken.transfer(strategy, sugarWithdrawAll, {"from": deployer})
        print("sugarWithdrawAll=", sugarWithdrawAll)

    renbtcToken = interface.IERC20(
        "0xEB4C2781e4ebA804CE9a9803C67d0893436bB27D")
    controller.withdrawAll(renbtcToken, {"from": deployer})

    # sett.withdrawAll({"from": deployer})
    snap.settWithdrawAll({"from": deployer})

    assert True
Example #22
0
def setup_badger(badger: BadgerSystem, settConfig):
    if rpc.is_active():
        seeder = accounts.at("0x3131B6964d96DE3Ad36C7Fe82e9bA9CcdBaf6baa",
                             force=True)
    else:
        seeder = accounts.load("badger_proxy_deployer")

    # Test Proxy Admin (owned by deployer)
    # badger.testProxyAdmin = deploy_proxy_admin(seeder)
    # badger.testProxyAdmin.transferOwnership(badger.deployer, {"from": seeder})

    badger.connect_test_proxy_admin(
        "testProxyAdmin", "0x58A3123f350A469eB4fCA01d8F6E857bc1F61b76")

    controller = badger.getController("native")
    console.print(controller)
    controller.initialize(seeder, badger.deployer, badger.keeper,
                          badger.deployer, {"from": seeder})

    assert badger.devProxyAdmin.getProxyAdmin(
        controller) == badger.devProxyAdmin

    # Strategy
    strategyLogic = badger.logic.StrategyPancakeLpOptimizer
    console.print("strategyLogic", strategyLogic)

    for key, vault in badger.sett_system.vaults.items():
        config = configs[key]
        console.print(key, vault, config)

        want = interface.IERC20(config["want"])

        vault.initialize(
            config["want"],
            controller,
            seeder,
            badger.keeper,
            badger.guardian,
            False,
            "",
            "",
            {"from": seeder},
        )

        controller.setVault(want, vault, {"from": seeder})
        # vault.setGovernance(badger.devMultisig, {"from": seeder})

        assert badger.devProxyAdmin.getProxyAdmin(
            vault) == badger.devProxyAdmin

    for key, strategy in badger.sett_system.strategies.items():
        config = configs[key]
        console.print(key, strategy, config)

        want = interface.IERC20(config["want"])

        assert badger.devProxyAdmin.getProxyAdmin(
            strategy) == badger.devProxyAdmin

        strategy.initialize(
            seeder,
            seeder,
            controller,
            badger.keeper,
            badger.guardian,
            [
                config["want"],
                config["token0"],
                config["token1"],
            ],
            [
                config["performanceFeeStrategist"],
                config["performanceFeeGovernance"],
                config["withdrawalFee"],
            ],
            config["wantPid"],
            {"from": seeder},
        )

        token0 = config["token0"]
        token1 = config["token1"]
        cake = registry.pancake.cake

        strategy.setTokenSwapPath(cake, token0, [cake, token0],
                                  {"from": seeder})
        strategy.setTokenSwapPath(cake, token1, [cake, token1],
                                  {"from": seeder})

        # Wiring
        console.print(controller.address, controller.governance())
        assert controller.governance() == seeder
        controller.approveStrategy(want, strategy, {"from": seeder})
        controller.setStrategy(want, strategy, {"from": seeder})
        strategy.setStrategist(badger.deployer, {"from": seeder})

        # controller.setGovernance(badger.devMultisig, {"from": seeder})

        badger.setStrategy(key, strategy)
        snap = SnapshotManager(badger, key)

        table = []

        table.append(["governance", strategy.governance()])
        table.append(["strategist", strategy.strategist()])
        table.append(["keeper", strategy.keeper()])
        table.append(["guardian", strategy.guardian()])
        table.append(["want", strategy.want()])
        table.append(["token0", strategy.token0()])
        table.append(["token1", strategy.token1()])
        table.append(["wantPid", strategy.wantPid()])
        table.append(
            ["performanceFeeGovernance",
             strategy.performanceFeeGovernance()])
        table.append(
            ["performanceFeeStrategist",
             strategy.performanceFeeStrategist()])
        table.append(["withdrawalFee", strategy.withdrawalFee()])
        table.append([
            "path0",
            strategy.getTokenSwapPath(registry.pancake.cake,
                                      strategy.token0()),
        ])
        table.append([
            "path1",
            strategy.getTokenSwapPath(registry.pancake.cake,
                                      strategy.token1()),
        ])

        print(tabulate(table, headers=["param", "value"]))
Example #23
0
def assert_migrate_single_user(settConfig):
    badger = badger_single_sett(settConfig)
    controller = badger.getController(settConfig["id"])
    sett = badger.getSett(settConfig["id"])
    strategy = badger.getStrategy(settConfig["id"])
    want = badger.getStrategyWant(settConfig["id"])
    strategyKeeper = accounts.at(strategy.keeper(), force=True)

    deployer = badger.deployer
    randomUser = accounts[6]

    snap = SnapshotManager(badger, settConfig["id"])

    startingBalance = want.balanceOf(deployer)
    depositAmount = startingBalance // 2
    assert startingBalance >= depositAmount

    # Deposit
    want.approve(sett, MaxUint256, {"from": deployer})
    snap.settDeposit(depositAmount, {"from": deployer})

    chain.sleep(15)
    chain.mine()

    sett.earn({"from": strategyKeeper})

    chain.snapshot()

    # Test no harvests
    chain.sleep(days(2))
    chain.mine()

    before = {
        "settWant": want.balanceOf(sett),
        "stratWant": strategy.balanceOf()
    }

    with brownie.reverts():
        controller.withdrawAll(strategy.want(), {"from": randomUser})

    controller.withdrawAll(strategy.want(), {"from": deployer})

    after = {
        "settWant": want.balanceOf(sett),
        "stratWant": strategy.balanceOf()
    }

    assert after["settWant"] > before["settWant"]
    assert after["stratWant"] < before["stratWant"]
    assert after["stratWant"] == 0

    # Test tend only
    if strategy.isTendable():
        chain.revert()

        chain.sleep(days(2))
        chain.mine()

        strategy.tend({"from": strategyKeeper})

        before = {
            "settWant": want.balanceOf(sett),
            "stratWant": strategy.balanceOf()
        }

        with brownie.reverts():
            controller.withdrawAll(strategy.want(), {"from": randomUser})

        controller.withdrawAll(strategy.want(), {"from": deployer})

        after = {
            "settWant": want.balanceOf(sett),
            "stratWant": strategy.balanceOf()
        }

        assert after["settWant"] > before["settWant"]
        assert after["stratWant"] < before["stratWant"]
        assert after["stratWant"] == 0

    # Test harvest, with tend if tendable
    chain.revert()

    chain.sleep(days(1))
    chain.mine()

    if strategy.isTendable():
        strategy.tend({"from": strategyKeeper})

    chain.sleep(days(1))
    chain.mine()

    before = {
        "settWant": want.balanceOf(sett),
        "stratWant": strategy.balanceOf(),
        "rewardsWant": want.balanceOf(controller.rewards()),
    }

    with brownie.reverts():
        controller.withdrawAll(strategy.want(), {"from": randomUser})

    controller.withdrawAll(strategy.want(), {"from": deployer})

    after = {
        "settWant": want.balanceOf(sett),
        "stratWant": strategy.balanceOf()
    }

    assert after["settWant"] > before["settWant"]
    assert after["stratWant"] < before["stratWant"]
    assert after["stratWant"] == 0
Example #24
0
def assert_single_user_harvest_flow_remove_fees(settConfig):
    suiteName = "assert_single_user_harvest_flow_remove_fees" + ": " + settConfig[
        "id"]

    badger = badger_single_sett(settConfig)
    controller = badger.getController(settConfig["id"])
    sett = badger.getSett(settConfig["id"])
    strategy = badger.getStrategy(settConfig["id"])
    want = badger.getStrategyWant(settConfig["id"])

    deployer = badger.deployer
    randomUser = accounts[6]

    snap = SnapshotManager(badger, settConfig["id"])

    tendable = strategy.isTendable()

    startingBalance = want.balanceOf(deployer)
    strategyKeeper = accounts.at(strategy.keeper(), force=True)

    depositAmount = Wei("1 ether")
    assert startingBalance >= depositAmount

    # Deposit
    want.approve(sett, MaxUint256, {"from": deployer})
    sett.deposit(depositAmount, {"from": deployer})

    # Earn
    sett.earn({"from": strategyKeeper})

    chain.sleep(days(0.5))
    chain.mine()

    if tendable:
        tx = snap.settTend({"from": strategyKeeper})

    chain.sleep(days(1))
    chain.mine()

    with brownie.reverts("onlyAuthorizedActors"):
        strategy.harvest({"from": randomUser})

    snap.settHarvest({"from": strategyKeeper})

    # Harvesting on the HarvestMetaFarm does not increase the underlying position, it sends rewards to the rewardsTree
    # For HarvestMetaFarm, we expect FARM rewards to be distributed to rewardsTree
    assert want.balanceOf(controller.rewards()) > 0

    chain.sleep(days(1))
    chain.mine()

    if tendable:
        tx = strategy.tend({"from": strategyKeeper})

    chain.sleep(days(3))
    chain.mine()

    tx = snap.settHarvest({"from": strategyKeeper})

    sett.withdrawAll({"from": deployer})

    endingBalance = want.balanceOf(deployer)

    report = {
        "time": "4 days",
        "gains": endingBalance - startingBalance,
        "gainsPercentage": (endingBalance - startingBalance) / startingBalance,
    }

    print(report)
Example #25
0
def assert_single_user_harvest_flow(settConfig):
    badger = badger_single_sett(settConfig)

    sett = badger.getSett(settConfig["id"])
    strategy = badger.getStrategy(settConfig["id"])
    want = badger.getStrategyWant(settConfig["id"])

    settKeeper = accounts.at(sett.keeper(), force=True)
    strategyKeeper = accounts.at(strategy.keeper(), force=True)

    snap = SnapshotManager(badger, settConfig["id"])

    deployer = badger.deployer
    randomUser = accounts[6]

    tendable = strategy.isTendable()

    startingBalance = want.balanceOf(deployer)

    depositAmount = startingBalance // 2
    assert startingBalance >= depositAmount
    assert startingBalance >= 0

    # Deposit
    want.approve(sett, MaxUint256, {"from": deployer})
    snap.settDeposit(depositAmount, {"from": deployer})

    assert want.balanceOf(sett) > 0
    print("want.balanceOf(sett)", want.balanceOf(sett))

    # Earn
    snap.settEarn({"from": settKeeper})

    if tendable:
        with brownie.reverts("onlyAuthorizedActors"):
            strategy.tend({"from": randomUser})

        snap.settTend({"from": strategyKeeper})

    chain.sleep(days(0.5))
    chain.mine()

    if tendable:
        snap.settTend({"from": strategyKeeper})

    chain.sleep(days(1))
    chain.mine()

    with brownie.reverts("onlyAuthorizedActors"):
        strategy.harvest({"from": randomUser})

    snap.settHarvest({"from": strategyKeeper})

    chain.sleep(days(1))
    chain.mine()

    if tendable:
        snap.settTend({"from": strategyKeeper})

    snap.settWithdraw(depositAmount // 2, {"from": deployer})

    chain.sleep(days(3))
    chain.mine()

    snap.settHarvest({"from": strategyKeeper})
    snap.settWithdraw(depositAmount // 2 - 1, {"from": deployer})
def harvest_all(badger: BadgerSystem, skip):
    for key, vault in badger.sett_system.vaults.items():
        if key in skip:
            continue

        console.print("\n[bold yellow]===== Harvest: " + str(key) + " =====[/bold yellow]\n")

        print("Harvest: " + key)

        snap = SnapshotManager(badger, key)
        strategy = badger.getStrategy(key)
        keeper = accounts.at(strategy.keeper())

        before = snap.snap()
        snap.printTable(before)
        snap.settHarvest({'from': keeper, "gas_price": gas_strategy, "gas_limit": 2000000, "allow_revert": True}, confirm=False)
        after = snap.snap()
        snap.printTable(after)

        snap.printCompare(before, after)
Example #27
0
def tend_all(badger: BadgerSystem, skip, min_profit=0):
    """
    Runs tend function for strategies if they are expected to be profitable.
    If a profit estimate fails for any reason the default behavior is to treat it as having a profit of zero.

    :param badger: badger system
    :param skip: strategies to skip checking
    :param min_profit: minimum estimated profit (in ETH or BNB) required for harvest to be executed on chain
    """
    table = []
    for key, vault in badger.sett_system.vaults.items():
        if key in skip:
            continue

        strategy = badger.getStrategy(key)

        if not strategy.isTendable():
            continue

        console.print("\n[bold green]===== Tend: " + key +
                      " =====[/bold green]\n")

        snap = SnapshotManager(badger, key)
        strategy = badger.getStrategy(key)

        before = snap.snap()

        if strategy.keeper() == badger.badgerRewardsManager:
            estimated_profit = snap.estimateProfitTendViaManager(
                key, strategy, {
                    "from": keeper,
                    "gas_limit": 1000000
                }, min_profit)
            if estimated_profit >= min_profit:
                snap.settTendViaManager(
                    strategy,
                    {
                        "from": keeper,
                        "gas_limit": 1000000
                    },
                    confirm=False,
                )
        else:
            keeper = accounts.at(strategy.keeper())
            estimated_profit = snap.estimateProfitTend(key, {
                "from": keeper,
                "gas_limit": 1000000
            }, min_profit)
            if estimated_profit >= min_profit:
                snap.settTend(
                    {
                        "from": keeper,
                        "gas_limit": 1000000
                    },
                    confirm=False,
                )

        tx_wait()

        if rpc.is_active():
            chain.mine()
        after = snap.snap()

        snap.printCompare(before, after)