Пример #1
0
def deposit():
    try:
        amt = 0
        try:
            amt = int(request.form.get('amount'))
        except:
            flash('Amount must be numeric')
            return redirect(url_for('home'))

        erc20_symbol = app.config['SYMB']
        wall = UserWallet.query.filter_by(uid=current_user.id).first()

        savingPlatform = app.config['PROTOCOL']  # Compound / Aave
        if savingPlatform == 'COMP':
            compSavings = SavingsCompound(wall, erc20_symbol)
            balance = getWalletTokenBalance(wall.address, erc20_symbol)
            if balance < amt:
                flash('Insuficent funds')
                return redirect(url_for('home'))
            ret = compSavings.doDeposit(amt)
        else:
            aaveSavings = SavingsAave(wall, erc20_symbol)
            balance = getWalletTokenBalance(wall.address, erc20_symbol)
            if balance < amt:
                flash('Insuficent funds')
                return redirect(url_for('home'))
            ret = aaveSavings.doDeposit(amt)

        if str(ret).startswith("Error"):
            flash(ret)
            return redirect(url_for('home'))

        return render_template('products/deposit.html')
    except Exception as e:
        app.logger.error(str(e), extra={'user': ''})
        return redirect(url_for('errors.error'))
Пример #2
0
def dashboard():
    try:

        showWalletInfo = request.args.get('show') or ''

        erc20_symbol = app.config['SYMB']
        wall = UserWallet.query.filter_by(uid=current_user.id).first()
        savingPlatform = app.config['PROTOCOL']  # Compound / Aave

        # need some class factory to remove if/else
        if savingPlatform == 'COMP':
            compSavings = SavingsCompound(wall, erc20_symbol)
            dashboard_data = compSavings.getDepositData()
            trans_data = compSavings.getUserTransactions()
            dashboard_data.apy = str(round(compSavings.getTokenAPY(), 2))
        else:  # Aave
            aaveSavings = SavingsAave(wall, erc20_symbol)
            dashboard_data = aaveSavings.getDepositData()
            trans_data = aaveSavings.getUserTransactions()
            dashboard_data.apy = str(round(aaveSavings.getTokenAPY(), 2))

        erc20_balance = ''
        ethBalance = ''
        avg_gp = 0
        if showWalletInfo.upper() == 'Y':
            avg_gp = str(
                getGasPrice() * 21000 / 1000000000) + ' ETH'  # gas 21000
            erc20_balance = str(
                getWalletTokenBalance(wall.address,
                                      erc20_symbol)) + ' ' + erc20_symbol
            ethBalance = str(getEthBalance(wall.address)) + ' ETH'

        return render_template('dashboard/dashboard.html',
                               data=dashboard_data,
                               transactionList=trans_data,
                               ad=wall.address,
                               tokenbalance=erc20_balance,
                               ethbalance=ethBalance,
                               gasPrice=avg_gp,
                               showAddr=showWalletInfo.upper())
    except Exception as e:
        app.logger.error(str(e), extra={'user': ''})
        return redirect(url_for('errors.error'))
Пример #3
0
    def tradeToken(self, token_symbol, token_amount):

        userToken = app.config['SYMB']  # token user owns

        availableBalance = getWalletTokenBalance(self.userWallet.address,
                                                 userToken)
        if (availableBalance < token_amount):
            return "Insuficent amount in your wallet"

        uni_contract_address = self.UNISWAP_CONTRACT_ADDR
        # convert in underlying token balance
        amount = convertAmountToWei(userToken, token_amount)

        if not isApproved(self.userWallet.address, userToken,
                          uni_contract_address, amount, 'UNI'):
            approve(userWall.address, userToken, uni_contract_address, amount,
                    self.userWallet.privateKey, 'UNI')

        w3 = getW3()
        abi_json = getContractAbiJson('UNI')
        abi = abi_json['abi']
        uniswap_contract = getContract(w3, abi, uni_contract_address)
        nonce = w3.eth.getTransactionCount(self.userWallet.address)

        # function swapExactTokensForTokens
        # uint amountIn,
        # uint amountOutMin,
        # address[] calldata path,
        # address to,
        # uint deadline
        # ) external returns (uint[] memory amounts);

        amountOutMin = int(
            amount) * 0.0098  # __convertAmountToWei('DAI', amt/2)
        addressPaths = [
            Web3.toChecksumAddress(getTokenAddress(userToken, 'UNI')),
            Web3.toChecksumAddress(getTokenAddress(token_symbol, 'UNI'))
        ]

        # current_time = datetime.datetime.now(datetime.timezone.utc)
        # unix_timestamp = current_time.timestamp() # works if Python >= 3.3
        # deadline = int(unix_timestamp + (20 * 60)) # 20 minutes
        deadline = int(time.time()) + 10000

        trade_tx = uniswap_contract.functions.swapExactTokensForTokens(
            int(amount), int(amountOutMin), addressPaths,
            self.userWallet.address, deadline).buildTransaction({
                'chainId':
                getChainId(),
                'gas':
                5000000,
                'gasPrice':
                w3.toWei('20', 'gwei'),
                'nonce':
                nonce
            })
        signed_txn = w3.eth.account.sign_transaction(
            trade_tx, self.userWallet.privateKey)
        try:
            tx = w3.eth.sendRawTransaction(signed_txn.rawTransaction)
            # return tx.hex()
            try:
                txn_receipt = w3.eth.waitForTransactionReceipt(tx, timeout=300)
            except Exception:
                return {'status': 'failed', 'error': 'timeout'}
            else:
                return {'status': 'success', 'receipt': txn_receipt}

        except ValueError as err:
            # return (json.loads(str(err).replace("'", '"')), 402, {'Content-Type': 'application/json'})
            return 'Error: ' + str(err)