Пример #1
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)
Пример #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")
        fpps_before = vault.getPricePerFullShare()

        keeper = accounts.at(strategy.keeper())
        strategy.tend({'from': keeper, "gas_price": gas_strategy})

        table.append([
            key,
            val(fpps_before),
            val(vault.getPricePerFullShare()),
            val(vault.getPricePerFullShare() - fpps_before),
        ])

        print("PPFS: Tend")
        print(tabulate(table, headers=["name", "before", "after", "diff"]))
Пример #3
0
def deploy_digg_native_sett(badger: BadgerSystem, digg):
    deployer = badger.deployer
    key = "native.digg"
    params = sett_config.native.badger.params
    params.want = digg.token

    rewards = badger.deploy_digg_rewards_faucet(key, digg.token)
    time.sleep(sleep_between_tx)

    params.geyser = rewards

    deploy_sett_by_key(
        badger,
        key,
        "StrategyDiggRewards",
        SettType.DIGG,
        params,
        deployer=deployer,
        governance=badger.devMultisig,
        strategist=badger.deployer,
        keeper=badger.keeper,
        guardian=badger.guardian,
    )

    strategy = badger.getStrategy(key)

    rewards.grantRole(PAUSER_ROLE, badger.keeper, {"from": deployer})
    rewards.grantRole(UNPAUSER_ROLE, badger.devMultisig, {"from": deployer})

    # Make strategy the recipient of the DIGG faucet
    rewards.initializeRecipient(strategy, {"from": deployer})
    def __init__(self, badger: BadgerSystem, key):
        self.badger = badger
        self.key = key
        self.sett = badger.getSett(key)
        self.strategy = badger.getStrategy(key)
        self.controller = Controller.at(self.sett.controller())
        self.want = interface.IERC20(self.sett.token())
        self.resolver = self.init_resolver(self.strategy.getName())
        self.snaps = {}
        self.settSnaps = {}
        self.entities = {}

        assert self.want == self.strategy.want()

        # Common entities for all strategies
        self.addEntity("sett", self.sett.address)
        self.addEntity("strategy", self.strategy.address)
        self.addEntity("controller", self.controller.address)
        self.addEntity("governance", self.strategy.governance())
        self.addEntity("governanceRewards", self.controller.rewards())
        self.addEntity("strategist", self.strategy.strategist())

        destinations = self.resolver.get_strategy_destinations()
        for key, dest in destinations.items():
            self.addEntity(key, dest)
Пример #5
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(vaultBefore, strategyBefore):
            print("Earn: " + key, vault, strategy)
            toEarn = True

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

            before = snap.snap()
            snap.printTable(before)

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

            after = snap.snap()
            snap.printTable(after)

            snap.printCompare(before, after)
Пример #6
0
def multisig_action(badger: BadgerSystem):
    multi = GnosisSafe(badger.opsMultisig)
    key = "native.bDiggBtcb"

    vault = badger.getSett(key)
    strategy = badger.getStrategy(key)

    multi.execute(
        MultisigTxMetadata(description="Set PoolId"),
        {"to": strategy.address, "data": strategy.setWantPid.encode_input(104)},
    )

    assert strategy.wantPid() == 104
Пример #7
0
def transfer_for_strategy(badger: BadgerSystem, key, amount, decimals=18):
    console.print("Transferring Amount for Strategy {}".format(key),
                  val(amount, decimals))
    manager = badger.badgerRewardsManager
    strategy = badger.getStrategy(key)

    before = snap_strategy_balance(badger, key, manager)

    transfer_for_strategy_internal(badger, key, amount)

    after = snap_strategy_balance(badger, key, manager)
    diff = diff_numbers_by_key(before, after)

    console.print("[green]==Transfer for {}==[/green]".format(key))
    to_tabulate("Diff {}".format(key), diff)
Пример #8
0
def swap_for_strategy(badger: BadgerSystem, key, amount):
    manager = badger.badgerRewardsManager
    print(key)
    strategy = badger.getStrategy(key)

    before = snap_strategy_balance(badger, key, manager)

    swap_for_strategy_internal(badger, key, amount)

    after = snap_strategy_balance(badger, key, manager)
    diff = diff_numbers_by_key(before, after)

    console.print("[green]==Swap for {}==[/green]".format(key))
    console.print("Amount", amount)
    to_tabulate("Diff {}".format(key), diff)
Пример #9
0
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})
    def __init__(
            self,
            badger: BadgerSystem,
            snap: SnapshotManager,
            settId: str,
            seed: int = 0,  # Default seed is 0 or unset, will generate.
    ):
        self.accounts = accounts[9:]  # Use the 10th account onwards.
        # User accounts (need to be provisioned before running sim).
        self.users = []

        self.debug = True

        self.badger = badger
        self.snap = snap
        self.sett = badger.getSett(settId)
        self.strategy = badger.getStrategy(settId)
        self.want = badger.getStrategyWant(settId)
        self.settKeeper = accounts.at(self.sett.keeper(), force=True)
        self.strategyKeeper = accounts.at(self.strategy.keeper(), force=True)

        # Actors generate valid actions based on the actor type. For example,
        # user actors need to have deposited first before they can withdraw
        # (withdraw before deposit is an invalid action).
        self.actors = [
            SettKeeperActor(self, self.settKeeper),
            StrategyKeeperActor(self, self.strategyKeeper),
            ChainActor(),
        ]
        if isinstance(snap, DiggSnapshotManager):
            self.actors.append(DiggActor(self, self.badger.deployer))
        # Ordered valid actions generated by actors.
        self.actions = []

        self.state = SimulationManagerState.IDLE

        # Track seed so we can configure this value if we want to repro test failures.
        self.seed = seed
        if self.seed == 0:
            self.seed = int(time.time())
        console.print(f"initialized simulation manager with seed: {self.seed}")
        random.seed(self.seed)
        console.print("Random Seed")
        self.provisioner = self._initProvisioner(settId)
        console.print("initialization complete")
Пример #11
0
def lp_for_strategy(badger: BadgerSystem, key):
    """
    Add maximum liquidity for associated strategy LP position
    """
    manager = badger.badgerRewardsManager
    strategy = badger.getStrategy(key)

    want = interface.IERC20(strategy.want())

    before = snap_strategy_balance(badger, key, manager)

    lp_for_strategy_internal(badger, key)

    after = snap_strategy_balance(badger, key, manager)
    diff = diff_numbers_by_key(before, after)

    console.print("[cyan]==LP for {}==[/cyan]".format(key))
    to_tabulate("Diff {}".format(key), diff)
Пример #12
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)
Пример #13
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(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)
Пример #14
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)
Пример #15
0
def snap_strategy_balance(badger: BadgerSystem, key, manager):
    digg = badger.digg

    strategy = badger.getStrategy(key)
    sett = badger.getSett(key)

    want = interface.IERC20(strategy.want())
    wbtc = interface.IERC20(registry.tokens.wbtc)

    state = {
        "manager (badger)": badger.token.balanceOf(manager),
        "manager (digg)": digg.token.balanceOf(manager),
        "manager (want)": want.balanceOf(manager),
        "manager (wbtc)": wbtc.balanceOf(manager),
        "balanceOfPool": strategy.balanceOfPool(),
        "balanceOfWant": strategy.balanceOfWant(),
        "balanceOf": strategy.balanceOf(),
        "pricePerFullShare": sett.getPricePerFullShare(),
    }
    return state
Пример #16
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()
                ),
            }
        )
Пример #17
0
def setup_badger(badger: BadgerSystem):
    # Set paths

    key = "native.bDiggBtcb"
    sett = badger.getSett(key)
    strategy = badger.getStrategy(key)

    multi = GnosisSafe(badger.opsMultisig)

    multi.execute(
        MultisigTxMetadata(description="Set path"),
        {
            "to":
            strategy.address,
            "data":
            strategy.setTokenSwapPath.encode_input(
                registry.pancake.cake,
                strategy.token0(),
                [
                    registry.pancake.cake, registry.tokens.btcb,
                    strategy.token0()
                ],
            ),
        },
    )

    multi.execute(
        MultisigTxMetadata(description="Set path"),
        {
            "to":
            strategy.address,
            "data":
            strategy.setTokenSwapPath.encode_input(
                registry.pancake.cake,
                strategy.token1(),
                [registry.pancake.cake, registry.tokens.btcb],
            ),
        },
    )
Пример #18
0
def setup_badger(badger: BadgerSystem):
    configs = {
        "native.pancakeBnbBtcb": {
            "want": registry.pancake.chefPairs.bnbBtcb,
            "token0": registry.tokens.btcb,
            "token1": registry.tokens.bnb,
            "performanceFeeStrategist": 1000,
            "performanceFeeGovernance": 1000,
            "withdrawalFee": 50,
            "wantPid": registry.pancake.chefPids.bnbBtcb,
        },
        "native.bBadgerBtcb": {
            "want": registry.pancake.chefPairs.bBadgerBtcb,
            "token0": registry.tokens.bBadger,
            "token1": registry.tokens.btcb,
            "performanceFeeStrategist": 1000,
            "performanceFeeGovernance": 1000,
            "withdrawalFee": 50,
            "wantPid": registry.pancake.chefPids.bBadgerBtcb,
        },
        "native.bDiggBtcb": {
            "want": registry.pancake.chefPairs.bDiggBtcb,
            "token0": registry.tokens.bDigg,
            "token1": registry.tokens.btcb,
            "performanceFeeStrategist": 1000,
            "performanceFeeGovernance": 1000,
            "withdrawalFee": 50,
            "wantPid": registry.pancake.chefPids.bDiggBtcb,
        },
    }

    # Set paths

    key = "native.bDiggBtcb"
    sett = badger.getSett(key)
    strategy = badger.getStrategy(key)

    multi = GnosisSafe(badger.opsMultisig)

    multi.execute(
        MultisigTxMetadata(description="Set path"),
        {
            "to":
            strategy.address,
            "data":
            strategy.setTokenSwapPath.encode_input(
                registry.pancake.cake,
                strategy.token0(),
                [
                    registry.pancake.cake, registry.tokens.btcb,
                    strategy.token0()
                ],
            ),
        },
    )

    multi.execute(
        MultisigTxMetadata(description="Set path"),
        {
            "to":
            strategy.address,
            "data":
            strategy.setTokenSwapPath.encode_input(
                registry.pancake.cake,
                strategy.token1(),
                [
                    registry.pancake.cake, registry.tokens.btcb,
                    strategy.token1()
                ],
            ),
        },
    )
Пример #19
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

        destination = get_expected_strategy_deposit_location(badger, key)

        vaultBefore = want.balanceOf(vault)
        destinationBefore = want.balanceOf(destination)
        strategyBefore = strategy.balanceOf()
        controllerBefore = want.balanceOf(controller)

        if vaultBefore == 0:
            print("No balance in Sett: ", key)
            continue

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

            keeper = accounts.at(vault.keeper())
            vault.earn({'from': keeper, "gas_price": gas_strategy})

        # Post safety for test run
        vaultAfter = want.balanceOf(vault)
        destinationAfter = want.balanceOf(destination)
        strategyAfter = strategy.balanceOf()
        controllerAfter = want.balanceOf(controller)

        table = []

        table.append([
            "vault",
            val(vaultBefore),
            val(vaultAfter),
            val(vaultAfter - vaultBefore)
        ])
        table.append([
            "destination",
            val(destinationBefore),
            val(destinationAfter),
            val(destinationAfter - destinationBefore),
        ])
        table.append([
            "strategy",
            val(strategyBefore),
            val(strategyAfter),
            val(strategyAfter - strategyBefore),
        ])
        table.append([
            "controller",
            val(controllerBefore),
            val(controllerAfter),
            val(controllerAfter - controllerBefore),
        ])

        print(tabulate(table, headers=["name", "before", "after", "diff"]))
        if toEarn:
            assert strategyAfter > strategyBefore
Пример #20
0
def post_deploy_config(badger: BadgerSystem):
    deployer = badger.deployer
    """
    Set initial conditions on immediate post-deploy Badger

    Transfer tokens to thier initial locations
        - Rewards Escrow (40%, minus tokens initially distributed via Sett Special StakingRewards)
        - Badger Hunt (15%)
        - DAO Timelock (35%)
        - Founder Rewards (10%)
    """

    # Approve BadgerTree to recieve rewards tokens
    print(deployer)
    print(badger.rewardsEscrow.owner())
    # badger.rewardsEscrow.approveRecipient(badger.badgerTree, {"from": deployer})

    # badger.rewardsEscrow.approveRecipient(
    #     badger.getGeyser("native.badger"), {"from": deployer}
    # )

    # badger.rewardsEscrow.approveRecipient(
    #     badger.getGeyser("native.uniBadgerWbtc"), {"from": deployer}
    # )

    # badger.rewardsEscrow.approveRecipient(
    #     badger.getGeyser("native.renCrv"), {"from": deployer}
    # )

    # badger.rewardsEscrow.approveRecipient(
    #     badger.getGeyser("native.sbtcCrv"), {"from": deployer}
    # )

    # badger.rewardsEscrow.approveRecipient(
    #     badger.getGeyser("native.tbtcCrv"), {"from": deployer}
    # )

    # badger.rewardsEscrow.approveRecipient(
    #     badger.getGeyser("harvest.renCrv"), {"from": deployer}
    # )

    # console.log("before signal locks", badger.token.balanceOf(deployer) / 1e18)

    # # Geyser Signals
    # """
    #     These signals are used to calculate the rewards distributions distributed via BadgerTree. The tokens are actually held in the RewardsEscrow and sent to the BadgerTree as needed.

    #     The escrow will only send a few days worth of rewards initially at a time to the RewardsTree as another failsafe mechanism.

    #     renbtcCRV — 76750 $BADGER
    #     sbtcCRV — 76,750 $BADGER
    #     tbtcCRV — 76,750 $BADGER
    #     Badger — 90,000 $BADGER / 2
    #         - 45000 in Sett StakingRewards
    #         - 45000 in Geyser
    #     Badger <>wBTC Uniswap LP — 130,000 $BADGER / 2
    #         - 65000 in Sett StakingRewards
    #         - 65000 in Geyser
    #     Super Sett
    #     Pickle renbtcCRV — 76,750 $BADGER
    #     Harvest renbtc CRV — 76,750 $BADGER
    # """

    # badger.signal_token_lock(
    #     "native.badger", badger_config.geyserParams.unlockSchedules.badger[0]
    # )

    # badger.signal_token_lock(
    #     "native.uniBadgerWbtc",
    #     badger_config.geyserParams.unlockSchedules.uniBadgerWbtc[0],
    # )

    # badger.signal_token_lock(
    #     "native.renCrv", badger_config.geyserParams.unlockSchedules.bRenCrv[0]
    # )

    # badger.signal_token_lock(
    #     "native.sbtcCrv", badger_config.geyserParams.unlockSchedules.bSbtcCrv[0]
    # )

    # badger.signal_token_lock(
    #     "native.tbtcCrv", badger_config.geyserParams.unlockSchedules.bTbtcCrv[0]
    # )

    # badger.signal_token_lock(
    #     "harvest.renCrv",
    #     badger_config.geyserParams.unlockSchedules.bSuperRenCrvHarvest[0],
    # )

    # console.log(
    #     "before initial token distribution", badger.token.balanceOf(deployer) / 1e18
    # )

    # ===== Initial Token Distribution =====
    # == Native Badger ==
    rewards = badger.getSettRewards("native.badger")
    strategy = badger.getStrategy("native.badger")

    badger.distribute_staking_rewards(
        "native.badger",
        badger_config.geyserParams.unlockSchedules.badger[0].amount,
        notify=False,
    )
    rewards.grantRole(APPROVED_STAKER_ROLE, strategy, {"from": deployer})

    # == Uni LP ==
    rewards = badger.getSettRewards("native.uniBadgerWbtc")
    strategy = badger.getStrategy("native.uniBadgerWbtc")

    badger.distribute_staking_rewards(
        "native.uniBadgerWbtc",
        badger_config.geyserParams.unlockSchedules.uniBadgerWbtc[0].amount,
        notify=False,
    )
    rewards.grantRole(APPROVED_STAKER_ROLE, strategy, {"from": deployer})

    console.log(
        "remaining after special pool distributions",
        badger.token.balanceOf(deployer) / 1e18,
    )

    distributedToPools = (
        badger_config.geyserParams.unlockSchedules.badger[0].amount +
        badger_config.geyserParams.unlockSchedules.uniBadgerWbtc[0].amount)

    # print(
    #     badger_config.geyserParams.unlockSchedules.badger[0],
    #     badger_config.geyserParams.unlockSchedules.uniBadgerWbtc[0],
    #     badger_config.geyserParams.unlockSchedules.bRenCrv[0],
    #     badger_config.geyserParams.unlockSchedules.bSbtcCrv[0],
    #     badger_config.geyserParams.unlockSchedules.bTbtcCrv[0],
    #     badger_config.geyserParams.unlockSchedules.bSuperRenCrvHarvest[0]
    # )

    supplyForWeek1Rewards = (
        badger_config.geyserParams.unlockSchedules.badger[0].amount +
        badger_config.geyserParams.unlockSchedules.uniBadgerWbtc[0].amount +
        badger_config.geyserParams.unlockSchedules.bRenCrv[0].amount +
        badger_config.geyserParams.unlockSchedules.bSbtcCrv[0].amount +
        badger_config.geyserParams.unlockSchedules.bTbtcCrv[0].amount +
        badger_config.geyserParams.unlockSchedules.bSuperRenCrvHarvest[0].
        amount)

    toEscrow = (badger_config.rewardsEscrowBadgerAmount - distributedToPools -
                supplyForWeek1Rewards)

    badger.initialRewardsEscrowBalance = toEscrow
    badger.initialBadgerTreeBalance = supplyForWeek1Rewards

    console.log(locals(), badger_config.rewardsEscrowBadgerAmount)

    # == Badger Hunt ==
    badger.token.transfer(
        badger.badgerHunt,
        badger_config.huntParams.badgerAmount,
        {"from": deployer},
    )

    # == Badger Tree ==
    badger.token.transfer(
        badger.badgerTree,
        supplyForWeek1Rewards,
        {"from": deployer},
    )

    # == Rewards Escrow ==
    badger.token.transfer(
        badger.rewardsEscrow,
        toEscrow,
        {"from": deployer},
    )

    # == DAO Timelock ==
    badger.token.transfer(
        badger.daoBadgerTimelock,
        badger_config.tokenLockParams.badgerLockAmount,
        {"from": deployer},
    )

    console.log("after daoBadgerTimelock",
                badger.token.balanceOf(deployer) / 1e18)

    # == Team Vesting ==
    badger.token.transfer(badger.teamVesting,
                          badger_config.founderRewardsAmount,
                          {"from": deployer})

    tokenDistributionTargets = {
        "deployer":
        0,
        "rewardsEscrow":
        toEscrow,
        "native.badger Pool":
        badger_config.geyserParams.unlockSchedules.badger[0].amount,
        "native.uniBadgerWbtc Pool":
        badger_config.geyserParams.unlockSchedules.uniBadgerWbtc[0].amount,
        "native.badger geyser":
        badger_config.geyserParams.unlockSchedules.badger[0].amount,
        "native.uniBadgerWbtc geyser":
        badger_config.geyserParams.unlockSchedules.uniBadgerWbtc[0].amount,
        "native.renCrv geyser":
        badger_config.geyserParams.unlockSchedules.bRenCrv[0].amount,
        "native.sbtcCrv geyser":
        badger_config.geyserParams.unlockSchedules.bSbtcCrv[0].amount,
        "native.tbtcCrv geyser":
        badger_config.geyserParams.unlockSchedules.bTbtcCrv[0].amount,
        "harvest.renCrv geyser":
        badger_config.geyserParams.unlockSchedules.bSuperRenCrvHarvest[0].
        amount,
        "daoBadgerTimelock":
        badger_config.tokenLockParams.badgerLockAmount,
        "teamVesting":
        badger_config.founderRewardsAmount,
        "badgerHunt":
        badger_config.huntParams.badgerAmount,
        "badgerTree":
        0,
    }

    tokenDistributionBalances = {
        "deployer":
        badger.token.balanceOf(deployer),
        "rewardsEscrow":
        badger.token.balanceOf(badger.rewardsEscrow),
        "native.badger Pool":
        badger.token.balanceOf(badger.getSettRewards("native.badger")),
        "native.uniBadgerWbtc Pool":
        badger.token.balanceOf(badger.getSettRewards("native.uniBadgerWbtc")),
        "native.badger geyser":
        badger.token.balanceOf(badger.getGeyser("native.badger")),
        "native.uniBadgerWbtc geyser":
        badger.token.balanceOf(badger.getGeyser("native.uniBadgerWbtc")),
        "native.renCrv geyser":
        badger.token.balanceOf(badger.getGeyser("native.renCrv")),
        "native.sbtcCrv geyser":
        badger.token.balanceOf(badger.getGeyser("native.sbtcCrv")),
        "native.tbtcCrv geyser":
        badger.token.balanceOf(badger.getGeyser("native.tbtcCrv")),
        "harvest.renCrv geyser":
        badger.token.balanceOf(badger.getGeyser("harvest.renCrv")),
        "daoBadgerTimelock":
        badger.token.balanceOf(badger.daoBadgerTimelock),
        "teamVesting":
        badger.token.balanceOf(badger.teamVesting),
        "badgerHunt":
        badger.token.balanceOf(badger.badgerHunt),
        "badgerTree":
        badger.initialBadgerTreeBalance,
    }

    if not badger.test:
        expectedSum = 0
        actualSum = 0
        for key, value in tokenDistributionTargets.items():
            print("expected", key, value / 1e18)
            print("actual", key, tokenDistributionBalances[key] / 1e18)
            expectedSum += value
            actualSum += tokenDistributionBalances[key]

        print("expectedSum", expectedSum / 1e18)
        print("actualSum", actualSum / 1e18)

        # assert expectedSum == badger_total_supply
        # assert actualSum == badger_total_supply

    console.log("after teamVesting", badger.token.balanceOf(deployer) / 1e18)
    """
    ===== Transfer Ownership =====
    - proxyAdmin should be owned by multisig
    - All contract owner / admin rights should be given to multisig
    """

    badger.rewardsEscrow.transferOwnership(badger.devMultisig,
                                           {"from": deployer})
Пример #21
0
def confirm_setup_sett(badger: BadgerSystem):
    common_controller_params = DotMap(
        governance=badger.deployer,
        strategist=badger.deployer,
        keeper=badger.keeper,
        onesplit=registry.onesplit.contract,
        rewards=badger.dao.agent,
    )

    # ===== Confirm Controller =====

    # Native Controller
    params = common_controller_params

    params.setts = [
        [
            badger.token,
            badger.getSett("native.badger"),
            badger.getStrategy("native.badger"),
        ],
        [
            registry.curve.pools.sbtcCrv.token,
            badger.getSett("native.sbtcCrv"),
            badger.getStrategy("native.sbtcCrv"),
        ],
        [
            registry.curve.pools.renCrv.token,
            badger.getSett("native.renCrv"),
            badger.getStrategy("native.renCrv"),
        ],
        [
            registry.curve.pools.tbtcCrv.token,
            badger.getSett("native.tbtcCrv"),
            badger.getStrategy("native.tbtcCrv"),
        ],
    ]
    print(badger.getStrategy("native.tbtcCrv"))
    confirm_controller_params(badger.getController("native"), params)

    # Harvest Controller
    params = common_controller_params
    params.setts = [[
        registry.curve.pools.renCrv.token,
        badger.getSett("harvest.renCrv"),
        badger.getStrategy("harvest.renCrv"),
    ]]
    confirm_controller_params(badger.getController("harvest"), params)

    # ===== Confirm Setts =====

    # Native Setts
    # TODO: Change governance and strategist to prod values
    common_native_sett_params = DotMap(
        governance=badger.deployer,
        strategist=AddressZero,
        keeper=badger.deployer,
        controller=badger.getController("native"),
        min=9500,
    )

    params = common_native_sett_params
    params.token = badger.token
    params.name = "Badger Sett Badger"
    params.symbol = "bBADGER"
    # params.name = "Badger Sett BadgerTest"
    # params.symbol = "bBGTEST"
    confirm_sett_params(badger.getSett("native.badger"), params)

    params = common_native_sett_params
    params.token = registry.curve.pools.sbtcCrv.token
    params.name = "Badger Sett Curve.fi renBTC/wBTC/sBTC"
    params.symbol = "bcrvRenWSBTC"
    confirm_sett_params(badger.getSett("native.sbtcCrv"), params)

    params = common_native_sett_params
    params.token = registry.curve.pools.renCrv.token
    params.name = "Badger Sett Curve.fi renBTC/wBTC"
    params.symbol = "bcrvRenWBTC"
    confirm_sett_params(badger.getSett("native.renCrv"), params)

    params = common_native_sett_params
    params.token = registry.curve.pools.tbtcCrv.token
    params.name = "Badger Sett Curve.fi tBTC/sbtcCrv"
    params.symbol = "btbtc/sbtcCrv"
    confirm_sett_params(badger.getSett("native.tbtcCrv"), params)

    # Harvest Setts
    harvest_sett_params = DotMap(
        governance=badger.deployer,
        strategist=AddressZero,
        keeper=badger.deployer,
        controller=badger.getController("harvest"),
        min=9500,
        token=registry.curve.pools.renCrv.token,
        name="Badger SuperSett (Harvest) Curve.fi renBTC/wBTC",
        symbol="bSupercrvRenWBTC",
    )
    confirm_sett_params(badger.getSett("harvest.renCrv"), harvest_sett_params)

    # ===== Confirm Strategies =====

    common_strategy_params = DotMap(
        governance=badger.deployer,
        strategist=badger.deployer,
        keeper=badger.keeper,
        controller=badger.getController("native"),
        guardian=badger.guardian,
        performanceFeeGovernance=1000,
        performanceFeeStrategist=1000,
        withdrawalFee=75,
    )

    # ===== Native Strategies =====

    # == Badger Native ==
    params = common_strategy_params
    params.name = "StrategyBadgerRewards"
    params.want = badger.token
    params.performanceFeeGovernance = 0
    params.performanceFeeStrategist = 0
    params.withdrawalFee = 0

    confirm_strategy_common_params(badger.getStrategy("native.badger"), params)

    confirm_strategy_badger_rewards_params(
        badger.getStrategy("native.badger"),
        DotMap(geyser=badger.getSettRewards("native.badger")),
    )

    # == Badger LP ==
    params = common_strategy_params
    params.name = "StrategyBadgerLpMetaFarm"
    params.want = badger.pair
    params.performanceFeeGovernance = 0
    params.performanceFeeStrategist = 0
    params.withdrawalFee = 0

    confirm_strategy_common_params(badger.getStrategy("native.uniBadgerWbtc"),
                                   params)

    confirm_strategy_badger_rewards_params(
        badger.getStrategy("native.uniBadgerWbtc"),
        DotMap(geyser=badger.getSettRewards("native.uniBadgerWbtc")),
    )

    # == Native SbtcCrv ==
    params = common_strategy_params
    params.name = "StrategyCurveGauge"
    params.want = registry.curve.pools.sbtcCrv.token
    params.performanceFeeGovernance = 1000
    params.performanceFeeStrategist = 1000
    params.withdrawalFee = 75

    confirm_strategy_common_params(badger.getStrategy("native.sbtcCrv"),
                                   params)

    params = common_strategy_params
    params.name = "StrategyCurveGauge"
    params.want = registry.curve.pools.renCrv.token
    params.performanceFeeGovernance = 1000
    params.performanceFeeStrategist = 1000
    params.withdrawalFee = 75

    confirm_strategy_common_params(badger.getStrategy("native.renCrv"), params)

    params = common_strategy_params
    params.name = "StrategyCurveGauge"
    params.want = registry.curve.pools.tbtcCrv.token
    params.performanceFeeGovernance = 1000
    params.performanceFeeStrategist = 1000
    params.withdrawalFee = 75

    confirm_strategy_common_params(badger.getStrategy("native.tbtcCrv"),
                                   params)

    # Harvest Strategies
    params.name = "StrategyHarvestMetaFarm"
    params.controller = badger.getController("harvest")
    params.want = registry.curve.pools.renCrv.token
    params.performanceFeeGovernance = 0
    params.performanceFeeStrategist = 0
    params.farmPerformanceFeeGovernance = 1000
    params.farmPerformanceFeeStrategist = 1000
    params.withdrawalFee = 75
    params.harvestVault = registry.harvest.vaults.renCrv
    params.vaultFarm = registry.harvest.farms.fRenCrv
    params.metaFarm = registry.harvest.farms.farm
    params.badgerTree = badger.badgerTree

    confirm_strategy_common_params(badger.getStrategy("harvest.renCrv"),
                                   params)
    confirm_strategy_harvest_meta_farm_params(
        badger.getStrategy("harvest.renCrv"), params)
    """
    def confirm_strategy_harvest_meta_farm_params(strategy, params):
    assert strategy.harvestVault() == params.harvestVault
    assert strategy.vaultFarm() == params.vaultFarm
    assert strategy.metaFarm() == params.metaFarm
    assert strategy.badgerTree() == params.badgerTree

    assert strategy.farm() == registry.harvest.farmToken
    assert strategy.depositHelper() == registry.harvest.depositHelper
    assert strategy.weth() == registry.tokens.weth

    assert (
        strategy.farmPerformanceFeeGovernance() == params.farmPerformanceFeeGovernance
    )
    assert (
        strategy.farmPerformanceFeeStrategist() == params.farmPerformanceFeeStrategist
    )
    """

    # Supporting Infrastructure: Rewards
    confirm_staking_rewards_params(
        badger.getSettRewards("native.badger"),
        DotMap(approvedStaker=badger.getStrategy("native.badger")),
    )

    confirm_staking_rewards_params(
        badger.getSettRewards("native.uniBadgerWbtc"),
        DotMap(approvedStaker=badger.getStrategy("native.uniBadgerWbtc")),
    )
Пример #22
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)
Пример #23
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