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 test_invoke_contract(self, args): if not self.Wallet: print("Please open a wallet") return args, from_addr = get_from_addr(args) if args and len(args) > 0: # Test invoke contract. tx, fee, results, num_ops = TestInvokeContract(self.Wallet, args, from_addr=from_addr) if tx is not None and results is not None: result_item = results passwd = prompt("[password]> ", is_password=True) if not self.Wallet.ValidatePassword(passwd): return print("Incorrect password") result = InvokeContract(self.Wallet, tx, fee, from_addr=from_addr) return result_item else: print("Error testing contract invoke") return print("Please specify a contract to invoke")
def test_invoke_contract(self, args): if not self.Wallet: print("Please open a wallet") return args, from_addr = get_from_addr(args) if args and len(args) > 0: tx, fee, results, num_ops = TestInvokeContract(self.Wallet, args, from_addr=from_addr) if tx is not None and results is not None: print( "\n-------------------------------------------------------------------------------------------------------------------------------------") print("Test invoke successful") print("Total operations: %s" % num_ops) print("Results %s" % [str(item) for item in 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") passwd = prompt("[password]> ", is_password=True) if not self.Wallet.ValidatePassword(passwd): return print("Incorrect password") result = InvokeContract(self.Wallet, tx, fee, from_addr=from_addr) return else: print("Error testing contract invoke") return print("Please specify a contract to invoke")
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 token_crowdsale_register(wallet, args, prompt_passwd=True): token = get_asset_id(wallet, args[0]) args, from_addr = get_from_addr(args) if len(args) < 2: raise Exception("Specify addr to register for crowdsale") register_addr = args[1:] tx, fee, results = token.CrowdsaleRegister(wallet, register_addr) if results[0].GetBigInteger() > 0: print("\n-----------------------------------------------------------") print("[%s] Will register addresses for crowdsale: %s " % (token.symbol, register_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 InvokeContract(wallet, tx, fee, from_addr) else: print("Could not register addresses: %s " % str(results[0])) return False
def test_invoke_contract(self, args): if not self.Wallet: print("Please open a wallet") return args, from_addr = get_from_addr(args) if args and len(args) > 0: tx, fee, results, num_ops = TestInvokeContract(self.Wallet, args, from_addr=from_addr) if tx is not None and results is not None: print( "\n-------------------------------------------------------------------------------------------------------------------------------------") print("Test invoke successful") print("Total operations: %s" % num_ops) print("Results %s" % [str(item) for item in 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") passwd = prompt("[password]> ", is_password=True) if not self.Wallet.ValidatePassword(passwd): return print("Incorrect password") result = InvokeContract(self.Wallet, tx, fee, from_addr=from_addr) return else: print("Error testing contract invoke") return print("Please specify a contract to invoke")
def token_crowdsale_register(wallet, args, prompt_passwd=True): token = get_asset_id(wallet, args[0]) args, from_addr = get_from_addr(args) if len(args) < 2: raise Exception("Specify addr to register for crowdsale") register_addr = args[1:] tx, fee, results = token.CrowdsaleRegister(wallet, register_addr) if results[0].GetBigInteger() > 0: print("\n-----------------------------------------------------------") print("[%s] Will register addresses for crowdsale: %s " % (token.symbol, register_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 InvokeContract(wallet, tx, fee, from_addr) else: print("Could not register addresses: %s " % str(results[0])) return False
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 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
def BuildAndRun(arguments, wallet, verbose=True, min_fee=DEFAULT_MIN_FEE): arguments, from_addr = get_from_addr(arguments) path = get_arg(arguments) contract_script = Compiler.instance().load_and_save(path) newpath = path.replace('.py', '.avm') print("Saved output to %s " % newpath) return DoRun(contract_script, arguments, wallet, path, verbose, from_addr, min_fee)
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 BuildAndRun(arguments, wallet, verbose=True, min_fee=DEFAULT_MIN_FEE, invocation_test_mode=True): arguments, from_addr = get_from_addr(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)
def LoadAndRun(arguments, wallet): arguments, from_addr = get_from_addr(arguments) path = get_arg(arguments) if '.avm' not in path: raise TypeError with open(path, 'rb') as f: content = f.read() try: content = binascii.unhexlify(content) except Exception: pass script = content return DoRun(script, arguments, wallet, path, from_addr=from_addr)
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
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
def LoadAndRun(arguments, wallet): arguments, from_addr = get_from_addr(arguments) path = get_arg(arguments) try: with open(path, 'rb') as f: content = f.read() try: content = binascii.unhexlify(content) except Exception as e: pass script = content DoRun(script, arguments, wallet, path, from_addr=from_addr) except Exception as e: print("Could not load script %s " % e)
def LoadAndRun(arguments, wallet): arguments, from_addr = get_from_addr(arguments) path = get_arg(arguments) try: with open(path, 'rb') as f: content = f.read() try: content = binascii.unhexlify(content) except Exception as e: pass script = content print("arguments.... %s " % arguments) DoRun(script, arguments, wallet, path, from_addr=from_addr) except Exception as e: print("Could not load script %s " % e)
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 ClaimGas(wallet, require_password=True, args=None): unclaimed_coins = wallet.GetUnclaimedCoins() unclaimed_coin_refs = [coin.Reference for coin in unclaimed_coins] if len(unclaimed_coin_refs) == 0: print("no claims to process") return False available_bonus = Blockchain.Default().CalculateBonusIgnoreClaimed(unclaimed_coin_refs) if available_bonus == Fixed8.Zero(): print("No gas to claim") return False claim_tx = ClaimTransaction() claim_tx.Claims = unclaimed_coin_refs claim_tx.Attributes = [] claim_tx.inputs = [] script_hash = wallet.GetChangeAddress() # the following can be used to claim gas that is in an imported contract_addr # example, wallet claim --from-addr={smart contract addr} if args: params, from_addr_str = get_from_addr(args) if from_addr_str: script_hash = wallet.ToScriptHash(from_addr_str) standard_contract = wallet.GetStandardAddress() claim_tx.Attributes = [TransactionAttribute(usage=TransactionAttributeUsage.Script, data=standard_contract.Data)] claim_tx.outputs = [ TransactionOutput(AssetId=Blockchain.SystemCoin().Hash, Value=available_bonus, script_hash=script_hash) ] context = ContractParametersContext(claim_tx) wallet.Sign(context) print("\n---------------------------------------------------------------") print("Will make claim for %s GAS" % available_bonus.ToString()) print("------------------------------------------------------------------\n") if require_password: print("Enter your password to complete this claim") passwd = prompt("[Password]> ", is_password=True) if not wallet.ValidatePassword(passwd): print("incorrect password") return if context.Completed: claim_tx.scripts = context.GetScripts() print("claim tx: %s " % json.dumps(claim_tx.ToJson(), indent=4)) relayed = NodeLeader.Instance().Relay(claim_tx) if relayed: print("Relayed Tx: %s " % claim_tx.Hash.ToString()) wallet.SaveTransaction(claim_tx) else: print("Could not relay tx %s " % claim_tx.Hash.ToString()) return claim_tx, relayed else: print("could not sign tx") return None, 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 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 ClaimGas(wallet, require_password=True, args=None): """ Args: wallet: require_password: args: Returns: (claim transaction, relayed status) if successful: (tx, True) if unsuccessful: (None, False) """ if args: params, from_addr_str = get_from_addr(args) else: params = None from_addr_str = None unclaimed_coins = wallet.GetUnclaimedCoins() unclaimed_count = len(unclaimed_coins) if unclaimed_count == 0: print("no claims to process") return None, False max_coins_per_claim = None if params: max_coins_per_claim = get_arg(params, 0, convert_to_int=True) if not max_coins_per_claim: print("max_coins_to_claim must be an integer") return None, False if max_coins_per_claim <= 0: print("max_coins_to_claim must be greater than zero") return None, False if max_coins_per_claim and unclaimed_count > max_coins_per_claim: unclaimed_coins = unclaimed_coins[:max_coins_per_claim] unclaimed_coin_refs = [coin.Reference for coin in unclaimed_coins] available_bonus = Blockchain.Default().CalculateBonusIgnoreClaimed( unclaimed_coin_refs) if available_bonus == Fixed8.Zero(): print("No gas to claim") return None, False claim_tx = ClaimTransaction() claim_tx.Claims = unclaimed_coin_refs claim_tx.Attributes = [] claim_tx.inputs = [] script_hash = wallet.GetChangeAddress() # the following can be used to claim gas that is in an imported contract_addr # example, wallet claim --from-addr={smart contract addr} if from_addr_str: script_hash = wallet.ToScriptHash(from_addr_str) standard_contract = wallet.GetStandardAddress() claim_tx.Attributes = [ TransactionAttribute(usage=TransactionAttributeUsage.Script, data=standard_contract.Data) ] claim_tx.outputs = [ TransactionOutput(AssetId=Blockchain.SystemCoin().Hash, Value=available_bonus, script_hash=script_hash) ] context = ContractParametersContext(claim_tx) wallet.Sign(context) print("\n---------------------------------------------------------------") print("Will make claim for %s GAS" % available_bonus.ToString()) if max_coins_per_claim and unclaimed_count > max_coins_per_claim: print( "NOTE: You are claiming GAS on %s unclaimed coins. %s additional claim transactions will be required to claim all available GAS." % (max_coins_per_claim, math.floor(unclaimed_count / max_coins_per_claim))) print( "------------------------------------------------------------------\n") if require_password: print("Enter your password to complete this claim") passwd = prompt("[Password]> ", is_password=True) if not wallet.ValidatePassword(passwd): print("incorrect password") return None, False if context.Completed: claim_tx.scripts = context.GetScripts() print("claim tx: %s " % json.dumps(claim_tx.ToJson(), indent=4)) relayed = NodeLeader.Instance().Relay(claim_tx) if relayed: print("Relayed Tx: %s " % claim_tx.Hash.ToString()) wallet.SaveTransaction(claim_tx) else: print("Could not relay tx %s " % claim_tx.Hash.ToString()) return claim_tx, relayed else: print("could not sign tx") return None, False
def ClaimGas(wallet, require_password=True, args=None): unclaimed_coins = wallet.GetUnclaimedCoins() unclaimed_coin_refs = [coin.Reference for coin in unclaimed_coins] if len(unclaimed_coin_refs) == 0: print("no claims to process") return False available_bonus = Blockchain.Default().CalculateBonusIgnoreClaimed( unclaimed_coin_refs) if available_bonus == Fixed8.Zero(): print("No gas to claim") return False claim_tx = ClaimTransaction() claim_tx.Claims = unclaimed_coin_refs claim_tx.Attributes = [] claim_tx.inputs = [] script_hash = wallet.GetChangeAddress() # the following can be used to claim gas that is in an imported contract_addr # example, wallet claim --from-addr={smart contract addr} if args: params, from_addr_str = get_from_addr(args) if from_addr_str: script_hash = wallet.ToScriptHash(from_addr_str) standard_contract = wallet.GetStandardAddress() claim_tx.Attributes = [ TransactionAttribute(usage=TransactionAttributeUsage.Script, data=standard_contract.Data) ] claim_tx.outputs = [ TransactionOutput(AssetId=Blockchain.SystemCoin().Hash, Value=available_bonus, script_hash=script_hash) ] context = ContractParametersContext(claim_tx) wallet.Sign(context) print("\n---------------------------------------------------------------") print("Will make claim for %s GAS" % available_bonus.ToString()) print( "------------------------------------------------------------------\n") if require_password: print("Enter your password to complete this claim") passwd = prompt("[Password]> ", is_password=True) if not wallet.ValidatePassword(passwd): print("incorrect password") return if context.Completed: claim_tx.scripts = context.GetScripts() print("claim tx: %s " % json.dumps(claim_tx.ToJson(), indent=4)) relayed = NodeLeader.Instance().Relay(claim_tx) if relayed: print("Relayed Tx: %s " % claim_tx.Hash.ToString()) wallet.SaveTransaction(claim_tx) else: print("Could not relay tx %s " % claim_tx.Hash.ToString()) return claim_tx, relayed else: print("could not sign tx") return None, 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