def BuildAndRun(arguments, wallet, verbose=True, min_fee=DEFAULT_MIN_FEE, invocation_test_mode=True): arguments, from_addr = get_from_addr(arguments) arguments, invoke_attrs = get_tx_attr_from_args(arguments) arguments, owners = get_owners_from_params(arguments) path = get_arg(arguments) contract_script = Build(arguments) if contract_script is not None: debug_map_path = path.replace('.py', '.debug.json') debug_map = None if os.path.exists(debug_map_path): with open(debug_map_path, 'r') as dbg: debug_map = json.load(dbg) return DoRun(contract_script, arguments, wallet, path, verbose, from_addr, min_fee, invocation_test_mode, debug_map=debug_map, invoke_attrs=invoke_attrs, owners=owners) else: print('Please check the path to your Python (.py) file to compile') return None, None, None, None
def BuildAndRun(arguments, wallet, verbose=True, min_fee=DEFAULT_MIN_FEE, invocation_test_mode=True): arguments, from_addr = get_from_addr(arguments) arguments, invoke_attrs = get_tx_attr_from_args(arguments) arguments, owners = get_owners_from_params(arguments) path = get_arg(arguments) contract_script = Compiler.instance().load_and_save(path) newpath = path.replace('.py', '.avm') logger.info("Saved output to %s " % newpath) debug_map_path = path.replace('.py', '.debug.json') debug_map = None if os.path.exists(debug_map_path): with open(debug_map_path, 'r') as dbg: debug_map = json.load(dbg) return DoRun(contract_script, arguments, wallet, path, verbose, from_addr, min_fee, invocation_test_mode, debug_map=debug_map, invoke_attrs=invoke_attrs, owners=owners)
def test_utilst_bad_type(self): args = ["--tx-attr=bytearray(b'\x00\x00')"] with self.assertRaises(Exception) as context: args, txattr = get_tx_attr_from_args(args) self.assertTrue('could not convert object' in context.exception) self.assertEqual(len(args), 0) self.assertEqual(len(txattr), 0)
def construct_send_basic(wallet, arguments): if not wallet: print("please open a wallet") return False if len(arguments) < 3: print("Not enough arguments") return False arguments, from_address = get_from_addr(arguments) arguments, priority_fee = get_fee(arguments) arguments, user_tx_attributes = get_tx_attr_from_args(arguments) arguments, owners = get_owners_from_params(arguments) to_send = get_arg(arguments) address_to = get_arg(arguments, 1) amount = get_arg(arguments, 2) assetId = get_asset_id(wallet, to_send) if assetId is None: print("Asset id not found") return False scripthash_to = lookup_addr_str(wallet, address_to) if scripthash_to is None: logger.debug("invalid address") return False scripthash_from = None if from_address is not None: scripthash_from = lookup_addr_str(wallet, from_address) if scripthash_from is None: logger.debug("invalid address") return False # if this is a token, we will use a different # transfer mechanism if type(assetId) is NEP5Token: return do_token_transfer(assetId, wallet, from_address, address_to, amount_from_string(assetId, amount), tx_attributes=user_tx_attributes) f8amount = get_asset_amount(amount, assetId) if f8amount is False: logger.debug("invalid amount") return False if float(amount) == 0: print("amount cannot be 0") return False fee = Fixed8.Zero() if priority_fee is not None: fee = priority_fee if fee is False: logger.debug("invalid fee") return False output = TransactionOutput(AssetId=assetId, Value=f8amount, script_hash=scripthash_to) contract_tx = ContractTransaction(outputs=[output]) return [contract_tx, scripthash_from, fee, owners, user_tx_attributes]
def test_12_utils_attr_str(self): args = ["--tx-attr=[{'usa:241'data':his is a remark'}]"] with self.assertRaises(Exception) as context: args, txattrs = get_tx_attr_from_args(args) self.assertTrue('could not convert object' in context.exception) self.assertEqual(len(args), 0) self.assertEqual(len(txattrs), 0)
def test_13_utilst_bad_type(self): args = ["--tx-attr=bytearray(b'\x00\x00')"] with self.assertRaises(Exception) as context: args, txattr = get_tx_attr_from_args(args) self.assertTrue('could not convert object' in context.exception) self.assertEqual(len(args), 0) self.assertEqual(len(txattr), 0)
def test_invoke_contract(self, args): if not self.Wallet: print("Please open a wallet") return args, from_addr = get_from_addr(args) args, invoke_attrs = get_tx_attr_from_args(args) args, owners = get_owners_from_params(args) if args and len(args) > 0: tx, fee, results, num_ops = TestInvokeContract( self.Wallet, args, from_addr=from_addr, invoke_attrs=invoke_attrs, owners=owners) if tx is not None and results is not None: parameterized_results = [ ContractParameter.ToParameter(item) for item in results ] print( "\n-------------------------------------------------------------------------------------------------------------------------------------" ) print("Test invoke successful") print("Total operations: %s" % num_ops) print("Results %s" % [item.ToJson() for item in parameterized_results]) print("Invoke TX GAS cost: %s" % (tx.Gas.value / Fixed8.D)) print("Invoke TX fee: %s" % (fee.value / Fixed8.D)) print( "-------------------------------------------------------------------------------------------------------------------------------------\n" ) print( "Enter your password to continue and invoke on the network\n" ) tx.Attributes = invoke_attrs passwd = prompt("[password]> ", is_password=True) if not self.Wallet.ValidatePassword(passwd): return print("Incorrect password") InvokeContract(self.Wallet, tx, fee, from_addr=from_addr, owners=owners) return else: print("Error testing contract invoke") return print("Please specify a contract to invoke")
def token_mint(wallet, args, prompt_passwd=True): token = get_asset_id(wallet, args[0]) mint_to_addr = args[1] args, invoke_attrs = get_tx_attr_from_args(args) if len(args) < 3: raise Exception("please specify assets to attach") asset_attachments = args[2:] tx, fee, results = token.Mint(wallet, mint_to_addr, asset_attachments, invoke_attrs=invoke_attrs) if results[0] is not None: print("\n-----------------------------------------------------------") print("[%s] Will mint tokens to address: %s " % (token.symbol, mint_to_addr)) print("Fee: %s " % (fee.value / Fixed8.D)) print( "-------------------------------------------------------------\n") if prompt_passwd: passwd = prompt("[Password]> ", is_password=True) if not wallet.ValidatePassword(passwd): print("incorrect password") return return InvokeWithTokenVerificationScript(wallet, tx, token, fee, invoke_attrs=invoke_attrs) else: print("Could not register addresses: %s " % str(results[0])) return False
def test_token_send_bad_user_attributes(self): with patch('neo.Prompt.Commands.Tokens.prompt', side_effect=[UserWalletTestCase.wallet_1_pass()]): wallet = self.GetWallet1(recreate=True) token = self.get_token(wallet) addr_from = wallet.GetDefaultContract().Address addr_to = self.watch_addr_str _, attributes = get_tx_attr_from_args( ['--tx-attr=[{"usa:241,"data":"This is a remark"}]']) send = token_send(wallet, token.symbol, addr_from, addr_to, 100, user_tx_attributes=attributes, prompt_passwd=True) self.assertTrue(send) res = send.ToJson() self.assertEqual(1, len(res['attributes'])) self.assertNotEqual(241, res['attributes'][0]['usage'])
def construct_send_many(wallet, arguments): if not wallet: print("please open a wallet") return False if len(arguments) is 0: print("Not enough arguments") return False outgoing = get_arg(arguments, convert_to_int=True) if outgoing is None: print("invalid outgoing number") return False if outgoing < 1: print("outgoing number must be >= 1") return False arguments, from_address = get_from_addr(arguments) arguments, change_address = get_change_addr(arguments) arguments, priority_fee = get_fee(arguments) arguments, owners = get_owners_from_params(arguments) arguments, user_tx_attributes = get_tx_attr_from_args(arguments) output = [] for i in range(outgoing): print('Outgoing Number ', i + 1) to_send = prompt("Asset to send: ") assetId = get_asset_id(wallet, to_send) if assetId is None: print("Asset id not found") return False if type(assetId) is NEP5Token: print('Sendmany does not support NEP5 tokens') return False address_to = prompt("Address to: ") scripthash_to = lookup_addr_str(wallet, address_to) if scripthash_to is None: logger.debug("invalid address") return False amount = prompt("Amount to send: ") f8amount = get_asset_amount(amount, assetId) if f8amount is False: logger.debug("invalid amount") return False if float(amount) == 0: print("amount cannot be 0") return False tx_output = TransactionOutput(AssetId=assetId, Value=f8amount, script_hash=scripthash_to) output.append(tx_output) contract_tx = ContractTransaction(outputs=output) scripthash_from = None if from_address is not None: scripthash_from = lookup_addr_str(wallet, from_address) if scripthash_from is None: logger.debug("invalid address") return False scripthash_change = None if change_address is not None: scripthash_change = lookup_addr_str(wallet, change_address) if scripthash_change is None: logger.debug("invalid address") return False fee = Fixed8.Zero() if priority_fee is not None: fee = priority_fee if fee is False: logger.debug("invalid fee") return False print("sending with fee: %s " % fee.ToString()) return [ contract_tx, scripthash_from, scripthash_change, fee, owners, user_tx_attributes ]
def construct_send_many(wallet, arguments): if len(arguments) is 0: print("Please specify the required parameter") return outgoing = get_arg(arguments, convert_to_int=True) if outgoing is None: print("Invalid outgoing number") return if outgoing < 1: print("Outgoing number must be >= 1") return arguments, from_address = get_from_addr(arguments) arguments, change_address = get_change_addr(arguments) arguments, priority_fee = get_fee(arguments) arguments, owners = get_owners_from_params(arguments) arguments, user_tx_attributes = get_tx_attr_from_args(arguments) output = [] for i in range(outgoing): try: print('Outgoing Number ', i + 1) to_send = prompt("Asset to send: ") assetId = get_asset_id(wallet, to_send) if assetId is None: print("Asset id not found") return if type(assetId) is NEP5Token: print('sendmany does not support NEP5 tokens') return address_to = prompt("Address to: ") scripthash_to = lookup_addr_str(wallet, address_to) if scripthash_to is None: logger.debug("invalid destination address") return amount = prompt("Amount to send: ") f8amount = get_asset_amount(amount, assetId) if f8amount is False: logger.debug("invalid amount") return if float(amount) == 0: print("Amount cannot be 0") return tx_output = TransactionOutput(AssetId=assetId, Value=f8amount, script_hash=scripthash_to) output.append(tx_output) except KeyboardInterrupt: print('Transaction cancelled') return contract_tx = ContractTransaction(outputs=output) scripthash_from = None if from_address is not None: scripthash_from = lookup_addr_str(wallet, from_address) if scripthash_from is None: logger.debug("invalid source address") return scripthash_change = None if change_address is not None: scripthash_change = lookup_addr_str(wallet, change_address) if scripthash_change is None: logger.debug("invalid change address") return fee = Fixed8.Zero() if priority_fee is not None: fee = priority_fee if fee is False: logger.debug("invalid fee") return print(f"Sending with fee: {fee.ToString()}") return [ contract_tx, scripthash_from, scripthash_change, fee, owners, user_tx_attributes ]
def construct_and_send(prompter, wallet, arguments, prompt_password=True): try: if not wallet: print("please open a wallet") return False if len(arguments) < 3: print("Not enough arguments") return False arguments, from_address = get_from_addr(arguments) arguments, user_tx_attributes = get_tx_attr_from_args(arguments) arguments, owners = get_owners_from_params(arguments) arguments, priority_fee = get_fee(arguments) to_send = get_arg(arguments) address_to = get_arg(arguments, 1) amount = get_arg(arguments, 2) assetId = get_asset_id(wallet, to_send) if assetId is None: print("Asset id not found") return False scripthash_to = lookup_addr_str(wallet, address_to) if scripthash_to is None: print("invalid address") return False scripthash_from = None if from_address is not None: scripthash_from = lookup_addr_str(wallet, from_address) # if this is a token, we will use a different # transfer mechanism if type(assetId) is NEP5Token: return do_token_transfer(assetId, wallet, from_address, address_to, amount_from_string(assetId, amount), prompt_passwd=prompt_password, tx_attributes=user_tx_attributes) f8amount = Fixed8.TryParse(amount, require_positive=True) if f8amount is None: print("invalid amount format") return False if type(assetId) is UInt256 and f8amount.value % pow(10, 8 - Blockchain.Default().GetAssetState(assetId.ToBytes()).Precision) != 0: print("incorrect amount precision") return False fee = Fixed8.Zero() if priority_fee is not None: fee = priority_fee print("sending with fee: %s " % fee.ToString()) output = TransactionOutput(AssetId=assetId, Value=f8amount, script_hash=scripthash_to) tx = ContractTransaction(outputs=[output]) ttx = wallet.MakeTransaction(tx=tx, change_address=None, fee=fee, from_addr=scripthash_from) if ttx is None: print("insufficient funds") return False if prompt_password: passwd = prompt("[Password]> ", is_password=True) if not wallet.ValidatePassword(passwd): print("incorrect password") return False standard_contract = wallet.GetStandardAddress() if scripthash_from is not None: signer_contract = wallet.GetContract(scripthash_from) else: signer_contract = wallet.GetContract(standard_contract) if not signer_contract.IsMultiSigContract and owners is None: data = standard_contract.Data tx.Attributes = [TransactionAttribute(usage=TransactionAttributeUsage.Script, data=data)] # insert any additional user specified tx attributes tx.Attributes = tx.Attributes + user_tx_attributes if owners: owners = list(owners) for owner in owners: tx.Attributes.append( TransactionAttribute(usage=TransactionAttributeUsage.Script, data=owner)) context = ContractParametersContext(tx, isMultiSig=signer_contract.IsMultiSigContract) wallet.Sign(context) if owners: owners = list(owners) gather_signatures(context, tx, owners) if context.Completed: tx.scripts = context.GetScripts() # print("will send tx: %s " % json.dumps(tx.ToJson(),indent=4)) relayed = NodeLeader.Instance().Relay(tx) if relayed: wallet.SaveTransaction(tx) print("Relayed Tx: %s " % tx.Hash.ToString()) return tx else: print("Could not relay tx %s " % tx.Hash.ToString()) else: print("Transaction initiated, but the signature is incomplete") print(json.dumps(context.ToJson(), separators=(',', ':'))) return False except Exception as e: print("could not send: %s " % e) traceback.print_stack() traceback.print_exc() return False
def construct_and_send(prompter, wallet, arguments, prompt_password=True): try: if not wallet: print("please open a wallet") return False if len(arguments) < 3: print("Not enough arguments") return False arguments, from_address = get_from_addr(arguments) arguments, user_tx_attributes = get_tx_attr_from_args(arguments) to_send = get_arg(arguments) address_to = get_arg(arguments, 1) amount = get_arg(arguments, 2) assetId = get_asset_id(wallet, to_send) if assetId is None: print("Asset id not found") return False scripthash_to = lookup_addr_str(wallet, address_to) if scripthash_to is None: print("invalid address") return False scripthash_from = None if from_address is not None: scripthash_from = lookup_addr_str(wallet, from_address) # if this is a token, we will use a different # transfer mechanism if type(assetId) is NEP5Token: return do_token_transfer(assetId, wallet, from_address, address_to, amount_from_string(assetId, amount), prompt_passwd=prompt_password) f8amount = Fixed8.TryParse(amount, require_positive=True) if f8amount is None: print("invalid amount format") return False if type(assetId) is UInt256 and f8amount.value % pow(10, 8 - Blockchain.Default().GetAssetState(assetId.ToBytes()).Precision) != 0: print("incorrect amount precision") return False fee = Fixed8.Zero() output = TransactionOutput(AssetId=assetId, Value=f8amount, script_hash=scripthash_to) tx = ContractTransaction(outputs=[output]) ttx = wallet.MakeTransaction(tx=tx, change_address=None, fee=fee, from_addr=scripthash_from) if ttx is None: print("insufficient funds") return False if prompt_password: passwd = prompt("[Password]> ", is_password=True) if not wallet.ValidatePassword(passwd): print("incorrect password") return False standard_contract = wallet.GetStandardAddress() if scripthash_from is not None: signer_contract = wallet.GetContract(scripthash_from) else: signer_contract = wallet.GetContract(standard_contract) if not signer_contract.IsMultiSigContract: data = standard_contract.Data tx.Attributes = [TransactionAttribute(usage=TransactionAttributeUsage.Script, data=data)] # insert any additional user specified tx attributes tx.Attributes = tx.Attributes + user_tx_attributes context = ContractParametersContext(tx, isMultiSig=signer_contract.IsMultiSigContract) wallet.Sign(context) if context.Completed: tx.scripts = context.GetScripts() # print("will send tx: %s " % json.dumps(tx.ToJson(),indent=4)) relayed = NodeLeader.Instance().Relay(tx) if relayed: wallet.SaveTransaction(tx) print("Relayed Tx: %s " % tx.Hash.ToString()) return tx else: print("Could not relay tx %s " % tx.Hash.ToString()) else: print("Transaction initiated, but the signature is incomplete") print(json.dumps(context.ToJson(), separators=(',', ':'))) return False except Exception as e: print("could not send: %s " % e) traceback.print_stack() traceback.print_exc() return False