示例#1
0
    def autoDeploy(self):
        self.Wallet.Rebuild()
        function_code = LoadContract([neo_fund_avm, '0710', '05', 'True'])
        self.contract_script = generate_deploy_script(
            function_code.Script, 'NeoFund', str(int(time.time())), 'Nick',
            '*****@*****.**', 'auto deploy', True,
            ord(function_code.ReturnType), function_code.ParameterList)

        if self.contract_script is not None:
            self.neo_fund_sc = function_code.ToJson()['hash']
            # self.neo_fund_sc_addr = ImportContractAddr(self.Wallet, [self.neo_fund_sc, test_pub_addr]).Address

            print('SC Hash: ', self.neo_fund_sc)
            # print('SC Addr: ',  self.neo_fund_sc_addr)

        return self.contract_script
示例#2
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
示例#3
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
示例#4
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()
    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
示例#6
0
    def test_loadcontract(self):
        # test for void (ff) type in params
        with self.assertRaises(ValueError) as e:
            LoadContract("path", False, False, False, "07ff10", "01")

        self.assertTrue("Void is not a valid input parameter type" in str(e.exception))

        # test for .py in path
        with self.assertRaises(ValueError) as e:
            res = LoadContract("path.py", False, False, False, "070710", "01")
            self.assertFalse(res)
        self.assertTrue("Please load a compiled .avm file" in str(e.exception))

        # test if a file is not found
        with mock.patch("builtins.open", new_callable=mock.mock_open) as mo:
            with self.assertRaises(Exception) as context:
                mock_file = mo.return_value
                mock_file.read.side_effect = None

                res = LoadContract("path.avm", False, False, False, "070710", "01")

                self.assertIn("Error loading contract for path", str(context.exception))
                self.assertTrue(res is None)

        # test params exception
        with mock.patch("builtins.open", mock.mock_open(read_data="path.avm")):
            with mock.patch("neo.Prompt.Commands.LoadSmartContract.binascii", return_value=TypeError):
                res = LoadContract("path.avm", False, False, False, "070710", "01")

        self.assertTrue(res)

        # test params exception
        with mock.patch("builtins.open", mock.mock_open(read_data="path.avm")):
            with mock.patch("builtins.bytearray", return_value=TypeError):
                res = LoadContract("path.avm", False, False, False, "070710", "01")

        self.assertTrue(res)

        # test good contract
        with mock.patch("builtins.open", mock.mock_open(read_data="path.avm")):
            res = LoadContract("path.avm", True, True, True, "070710", "01")

        self.assertTrue(res)

        # test a contract with no params
        with mock.patch("builtins.open", mock.mock_open(read_data="path.avm")):
            res = LoadContract("path.avm", False, False, False, "", "01")

        self.assertTrue(res)
示例#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 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
示例#8
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}