示例#1
0
    def GetBalance(self, wallet, address, as_string=False):
        """
        Get the token balance.

        Args:
            wallet (neo.Wallets.Wallet): a wallet instance.
            address (str): public address of the account to get the token balance of.
            as_string (bool): whether the return value should be a string. Default is False, returning an integer.

        Returns:
            int/str: token balance value as int (default), token balanace as string if `as_string` is set to True. 0 if balance retrieval failed.
        """
        addr = parse_param(address, wallet)
        if isinstance(addr, UInt160):
            addr = addr.Data
        sb = ScriptBuilder()
        sb.EmitAppCallWithOperationAndArgs(self.ScriptHash, 'balanceOf', [addr])

        tx, fee, results, num_ops = test_invoke(sb.ToArray(), wallet, [])

        try:
            val = results[0].GetBigInteger()
            precision_divisor = pow(10, self.decimals)
            balance = Decimal(val) / Decimal(precision_divisor)
            if as_string:
                formatter_str = '.%sf' % self.decimals
                balance_str = format(balance, formatter_str)
                return balance_str
            return balance
        except Exception as e:
            logger.error("could not get balance: %s " % e)
            traceback.print_stack()

        return 0
示例#2
0
    def Query(self, wallet):
        """
        Query the smart contract for its token information (name, symbol, decimals).

        Args:
            wallet (neo.Wallets.Wallet): a wallet instance.

        Returns:
            None: if the NEP5Token instance `Name` is already set.
            True: if all information was retrieved.
            False: if information retrieval failed.
        """
        if self.name is not None:
            # don't query twice
            return

        sb = ScriptBuilder()
        sb.EmitAppCallWithOperation(self.ScriptHash, 'name')
        sb.EmitAppCallWithOperation(self.ScriptHash, 'symbol')
        sb.EmitAppCallWithOperation(self.ScriptHash, 'decimals')

        tx, fee, results, num_ops = test_invoke(sb.ToArray(), wallet, [])

        try:
            self.name = results[0].GetString()
            self.symbol = results[1].GetString()
            self.decimals = results[2].GetBigInteger()
            return True
        except Exception as e:
            logger.error("could not query token %s " % e)
        return False
示例#3
0
    def Transfer(self, wallet, from_addr, to_addr, amount, tx_attributes=None):
        """
        Transfer a specified amount of the NEP5Token to another address.

        Args:
            wallet (neo.Wallets.Wallet): a wallet instance.
            from_addr (str): public address of the account to transfer the given amount from.
            to_addr (str): public address of the account to transfer the given amount to.
            amount (int): quantity to send.
            tx_attributes (list): a list of TransactionAtribute objects.

        Returns:
            tuple:
                InvocationTransaction: the transaction.
                int: the transaction fee.
                list: the neo VM evaluationstack results.
        """
        if not tx_attributes:
            tx_attributes = []

        sb = ScriptBuilder()
        sb.EmitAppCallWithOperationAndArgs(self.ScriptHash, 'transfer',
                                           [parse_param(from_addr, wallet), parse_param(to_addr, wallet),
                                            parse_param(amount)])

        tx, fee, results, num_ops = test_invoke(sb.ToArray(), wallet, [], from_addr=from_addr, invoke_attrs=tx_attributes)

        return tx, fee, results
示例#4
0
    def GetBalance(self, wallet, address, as_string=False):
        """
        Get the token balance.

        Args:
            wallet (neo.Wallets.Wallet): a wallet instance.
            address (str): public address of the account to get the token balance of.
            as_string (bool): whether the return value should be a string. Default is False, returning an integer.

        Returns:
            int/str: token balance value as int (default), token balanace as string if `as_string` is set to True. 0 if balance retrieval failed.
        """
        addr = parse_param(address, wallet)
        if isinstance(addr, UInt160):
            addr = addr.Data
        sb = ScriptBuilder()
        sb.EmitAppCallWithOperationAndArgs(self.ScriptHash, 'balanceOf', [addr])

        tx, fee, results, num_ops = test_invoke(sb.ToArray(), wallet, [])

        try:
            val = results[0].GetBigInteger()
            precision_divisor = pow(10, self.decimals)
            balance = Decimal(val) / Decimal(precision_divisor)
            if as_string:
                formatter_str = '.%sf' % self.decimals
                balance_str = format(balance, formatter_str)
                return balance_str
            return balance
        except Exception as e:
            logger.error("could not get balance: %s " % e)
            traceback.print_stack()

        return 0
def GetWithdrawalBalance(wallet, contract_hash, from_addr, asset_type):
    sb = ScriptBuilder()
    sb.EmitAppCallWithOperationAndData(contract_hash, 'balance_%s' % asset_type, from_addr)

    try:
        tx, fee, results, num_ops = test_invoke(sb.ToArray(), wallet, [])

        return results[0].GetBigInteger()
    except Exception as e:
        print("could not get balance: %s " % e)
示例#6
0
    def load_smart_contract(self, args):
        if not self.Wallet:
            print("Please open a wallet")
            return

        args, from_addr = get_from_addr(args)
        print("-------------------------------------->")
        print(args)
        print("<<<<<<<<<<<<-------------------------------------->")
        print(from_addr)
        print("<<<<<<<<<<<<----------------------+++++---------------->")
        function_code = LoadContract(args[1:])

        if function_code:

            contract_script = GatherContractDetails(function_code)

            if contract_script is not None:

                tx, fee, results, num_ops = test_invoke(contract_script,
                                                        self.Wallet, [],
                                                        from_addr=from_addr)

                if tx is not None and results is not None:
                    print(
                        "\n-------------------------------------------------------------------------------------------------------------------------------------"
                    )
                    print("Test deploy invoke successful")
                    print("Total operations executed: %s " % num_ops)
                    print("Results:")
                    print([item.GetInterface() for item in results])
                    print("Deploy Invoke TX GAS cost: %s " %
                          (tx.Gas.value / Fixed8.D))
                    print("Deploy Invoke TX Fee: %s " % (fee.value / Fixed8.D))
                    print(
                        "-------------------------------------------------------------------------------------------------------------------------------------\n"
                    )
                    print(
                        "Enter your password to continue and deploy this contract"
                    )

                    passwd = prompt("[password]> ", is_password=True)
                    if not self.Wallet.ValidatePassword(passwd):
                        return print("Incorrect password")

                    result = InvokeContract(self.Wallet,
                                            tx,
                                            Fixed8.Zero(),
                                            from_addr=from_addr)

                    return
                else:
                    print("Test invoke failed")
                    print("TX is %s, results are %s" % (tx, results))
                    return
示例#7
0
    def load_smart_contract(self, args):

        if not self.Wallet:
            print("please open wallet")
            return

        function_code = LoadContract(args[1:])

        if function_code:

            #cname=None
            #if len(args) > 6:
            #    cname = args[6:][0]
            #print("name="+args[6:][0])
            #contract_script = GatherContractDetails(function_code, self, cname)

            contract_script = GatherContractDetails(function_code, self)

            if contract_script is not None:

                tx, fee, results, num_ops = test_invoke(
                    contract_script, self.Wallet, [])

                if tx is not None and results is not None:
                    print(
                        "\n-------------------------------------------------------------------------------------------------------------------------------------"
                    )
                    print("Test deploy invoke successful")
                    print("Total operations executed: %s " % num_ops)
                    print("Results %s " % [str(item) for item in results])
                    print("Deploy Invoke TX gas cost: %s " %
                          (tx.Gas.value / Fixed8.D))
                    print("Deploy Invoke TX Fee: %s " % (fee.value / Fixed8.D))
                    print(
                        "-------------------------------------------------------------------------------------------------------------------------------------\n"
                    )
                    print(
                        "Enter your password to continue and deploy this contract"
                    )

                    passwd = 'coz'
                    #passwd = prompt("[password]> ", is_password=True)
                    if not self.Wallet.ValidatePassword(passwd):
                        return print("Incorrect password")

                    result = InvokeContract(self.Wallet, tx, Fixed8.Zero())

                    if result is False:
                        return None

                    return tx
                else:
                    print("test ivoke failed")
                    print("tx is, results are %s %s " % (tx, results))
                    return None
示例#8
0
    def invokeDeploy(self):
        if self.contract_script:
            tx, fee, results, num_ops = test_invoke(self.contract_script,
                                                    self.Wallet, [])
            print("tx", tx.Hash)
            print("tx.inputs", tx.inputs)
            print("fee", fee)
            InvokeContract(self.Wallet, tx, fee)

            print('\nDEPLOY', results)
            print('new_sc:', self.neo_fund_sc)
            print('deploing Contract...')
示例#9
0
    def worker(self):
        self.chain.Pause()
        BuildAndRun(self.args, wallet=self.wallet, verbose=True)
        self.chain.Resume()

        avm_path = self.scPath.replace('.py', '.avm')
        self.args[0] = avm_path

        from_addr = None

        current_height = 0
        code = LoadContract(args=self.args)
        # /scripts/sc.avm 0710 02 True False False
        if code:
            script = generate_deploy_script(
                code.Script,
                "myTestSmartContract",  # name
                "test",  # version
                "",  # author
                "",  # email
                "",  # description
                code.ContractProperties,
                code.ReturnTypeBigInteger,
                code.ParameterList)
            if script is not None:
                tx, fee, results, num_ops = test_invoke(script,
                                                        self.wallet, [],
                                                        from_addr=from_addr)
                if tx is not None and results is not None:
                    print("Test deploy invoke successful")
                    print("Deploy Invoke TX GAS cost: %s " %
                          (tx.Gas.value / Fixed8.D))
                    print("Deploy Invoke TX Fee: %s " % (fee.value / Fixed8.D))
                    print("-------------------------")
                    while not self.isSynced:
                        self.show_state()
                        time.sleep(1)
                    result = InvokeContract(self.wallet,
                                            tx,
                                            Fixed8.Zero(),
                                            from_addr=from_addr)
                    print("Result: ", result.ToJson(), self.isSynced)
                    print("Result: ", tx.ToJson())
                    current_height = self.chain.Height + 1

            print("Script:", script)
        # we expect the transaction to be included in the next block:
        while current_height > self.chain.Height:
            self.show_state()
            time.sleep(5)
        self.twist.stop()
示例#10
0
    def load_smart_contract(self, args):
        if not self.Wallet:
            print("Please open a wallet")
            return

        function_code = LoadContract(args[1:])

        if function_code:

            contract_script = GatherContractDetails(function_code, self)

            if contract_script is not None:

                tx, fee, results, num_ops = test_invoke(
                    contract_script, self.Wallet, [])

                if tx is not None and results is not None:
                    print(
                        "\n-------------------------------------------------------------------------------------------------------------------------------------"
                    )
                    print("Test deploy invoke successful")
                    print("Total operations executed: %s " % num_ops)
                    print("Results:")
                    print("\t(Raw) %s" % [str(item) for item in results])
                    #print("\t(Int) %s" % [item.GetBigInteger() for item in results])
                    print("\t(Str) %s" %
                          [item.GetString() for item in results])
                    print("\t(Bool) %s" %
                          [item.GetBoolean() for item in results])
                    print("Deploy Invoke TX GAS cost: %s " %
                          (tx.Gas.value / Fixed8.D))
                    print("Deploy Invoke TX Fee: %s " % (fee.value / Fixed8.D))
                    print(
                        "-------------------------------------------------------------------------------------------------------------------------------------\n"
                    )
                    print(
                        "Enter your password to continue and deploy this contract"
                    )

                    passwd = prompt("[password]> ", is_password=True)
                    if not self.Wallet.ValidatePassword(passwd):
                        return print("Incorrect password")

                    result = InvokeContract(self.Wallet, tx, Fixed8.Zero())

                    return
                else:
                    print("Test invoke failed")
                    print("TX is %s, results are %s" % (tx, results))
                    return
示例#11
0
def CancelWithdrawalHolds(wallet, contract_hash, require_password=True):
    wallet.LoadHolds()
    to_cancel = []
    for hold in wallet._holds:
        if hold.FromAddress == contract_hash:
            to_cancel.append(hold)
    if len(to_cancel) < 1:
        print("No holds to cancel")
        return

    sb = ScriptBuilder()
    for hold in to_cancel:
        sb.EmitAppCallWithOperationAndData(hold.InputHash, 'cancel_hold',
                                           hold.Vin)

    try:
        tx, fee, results, num_ops = test_invoke(sb.ToArray(), wallet, [])

        for i in results:
            if not i.GetBoolean():
                print("Error executing hold cleanup")
                return

        if require_password:
            print(
                "\n---------------------------------------------------------------"
            )
            print("Will cancel %s holds" % len(to_cancel))
            print("FEE IS %s " % fee.ToString())
            print("GAS IS %s " % tx.Gas.ToString())
            print(
                "------------------------------------------------------------------\n"
            )

            print("Enter your password to complete this request")

            passwd = prompt("[Password]> ", is_password=True)

            if not wallet.ValidatePassword(passwd):
                print("incorrect password")
                return

        result = InvokeContract(wallet, tx, fee)
        return result

    except Exception as e:
        print("could not cancel hold(s): %s " % e)
示例#12
0
def CleanupCompletedHolds(wallet, require_password=True):

    completed = wallet.LoadCompletedHolds()

    if len(completed) < 1:
        print("No holds to cleanup")
        return False

    sb = ScriptBuilder()
    for hold in completed:
        sb.EmitAppCallWithOperationAndData(hold.InputHash, 'cleanup_hold',
                                           hold.Vin)

    try:
        tx, fee, results, num_ops = test_invoke(sb.ToArray(), wallet, [])

        for i in results:
            if not i.GetBoolean():
                print("Error executing hold cleanup")
                return False

        if require_password:
            print(
                "\n---------------------------------------------------------------"
            )
            print("Will cleanup %s holds" % len(completed))
            print("FEE IS %s " % fee.ToString())
            print("GAS IS %s " % tx.Gas.ToString())
            print(
                "------------------------------------------------------------------\n"
            )

            print("Enter your password to complete this request")

            passwd = prompt("[Password]> ", is_password=True)

            if not wallet.ValidatePassword(passwd):
                print("incorrect password")
                return

        result = InvokeContract(wallet, tx, fee)
        return result

    except Exception as e:
        print("could not cancel hold(s): %s " % e)
    return False
示例#13
0
def CancelWithdrawalHolds(wallet, contract_hash, require_password=True):
    wallet.LoadHolds()
    to_cancel = []
    for hold in wallet._holds:
        if hold.FromAddress == contract_hash:
            to_cancel.append(hold)
    if len(to_cancel) < 1:
        print("No holds to cancel")
        return

    sb = ScriptBuilder()
    for hold in to_cancel:
        sb.EmitAppCallWithOperationAndData(hold.InputHash, 'cancel_hold', hold.Vin)

    try:
        tx, fee, results, num_ops = test_invoke(sb.ToArray(), wallet, [])

        for i in results:
            if not i.GetBoolean():
                print("Error executing hold cleanup")
                return

        if require_password:
            print("\n---------------------------------------------------------------")
            print("Will cancel %s holds" % len(to_cancel))
            print("FEE IS %s " % fee.ToString())
            print("GAS IS %s " % tx.Gas.ToString())
            print("------------------------------------------------------------------\n")

            print("Enter your password to complete this request")

            passwd = prompt("[Password]> ", is_password=True)

            if not wallet.ValidatePassword(passwd):
                print("incorrect password")
                return

        result = InvokeContract(wallet, tx, fee)
        return result

    except Exception as e:
        print("could not cancel hold(s): %s " % e)
示例#14
0
    def load_smart_contract(self, args):
        if not self.Wallet:
            print("Please open a wallet")
            return

        args, from_addr = get_from_addr(args)

        function_code = LoadContract(args[1:])

        if function_code:

            contract_script = GatherContractDetails(function_code, self)

            if contract_script is not None:

                tx, fee, results, num_ops = test_invoke(contract_script, self.Wallet, [], from_addr=from_addr)

                if tx is not None and results is not None:
                    print(
                        "\n-------------------------------------------------------------------------------------------------------------------------------------")
                    print("Test deploy invoke successful")
                    print("Total operations executed: %s " % num_ops)
                    print("Results:")
                    print([item.GetInterface() for item in results])
                    print("Deploy Invoke TX GAS cost: %s " % (tx.Gas.value / Fixed8.D))
                    print("Deploy Invoke TX Fee: %s " % (fee.value / Fixed8.D))
                    print(
                        "-------------------------------------------------------------------------------------------------------------------------------------\n")
                    print("Enter your password to continue and deploy this contract")

                    passwd = prompt("[password]> ", is_password=True)
                    if not self.Wallet.ValidatePassword(passwd):
                        return print("Incorrect password")

                    result = InvokeContract(self.Wallet, tx, Fixed8.Zero(), from_addr=from_addr)

                    return
                else:
                    print("Test invoke failed")
                    print("TX is %s, results are %s" % (tx, results))
                    return
示例#15
0
def CleanupCompletedHolds(wallet, require_password=True):

    completed = wallet.LoadCompletedHolds()

    if len(completed) < 1:
        print("No holds to cleanup")
        return False

    sb = ScriptBuilder()
    for hold in completed:
        sb.EmitAppCallWithOperationAndData(hold.InputHash, 'cleanup_hold', hold.Vin)

    try:
        tx, fee, results, num_ops = test_invoke(sb.ToArray(), wallet, [])

        for i in results:
            if not i.GetBoolean():
                print("Error executing hold cleanup")
                return False

        if require_password:
            print("\n---------------------------------------------------------------")
            print("Will cleanup %s holds" % len(completed))
            print("FEE IS %s " % fee.ToString())
            print("GAS IS %s " % tx.Gas.ToString())
            print("------------------------------------------------------------------\n")

            print("Enter your password to complete this request")

            passwd = prompt("[Password]> ", is_password=True)

            if not wallet.ValidatePassword(passwd):
                print("incorrect password")
                return

        result = InvokeContract(wallet, tx, fee)
        return result

    except Exception as e:
        print("could not cancel hold(s): %s " % e)
    return False
示例#16
0
    def GetBalance(self, wallet, address, as_string=False):
        """
        Get the token balance.

        Args:
            wallet (neo.Wallets.Wallet): a wallet instance.
            address (str): public address of the account to get the token balance of.
            as_string (bool): whether the return value should be a string. Default is False, returning an integer.

        Returns:
            int/str: token balance value as int (default), token balanace as string if `as_string` is set to True. 0 if balance retrieval failed.
        """
        addr = PromptUtils.parse_param(address, wallet)
        if isinstance(addr, UInt160):
            addr = addr.Data
        sb = ScriptBuilder()
        sb.EmitAppCallWithOperationAndArgs(self.ScriptHash, 'balanceOf',
                                           [addr])

        tx, fee, results, num_ops, engine_success = test_invoke(
            sb.ToArray(), wallet, [])
        if engine_success:
            try:
                val = results[0].GetBigInteger()
                precision_divisor = pow(10, self.decimals)
                balance = Decimal(val) / Decimal(precision_divisor)
                if as_string:
                    formatter_str = '.%sf' % self.decimals
                    balance_str = format(balance, formatter_str)
                    return balance_str
                return balance
            except Exception as e:
                logger.error("could not get balance: %s " % e)
                traceback.print_stack()
        else:
            addr_str = Crypto.ToAddress(UInt160(data=addr))
            logger.error(
                f"Could not get balance of address {addr_str} for token contract {self.ScriptHash}. VM execution failed. Make sure the contract exists on the network and that it adheres to the NEP-5 standard"
            )

        return 0
示例#17
0
    def load_smart_contract(self, args):

        if not self.Wallet:
            print("please open wallet")
            return

        function_code = LoadContract(args[1:])

        if function_code is not None:

            contract_script = GatherContractDetails(function_code, self)

            if contract_script is not None:

                tx, fee, results, num_ops = test_invoke(
                    contract_script, self.Wallet, [])

                if tx is not None and results is not None:
                    self._invoke_test_tx = tx
                    self._invoke_test_tx_fee = fee
                    print(
                        "\n-------------------------------------------------------------------------------------------------------------------------------------"
                    )
                    print("Test deploy invoke successful")
                    print("Total operations executed: %s " % num_ops)
                    print("Results %s " % [str(item) for item in results])
                    print("Deploy Invoke TX gas cost: %s " %
                          (tx.Gas.value / Fixed8.D))
                    print("Deploy Invoke TX Fee: %s " % (fee.value / Fixed8.D))
                    print(
                        "-------------------------------------------------------------------------------------------------------------------------------------\n"
                    )
                    print(
                        "You may now deploy this contract on the blockchain by using the 'invoke' command with no arguments or type 'cancel' to cancel deploy\n"
                    )
                    return
                else:
                    print("test ivoke failed")
                    print("tx is, results are %s %s " % (tx, results))
                    return
示例#18
0
    def load_smart_contract(self, args):
        if not self.Wallet:
            print("Please open a wallet")
            return

        args, from_addr = get_from_addr(args)

        function_code = LoadContract(args[1:])

        if function_code:
            # Fill contract info and generate bytescript.
            contract_script = self.GatherContractDetails(function_code)
            contract_script_json = function_code.ToJson()
            hash = contract_script_json['hash']

            if contract_script is not None:
                # testing invoke contract.
                tx, fee, results, num_ops = test_invoke(contract_script,
                                                        self.Wallet, [],
                                                        from_addr=from_addr)

                if tx is not None and results is not None:
                    print(
                        "Enter your password to continue and deploy this contract"
                    )
                    passwd = prompt("[password]> ", is_password=True)
                    if not self.Wallet.ValidatePassword(passwd):
                        return print("Incorrect password")
                    # Deploy contract to the blockchain.
                    result = InvokeContract(self.Wallet,
                                            tx,
                                            Fixed8.Zero(),
                                            from_addr=from_addr)

                    return hash
                else:
                    print("Test invoke failed")
                    print("TX is %s, results are %s" % (tx, results))
                    return
示例#19
0
    def Transfer(self, wallet, from_addr, to_addr, amount):
        """
        Transfer a specified amount of the NEP5Token to another address.

        Args:
            wallet (neo.Wallets.Wallet): a wallet instance.
            from_addr (str): public address of the account to transfer the given amount from.
            to_addr (str): public address of the account to transfer the given amount to.
            amount (int): quantity to send.

        Returns:
            tuple:
                InvocationTransaction: the transaction.
                int: the transaction fee.
                list: the neo VM evaluationstack results.
        """
        sb = ScriptBuilder()
        sb.EmitAppCallWithOperationAndArgs(self.ScriptHash, 'transfer',
                                           [parse_param(from_addr, wallet), parse_param(to_addr, wallet),
                                            parse_param(amount)])

        tx, fee, results, num_ops = test_invoke(sb.ToArray(), wallet, [], from_addr=from_addr)

        return tx, fee, results
示例#20
0
    def execute(self, arguments):
        wallet = PromptData.Wallet
        if not wallet:
            print("Please open a wallet")
            return False

        if len(arguments) < 5:
            print("Please specify the required parameters")
            return False

        args, from_addr = PromptUtils.get_from_addr(arguments)
        arguments, priority_fee = PromptUtils.get_fee(arguments)

        p_fee = Fixed8.Zero()
        if priority_fee is not None:
            p_fee = priority_fee
            if p_fee is False:
                logger.debug("invalid fee")
                return False

        path = args[0]

        try:
            needs_storage = bool(util.strtobool(args[1]))
            needs_dynamic_invoke = bool(util.strtobool(args[2]))
            is_payable = bool(util.strtobool(args[3]))

        except ValueError:
            print("Invalid boolean option")
            return False

        params = args[4]
        return_type = args[5]

        try:
            function_code = LoadContract(path, needs_storage,
                                         needs_dynamic_invoke, is_payable,
                                         params, return_type)
        except (ValueError, Exception) as e:
            print(str(e))
            return False

        contract_script = GatherContractDetails(function_code)
        if not contract_script:
            print("Failed to generate deploy script")
            return False

        tx, fee, results, num_ops, engine_success = test_invoke(
            contract_script, wallet, [], from_addr=from_addr)
        if tx and results:
            print(
                "\n-------------------------------------------------------------------------------------------------------------------------------------"
            )
            print("Test deploy invoke successful")
            print(f"Total operations executed: {num_ops}")
            print("Results:")
            print([item.GetInterface() for item in results])
            print(f"Deploy Invoke TX GAS cost: {tx.Gas.value / Fixed8.D}")
            print(f"Deploy Invoke TX Fee: {fee.value / Fixed8.D}")
            print(
                "-------------------------------------------------------------------------------------------------------------------------------------\n"
            )
            comb_fee = p_fee + fee
            if comb_fee != fee:
                print(
                    f"Priority Fee ({p_fee.value / Fixed8.D}) + Deploy Invoke TX Fee ({fee.value / Fixed8.D}) = {comb_fee.value / Fixed8.D}\n"
                )
            print("Enter your password to continue and deploy this contract")

            passwd = prompt("[password]> ", is_password=True)
            if not wallet.ValidatePassword(passwd):
                print("Incorrect password")
                return False

            return InvokeContract(wallet, tx, comb_fee, from_addr=from_addr)
        else:
            print("Test invoke failed")
            print(f"TX is {tx}, results are {results}")
            return False
def echo_post(request):
    if walletinfo.Wallet is None:
        wallethandler()
        #print("Wallet %s " % json.dumps(walletinfo.Wallet.ToJson(), indent=4)
        #print("Wallet %s " % json.dumps(walletinfo.Wallet.ToJson(), indent=4))
        #return json.dumps(walletinfo.Wallet.ToJson(), indent=4)
    body = json.loads(request.content.read().decode('utf-8'))
    print('2 ----2 -> Incomming Body %s' % body)
    returnvalue = 'Issue in creating wallet.Please try manual approach'
    failed_data = {
        "status":
        "failed",
        "reason":
        "Contract Not Deployed due to issues such as **smart_contract_location: not ending with .py and/or .avm .smart_contract_location link might not be raw url.Click raw button on your github file to get the correct url**. Issue might also be caused by insufficient balance in the wallet.Please try manual approach or chat with @sharedmocha#8871 on discord."
    }
    hash_json_failed = failed_data

    if (body['is_the_file__smartcontract_or_avm'] == "sc"):
        print("SMART CONTRACT ------- IN")
        sc_location = body['smart_contract_location']
        r = requests.get(sc_location, allow_redirects=True)
        localtime = str(time.time())  # this removes the decimals
        temp_filename = localtime + sc_location
        filename = re.sub('[^ a-zA-Z0-9]', '', temp_filename)
        path = '/home/ubuntu/' + filename
        scname = path + '.py'
        avmname = '/' + path + '.avm'
        try:
            open(scname, 'wb').write(r.content)
            sc_args = []
            sc_args.append(scname)
            BuildAndRun(sc_args, walletinfo.Wallet)
        except Exception as e:
            print('Exception creating file: %s' % e)
            return 'Issue Downloading and Saving your smart contract.Please try manual approach'

    else:
        sc_location = body['smart_contract_location']
        r = requests.get(sc_location, allow_redirects=True)
        localtime = str(time.time())  # this removes the decimals
        temp_filename = localtime + sc_location
        filename = re.sub('[^ a-zA-Z0-9]', '', temp_filename)
        path = '/home/ubuntu/' + filename
        scname = path + '.py'
        avmname = '/' + path + '.avm'
        try:
            open(avmname, 'wb').write(r.content)
        except Exception as e:
            print('Exception creating file: %s' % e)
            return 'Issue Downloading and Saving your smart contract avm file.Please try manual approach'

    # Deploy samrt contract  ....

    try:
        if (body['password'] != "nosforall"):
            return {
                "status": "failed",
                "reason": "Incorrect Password Provided."
            }
        args = []
        args.append("contract")
        args.append(avmname)
        args.append(body['input_type'])
        args.append(body['output_type'])
        args.append(body['does_smart_contract_needsstorage'])
        args.append(body['does_smart_contract_needsdynamicinvoke'])
        args, from_addr = get_from_addr(args)
        function_code = LoadContract(args[1:])
        failed_data = {
            "status":
            "failed",
            "reason":
            "Contract Not Deployed due to issues (or) Insufficient Balance.Please try manual approach."
        }
        function_code_json = function_code.ToJson()
        sc_hash = function_code_json['hash']
        success_data = {
            "status":
            "success",
            "hash":
            sc_hash,
            "details":
            "Wait for few minutes before you try invoke on your smart contract."
        }
        hash_json_success = success_data
        userinputs_args = []
        userinputs_args.append(body['smart_contract_name'])
        userinputs_args.append(body['smart_contract_version'])
        userinputs_args.append(body['smart_contract_author'])
        userinputs_args.append(body['smart_contract_creator_email'])
        userinputs_args.append(body['smart_contract_description'])
        if function_code:
            contract_script = GatherContractDetails(function_code,
                                                    userinputs_args)
            if contract_script is not None:
                tx, fee, results, num_ops = test_invoke(contract_script,
                                                        walletinfo.Wallet, [],
                                                        from_addr=from_addr)
                if tx is not None and results is not None:
                    print(
                        "\n-------------------------------------------------------------------------------------------------------------------------------------"
                    )
                    print("Test deploy invoke successful")
                    print("Total operations executed: %s " % num_ops)
                    print("Results:")
                    print([item.GetInterface() for item in results])
                    print("Deploy Invoke TX GAS cost: %s " %
                          (tx.Gas.value / Fixed8.D))
                    print("Deploy Invoke TX Fee: %s " % (fee.value / Fixed8.D))
                    print(
                        "-------------------------------------------------------------------------------------------------------------------------------------\n"
                    )
                    result = InvokeContract(walletinfo.Wallet,
                                            tx,
                                            Fixed8.Zero(),
                                            from_addr=from_addr)
                    if result:
                        return hash_json_success
                    else:
                        #return hash_json_failed
                        return hash_json_failed

                    #return result
                else:
                    print("Test invoke failed")
                    print("TX is %s, results are %s" % (tx, results))
                    return hash_json_failed
    except Exception as e:

        # print("Pubkey %s" % key.PublicKey.encode_point(True))

        print('Exception creating wallet: %s' % e)
        walletinfo.Wallet = None
        return hash_json_failed

    # Open and Replace Wallet
    # Echo it
    # test

    return {'post-body': returnvalue}
def RequestWithdrawFrom(wallet, asset_id, contract_hash, to_addr, amount, require_password=True):
    asset_type = asset_id.lower()
    if asset_type not in ['neo', 'gas']:
        raise Exception('please specify neo or gas to withdraw')

    readable_addr = to_addr
    asset_id = get_asset_id(wallet, asset_type)

    contract = Blockchain.Default().GetContract(contract_hash)

    shash = contract.Code.ScriptHash()

    contract_addr = Crypto.ToAddress(shash)

    to_addr = parse_param(to_addr, wallet)
    amount = get_asset_amount(amount, asset_id)

    if shash not in wallet._watch_only:
        print("Add withdrawal contract address to your watch only: import watch_addr %s " % contract_addr)
        return False
    if amount < Fixed8.Zero():
        print("Cannot withdraw negative amount")
        return False

    unspents = wallet.FindUnspentCoinsByAssetAndTotal(
        asset_id=asset_id, amount=amount, from_addr=shash, use_standard=False, watch_only_val=64, reverse=True
    )

    if not unspents or len(unspents) == 0:
        print("no eligible withdrawal vins")
        return False

    balance = GetWithdrawalBalance(wallet, shash, to_addr, asset_type)

    balance_fixed8 = Fixed8(balance)
    orig_amount = amount
    if amount <= balance_fixed8:
        sb = ScriptBuilder()

        for uns in unspents:
            if amount > Fixed8.Zero():
                to_spend = amount
                if to_spend > uns.Output.Value:
                    to_spend = uns.Output.Value
                amount_bytes = bytearray(to_spend.value.to_bytes(8, 'little'))
                data = to_addr + amount_bytes
                data = data + uns.RefToBytes()
                sb.EmitAppCallWithOperationAndData(shash, 'withdraw_%s' % asset_type, data)
                amount -= uns.Output.Value

        tx, fee, results, num_ops = test_invoke(sb.ToArray(), wallet, [])

        for item in results:
            if not item.GetBoolean():
                print("Error performitng withdrawals")
                return False

        if require_password:
            print("\n---------------------------------------------------------------")
            print("Will make withdrawal request for %s %s from %s to %s " % (orig_amount.ToString(), asset_type, contract_addr, readable_addr))
            print("FEE IS %s " % fee.ToString())
            print("GAS IS %s " % tx.Gas.ToString())
            print("------------------------------------------------------------------\n")

            print("Enter your password to complete this request")

            passwd = prompt("[Password]> ", is_password=True)

            if not wallet.ValidatePassword(passwd):
                print("incorrect password")
                return

        result = InvokeContract(wallet, tx, fee)
        return result
    else:
        print("insufficient balance")
        return False