Example #1
0
def test_vault_out_of_order_in_approx_out(vault, users, pool, depositAmounts):
    depositors = users[:4]
    deposits = {u: [] for u in depositors}
    for i, u in enumerate(depositors):
        for d0, d1 in depositAmounts[i]:
            shares = vault.balanceOf(u)
            amount0Before = pool.token0.balanceOf(u)
            amount1Before = pool.token1.balanceOf(u)
            # deposit to then withdraw in a different order
            vault.deposit(d0, d1, 0, 0, u, chain.time() + 60, {"from": u})
            sharesOut = vault.balanceOf(u) - shares
            amount0In = amount0Before - pool.token0.balanceOf(u)
            amount1In = amount1Before - pool.token1.balanceOf(u)
            deposits[u].append((sharesOut, amount0In, amount1In))
    for u in depositors:
        for d in deposits[u]:
            shares, amount0In, amount1In = d
            amount0Before = pool.token0.balanceOf(u)
            amount1Before = pool.token1.balanceOf(u)
            vault.withdraw(shares, 0, 0, u, chain.time() + 60, {"from": u})
            amount0Out = pool.token0.balanceOf(u) - amount0Before
            amount1Out = pool.token1.balanceOf(u) - amount1Before
            # We don't check if out is less than in here, but we make that check above
            # so it doesn't happen in back-to-back deposit then withdraw
            # If someone sandwhiches a deposit and squeezes out a wei or two... gg hope you're proud of yourself
            assert int(amount0Out) == pytest.approx(amount0In, abs=1e3)
            assert int(amount1Out) == pytest.approx(amount1In, abs=1e3)
Example #2
0
def test_eth_vault_withdraw_from(vault, users, pool):
    a0InBefore = pool.token0.balanceOf(users[1])
    a1InBefore = pool.token1.balanceOf(users[1])
    sharesBefore = vault.balanceOf(users[1])
    vault.deposit(1e18, 1e18, 0, 0, users[0],
                  chain.time() + 60, {"from": users[0]})
    vault.deposit(1e18, 1e18, 0, 0, users[1],
                  chain.time() + 60, {"from": users[1]})
    a0In = pool.token0.balanceOf(users[1]) - a0InBefore
    a1In = pool.token1.balanceOf(users[1]) - a1InBefore
    shares = vault.balanceOf(users[1]) - sharesBefore
    before0Bal, beforeBal = (
        pool.token0.balanceOf(users[2].address),
        pool.token1.balanceOf(users[2].address),
    )
    vault.approve(users[2], shares, {"from": users[1]})
    vault.withdrawFrom(users[1], shares, 0, 0, users[2],
                       chain.time() + 60, {"from": users[2]})
    after0Bal, afterBal = (
        pool.token0.balanceOf(users[2].address),
        pool.token1.balanceOf(users[2].address),
    )
    assert int(before0Bal + a0In) == pytest.approx(after0Bal)
    assert int(beforeBal + a1In) == pytest.approx(afterBal)
    with reverts("INSUFFICIENT_ALLOWANCE"):
        vault.withdrawFrom(users[0], shares, 0, 0, users[2],
                           chain.time() + 60, {"from": users[2]})
Example #3
0
def test_dutch_auction(FixedToken, auction_factory, dutch_auction_template,
                       fixed_token_template, token_factory):
    name = "Test Token"
    symbol = "TTOKEN"
    token_2 = _create_token(token_factory, fixed_token_template, name, symbol,
                            TOTAL_TOKENS_2, 1, accounts[2], accounts[2])
    token_2 = FixedToken.at(token_2)
    assert token_2.balanceOf(accounts[2]) == TOTAL_TOKENS_2

    funder = accounts[2]
    tokens_to_market = 50000 * TENPOW18
    start_time = chain.time() + 50
    end_time = chain.time() + 1000
    start_price = 0.01 * TENPOW18
    minimum_price = 0.001 * TENPOW18
    operator = accounts[2]
    wallet = accounts[2]
    point_list = ZERO_ADDRESS
    payment_currency = ETH_ADDRESS

    data = dutch_auction_template.getAuctionInitData(
        auction_factory, token_2, tokens_to_market, start_time, end_time,
        payment_currency, start_price, minimum_price, operator, point_list,
        wallet)

    chain.sleep(10)

    token_2.approve(auction_factory, tokens_to_market, {"from": accounts[2]})

    template_id = auction_factory.getTemplateId(dutch_auction_template)

    tx = auction_factory.createMarket(template_id, token_2, tokens_to_market,
                                      accounts[2], data, {'from': accounts[2]})

    assert "MarketCreated" in tx.events
Example #4
0
def test_eth_vault_withdraw_from(eth_vault, users, eth_pool):
    aEthBefore = web3.eth.get_balance(users[1])
    aInBefore = eth_pool.token.balanceOf(users[1])
    sharesBefore = eth_vault.balanceOf(users[1])
    eth_vault.depositETH(1e18, 0, 0, users[0],
                         chain.time() + 60, {
                             "from": users[0],
                             "value": 1e18
                         })
    eth_vault.depositETH(1e18, 0, 0, users[1],
                         chain.time() + 60, {
                             "from": users[1],
                             "value": 1e18
                         })
    aEthIn = aEthBefore - web3.eth.get_balance(users[1])
    aIn = aInBefore - eth_pool.token.balanceOf(users[1])
    shares = eth_vault.balanceOf(users[1]) - sharesBefore
    beforeEthBal, beforeBal = (
        web3.eth.get_balance(users[2].address),
        eth_pool.token.balanceOf(users[2].address),
    )
    eth_vault.approve(users[2], shares, {"from": users[1]})
    eth_vault.withdrawETHFrom(users[1], shares, 0, 0, users[2],
                              chain.time() + 60, {"from": users[2]})
    afterEthBal, afterBal = (
        web3.eth.get_balance(users[2].address),
        eth_pool.token.balanceOf(users[2].address),
    )
    assert int(beforeEthBal + aEthIn) == pytest.approx(afterEthBal)
    assert int(beforeBal + aIn) == pytest.approx(afterBal)
    with reverts("INSUFFICIENT_ALLOWANCE"):
        eth_vault.withdrawETHFrom(users[0], shares, 0, 0, users[2],
                                  chain.time() + 60, {"from": users[2]})
Example #5
0
def test_crowdsale_end_less_than_start(crowdsale_init_helper, mintable_token):
    mintable_token.mint(accounts[0], AUCTION_TOKENS, {"from": accounts[0]})
    assert mintable_token.balanceOf(accounts[0]) == AUCTION_TOKENS
    start_time = chain.time() + 10
    end_time = start_time - 1
    wallet = accounts[4]
    operator = accounts[0]
    mintable_token.approve(crowdsale_init_helper, AUCTION_TOKENS, {"from": accounts[0]})
    with reverts("Crowdsale: start time is not before end time"):
        crowdsale_init_helper.initCrowdsale(accounts[0], mintable_token, ETH_ADDRESS, CROWDSALE_TOKENS, start_time, end_time, CROWDSALE_RATE, CROWDSALE_GOAL, operator,ZERO_ADDRESS, wallet, {"from": accounts[0]})    
    
    end_time = start_time + CROWDSALE_TIME
    start_time = chain.time() - 10
    with reverts("Crowdsale: start time is before current time"):
        crowdsale_init_helper.initCrowdsale(accounts[0], mintable_token, ETH_ADDRESS, CROWDSALE_TOKENS, start_time, end_time, CROWDSALE_RATE, CROWDSALE_GOAL, operator,ZERO_ADDRESS, wallet, {"from": accounts[0]})    
    
    
    start_time = chain.time() + 10
    payment_currency = ZERO_ADDRESS
    with reverts("Crowdsale: payment currency is the zero address"):
        crowdsale_init_helper.initCrowdsale(accounts[0], mintable_token, payment_currency, CROWDSALE_TOKENS, start_time, end_time, CROWDSALE_RATE, CROWDSALE_GOAL, operator,ZERO_ADDRESS, wallet, {"from": accounts[0]})    

    wallet = ZERO_ADDRESS
    with reverts("Crowdsale: wallet is the zero address"):
        crowdsale_init_helper.initCrowdsale(accounts[0], mintable_token, ETH_ADDRESS, CROWDSALE_TOKENS, start_time, end_time, CROWDSALE_RATE, CROWDSALE_GOAL, operator,ZERO_ADDRESS, wallet, {"from": accounts[0]})    

    wallet = accounts[4]
    operator = ZERO_ADDRESS
    with reverts("Crowdsale: operator is the zero address"):
        crowdsale_init_helper.initCrowdsale(accounts[0], mintable_token, ETH_ADDRESS, CROWDSALE_TOKENS, start_time, end_time, CROWDSALE_RATE, CROWDSALE_GOAL, operator,ZERO_ADDRESS, wallet, {"from": accounts[0]})    
def test_stateful(state_machine, accounts, ve_token, ve_boardroom, coin_a,
                  coin_b, coin_c, token):
    for i in range(5):
        # ensure accounts[:5] all have tokens that may be locked
        token.approve(ve_token, 2**256 - 1, {"from": accounts[i]})
        token.transfer(accounts[i], 10**18 * 10000000, {"from": accounts[0]})

    # accounts[0] locks 10,000,000 tokens for 2 years - longer than the maximum duration of the test
    ve_token.create_lock(10**18 * 10000000,
                         chain.time() + YEAR * 2, {"from": accounts[0]})

    # a week later we deploy the fee distributor
    chain.sleep(WEEK)
    distributor = ve_boardroom()
    distributor.add_token(coin_a, chain.time())
    distributor.add_token(coin_c, chain.time())
    distributor.add_token(coin_b, chain.time())
    distributor.delete_token(coin_c)

    state_machine(
        StateMachine,
        distributor,
        accounts[:5],
        ve_token,
        coin_a,
        coin_b,
        settings={"stateful_step_count": 30},
    )
Example #7
0
    def rule_increase_unlock_time(self, st_account, st_lock_duration):
        unlock_time = (chain.time() + st_lock_duration * WEEK) // WEEK * WEEK

        if self.voting_balances[st_account]["unlock_time"] <= chain.time():
            with brownie.reverts("Lock expired"):
                self.voting_escrow.increase_unlock_time(
                    unlock_time, {"from": st_account, "gas": GAS_LIMIT}
                )

        elif self.voting_balances[st_account]["value"] == 0:
            with brownie.reverts("Nothing is locked"):
                self.voting_escrow.increase_unlock_time(
                    unlock_time, {"from": st_account, "gas": GAS_LIMIT}
                )

        elif unlock_time <= self.voting_balances[st_account]["unlock_time"]:
            with brownie.reverts("Can only increase lock duration"):
                self.voting_escrow.increase_unlock_time(
                    unlock_time, {"from": st_account, "gas": GAS_LIMIT}
                )

        elif unlock_time > chain.time() + 86400 * 365 * 4:
            with brownie.reverts("Voting lock can be 4 years max"):
                self.voting_escrow.increase_unlock_time(
                    unlock_time, {"from": st_account, "gas": GAS_LIMIT}
                )

        else:
            tx = self.voting_escrow.increase_unlock_time(
                unlock_time, {"from": st_account, "gas": GAS_LIMIT}
            )
            self.voting_balances[st_account]["unlock_time"] = tx.events["Deposit"]["locktime"]
Example #8
0
    def rule_create_lock(self, st_account, st_value, st_lock_duration):
        unlock_time = (chain.time() + st_lock_duration * WEEK) // WEEK * WEEK

        if st_value == 0:
            with brownie.reverts("dev: need non-zero value"):
                self.voting_escrow.create_lock(
                    st_value, unlock_time, {"from": st_account, "gas": GAS_LIMIT}
                )

        elif self.voting_balances[st_account]["value"] > 0:
            with brownie.reverts("Withdraw old tokens first"):
                self.voting_escrow.create_lock(
                    st_value, unlock_time, {"from": st_account, "gas": GAS_LIMIT}
                )

        elif unlock_time <= chain.time():
            with brownie.reverts("Can only lock until time in the future"):
                self.voting_escrow.create_lock(
                    st_value, unlock_time, {"from": st_account, "gas": GAS_LIMIT}
                )

        elif unlock_time > chain.time() + 86400 * 365 * 4:
            with brownie.reverts("Voting lock can be 4 years max"):
                self.voting_escrow.create_lock(
                    st_value, unlock_time, {"from": st_account, "gas": GAS_LIMIT}
                )

        else:
            tx = self.voting_escrow.create_lock(
                st_value, unlock_time, {"from": st_account, "gas": GAS_LIMIT}
            )
            self.voting_balances[st_account] = {
                "value": st_value,
                "unlock_time": tx.events["Deposit"]["locktime"],
            }
Example #9
0
def test_stake(accounts, farming, niftsy20, dai):
    niftsy20.approve(farming, STAKED_AMOUNT, {'from': accounts[0]})
    niftsy20.approve(farming, STAKED_AMOUNT, {'from': accounts[1]})

    niftsy20.transfer(accounts[1], STAKED_AMOUNT, {'from': accounts[0]})

    farming.WrapForFarming(accounts[0], (niftsy20.address, STAKED_AMOUNT), 0,
                           {'from': accounts[0]})

    farming.WrapForFarming(accounts[1], (niftsy20.address, STAKED_AMOUNT / 2),
                           chain.time() + 100, {'from': accounts[1]})

    assert farming.getAvailableRewardAmount(1, niftsy20) == 0
    assert farming.getAvailableRewardAmount(2, niftsy20) == 0
    assert farming.balanceOf(accounts[1]) == 1
    assert farming.balanceOf(accounts[0]) == 1
    assert farming.getWrappedToken(1)[0] == zero_address
    assert farming.getWrappedToken(1)[1] == 0
    assert farming.getWrappedToken(2)[0] == zero_address
    assert farming.getWrappedToken(2)[1] == 0
    assert farming.ownerOf(1) == accounts[0]
    assert farming.ownerOf(2) == accounts[1]
    assert farming.getWrappedToken(1)[4] <= chain.time() + 100
    assert farming.getWrappedToken(1)[4] == 0
    assert farming.getWrappedToken(2)[4] <= chain.time() + 100
    assert farming.getWrappedToken(2)[4] > 0
    assert niftsy20.balanceOf(farming) == STAKED_AMOUNT + STAKED_AMOUNT / 2
    assert farming.getERC20CollateralBalance(1, niftsy20) == STAKED_AMOUNT
    assert farming.getERC20CollateralBalance(2, niftsy20) == STAKED_AMOUNT / 2
    assert farming.rewards(1)[0] <= chain.time() + 100
    assert farming.rewards(1)[0] > 0
    assert farming.rewards(2)[0] <= chain.time() + 100
    assert farming.rewards(2)[0] > 0
    assert farming.totalSupply() == 2
Example #10
0
def test_frames_crowdsale_setStartDate(frames_crowdsale):
    tx = frames_crowdsale.setStartDate(chain.time() + 100,
                                       {'from': accounts[0]})
    assert 'StartDateUpdated' in tx.events
    with reverts("dev: Not owner"):
        frames_crowdsale.setStartDate(chain.time() + 100,
                                      {'from': accounts[3]})
Example #11
0
def test_eth_vault_out_of_order_in_approx_out(eth_vault, users, eth_pool,
                                              depositAmounts):
    depositors = users[:4]
    deposits = {u: [] for u in depositors}
    for i, u in enumerate(depositors):
        for dEth, d in depositAmounts[i]:
            shares = eth_vault.balanceOf(u)
            amountEthBefore = web3.eth.get_balance(u.address)
            amountBefore = eth_pool.token.balanceOf(u)
            # deposit to then withdraw in a different order
            eth_vault.depositETH(d, 0, 0, u,
                                 chain.time() + 60, {
                                     "from": u,
                                     "value": dEth
                                 })
            sharesOut = eth_vault.balanceOf(u) - shares
            amountEthIn = amountEthBefore - web3.eth.get_balance(u.address)
            amountIn = amountBefore - eth_pool.token.balanceOf(u)
            deposits[u].append((sharesOut, amountEthIn, amountIn))
    for u in depositors:
        for d in deposits[u]:
            shares, amountEthIn, amountIn = d
            amountEthBefore = web3.eth.get_balance(u.address)
            amountBefore = eth_pool.token.balanceOf(u)
            eth_vault.withdrawETH(shares, 0, 0, u,
                                  chain.time() + 60, {"from": u})
            amountEthOut = web3.eth.get_balance(u.address) - amountEthBefore
            amountOut = eth_pool.token.balanceOf(u) - amountBefore
            # We don't check if out is less than in here, but we make that check above
            # so it doesn't happen in back-to-back deposit then withdraw
            # If someone sandwhiches a deposit and squeezes out a wei or two... gg hope you're proud of yourself
            assert int(amountEthOut) == pytest.approx(amountEthIn, abs=1e3)
            assert int(amountOut) == pytest.approx(amountIn, abs=1e3)
Example #12
0
def batch_auction_pay_by_token(BatchAuction, fixed_token_payment_currency,
                               fixed_token_cal):
    funder = accounts[5]
    start_time = chain.time() + 10
    end_time = start_time + AUCTION_TIME
    wallet = accounts[1]
    batch_auction_pay_by_token = BatchAuction.deploy({"from": accounts[0]})
    auction_tokens = 100 * TENPOW18
    fixed_token_cal.approve(batch_auction_pay_by_token, auction_tokens,
                            {"from": funder})

    start_time = chain.time() + 10
    end_time = start_time - 10

    with reverts("BatchAuction: end time must be older than start price"):
        batch_auction_pay_by_token.initAuction(
            funder, fixed_token_cal, auction_tokens, start_time, end_time,
            fixed_token_payment_currency, AUCTION_MINIMUM_COMMITMENT,
            accounts[0], ZERO_ADDRESS, wallet, {"from": accounts[0]})

    start_time = chain.time() + 10
    end_time = start_time + AUCTION_TIME
    batch_auction_pay_by_token.initAuction(
        funder, fixed_token_cal, auction_tokens, start_time, end_time,
        fixed_token_payment_currency, AUCTION_MINIMUM_COMMITMENT, accounts[0],
        ZERO_ADDRESS, wallet, {"from": accounts[0]})
    with reverts("BatchAuction: auction already initialized"):
        batch_auction_pay_by_token.initAuction(
            funder, fixed_token_cal, auction_tokens, start_time, end_time,
            fixed_token_payment_currency, AUCTION_MINIMUM_COMMITMENT,
            accounts[0], ZERO_ADDRESS, wallet, {"from": accounts[0]})

    chain.sleep(10)
    return batch_auction_pay_by_token
Example #13
0
def parent_nft(DigitalaxGenesisNFT, access_controls):
    fundsMultisig = accounts[1]
    genesisStartTimestamp = chain.time() + 10
    genesisEndTimestamp = chain.time() + 10 + GENESIS_AUCTION_TIME

    parent_nft = DigitalaxGenesisNFT.deploy(access_controls, fundsMultisig,
                                            genesisStartTimestamp,
                                            genesisEndTimestamp,
                                            GENESIS_TOKEN_URI,
                                            {"from": accounts[0]})
    return parent_nft
Example #14
0
def staked_nft(DigitalaxGenesisNFT, access_controls):
    fundsMultisig = accounts[1]
    genesisStartTimestamp = chain.time() + 10
    genesisEndTimestamp = chain.time() + 10 + GENESIS_AUCTION_TIME
    staked_nft = DigitalaxGenesisNFT.deploy(access_controls, fundsMultisig,
                                            genesisStartTimestamp,
                                            genesisEndTimestamp,
                                            GENESIS_TOKEN_URI,
                                            {"from": accounts[0]})
    chain.sleep(10)

    # Add some transactions for this instance to test
    txn = staked_nft.buy({'from': accounts[1], 'value': '1 ethers'})
    assert 'GenesisPurchased' in txn.events
    txn = staked_nft.buyOrIncreaseContribution({
        'from': accounts[1],
        'value': '0.5 ethers'
    })
    txn = staked_nft.buyOrIncreaseContribution({
        'from': accounts[2],
        'value': '0.1 ethers'
    })
    txn = staked_nft.buyOrIncreaseContribution({
        'from': accounts[3],
        'value': '0.2 ethers'
    })
    txn = staked_nft.buyOrIncreaseContribution({
        'from': accounts[4],
        'value': '1.1 ethers'
    })
    txn = staked_nft.buyOrIncreaseContribution({
        'from': accounts[5],
        'value': '1.1 ethers'
    })
    txn = staked_nft.buyOrIncreaseContribution({
        'from': accounts[6],
        'value': '1.7 ethers'
    })
    txn = staked_nft.buyOrIncreaseContribution({
        'from': accounts[7],
        'value': '0.1 ethers'
    })
    txn = staked_nft.buyOrIncreaseContribution({
        'from': accounts[8],
        'value': '0.3 ethers'
    })
    txn = staked_nft.buyOrIncreaseContribution({
        'from': accounts[9],
        'value': '0.5 ethers'
    })
    assert 'GenesisPurchased' in txn.events
    return staked_nft
Example #15
0
def makeWrapNFT(wrapper, erc721mock, fields, values, account, transferFeeContract):
    START_NATIVE_COLLATERAL_ = '1 ether'
    ADD_NATIVE_COLLATERAL_ = '2 ether'
    ERC20_COLLATERAL_AMOUNT_ = 2e17;
    TRANSFER_FEE_ = 2e18
    ROAYLTY_PERCENT_ = 10
    UNWRAP_FEE_THRESHOLD_ = 6e18
    protokolFee_ = 10
    chargeFeeAfter_ = 10
    ROYALTYBENEFICIARY_= '0xbd7e5fb7525ed8583893ce1b1f93e21cc0cf02f6'
    zero_address_ = '0x0000000000000000000000000000000000000000'
    UNWRAPAFTER_ = chain.time() + 10

    #logging.info('TRANSFER_FEE_ from make 1= {}'.format(TRANSFER_FEE_))

    #logging.info('make UNWRAPAFTER_ = {}'.format(UNWRAPAFTER_))
    
    UNDERLINECONTRACT_ = erc721mock.address
    UNWRAPAFTER_ = chain.time() + 10
    for i in range(len(fields)):
        if fields[i] ==  'originalTokenId':
            ORIGINAL_NFT_IDs_ = []
            ORIGINAL_NFT_IDs_.append(values[i])
        elif fields[i] ==  'unwrapAfter':
            UNWRAPAFTER_ = values[i]
        elif fields[i] ==  'transferFee':
            TRANSFER_FEE_ = values[i]
        elif fields[i] ==  'royaltyBeneficiary':
            ROYALTYBENEFICIARY_ = values[i]
        elif fields[i] ==  'royaltyPercent':
            ROAYLTY_PERCENT_ = values[i]
        elif fields[i] ==  'start_native_collateral':
            START_NATIVE_COLLATERAL_ = values[i]
        else: #result
            UNWRAP_FEE_THRESHOLD_ = values[i]
    #logging.info('TRANSFER_FEE_ from make 2= {}'.format(TRANSFER_FEE_))

    erc721mock.approve(wrapper.address, ORIGINAL_NFT_IDs_[0], {'from':account})
    
    wrapper.wrap721(
        
        UNDERLINECONTRACT_, 
        ORIGINAL_NFT_IDs_[0], 
        UNWRAPAFTER_,
        TRANSFER_FEE_,
        ROYALTYBENEFICIARY_,
        ROAYLTY_PERCENT_,
        UNWRAP_FEE_THRESHOLD_, 
        transferFeeContract.address,
        {'from':account, 'value':START_NATIVE_COLLATERAL_})
    assert erc721mock.ownerOf(ORIGINAL_NFT_IDs_[0]) == wrapper.address
    assert wrapper.ownerOf(wrapper.lastWrappedNFTId()) == account
Example #16
0
def test_market_create_auction_data(DutchAuction, dutch_auction,
                                    auction_factory, dutch_auction_template,
                                    fixed_token_cal):
    assert fixed_token_cal.balanceOf(accounts[0]) == AUCTION_TOKENS
    template_id = auction_factory.getTemplateId(dutch_auction_template)
    start_date = chain.time() + 10
    end_date = start_date + AUCTION_TIME
    wallet = accounts[1]

    new_dutch_auction = auction_factory.deployMarket(template_id).return_value
    chain.sleep(20)
    fixed_token_cal.approve(new_dutch_auction, AUCTION_TOKENS,
                            {"from": accounts[0]})
    new_dutch_auction = DutchAuction.at(new_dutch_auction)
    _data = new_dutch_auction.getAuctionInitData(accounts[0], fixed_token_cal,
                                                 AUCTION_TOKENS, start_date,
                                                 end_date, ETH_ADDRESS,
                                                 AUCTION_START_PRICE,
                                                 AUCTION_RESERVE, wallet,
                                                 {"from": accounts[0]})

    new_dutch_auction = auction_factory.createMarket(
        template_id, _data, new_dutch_auction).return_value
    new_dutch_auction = DutchAuction.at(new_dutch_auction)
    assert new_dutch_auction.totalTokensCommitted() == 0

    token_buyer = accounts[2]
    eth_to_transfer = 20 * TENPOW18
    tx = new_dutch_auction.commitEth(accounts[0], {
        "from": accounts[0],
        "value": eth_to_transfer
    })
    assert "AddedCommitment" in tx.events
def test_hyperbolic_auction_with_abi_data(HyperbolicAuction,fixed_token2):
    assert fixed_token2.balanceOf(accounts[0]) == AUCTION_TOKENS
    
    start_time = chain.time() +10
    end_time = start_time + AUCTION_TIME
    wallet = accounts[1]
    operator = accounts[0]
    hyperbolic_auction_init_with_abi = HyperbolicAuction.deploy({"from": accounts[0]})

    fixed_token2.approve(hyperbolic_auction_init_with_abi, AUCTION_TOKENS, {"from": accounts[0]})

    _data = hyperbolic_auction_init_with_abi.getAuctionInitData(
        accounts[0],
        fixed_token2,
        AUCTION_TOKENS,
        start_time,
        end_time,
        ETH_ADDRESS,
        HYPERBOLIC_AUCTION_FACTOR,
        AUCTION_RESERVE,
        operator,
        ZERO_ADDRESS,
        wallet,
        {"from": accounts[0]}
    )

    hyperbolic_auction_init_with_abi.initMarket(_data)
    chain.sleep(12)
    token_buyer =  accounts[2]
    eth_to_transfer = 20 * TENPOW18
    tx = hyperbolic_auction_init_with_abi.commitEth(token_buyer, True, {"from": token_buyer, "value":eth_to_transfer})
    assert 'AddedCommitment' in tx.events
    return hyperbolic_auction_init_with_abi
Example #18
0
def staking_rewards_mock(DigitalaxRewards, MockStaking, mona_token,
                         access_controls, staking_genesis_mock,
                         staking_nft_mock, staking_lp_mock):
    start_time = chain.time()
    staking_rewards_mock = DigitalaxRewards.deploy(mona_token, access_controls,
                                                   staking_genesis_mock,
                                                   staking_nft_mock,
                                                   staking_lp_mock, start_time,
                                                   start_time, 0, 0, 0,
                                                   {'from': accounts[0]})
    access_controls.addMinterRole(staking_rewards_mock)
    assert access_controls.hasMinterRole(staking_rewards_mock) == True
    staking_genesis_mock.setRewardsContract(staking_rewards_mock)
    staking_nft_mock.setRewardsContract(staking_rewards_mock)
    staking_lp_mock.setRewardsContract(staking_rewards_mock)

    weeks = [0, 1, 2, 3, 4, 5]
    rewards = [
        700 * TENPOW18, 700 * TENPOW18, 500 * TENPOW18, 350 * TENPOW18,
        150 * TENPOW18, 100 * TENPOW18
    ]
    staking_rewards_mock.setRewards(weeks, rewards)

    weeks = [0, 1]
    rewards = [450 * TENPOW18, 350 * TENPOW18]
    staking_rewards_mock.bonusRewards(staking_genesis_mock, weeks, rewards)

    return staking_rewards_mock
Example #19
0
    def post_deploy_setup(self, deploy=True):
        """
        Distribute digg to Geyser and allow strategy to take
        """
        super().post_deploy_setup(deploy=deploy)

        if not deploy:
            return

        amount = digg_config_test.geyserParams.unlockSchedules.digg[0].amount
        digg = self.digg.token

        digg.transfer(self.rewards, amount, {'from': self.deployer})
        self.rewards.notifyRewardAmount(chain.time(), days(7),
                                        digg.fragmentsToShares(amount),
                                        {'from': self.deployer})
        print(digg.balanceOf(self.rewards), digg.sharesOf(self.rewards))

        self.rewards.grantRole(PAUSER_ROLE, self.keeper,
                               {'from': self.deployer})
        self.rewards.grantRole(UNPAUSER_ROLE, self.guardian,
                               {'from': self.deployer})

        # Make strategy the recipient of the DIGG faucet
        self.rewards.initializeRecipient(self.strategy,
                                         {"from": self.deployer})
Example #20
0
def dutch_auction(DutchSwapAuction, auction_token):
    
    startDate = chain.time() +10
    endDate = startDate + AUCTION_TIME
    wallet = accounts[1]
    funder = accounts[0]

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

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

    # Cannot contribute early
    # with reverts():
    #     tx = token_buyer.transfer(dutch_auction, eth_to_transfer)

    # testing pre auction calcs
    assert dutch_auction.calculateCommitment(0) == 0 
    assert dutch_auction.calculateCommitment(AUCTION_START_PRICE) == AUCTION_START_PRICE
    assert dutch_auction.calculateCommitment(AUCTION_START_PRICE*AUCTION_TOKENS / TENPOW18) == AUCTION_START_PRICE*AUCTION_TOKENS / TENPOW18
    assert dutch_auction.calculateCommitment(10 * AUCTION_START_PRICE*AUCTION_TOKENS ) == AUCTION_START_PRICE*AUCTION_TOKENS / TENPOW18

    # Move the chain to the moment the auction begins
    chain.sleep(10)
    return dutch_auction
Example #21
0
def staking_rewards(GazeLPStaking, GazeRewards, gaze_coin, lp_token,
                    weth_token, access_control):
    staking_rewards = GazeLPStaking.deploy({'from': accounts[0]})
    staking_rewards.initLPStaking(gaze_coin, lp_token, weth_token,
                                  access_control, {"from": accounts[0]})

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

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

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

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

    chain.sleep(20)
    chain.mine()

    return staking_rewards
Example #22
0
def test_init_market_from_data(crowdsale_init_helper, mintable_token, fixed_token2):
    mintable_token.mint(accounts[0], CROWDSALE_TOKENS, {"from": accounts[0]})
    assert mintable_token.balanceOf(accounts[0]) == AUCTION_TOKENS
    funder = accounts[0]
    start_time = chain.time() + 10
    end_time = start_time + CROWDSALE_TIME
    wallet = accounts[4]
    operator = accounts[0]
    
    mintable_token.approve(crowdsale_init_helper, CROWDSALE_TOKENS, {"from": funder})
    
    _data = crowdsale_init_helper.getCrowdsaleInitData(accounts[0],mintable_token, ETH_ADDRESS, CROWDSALE_TOKENS, start_time, end_time, CROWDSALE_RATE, CROWDSALE_GOAL, operator, ZERO_ADDRESS, wallet, {"from": accounts[0]})
    
    crowdsale_init_helper.initMarket(_data)
    
    totalAmountRaised = 0
    token_buyer =  accounts[1]
    eth_to_transfer = 5 * TENPOW18
    totalAmountRaised += eth_to_transfer
    chain.sleep(10)
    tx = crowdsale_init_helper.buyTokensEth(token_buyer, True, {"value": eth_to_transfer, "from": token_buyer})
    
    
    assert crowdsale_init_helper.operator() == operator
    assert 'TokensPurchased' in tx.events
    assert crowdsale_init_helper.marketStatus()[0] == totalAmountRaised
    assert crowdsale_init_helper.auctionSuccessful() == False
    def rule_increase_amount(self, st_account, st_value):
        if st_value == 0:
            with brownie.reverts("dev: need non-zero value"):
                self.voting_escrow.increase_amount(st_value, {
                    'from': st_account,
                    'gas': GAS_LIMIT
                })

        elif self.voting_balances[st_account]['value'] == 0:
            with brownie.reverts("No existing lock found"):
                self.voting_escrow.increase_amount(st_value, {
                    'from': st_account,
                    'gas': GAS_LIMIT
                })

        elif self.voting_balances[st_account]['unlock_time'] <= chain.time():
            with brownie.reverts("Cannot add to expired lock. Withdraw"):
                self.voting_escrow.increase_amount(st_value, {
                    'from': st_account,
                    'gas': GAS_LIMIT
                })

        else:
            self.voting_escrow.increase_amount(st_value, {
                'from': st_account,
                'gas': GAS_LIMIT
            })
            self.voting_balances[st_account]['value'] += st_value
Example #24
0
def crowdsale_2(Crowdsale, mintable_token, fixed_token2):
    crowdsale = Crowdsale.deploy({"from": accounts[0]})
    mintable_token.mint(accounts[0], CROWDSALE_TOKENS_2, {"from": accounts[0]})
    assert mintable_token.balanceOf(accounts[0]) == CROWDSALE_TOKENS_2

    start_time = chain.time() + 10
    end_time = start_time + CROWDSALE_TIME
    operator = accounts[0]
    wallet = accounts[4]
    
    mintable_token.approve(crowdsale, CROWDSALE_TOKENS_2, {"from": accounts[0]})
    crowdsale.initCrowdsale(
        accounts[0],
        mintable_token,
        fixed_token2,
        CROWDSALE_TOKENS_2,
        start_time,
        end_time,
        CROWDSALE_RATE_2,
        CROWDSALE_GOAL,
        operator,
        ZERO_ADDRESS,
        wallet,
        {"from": accounts[0]}
    )
    assert mintable_token.balanceOf(crowdsale) == CROWDSALE_TOKENS_2
    chain.sleep(10)
    return crowdsale 
Example #25
0
def test_getMarkets(miso_helper, auction_factory, dutch_auction_template,
                    fixed_token_cal):

    assert fixed_token_cal.balanceOf(accounts[0]) == AUCTION_TOKENS
    template_id = auction_factory.getTemplateId(dutch_auction_template)
    minimum_fee = 0.1 * TENPOW18
    integrator_fee_percent = 10
    ETH_TO_FEE = 1 * TENPOW18
    auction_factory.setMinimumFee(minimum_fee, {"from": accounts[0]})
    auction_factory.setIntegratorFeePct(integrator_fee_percent,
                                        {"from": accounts[0]})

    start_date = chain.time() + 20
    end_date = start_date + AUCTION_TIME
    operator = accounts[0]
    wallet = accounts[1]

    chain.sleep(10)

    fixed_token_cal.approve(auction_factory, AUCTION_TOKENS,
                            {"from": accounts[0]})
    _data = dutch_auction_template.getAuctionInitData(
        auction_factory, fixed_token_cal, AUCTION_TOKENS, start_date, end_date,
        ETH_ADDRESS, AUCTION_START_PRICE, AUCTION_RESERVE, operator,
        ZERO_ADDRESS, wallet, {"from": accounts[0]})

    tx = auction_factory.createMarket(template_id, fixed_token_cal,
                                      AUCTION_TOKENS, wallet, _data, {
                                          "from": accounts[0],
                                          "value": ETH_TO_FEE
                                      })

    markets = miso_helper.getMarkets()
    print("markets:", markets)
    def post_deploy_setup(self, deploy=True):
        """
        Distribute digg to geyser and allow strategy to take
        """
        super().post_deploy_setup(deploy=deploy)

        # Track our digg system within badger system for convenience.
        self.badger.add_existing_digg(self.digg)
        if not deploy:
            return

        digg = self.digg.token
        # Transfer initial emissions to DiggFaucet
        amount = digg_config_test.geyserParams.unlockSchedules.digg[0].amount
        digg.transfer(self.rewards, amount, {"from": self.deployer})
        self.rewards.notifyRewardAmount(
            chain.time(),
            days(7),
            digg.fragmentsToShares(amount),
            {"from": self.deployer},
        )

        self.rewards.grantRole(PAUSER_ROLE, self.keeper,
                               {"from": self.deployer})
        self.rewards.grantRole(UNPAUSER_ROLE, self.guardian,
                               {"from": self.deployer})

        # Make strategy the recipient of the DIGG faucet
        self.rewards.initializeRecipient(self.strategy,
                                         {"from": self.deployer})

        if self.strategy.paused():
            self.strategy.unpause({"from": self.governance})
Example #27
0
def test_create_crowdsale_data(Crowdsale, auction_factory, fixed_token_cal,
                               crowdsale_template):
    assert fixed_token_cal.balanceOf(accounts[0]) == AUCTION_TOKENS
    start_time = chain.time() + 10
    end_time = start_time + CROWDSALE_TIME
    operator = accounts[0]
    wallet = accounts[1]
    template_id = auction_factory.getTemplateId(crowdsale_template)

    fixed_token_cal.approve(auction_factory, CROWDSALE_TOKENS,
                            {"from": accounts[0]})

    _data = crowdsale_template.getCrowdsaleInitData(
        auction_factory, fixed_token_cal, ETH_ADDRESS, CROWDSALE_TOKENS,
        start_time, end_time, CROWDSALE_RATE, CROWDSALE_GOAL, operator,
        ZERO_ADDRESS, wallet, {"from": accounts[0]})

    new_crowdsale = auction_factory.createMarket(template_id, fixed_token_cal,
                                                 CROWDSALE_TOKENS, wallet,
                                                 _data).return_value
    new_crowdsale = Crowdsale.at(new_crowdsale)
    chain.sleep(20)

    token_buyer = accounts[1]
    eth_to_transfer = 5 * TENPOW18

    tx = new_crowdsale.buyTokensEth(token_buyer, True, {
        "value": eth_to_transfer,
        "from": token_buyer
    })
    assert 'TokensPurchased' in tx.events
def test_fails_on_excess_eth_usdc_price_change(interface, whale, steth_token, vault_user, ust_recipient, liquidator, mock_vault, feed_usdc_eth, helpers):
    router = interface.UniswapV3Router(UNISWAP_ROUTER_V3)
    factory = interface.UniswapV3Factory(router.factory())
    pool = interface.UniswapV3Pool(factory.getPool(USDC_TOKEN, WETH_TOKEN, UNISWAP_USDC_POOL_3_FEE))

    feed_price = helpers.get_price(feed_usdc_eth, True)
    print("chainlink eth->usdc price", feed_price)
    deadline = chain.time() + 3600
    liquidity_amount = 10_000 * 10 ** 18
    router.exactInputSingle(
        (
            WETH_TOKEN,
            USDC_TOKEN,
            UNISWAP_USDC_POOL_3_FEE,
            whale,  # recipient
            deadline,  # deadline
            liquidity_amount,  # amount_in,
            0,  # amount_out_min,
            0,  # sqrtPriceLimitX96
        ),
        {"from": whale, "amount": liquidity_amount},
    )
    sqrtPriceX96 = pool.slot0()[0]
    pool_price = (10 ** WETH_DECIMALS) / (10 ** USDC_DECIMALS) * (2 ** 192 / sqrtPriceX96 ** 2)
    print("pool eth->usdc price", pool_price)
    assert feed_price * (100 - MAX_ETH_USDC_PRICE_DIFF_PERCENT) / 100 >= pool_price

    steth_amount = 10 ** 18
    steth_token.transfer(liquidator, steth_amount, {"from": vault_user})

    with reverts():
        liquidator.liquidate(ust_recipient, {"from": mock_vault})
Example #29
0
def crowdsale_3(Crowdsale, mintable_token, pool_liquidity):
    crowdsale = Crowdsale.deploy({"from": accounts[0]})
    mintable_token.mint(accounts[0], AUCTION_TOKENS, {"from": accounts[0]})
    assert mintable_token.balanceOf(accounts[0]) == AUCTION_TOKENS

    start_time = chain.time() + 10
    end_time = start_time + CROWDSALE_TIME
    wallet = accounts[4]
    operator = pool_liquidity
    
    mintable_token.approve(crowdsale, AUCTION_TOKENS, {"from": accounts[0]})
    crowdsale.initCrowdsale(
        accounts[0],
        mintable_token,
        ETH_ADDRESS,
        CROWDSALE_TOKENS,
        start_time,
        end_time,
        CROWDSALE_RATE,
        CROWDSALE_GOAL,
        operator,
        ZERO_ADDRESS,
        wallet,
        {"from": accounts[0]}
    )
    assert mintable_token.balanceOf(crowdsale) == AUCTION_TOKENS
    chain.sleep(10)
    return crowdsale
Example #30
0
def test_perf_fee(vault, strategist, pool, user, strat_simp_gwap, keeper,
                  mock_router, delegate, registry):
    registry.setFeeTo(delegate, {'from': delegate})
    strat_simp_gwap.setMaxTickDiff(vault, 2**23 - 2, {"from": strategist})
    vault.setPerformanceFee(1000, {'from': strategist})
    chain.sleep(300)
    strat_simp_gwap.rebalance(vault,
                              pool.pool.slot0().dict()["tick"],
                              {"from": keeper})
    vault.deposit(
        1e30,
        1e30,
        0,
        0,
        user,
        chain.time() + 60,
        {"from": user},
    )
    lower, upper = vault.mainPosition()
    lower = int(1.0001**(lower / 2) * (1 << 96))
    upper = int(1.0001**(upper / 2) * (1 << 96))
    assert vault.balanceOf(delegate) == 0
    for _ in range(5):
        mock_router.swapLimit(pool.pool, True, 1e30, lower, {'from': user})
        mock_router.swapLimit(pool.pool, False, 1e30, upper, {'from': user})
    strat_simp_gwap.rebalance(vault,
                              pool.pool.slot0().dict()["tick"],
                              {"from": keeper})
    assert vault.balanceOf(delegate) > 0