def execute(self, arguments): wallet = PromptData.Wallet if len(arguments) < 2: print("Please specify the required parameters") return False if len(arguments) > 6: # the 3rd and 4th argument are for attaching neo/gas, 5th for attaching a fee, 6th for attaching attributes print("Too many parameters supplied. Please check your command") return False arguments, priority_fee = PromptUtils.get_fee(arguments) arguments, invoke_attrs = PromptUtils.get_tx_attr_from_args(arguments) token_str = arguments[0] try: token = PromptUtils.get_token(wallet, token_str) except ValueError as e: print(str(e)) return False to_addr = arguments[1] if not isValidPublicAddress(to_addr): print(f"{to_addr} is not a valid address") return False remaining_args = arguments[2:] asset_attachments = [] for optional in remaining_args: _, neo_to_attach, gas_to_attach = PromptUtils.get_asset_attachments([optional]) if "attach-neo" in optional: if not neo_to_attach: print(f"Could not parse value from --attach-neo. Value must be an integer") return False else: asset_attachments.append(optional) if "attach-gas" in optional: if not gas_to_attach: print(f"Could not parse value from --attach-gas") return False else: asset_attachments.append(optional) fee = Fixed8.Zero() if priority_fee is not None: fee = priority_fee if fee is False: logger.debug("invalid fee") return False return token_mint(token, wallet, to_addr, asset_attachments=asset_attachments, fee=fee, invoke_attrs=invoke_attrs)
def execute(self, arguments): wallet = PromptData.Wallet if len(arguments) < 2: print("Please specify the required parameters") return False arguments, priority_fee = PromptUtils.get_fee(arguments) token_str = arguments[0] try: token = PromptUtils.get_token(wallet, token_str) except ValueError as e: print(str(e)) return False register_addr = arguments[1:] addr_list = [] for addr in register_addr: if isValidPublicAddress(addr): addr_list.append(addr) else: print(f"{addr} is not a valid address") return False 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 tx, fee, results = token.CrowdsaleRegister(wallet, addr_list) if tx and results: if results[0].GetBigInteger() > 0: print("\n-----------------------------------------------------------") print("[%s] Will register addresses for crowdsale: %s " % (token.symbol, register_addr)) print("Invocation Fee: %s " % (fee.value / Fixed8.D)) print("-------------------------------------------------------------\n") comb_fee = p_fee + fee if comb_fee != fee: print(f"Priority Fee ({p_fee.value / Fixed8.D}) + Invocation Fee ({fee.value / Fixed8.D}) = {comb_fee.value / Fixed8.D}\n") print("Enter your password to send to the network") passwd = prompt("[Password]> ", is_password=True) if not wallet.ValidatePassword(passwd): print("incorrect password") return False return InvokeContract(wallet, tx, comb_fee) print("Could not register address(es)") return False
def test_string_from_fixed8(self): amount_str = Utils.string_from_fixed8(100234, 8) self.assertEqual(amount_str, '0.00100234') amount_str = Utils.string_from_fixed8(534353400234, 8) self.assertEqual(amount_str, '5343.53400234') amount_str = Utils.string_from_fixed8(534353400234, 2) self.assertEqual(amount_str, '5343534002.34')
def test_owner_and_assets(self): args = [1, 2, "--owners=['APRgMZHZubii29UXF9uFa6sohrsYupNAvx','AXjaFSP23Jkbe6Pk9pPGT6NBDs1HVdqaXK',]", '--attach-neo=10'] args, owners = Utils.get_owners_from_params(args) args, neo, gas = Utils.get_asset_attachments(args) self.assertEqual(args, [1, 2]) self.assertEqual(len(owners), 2) self.assertIsInstance(list(owners)[0], UInt160) self.assertEqual(neo, Fixed8.FromDecimal(10))
def test_parse_no_address(self): params = ['a', 'b', 'c'] params, result = Utils.get_parse_addresses(params) self.assertEqual(params, ['a', 'b', 'c']) self.assertTrue(result) params = ['a', 'b', 'c', '--no-parse-addr'] params, result = Utils.get_parse_addresses(params) self.assertEqual(params, ['a', 'b', 'c']) self.assertFalse(result)
def execute(self, arguments): wallet = PromptData.Wallet if not wallet: print("Please open a wallet") return False arguments, from_addr = PromptUtils.get_from_addr(arguments) arguments, invoke_attrs = PromptUtils.get_tx_attr_from_args(arguments) arguments, owners = PromptUtils.get_owners_from_params(arguments) if len(arguments) < 1: print("Please specify the required parameters") return False hash_string = arguments[0] try: script_hash = UInt160.ParseString(hash_string) except Exception: # because UInt160 throws a generic exception. Should be fixed in the future print("Invalid script hash") return False tx, fee, results, num_ops, engine_success = TestInvokeContract(wallet, arguments, from_addr=from_addr, invoke_attrs=invoke_attrs, owners=owners) if tx and results: parameterized_results = [ContractParameter.ToParameter(item).ToJson() for item in results] print( "\n-------------------------------------------------------------------------------------------------------------------------------------") print("Test invoke successful") print(f"Total operations: {num_ops}") print(f"Results {str(parameterized_results)}") print(f"Invoke TX GAS cost: {tx.Gas.value / Fixed8.D}") print(f"Invoke TX fee: {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 wallet.ValidatePassword(passwd): return print("Incorrect password") return InvokeContract(wallet, tx, fee, from_addr=from_addr, owners=owners) else: print("Error testing contract invoke") return False
def execute(self, arguments): if PromptData.Wallet: PromptData.close_wallet() path = PromptUtils.get_arg(arguments, 0) if not path: print("Please specify the required parameter") return if not os.path.exists(path): print("Wallet file not found") return passwd = prompt("[password]> ", is_password=True) password_key = to_aes_key(passwd) try: PromptData.Wallet = UserWallet.Open(path, password_key) PromptData.Prompt.start_wallet_loop() print("Opened wallet at %s" % path) return PromptData.Wallet except Exception as e: print("Could not open wallet: %s" % e)
def test_owner_2(self): args = [1, 2, "--owners=['ABC','DEF',]"] args, owners = Utils.get_owners_from_params(args) self.assertEqual(args, [1, 2]) self.assertEqual(owners, set())
def execute(self, arguments): if PromptData.Wallet: PromptData.close_wallet() path = PromptUtils.get_arg(arguments, 0) if not path: print("Please specify the required parameter") return if not os.path.exists(path): print("Wallet file not found") return try: passwd = prompt("[password]> ", is_password=True) except KeyboardInterrupt: print("Wallet opening cancelled") return password_key = to_aes_key(passwd) try: PromptData.Wallet = UserWallet.Open(path, password_key) print("Opened wallet at %s" % path) asyncio.create_task( PromptData.Wallet.sync_wallet( start_block=PromptData.Wallet._current_height)) return PromptData.Wallet except Exception as e: print("Could not open wallet: %s" % e)
def execute(self, arguments): wallet = PromptData.Wallet if len(arguments) < 4: print("Please specify the required parameters") return False if len(arguments) > 5: # the 5th argument is the optional attributes, print("Too many parameters supplied. Please check your command") return False _, user_tx_attributes = PromptUtils.get_tx_attr_from_args(arguments) token = arguments[0] from_addr = arguments[1] to_addr = arguments[2] try: amount = float(arguments[3]) except ValueError: print(f"{arguments[3]} is not a valid amount") return False try: success = token_send(wallet, token, from_addr, to_addr, amount, user_tx_attributes) except ValueError as e: # occurs if arguments are invalid print(str(e)) success = False return success
def test_owner_1(self): args = [1, 2] args, owners = Utils.get_owners_from_params(args) self.assertEqual(args, [1, 2]) self.assertIsNone(owners)
def execute(self, arguments): wallet = PromptData.Wallet if len(arguments) != 3: print("Please specify the required parameters") return False token_str = arguments[0] from_addr = arguments[1] to_addr = arguments[2] try: token = PromptUtils.get_token(wallet, token_str) except ValueError as e: print(str(e)) return False try: allowance = token_get_allowance(wallet, token_str, from_addr, to_addr) print( f"{token.symbol} allowance for {from_addr} from {to_addr} : {allowance} " ) return True except ValueError as e: print(str(e)) return False
def test_utils_8(self): args = [1, 2, '--attach-gas=100.0003', '--attach-neo=6'] args, neo, gas = Utils.get_asset_attachments(args) self.assertEqual(args, [1, 2]) self.assertEqual(neo, Fixed8.FromDecimal(6)) self.assertEqual(gas, Fixed8.FromDecimal(100.0003))
def execute(self, arguments): start_block = PromptUtils.get_arg(arguments, 0, convert_to_int=True) if not start_block or start_block < 0: start_block = 0 print(f"Restarting at block {start_block}") task = asyncio.create_task( PromptData.Wallet.sync_wallet(start_block, rebuild=True)) return task
def execute(self, arguments): wallet = PromptData.Wallet if len(arguments) < 4: print("Please specify the required parameters") return False if len(arguments) > 6: # the 5th and 6th arguments are optional print("Too many parameters supplied. Please check your command") return False arguments, priority_fee = PromptUtils.get_fee(arguments) arguments, user_tx_attributes = PromptUtils.get_tx_attr_from_args( arguments) token = arguments[0] from_addr = arguments[1] to_addr = arguments[2] try: amount = float(arguments[3]) except ValueError: print(f"{arguments[3]} is not a valid amount") return False fee = Fixed8.Zero() if priority_fee is not None: fee = priority_fee if fee is False: logger.debug("invalid fee") return False try: success = token_send(wallet, token, from_addr, to_addr, amount, fee=fee, user_tx_attributes=user_tx_attributes) except ValueError as e: # occurs if arguments are invalid print(str(e)) success = False return success
def test_utils_4(self): args = [1, 2, '--attach-neo=100'] args, neo, gas = Utils.get_asset_attachments(args) self.assertEqual(args, [1, 2]) self.assertEqual(neo, Fixed8.FromDecimal(100)) self.assertIsNone(gas)
def test_utils_6(self): args = [1, 2, '--attachgas=100.0003'] args, neo, gas = Utils.get_asset_attachments(args) self.assertEqual(args, [1, 2, '--attachgas=100.0003']) self.assertIsNone(neo) self.assertIsNone(gas)
def test_utils_2(self): args = [] args, neo, gas = Utils.get_asset_attachments(args) self.assertEqual(args, []) self.assertIsNone(neo) self.assertIsNone(gas)
def execute(self, arguments): addr_to_delete = PromptUtils.get_arg(arguments, 0) if not addr_to_delete: print("Please specify the required parameter") return False return DeleteAddress(PromptData.Wallet, addr_to_delete)
def test_owner_3(self): args = [1, 2, "--owners=['APRgMZHZubii29UXF9uFa6sohrsYupNAvx','AXjaFSP23Jkbe6Pk9pPGT6NBDs1HVdqaXK',]"] args, owners = Utils.get_owners_from_params(args) self.assertEqual(args, [1, 2]) self.assertEqual(len(owners), 2) self.assertIsInstance(list(owners)[0], UInt160)
def InvokeContract(wallet, tx, fee=Fixed8.Zero(), from_addr=None, owners=None): if from_addr is not None: from_addr = PromptUtils.lookup_addr_str(wallet, from_addr) try: wallet_tx = wallet.MakeTransaction(tx=tx, fee=fee, use_standard=True, from_addr=from_addr) except ValueError: print("Insufficient funds") return False except TXFeeError as e: print(e) return False if wallet_tx: if owners: for owner in list(owners): wallet_tx.Attributes.append( TransactionAttribute( usage=TransactionAttributeUsage.Script, data=owner)) wallet_tx.Attributes = make_unique_script_attr(tx.Attributes) context = ContractParametersContext(wallet_tx) wallet.Sign(context) if owners: gather_signatures(context, wallet_tx, list(owners)) if context.Completed: wallet_tx.scripts = context.GetScripts() relayed = False # print("SENDING TX: %s " % json.dumps(wallet_tx.ToJson(), indent=4)) relayed = NodeLeader.Instance().Relay(wallet_tx) if relayed: print("Relayed Tx: %s " % wallet_tx.Hash.ToString()) wallet.SaveTransaction(wallet_tx) return wallet_tx else: print("Could not relay tx %s " % wallet_tx.Hash.ToString()) else: print("Incomplete signature") else: print("Insufficient funds") return False
def execute(self, arguments): wallet = PromptData.Wallet if len(arguments) < 4: print("Please specify the required parameters") return False arguments, priority_fee = PromptUtils.get_fee(arguments) token_str = arguments[0] from_addr = arguments[1] to_addr = arguments[2] try: amount = float(arguments[3]) except ValueError: print(f"{arguments[3]} is not a valid amount") return False 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 try: token = _validate_nep5_args(wallet, token_str, from_addr, to_addr, amount) except ValueError as e: print(str(e)) return False decimal_amount = amount_from_string(token, amount) tx, fee, results = token.Approve(wallet, from_addr, to_addr, decimal_amount) if tx and results: if results[0].GetBigInteger() == 1: print("\n-----------------------------------------------------------") print(f"Approve allowance of {amount} {token.symbol} from {from_addr} to {to_addr}") print(f"Invocation 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}) + Invocation Fee ({fee.value / Fixed8.D}) = {comb_fee.value / Fixed8.D}\n") print("Enter your password to send to the network") passwd = prompt("[Password]> ", is_password=True) if not wallet.ValidatePassword(passwd): print("incorrect password") return False return InvokeContract(wallet, tx, comb_fee) print("Failed to approve tokens. Make sure you are entitled for approving.") return False
def token_history(wallet, token_str): notification_db = NotificationDB.instance() try: token = PromptUtils.get_token(wallet, token_str) except ValueError: raise events = notification_db.get_by_contract(token.ScriptHash) return token, events
def execute(self, arguments): PromptData.Prompt.stop_wallet_loop() start_block = PromptUtils.get_arg(arguments, 0, convert_to_int=True) if not start_block or start_block < 0: start_block = 0 print(f"Restarting at block {start_block}") PromptData.Wallet.Rebuild(start_block) PromptData.Prompt.start_wallet_loop()
def process_params(sb, param, wallet, no_parse_addresses): item = PromptUtils.parse_param(param, wallet, parse_addr=no_parse_addresses) if type(item) is list: item.reverse() listlength = len(item) for listitem in item: process_params(sb, listitem, wallet, no_parse_addresses) sb.push(listlength) sb.Emit(PACK) else: sb.push(item)
def execute(self, arguments): wallet = PromptData.Wallet if len(arguments) < 4: print("Please specify the required parameters") return if len(arguments) > 5: # the 5th argument is the optional attributes, print("Too many parameters supplied. Please check your command") return addr = arguments[0] if not isValidPublicAddress(addr): print("Invalid address specified") return try: from_addr = wallet.ToScriptHash(addr) except ValueError as e: print(str(e)) return asset_id = PromptUtils.get_asset_id(wallet, arguments[1]) if not asset_id: print(f"Unknown asset id: {arguments[1]}") return try: index = int(arguments[2]) except ValueError: print(f"Invalid unspent index value: {arguments[2]}") return try: divisions = int(arguments[3]) except ValueError: print(f"Invalid divisions value: {arguments[3]}") return if divisions < 2: print("Divisions cannot be lower than 2") return if len(arguments) == 5: fee = Fixed8.TryParse(arguments[4], require_positive=True) if not fee: print(f"Invalid fee value: {arguments[4]}") return else: fee = Fixed8.Zero() return SplitUnspentCoin(wallet, asset_id, from_addr, index, divisions, fee)
def execute(self, arguments): item = PromptUtils.get_arg(arguments) if not item: print(f"run `{self.command_desc().command} help` to see supported queries") return try: return self.execute_sub_command(item, arguments[1:]) except KeyError: print(f"{item} is an invalid parameter") return
def execute(self, arguments): path = PromptUtils.get_arg(arguments, 0) if not path: print("Please specify a path") return if os.path.exists(path): print("File already exists") return if PromptData.Wallet: PromptData.close_wallet() try: passwd1 = prompt("[password]> ", is_password=True) passwd2 = prompt("[password again]> ", is_password=True) except KeyboardInterrupt: print("Wallet creation cancelled") return if passwd1 != passwd2 or len(passwd1) < 10: print( "Please provide matching passwords that are at least 10 characters long" ) return password_key = to_aes_key(passwd1) try: PromptData.Wallet = UserWallet.Create(path=path, password=password_key) contract = PromptData.Wallet.GetDefaultContract() key = PromptData.Wallet.GetKey(contract.PublicKeyHash) print("Wallet %s" % json.dumps(PromptData.Wallet.ToJson(), indent=4)) print("Pubkey %s" % key.PublicKey.encode_point(True)) except Exception as e: print("Exception creating wallet: %s" % e) PromptData.Wallet = None if os.path.isfile(path): try: os.remove(path) except Exception as e: print("Could not remove {}: {}".format(path, e)) return if PromptData.Wallet: asyncio.create_task( PromptData.Wallet.sync_wallet( start_block=PromptData.Wallet._current_height)) return PromptData.Wallet
def execute(self, arguments): wallet = PromptData.Wallet item = PromptUtils.get_arg(arguments) if not wallet: print("Please open a wallet") return try: return self.execute_sub_command(item, arguments[1:]) except KeyError: print(f"{item} is an invalid parameter") return
def InvokeContract(wallet, tx, fee=Fixed8.Zero(), from_addr=None, owners=None): if from_addr is not None: from_addr = PromptUtils.lookup_addr_str(wallet, from_addr) try: wallet_tx = wallet.MakeTransaction(tx=tx, fee=fee, use_standard=True, from_addr=from_addr) except ValueError: print("Insufficient funds") return False if wallet_tx: if owners: for owner in list(owners): wallet_tx.Attributes.append(TransactionAttribute(usage=TransactionAttributeUsage.Script, data=owner)) wallet_tx.Attributes = make_unique_script_attr(tx.Attributes) context = ContractParametersContext(wallet_tx) wallet.Sign(context) if owners: gather_signatures(context, wallet_tx, list(owners)) if context.Completed: wallet_tx.scripts = context.GetScripts() passed, reason = validate_simple_policy(wallet_tx) if not passed: print(reason) return False nodemgr = NodeManager() relayed = nodemgr.relay(wallet_tx) if relayed: print("Relayed Tx: %s " % wallet_tx.Hash.ToString()) wallet.SaveTransaction(wallet_tx) return wallet_tx else: print("Could not relay tx %s " % wallet_tx.Hash.ToString()) else: print("Incomplete signature") else: print("Insufficient funds") return False