def main():
    um = interface.UnslashedMarket(
        '0x746d94f1161C991675Ede99aBCDb0412a4fEE43E')
    ut = interface.ERC20('0x2B76f72BFFcBE386EE6BD5F801f24f472dc9f633')
    agent = accounts.at('0x3e40d73eb977dc6a537af587d48316fee66e9c8c',
                        force=True)
    premium_balance_before = ut.balanceOf(agent.address)
    StETH = interface.ERC20('0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84')
    curve_pool = '0xDC24316b9AE028F1497c275EB9192a3Ea0f67022'
    agent_steth_balance = StETH.balanceOf(agent.address)
    # get all the ETH we can from the insurance fund's StETH
    # we won't do this in the real purchase tx, it's for the ease of calc for now
    StETH.approve(curve_pool, agent_steth_balance, {'from': agent})
    interface.StableSwapSTETH(curve_pool).exchange(1, 0, agent_steth_balance,
                                                   0.9 * agent_steth_balance,
                                                   {'from': agent})

    DESIRED_AMOUNT_COVERED = 400000
    CURRENT_AMOUNT_COVERED = 196749

    deposit_delta = um.coverToPremiumTokens(
        (DESIRED_AMOUNT_COVERED - CURRENT_AMOUNT_COVERED) *
        0.05) * um.premiumTokenPrice18eRatio()

    print("ETH required to make deposit: ", deposit_delta / 1e18)

    um.depositPremium({'from': agent, 'value': deposit_delta})

    premium_balance_after = ut.balanceOf(agent.address)
    print("Premium tokens delta: ",
          (premium_balance_after - premium_balance_before) / 1e18)
    print("Premium tokens balance after: ", (premium_balance_after) / 1e18)
def main():
    dao_voting = interface.Voting("0x2e59A20f205bB85a89C53f1936454680651E618e")
    dao_agent = interface.Agent("0x3e40D73EB977Dc6a537aF587D48316feE66E9C8c")

    unslashed_token = interface.ERC20(
        "0x2B76f72BFFcBE386EE6BD5F801f24f472dc9f633")
    steth_token = interface.ERC20("0xae7ab96520de3a18e5e111b5eaab095312d7fe84")
    ldo_token = interface.ERC20("0x5A98FcBEA516Cf06857215779Fd812CA3beF1B32")

    vote_id = 44

    eth_before = dao_agent.balance()
    unslashed_token_before = unslashed_token.balanceOf(dao_agent)
    steth_token_before = steth_token.balanceOf(dao_agent)
    ldo_token_before = ldo_token.balanceOf(dao_agent)

    print()
    print('Lido DAO agent balances before the vote execution')
    print_value('ETH:                          ', eth_before)
    print_value('Unslashed Lido Premium token: ', unslashed_token_before)
    print_value('stETH:                        ', steth_token_before)
    print_value('LDO:                          ', ldo_token_before)
    print()

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

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

    eth_after = dao_agent.balance()
    unslashed_token_after = unslashed_token.balanceOf(dao_agent)
    steth_token_after = steth_token.balanceOf(dao_agent)
    ldo_token_after = ldo_token.balanceOf(dao_agent)

    print()
    print('Lido DAO agent balances after the vote execution')
    print_value('ETH:                          ', eth_after)
    print_value('Unslashed Lido Premium token: ', unslashed_token_after)
    print_value('stETH:                        ', steth_token_after)
    print_value('LDO:                          ', ldo_token_after)
    print()

    eth_delta = eth_after - eth_before
    unslashed_token_delta = unslashed_token_after - unslashed_token_before
    steth_token_delta = steth_token_after - steth_token_before
    ldo_token_delta = ldo_token_after - ldo_token_before

    print()
    print('Lido DAO agent balances deltas')
    print_delta('ETH:                          ', eth_delta)
    print_delta('Unslashed Lido Premium token: ', unslashed_token_delta)
    print_delta('stETH:                        ', steth_token_delta)
    print_delta('LDO:                          ', ldo_token_delta)
    print()
예제 #3
0
def price_direct(token_in, token_out):
    """
    Calculate a price based on Uniswap Pair reserves.
    Only supports direct pairs.
    """
    pair = interface.UniswapPair(factory.getPair(token_in, token_out))
    reserves = dict(zip([pair.token0(), pair.token1()], pair.getReserves()))
    reserves_in = reserves[token_in] / 10 ** interface.ERC20(token_in).decimals()
    reserves_out = reserves[token_out] / 10 ** interface.ERC20(token_out).decimals()
    return reserves_out / reserves_in
예제 #4
0
def price_router(token_in, token_out):
    """
    Calculate a price based on Uniswap Router quote for selling one `token_in`.
    Always uses intermediate WETH pair.
    """
    amount_in = 10**interface.ERC20(token_in).decimals()
    path = [token_in, token_out
            ] if weth in (token_in,
                          token_out) else [token_in, weth, token_out]
    quote = router.getAmountsOut(amount_in, path)
    amount_out = quote[-1] / 10**interface.ERC20(token_out).decimals()
    return amount_out
예제 #5
0
def main():
    lido = interface.Lido(steth_token_address)
    lido.submit(ZERO_ADDRESS, {"from": accounts[2], "value": "10 ether"})
    lido.submit(ZERO_ADDRESS, {"from": accounts[3], "value": "10 ether"})

    steth_token = interface.ERC20(steth_token_address)
    steth_token.transfer(accounts[0], Wei("10 ether"), {"from": accounts[2]})
    steth_token.transfer(accounts[0], Wei("10 ether"), {"from": accounts[3]})

    ldo_token = interface.ERC20(ldo_token_address)
    ldo_whale = accounts.at("0x454f11d58e27858926d7a4ece8bfea2c33e97b13",
                            force=True)
    ldo_token.transfer(accounts[0], Wei("50000 ether"), {"from": ldo_whale})
예제 #6
0
def main():
    tree = json.load(open("snapshot/02-merkle.json"))
    whale = accounts.at("0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7", force=True)
    dai = interface.ERC20("0x6B175474E89094C44Da98b954EedeAC495271d0F", owner=whale)
    pytho = Pytho.deploy("Pytho", "PYTHO", tree["tokenTotal"], {"from": whale})
    distributor = MerkleDistributor.deploy(pytho, tree["merkleRoot"], {"from": whale})
    pytho.transfer(distributor, tree["tokenTotal"])
    # the hacker sends everything back
    dai.transfer(pytho, tree["tokenTotal"])

    for user, claim in tree["claims"].items():
        distributor.claim(claim["index"], user, claim["amount"], claim["proof"])
        assert pytho.balanceOf(user) == claim["amount"]
        print("remaining in distributor:", pytho.balanceOf(distributor).to("ether"))
    assert pytho.balanceOf(distributor) == 0

    for user in tree["claims"]:
        user = accounts.at(user, force=True)
        amount = pytho.balanceOf(user)
        before = dai.balanceOf(user)
        assert pytho.rate() == "1 ether"
        pytho.burn(amount, {"from": user})
        assert pytho.balanceOf(user) == 0
        assert dai.balanceOf(user) == before + amount
        print("rate:", pytho.rate().to("ether"))
        print("remaining supply:", pytho.totalSupply().to("ether"))
        print("remaining dai:", dai.balanceOf(pytho).to("ether"))

    assert dai.balanceOf(pytho) == 0
    assert pytho.totalSupply() == 0
def main():
    agent = accounts.at('0x3e40d73eb977dc6a537af587d48316fee66e9c8c',
                        force=True)
    eth_spent = 0

    for cover in unslashed_covers:
        print("Calc cover for ", cover["policy_name"])
        eth_to_cover = cover["damage_eth_covered"]
        um = interface.UnslashedMarket(cover["marketAddress"])
        ut = interface.ERC20(cover["premiumToken"])

        deposit_delta = um.coverToPremiumTokens(
            eth_to_cover * 1e18) * um.premiumTokenPrice18eRatio() / 1e18

        print("Cover for", eth_to_cover * 0.05, " ETH")
        print("ETH required to make deposit: ", deposit_delta / 1e18)

        premium_balance_before = ut.balanceOf(agent.address)
        um.depositPremium({'from': agent, 'value': deposit_delta})
        premium_balance_after = ut.balanceOf(agent.address)
        print("Premium tokens delta: ",
              (premium_balance_after - premium_balance_before) / 1e18)
        print("Premium tokens balance after: ", (premium_balance_after) / 1e18)
        # print("To address", cover["marketAddress"])
        print("ETH amount", Wei(deposit_delta), deposit_delta / 1e18)
        # print("Premium tokens contract", cover["premiumToken"])
        # print("Premium tokens received", Eth(ut.balanceOf("0xD089cc83f5B803993E266ACEB929e52A993Ca2C8")))
        eth_spent += deposit_delta

    print("total ETH spent", eth_spent / 1e18)
예제 #8
0
def main():
    account = None
    if network.show_active() in ["mainnet-fork"]:
        account = accounts.at(myWalletAddress, force=True)
    elif network.show_active() in ["mainnet"]:
        account = accounts.load("maindev")

    # Set the gas price
    network.gas_price("120 gwei")
    network.gas_limit("auto")

    # Deploy/Get contract
    #bountyHunter = BountyHunter.deploy({"from":account})
    bountyHunter = BountyHunter.at(BOUNTY_HUNTER_ADDRESS)

    print("My wallet eth amount before claim: " + str(account.balance()))

    print("Claiming bounty...")
    bountyHunter.claimBounty({"from": account, "value": ETH_TO_SELL})

    print("Amount of Eth required: " + str(ETH_TO_SELL - bountyHunter.balance()))

    # print("The amount of Eth needed to buy back UNI tokens: " + str(200000000000000000 - bountyHunter.balance()))
    print("My wallet eth amount after claim: " + str(account.balance()))
    uniToken = interface.ERC20(UNI_TOKEN_ADDRESS)
    print("My wallet uni amount after claim: " + str(uniToken.balanceOf(myWalletAddress)))
예제 #9
0
def main():
    tree = json.load(open("snapshot/04-merkle.json"))
    whale = accounts.at("0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7",
                        force=True)
    dai = interface.ERC20("0x6B175474E89094C44Da98b954EedeAC495271d0F",
                          owner=whale)
    corn = Cornichon.at('0xa456b515303B2Ce344E9d2601f91270f8c2Fea5E',
                        owner=whale)
    distributor = MerkleDistributor.at(
        '0x8896C47Cf854644cDC4Dd949a11048a57bDBA9Bc', owner=whale)
    # a hacker sends everything back
    dai.transfer(corn, tree["tokenTotal"])

    for user, claim in tree["claims"].items():
        distributor.claim(claim["index"], user, claim["amount"],
                          claim["proof"])
        assert corn.balanceOf(user) == claim["amount"]
        print("remaining in distributor:",
              corn.balanceOf(distributor).to("ether"))
    assert corn.balanceOf(distributor) == 0

    for user in tree["claims"]:
        user = accounts.at(user, force=True)
        amount = corn.balanceOf(user)
        before = dai.balanceOf(user)
        assert corn.rate() == "1 ether"
        corn.burn(amount, {"from": user})
        assert corn.balanceOf(user) == 0
        assert dai.balanceOf(user) == before + amount
        print("rate:", corn.rate().to("ether"))
        print("remaining supply:", corn.totalSupply().to("ether"))
        print("remaining dai:", dai.balanceOf(corn).to("ether"))

    assert dai.balanceOf(corn) == 0
    assert corn.totalSupply() == 0
예제 #10
0
def main():
    tree = json.load(open("snapshot/02-merkle.json"))
    whale = accounts.at("0x70178102aa04c5f0e54315aa958601ec9b7a4e08",
                        force=True)
    dai = interface.ERC20("0x6B175474E89094C44Da98b954EedeAC495271d0F",
                          owner=whale)
    piou = PercentIOU.at('0x4De840147DB6d0655917f43dA8a2e86c26AaFB0a',
                         owner=whale)
    distributor = MerkleDistributor.at(
        '0xA742Ce2E4426290017ab165b0F7d8Ab131E4a9f5', owner=whale)
    # a hacker sends everything back
    dai.transfer(piou, tree["tokenTotal"])

    for user, claim in tree["claims"].items():
        distributor.claim(claim["index"], user, claim["amount"],
                          claim["proof"])
        assert piou.balanceOf(user) == claim["amount"]
        print("remaining in distributor:",
              piou.balanceOf(distributor).to("ether"))
    assert piou.balanceOf(distributor) == 0

    for user in tree["claims"]:
        user = accounts.at(user, force=True)
        amount = piou.balanceOf(user)
        before = dai.balanceOf(user)
        assert piou.rate() == "1 ether"
        piou.burn(amount, {"from": user})
        assert piou.balanceOf(user) == 0
        assert dai.balanceOf(user) == before + amount
        print("rate:", piou.rate().to("ether"))
        print("remaining supply:", piou.totalSupply().to("ether"))
        print("remaining dai:", dai.balanceOf(piou).to("ether"))

    assert dai.balanceOf(piou) == 0
    assert piou.totalSupply() == 0
예제 #11
0
def token_price(token):
    # stablecoin => 1
    if str(token) in STABLECOINS:
        return 1
    # eth => weth
    if token == '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE':
        token = weth
    # yearn vault => underlying price * price per share
    if str(token) in VAULT_ALIASES:
        token = interface.yVault(token)
        underlying, share_price = fetch_multicall(
            [token, 'token'],
            [token, 'getPricePerFullShare'],
        )
        return token_price(underlying) * share_price / 1e18
    # curve lp => first component price * virtual price
    if curve.is_curve_lp_token(token):
        return curve.get_base_price(token) * curve.get_virtual_price(token)
    # compound ctoken => underlying price * exchange rate
    if is_compound_market(token):
        token = interface.CErc20(token)
        underlying, exchange_rate, decimals = fetch_multicall(
            [token, 'underlying'],
            [token, 'exchangeRateCurrent'],
            [token, 'decimals'],
        )
        exchange_rate /= 1e18
        under_decimals = interface.ERC20(underlying).decimals()
        return token_price(underlying) * exchange_rate * 10**(decimals -
                                                              under_decimals)
    # uniswap or sushi lp => share of reserves
    if is_uniswap_pool(token):
        return uniswap_lp_price(token)
    # try to get quote from sushiswap or uniswap
    return price_router(token)
예제 #12
0
def main():
    with open('snapshot/07-merkle-distribution.json') as fp:
        tree = json.load(fp)

    ychad = accounts.at("0xFEB4acf3df3cDEA7399794D0869ef76A6EfAff52")

    dai = interface.ERC20('0x6B175474E89094C44Da98b954EedeAC495271d0F')
    distributor = MerkleDistributor.deploy(dai, tree['merkleRoot'],
                                           {'from': ychad})

    dai.transfer(distributor, tree['tokenTotal'], {'from': ychad})

    for i, (address, claim) in enumerate(tree['claims'].items()):
        if not i % 50:
            print(f"Distribution in progress, {i} / {len(tree['claims'])}...")

        balance = dai.balanceOf(address)
        distributor.claim(claim['index'], address, claim['amount'],
                          claim['proof'], 0, {'from': ychad})

        assert dai.balanceOf(address) == balance + claim['amount']

    assert dai.balanceOf(distributor) == 0

    print("Distribution was successful!")
예제 #13
0
def main():
    dai = interface.ERC20('0x6b175474e89094c44da98b954eedeac495271d0f')
    old_strategy = YearnDaiCompStratV2.at(
        '0x5b62F24581Ea4bc6d6C5C101DD2Ae7233E422884')
    live_strategy = YearnDaiCompStratV2.at(
        '0x4C6e9d7E5d69429100Fcc8afB25Ea980065e2773')
    vault = Vault.at('0x9B142C2CDAb89941E9dcd0B6C1cf6dEa378A8D7C')

    print(f'strategy YearnDaiCompStratV2: {live_strategy.address}')
    print(f'Vault: {vault.address}')
    print(f'Vault name: {vault.name()} and symbol: {vault.symbol()}')
    strategist_confirmed = live_strategy.strategist()
    print(f'Strategy strategist: {strategist_confirmed}')

    account_name = input(f"What account to use?: ")
    dev = accounts.load(account_name)
    print(f"You are using: 'dev' [{dev.address}]")
    devDai = dai.balanceOf(dev).to('ether')
    print(f"You're DAI balance is: [{devDai}]")
    are_you_strategist = strategist_confirmed == dev.address
    print(f"Are you strategist? {are_you_strategist}")

    if input("Continue? y/[N]: ").lower() != "y":
        return

    vault.migrateStrategy(old_strategy, live_strategy, {
        "from": dev,
        'gas_price': Wei("25 gwei")
    })

    print('migrate time')
    if input("Continue? y/[N]: ").lower() != "y":
        return

    live_strategy.harvest({"from": dev, 'gas_price': Wei("25 gwei")})
예제 #14
0
def get_treasury_data(treasury_address, treasury_tokens):
    return [
        Treasury(
            name=token_name,
            token=interface.ERC20(token_address),
            treasury_address=treasury_address,
        ) for token_name, token_address in treasury_tokens.items()
    ]
예제 #15
0
def uniswap_lp_price(address):
    """ Get Uniswap LP token price. """
    pair = interface.UniswapPair(address)
    router = FACTORY_TO_ROUTER[pair.factory()]
    tokens = [interface.ERC20(token) for token in [pair.token0(), pair.token1()]]
    scales = [10 ** token.decimals() for token in tokens]
    prices = [price_router(token, router=router) for token in tokens]
    supply = pair.totalSupply() / 1e18
    return sum(reserve / scale * price for reserve, scale, price in zip(pair.getReserves(), scales, prices)) / supply
예제 #16
0
 def __post_init__(self):
     self.vault = constants.VAULT_INTERFACES.get(
         self.vault, interface.yVault)(self.vault)
     self.controller = constants.CONTROLLER_INTERFACES[self.controller](
         self.controller)
     self.strategy = constants.STRATEGY_INTERFACES[self.strategy](
         self.strategy)
     self.token = interface.ERC20(self.token)
     self.name = constants.VAULT_ALIASES[str(self.vault)]
예제 #17
0
def token_name(address):
    if address is None:
        return 'ETH'
    if address == '0x57f1887a8BF19b14fC0dF6Fd9B2acc9Af147eA85':
        return 'ENS'
    token = interface.ERC20(address)
    try:
        return token.symbol()
    except ValueError:
        return address
예제 #18
0
def token_name(address):
    if address is None:
        return 'ETH'
    if address == '0x57f1887a8BF19b14fC0dF6Fd9B2acc9Af147eA85':
        return 'ENS'
    token = interface.ERC20(address)
    try:
        return token.symbol()
    except (OverflowError, ValueError): # BadFunctionCallOutput
        return address
예제 #19
0
def main():
    dai = interface.ERC20('0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2')
    strategy = YearnWethCreamStratV2.at(
        '0x97785a81B3505Ea9026b2aFFa709dfd0C9Ef24f6')
    vault = Vault.at('0xf20731f26e98516dd83bb645dd757d33826a37b5')

    print(f'strategy YearnWethCreamStratV2: {strategy.address}')
    print(f'Vault: {vault.address}')
    print(f'Vault name: {vault.name()} and symbol: {vault.symbol()}')
    strategist_confirmed = strategy.strategist()
    print(f'Strategy strategist: {strategist_confirmed}')

    account_name = input(f"What account to use?: ")
    dev = accounts.load(account_name)
    print(f"You are using: 'dev' [{dev.address}]")
    devDai = dai.balanceOf(dev).to('ether')
    print(f"You're DAI balance is: [{devDai}]")
    are_you_strategist = strategist_confirmed == dev.address
    print(f"Are you strategist? {are_you_strategist}")

    if input("Continue? y/[N]: ").lower() != "y":
        return

    deposit_limit = Wei('500 ether')
    deposit_limit_eth = deposit_limit.to('ether')

    if input(f"Set deposit limit to: {deposit_limit_eth}?").lower() != "y":
        return

# vault.setDepositLimit(deposit_limit, {"from": dev, 'gas_price':Wei("17 gwei")})

    if input(f"Add strategy: {strategy} ?").lower() != "y":
        return

    #vault.addStrategy(strategy, deposit_limit, deposit_limit, 500, {"from": dev, 'gas_price':Wei("17 gwei")})

    amount = Wei('0.1 ether')
    amountE = amount.to('ether')

    if input(f"approve: {amountE} WETH?").lower() != "y":
        return
    #dai.approve(vault, amount*100, {"from": dev, 'gas_price':Wei("17 gwei")})

    print('deposit amount:', amount.to('ether'))
    if input("Continue? y/[N]: ").lower() != "y":
        return
    #vault.deposit(amount, {"from": dev, 'gas_price':Wei("17 gwei")})

    print('harvest time')
    if input("Continue? y/[N]: ").lower() != "y":
        return

    strategy.harvest({"from": dev, 'gas_price': Wei("25 gwei")})
예제 #20
0
def price_router(token_in, token_out=usdc, router=None):
    """
    Calculate a price based on Uniswap Router quote for selling one `token_in`.
    Always uses intermediate WETH pair.
    """
    tokens = [interface.ERC20(token) for token in [token_in, token_out]]
    router = interface.UniswapRouter(router or ROUTERS["uniswap"])
    amount_in = 10 ** tokens[0].decimals()
    path = [token_in, token_out] if weth in (token_in, token_out) else [token_in, weth, token_out]
    quote = router.getAmountsOut(amount_in, path)
    amount_out = quote[-1] / 10 ** tokens[1].decimals()
    return amount_out
예제 #21
0
def seize():
    penguin = accounts.at('0x907d9b32654b8d43e8737e0291ad9bfcce01dad6',
                          force=True)
    strategy = interface.Strategy('0xCd892a97951d46615484359355e3Ed88131f829D')
    controller = interface.ControllerV4(
        "0x6847259b2B3A4c17e7c43C54409810aF48bA5210")
    comp = interface.ERC20("0xc00e94Cb662C3520282E6f5717214004A7f26888")
    print('comp strategy', comp.balanceOf(strategy).to('ether'))
    controller.inCaseStrategyTokenGetStuck(strategy, comp, {'from': penguin})
    print('comp controller', comp.balanceOf(controller).to('ether'))
    controller.inCaseTokensGetStuck(comp, comp.balanceOf(controller),
                                    {'from': penguin})
    print('comp penguin', comp.balanceOf(penguin).to('ether'))
예제 #22
0
def test_rebases(
    vault_proxy,
    steth_token,
    stranger,
    another_stranger,
    emergency_admin,
    lido_oracle_report,
    interface,
    helpers
):
    vault = as_vault_v3(vault_proxy)
    beth_token = interface.ERC20(vault.beth_token())
    wormhole_token_bridge = Contract.from_abi(
        'BridgeConnectorWormhole',
        vault.bridge_connector(),
        BridgeConnectorWormhole.abi
    ).wormhole_token_bridge()
    liquidations_admin = accounts.at(vault.liquidations_admin(), force=True)

    assert vault.version() == 2 

    state_history_before = {}
    state_history_after = {}
    with chain_snapshot():
        state_history_before = record_vault_state_history(
            vault,
            steth_token,
            beth_token,
            wormhole_token_bridge,
            stranger,
            another_stranger,
            liquidations_admin,
            lido_oracle_report
        )

    upgrade_vault_to_v3(vault_proxy, impl_deployer=stranger, emergency_admin=emergency_admin)
    
    with chain_snapshot():
        state_history_after = record_vault_state_history(
            vault,
            steth_token,
            beth_token,
            wormhole_token_bridge,
            stranger,
            another_stranger,
            liquidations_admin,
            lido_oracle_report
        )

    # no diff in v2 and v3 versions in vaults math
    assert dictdiff(state_history_before, state_history_after) == {}
예제 #23
0
def main():
    user = (
        accounts[-1] if rpc.is_active() else accounts.load(input("brownie account: "))
    )

    recycle = Recycle.at("0x3f1C19b09b474f7b7a8B09488Fc8648b278930cc")

    dai = interface.ERC20("0x6B175474E89094C44Da98b954EedeAC495271d0F")
    usdc = interface.ERC20("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48")
    usdt = interface.USDT("0xdAC17F958D2ee523a2206206994597C13D831ec7")
    token3crv = interface.ERC20("0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490")
    y3crv = interface.ERC20("0x9cA85572E6A3EbF24dEDd195623F188735A5179f")

    coins = [dai, usdc, usdt, y3crv]
    symbols = {token3crv: "3CRV", y3crv: "y3CRV"}

    balances = {
        symbols.get(coin, coin.symbol()): coin.balanceOf(user) / 10 ** coin.decimals()
        for coin in coins
    }
    balances = {name: balance for name, balance in balances.items() if balance > 0}

    print(f"Recycling...")
    for coin, balance in balances.items():
        print(f"  {coin} = {balance}")

    if not click.confirm("Continue?"):
        return

    for coin in coins:
        if coin.balanceOf(user) > coin.allowance(user, recycle):
            print(f"Approving {coin.name()}")
            coin.approve(recycle, 2 ** 256 - 1, {"from": user})

    tx = recycle.recycle({"from": user})
    print(
        "Got", tx.events["Recycled"]["received_y3crv"] / 10 ** y3crv.decimals(), "y3CRV"
    )
예제 #24
0
def stateOfVault(vault, strategy):
    print('\n----state of vault----')

    currency = interface.ERC20(vault.token())
    decimals = currency.decimals()
    balanceIn = currency.balanceOf(vault) / (10**decimals)
    print(f'Want Balance in Vault: {balanceIn:.5f}')
    strState = vault.strategies(strategy)
    totalDebt = strState[5].to('ether')
    totalReturns = strState[6].to('ether')
    print(f'Total Strategy Debt: {totalDebt:.5f}')
    print(f'Total Strategy Returns: {totalReturns:.5f}')
    balance = vault.totalAssets().to('ether')
    print(f'Total Assets: {balance:.5f}')
예제 #25
0
def insider_hack():
    strategy = interface.Strategy("0xCd892a97951d46615484359355e3Ed88131f829D")
    strategist = accounts.at(strategy.strategist(), force=True)  # EOA
    controller = interface.ControllerV4(
        "0x6847259b2B3A4c17e7c43C54409810aF48bA5210")
    dai = interface.ERC20("0x6B175474E89094C44Da98b954EedeAC495271d0F")
    cdai = interface.ERC20("0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643")
    jar = interface.PickleJar(controller.jars(dai))

    def status():
        contracts = {
            "jar": jar,
            "strategy": strategy,
            "strategist": strategist,
        }
        data = []
        for name, c in contracts.items():
            data.append([
                name,
                dai.balanceOf(c).to("ether"),
                cdai.balanceOf(c) / 1e8,
            ])
        print(tabulate(data, headers=["contract", "dai", "cdai"]))

    status()
    controller.withdrawAll(dai, {"from": strategist})
    status()
    for i in range(3):
        jar.earn({"from": strategist})
    status()
    controller.inCaseStrategyTokenGetStuck(strategy, cdai,
                                           {"from": strategist})
    status()
    controller.inCaseTokensGetStuck(cdai, cdai.balanceOf(controller),
                                    {"from": strategist})
    status()
def main():
    safe = ApeSafe('0xD089cc83f5B803993E266ACEB929e52A993Ca2C8')
    agent_address = '0x3e40d73eb977dc6a537af587d48316fee66e9c8c'

    eth_spent = 0

    for cover in unslashed_covers:
        print("Calc cover for ", cover["policy_name"])
        eth_to_cover = cover["damage_eth_covered"]

        if eth_to_cover == 0:
            continue

        um = safe.contract(cover["marketAddress"])
        ut = interface.ERC20(cover["premiumToken"])

        deposit_delta = um.coverToPremiumTokens(
            eth_to_cover * 1e18) * um.premiumTokenPrice18eRatio() / 1e18

        print("Cover for", eth_to_cover, " ETH")
        print("ETH required to make deposit: ", deposit_delta / 1e18)

        premium_balance_before = ut.balanceOf(agent_address)
        um.depositPremium({'value': deposit_delta})
        premium_balance_after = ut.balanceOf(agent_address)
        print("Premium tokens delta: ",
              (premium_balance_after - premium_balance_before) / 1e18)
        print("Premium tokens balance after: ", (premium_balance_after) / 1e18)
        print("ETH amount", Wei(deposit_delta), deposit_delta / 1e18)

        eth_spent += deposit_delta

    print("total ETH to spend", eth_spent / 1e18)

    safe_tx = safe.multisend_from_receipts()
    print("safe tx preview:")
    safe.preview(safe_tx)

    sys.stdout.write('Are you sure (y/n)? ')

    if not prompt_bool():
        print('Aborting')
        return

    safe.post_transaction(safe_tx)

    print("safe tx sent!")
예제 #27
0
def price_router(token_in, token_out=usdc, router=None):
    """
    Calculate a price based on Uniswap Router quote for selling one `token_in`.
    Always uses intermediate WETH pair.
    """
    tokens = [interface.ERC20(token) for token in [token_in, token_out]]
    amount_in = 10**tokens[0].decimals()
    path = [token_in, token_out
            ] if weth in (token_in,
                          token_out) else [token_in, weth, token_out]
    for router in ['sushiswap', 'uniswap']:
        router = ROUTERS[router]
        try:
            quote = router.getAmountsOut(amount_in, path)
            amount_out = quote[-1] / 10**tokens[1].decimals()
            return amount_out
        except ValueError:
            pass
예제 #28
0
def priceOfCurvePool(lp_token: interface.CurvePool,
                     router_address: str) -> float:
    total_supply = lp_token.totalSupply() / 10**18

    total_dollars_locked = 0
    for i in range(5):
        try:
            coin = interface.ERC20(lp_token.coins(i))
            total_dollars_locked += priceUnknownToken(
                coin,
                router_address) * lp_token.balances(i) / 10**coin.decimals()
        except ValueError:
            break

    if total_dollars_locked == 0:
        raise ValueError(f"Can't price {lp_token}")

    return total_dollars_locked / total_supply
예제 #29
0
 def __post_init__(self):
     self.vault = constants.VAULT_INTERFACES.get(
         self.vault, interface.yVault)(self.vault)
     self.controller = constants.CONTROLLER_INTERFACES[self.controller](
         self.controller)
     if self.strategy not in constants.STRATEGY_INTERFACES:
         warnings.warn(
             f'no strategy interface for {self.strategy}, reading from etherscan'
         )
     self.strategy = constants.STRATEGY_INTERFACES.get(
         self.strategy, Contract)(self.strategy)
     self.token = interface.ERC20(self.token)
     if str(self.vault) not in constants.VAULT_ALIASES:
         warnings.warn(
             f'no vault alias for {self.vault}, reading from vault.sybmol()'
         )
     self.name = constants.VAULT_ALIASES.get(str(self.vault),
                                             self.vault.symbol())
     self.decimals = self.vault.decimals(
     )  # vaults inherit decimals from token
예제 #30
0
def main():
    with open('snapshot/10-usdc-merkle-distribution.json') as fp:
        tree = json.load(fp)
    deployer = accounts.at(DEPLOYER_ADDRESS)
    usdc = interface.ERC20(USDC_ADDRESS)
    print(f'Deployer address {DEPLOYER_ADDRESS}')
    print(f'Deployer USDC balance: {usdc.balanceOf(deployer)}')
    print(f'Deployer eth balance: {deployer.balance()}')
    distributor = MerkleDistributor.deploy(usdc, tree['merkleRoot'], {'from': deployer})

    usdc.transfer(distributor, tree['tokenTotal'], {'from': deployer})
    for i, (address, claim) in enumerate(tree['claims'].items()):
        if not i % 50:
            print(f"Distribution in progress, {i} / {len(tree['claims'])}...")
        balance = usdc.balanceOf(address)
        distributor.claim(
            claim['index'], address, claim['amount'], claim['proof'], 0, {'from': deployer}
        )
        assert usdc.balanceOf(address) == balance + claim['amount']
    assert usdc.balanceOf(distributor) == 0
    print("Distribution was successful!")