def make_deploy_transaction(code_str: str, need_storage: bool, name: str, code_version: str, author: str, email: str, desp: str, payer: str, gas_limit: int, gas_price: int): unix_time_now = int(time()) deploy_tx = DeployTransaction() deploy_tx.payer = Address.b58decode(payer).to_array() deploy_tx.attributes = bytearray() deploy_tx.nonce = unix_time_now deploy_tx.code = bytearray.fromhex(code_str) deploy_tx.code_version = code_version deploy_tx.version = 0 deploy_tx.need_storage = need_storage deploy_tx.name = name deploy_tx.author = author deploy_tx.email = email deploy_tx.gas_limit = gas_limit deploy_tx.gas_price = gas_price deploy_tx.description = desp return deploy_tx
def query_balance(self, asset: str, b58_address: str) -> int: raw_address = Address.b58decode(b58_address).to_array() contract_address = util.get_asset_address(asset) invoke_code = build_native_invoke_code(contract_address, bytes([0]), "balanceOf", raw_address) unix_time_now = int(time()) payer = Address(ZERO_ADDRESS).to_array() version = 0 tx_type = 0xd1 gas_price = 0 gas_limit = 0 attributes = bytearray() signers = list() hash_value = bytearray() tx = Transaction(version, tx_type, unix_time_now, gas_price, gas_limit, payer, invoke_code, attributes, signers, hash_value) res = self.__sdk.rpc.send_raw_transaction_pre_exec(tx) r = bytearray.fromhex(res) r.reverse() return int(r.hex(), 16)
def balance_of(self, b58_address: str) -> int: """ This interface is used to call the BalanceOf method in ope4 that query the ope4 token balance of the given base58 encode address. :param b58_address: the base58 encode address. :return: the oep4 token balance of the base58 encode address. """ func = InvokeFunction('balanceOf') Oep4.__b58_address_check(b58_address) address = Address.b58decode(b58_address).to_bytes() func.set_params_value(address) result = self.__sdk.get_network().send_neo_vm_transaction( self.__hex_contract_address, None, None, 0, 0, func, True) try: balance = ContractDataParser.to_int(result['Result']) except SDKException: balance = 0 return balance
def test_setGP(self): payerAcct = adminAcct param_list = [] param_list.append("setGP".encode()) userBase58Address1 = "AQf4Mzu1YJrhz9f3aRkkwSm9n3qhXGSh4p" acct = Address.b58decode(userBase58Address1).to_array() # print('acct is ', acct) # hash = "616f2a4a38396ff203ea01e6c070ae421bb8ce2d" # print("acct1 is ", bytearray.fromhex(hash)) # return True param_list1 = [124, 100, 100000000000,[[1001, 1], [1002, 1], [1003, 1]]] param_list.append(param_list1) print("***** setGP", param_list) hash = self.test_invoke(payerAcct, param_list) print("hash === setGP", hash) return True
def test_getPlayerBetBalance(self): payerAcct = adminAcct param_list = [] param_list.append("getPlayerBetBalance".encode()) param_list1 = [] param_list1.append(211) userBase58Address1 = "ATdX8jx2Zc9yqqgeu24xVRzqT7GJ5MAqTE" acct = Address.b58decode(userBase58Address1).to_array() param_list1.append(acct) param_list.append(param_list1) # print("***** getExplodePoint", param_list) res = self.test_invokeRead(payerAcct, param_list) if res: num = bytearray.fromhex(res) num.reverse() betBalance = int(num.hex(), 16) else: betBalance = "Not Exist" print("res === getPlayerBetBalance ===", betBalance) return True
def __init__(self, version=0, tx_type: TxType or int = None, gas_price: int = 0, gas_limit: int = 0, payer: Union[str, bytes, Address, None] = b'', payload: bytearray = bytearray(), nonce: int = None, attributes: bytearray = bytearray(), sig_list: List[Sig] = None): if gas_price < 0: raise SDKException( ErrorCode.other_error( 'the gas price should be equal or greater than zero.')) if gas_limit < 0: raise SDKException( ErrorCode.other_error( 'the gas limit should be equal or greater than zero.')) self.version = version if isinstance(tx_type, int): tx_type = TxType(tx_type) if tx_type is not None: self.tx_type = tx_type.value if not nonce: nonce = randint(0, 0xFFFFFFFF) self.nonce = nonce self.gas_price = gas_price self.gas_limit = gas_limit if not payer: payer = b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' if isinstance(payer, str): payer = Address.b58decode(payer).to_bytes() if isinstance(payer, Address): payer = payer.to_bytes() self.payer = payer self.payload = payload self.attributes = attributes if not sig_list: sig_list = list() self.sig_list = sig_list
def test_push_address(self): b58_address_list = [ 'AS7MjVEicEsJ4zjEfm2LoKoYoFsmapD7rT', 'AFmseVrdL9f9oyCzZefL9tG6UbviEH9ugK', 'AS3SCXw8GKTEeXpdwVw7EcC4rqSebFYpfb', 'AJkkLbouowk6teTaxz1F2DYKfJh24PVk3r', 'Ad4pjz2bqep4RhQrUAzMuZJkBC3qJ1tZuT', 'AK98G45DhmPXg4TFPG1KjftvkEaHbU8SHM' ] wasm_address_list = [ '71609b2c2f7b9447b089ad1da31586f42ca9eb10', '0000000000000000000000000000000000000007', '70a2ababdae0a9d1f9fc7296df3c6d343b772cf7', '20b1dc499cdf56ba70a574a1e17ac986d1f06ec2', 'e98f4998d837fcdd44a50561f7f32140c7c6c260', '24ed4f965d3a5a76f5d0e87633c0b76941fc8827' ] for index, b58_address in enumerate(b58_address_list): self.builder.push_address(Address.b58decode(b58_address)) self.assertEqual(wasm_address_list[index], self.builder.to_bytes().hex()) self.builder.clear_up()
def balance_of(self, b58_address: str) -> int: """ This interface is used to call the BalanceOf method in ope4 that query the ope4 token balance of the given base58 encode address. :param b58_address: the base58 encode address. :return: the oep4 token balance of the base58 encode address. """ func = self.__abi_info.get_function('balanceOf') Oep4.__b58_address_check(b58_address) address = Address.b58decode(b58_address).to_array() func.set_params_value((address, )) balance = self.__sdk.neo_vm().send_transaction(self.__contract_address, None, None, 0, 0, func, True) array = bytearray(binascii.a2b_hex(balance.encode('ascii'))) array.reverse() try: balance = int(binascii.b2a_hex(array).decode('ascii'), 16) except ValueError: balance = 0 return balance
def transfer(self, from_acct: Account, b58_to_address: str, value: int, payer_acct: Account, gas_limit: int, gas_price: int) -> str: """ This interface is used to call the Transfer method in ope4 that transfer an amount of tokens from one account to another account. :param from_acct: an Account class that send the oep4 token. :param b58_to_address: a base58 encode address that receive the oep4 token. :param value: an int value that indicate the amount oep4 token that will be transferred in this transaction. :param payer_acct: an Account class that used to pay for the transaction. :param gas_limit: an int value that indicate the gas limit. :param gas_price: an int value that indicate the gas price. :return: the hexadecimal transaction hash value. """ func = self.__abi_info.get_function('transfer') if not isinstance(value, int) or isinstance(value, float): raise SDKException( ErrorCode.param_err( 'the data type of value should be number.')) if value < 0: raise SDKException( ErrorCode.param_err( 'the value should be equal or great than 0.')) if not isinstance(from_acct, Account): raise SDKException( ErrorCode.param_err( 'the data type of from_acct should be Account.')) Oep4.__b58_address_check(b58_to_address) from_address = from_acct.get_address().to_array() to_address = Address.b58decode(b58_to_address).to_array() value = self.__to_int_according_to_decimal(value) params = (from_address, to_address, value) func.set_params_value(params) tx_hash = self.__sdk.neo_vm().send_transaction(self.__contract_address, from_acct, payer_acct, gas_limit, gas_price, func, False) return tx_hash
def new_add_recovery_transaction(self, ont_id: str, pub_key: str or bytes, b58_recovery_address: str, b58_payer_address: str, gas_limit: int, gas_price: int): """ This interface is used to generate a Transaction object which is used to add the recovery. :param ont_id: OntId. :param pub_key: the hexadecimal public key in the form of string. :param b58_recovery_address: a base58 encode address which indicate who is the recovery. :param b58_payer_address: a base58 encode address which indicate who will pay for the transaction. :param gas_limit: an int value that indicate the gas limit. :param gas_price: an int value that indicate the gas price. :return: """ if isinstance(pub_key, str): bytes_pub_key = binascii.a2b_hex(pub_key) elif isinstance(pub_key, bytes): bytes_pub_key = pub_key else: raise SDKException(ErrorCode.params_type_error('a bytes or str type of public key is required.')) bytes_recovery_address = Address.b58decode(b58_recovery_address).to_bytes() args = dict(ontid=ont_id.encode('utf-8'), recovery=bytes_recovery_address, pk=bytes_pub_key) tx = self.__generate_transaction('addRecovery', args, b58_payer_address, gas_limit, gas_price) return tx
def approve(self, owner_acct: Account, b58_spender_address: str, amount: int, payer_acct: Account, gas_limit: int, gas_price: int): """ This interface is used to call the Approve method in ope4 that allows spender to withdraw a certain amount of oep4 token from owner account multiple times. If this function is called again, it will overwrite the current allowance with new value. :param owner_acct: an Account class that indicate the owner. :param b58_spender_address: a base58 encode address that be allowed to spend the oep4 token in owner's account. :param amount: an int value that indicate the amount oep4 token that will be transferred in this transaction. :param payer_acct: an Account class that used to pay for the transaction. :param gas_limit: an int value that indicate the gas limit. :param gas_price: an int value that indicate the gas price. :return: the hexadecimal transaction hash value. """ func = self.__abi_info.get_function('approve') if not isinstance(amount, int): raise SDKException( ErrorCode.param_err('the data type of amount should be int.')) if amount < 0: raise SDKException( ErrorCode.param_err( 'the amount should be equal or great than 0.')) owner_address = owner_acct.get_address().to_array() Oep4.__b58_address_check(b58_spender_address) spender_address = Address.b58decode(b58_spender_address).to_array() amount = self.__to_int_according_to_decimal(amount) params = (owner_address, spender_address, amount) func.set_params_value(params) tx_hash = self.__sdk.neo_vm().send_transaction(self.__contract_address, owner_acct, payer_acct, gas_limit, gas_price, func, False) return tx_hash
def convert_params(func, func_map: {}): params_list = [] params_list.append(func_map["function_name"].encode()) params = [] temp_l = "" for i in range(len(func_map["param_list"])): if func.parameters[i].type == "String": params.append(str(func_map["param_list"][i])) temp_l += str(func_map["param_list"][i]) + ":" elif func.parameters[i].type == "ByteArray": temp_l += str(func_map["param_list"][i]) + ":" try: addr = bytearray() if func_map["param_list"][i].startswith("A"): addr = Address.b58decode( func_map["param_list"][i]).to_array() else: addr = Address(bytearray.fromhex( func_map["param_list"][i])).to_array() params.append(addr) except Exception as e: params.append(bytearray(func_map["param_list"][i].encode())) elif func.parameters[i].type == "Integer": params.append(func_map["param_list"][i]) temp_l += str(func_map["param_list"][i]) + ":" elif func.parameters[i].type == "Array": param_l = [] for param in func_map["param_list"][i]: print(type(param)) if type(param) is dict: temp = [] for p in dict(param).values(): if type(p) is str: temp_l = str(p).split(":")[1] + ":" if str(p).split(":")[0] == "String": temp.append(str(p).split(":")[1]) elif str(p).split(":")[0] == "ByteArray": try: temp.append( Address.b58decode( str(p).split(":")[1]).to_array()) except Exception as e: temp.append(str(p).split(":")[1].encode()) elif type(p) is bool: temp.append(p) if p: temp_l += "false:" else: temp_l += "true:" elif type(p) is int: temp.append(p) temp_l += str(p) + ":" else: print("not supported data type") temp_l += "not supported data type" + ":" return param_l.append(temp) elif type(param) is list: param_l.append(param) else: temp_l += "not supported data type" + ":" print("only support dict") return temp_l, None if len(params) == 0: params = param_l else: params.append(param_l) params_list.append(params) return temp_l, params_list
import requests from datetime import datetime from ontology.smart_contract.neo_vm import NeoVm from ontology.crypto.digest import Digest from ontology.utils.util import bigint_to_neo_bytes rpc_address = 'http://127.0.0.1:20336' sdk = OntologySdk() sdk.rpc.set_address(rpc_address) wallet_path = "D:\\test-python-sdk\\wallet.dat" sdk.wallet_manager.open_wallet(wallet_path) admin_addr = "ASwaf8mj2E3X18MHvcJtXoDsMqUjJswRWS" admin_pwd = "123123" ownerAcct = sdk.wallet_manager.get_account(admin_addr, admin_pwd) ownerAddress = Address.b58decode(admin_addr).to_array() challengerAddress = "ARDskfQuvTa7TvbCVNX8MP5zjg7SUdDgSa" challengerAccount = Address.b58decode(challengerAddress).to_array() challengerAcct = sdk.wallet_manager.get_account(challengerAddress, admin_pwd) challengerAddress1 = "ASJeGy7CPoa2EvTEAyQFd5uxD9mr8ejVxE" challengerAccount1 = Address.b58decode(challengerAddress1).to_array() challengerAcct1 = sdk.wallet_manager.get_account(challengerAddress1, admin_pwd) tokenAddress = "3cf3cd1332a4c7eabcb3665d2b6e3388047bd6e4" token_address = bytearray.fromhex(tokenAddress) token_address.reverse() PLCRAddress = "b7e54aa69c0c60a93104a8613e3935cf7db7294f" PLCR_address = bytearray.fromhex(PLCRAddress)
def address_to_hex(address): if address is None or address == '': print('address is none') return print('Result is:') print('\t', Address.b58decode(address).to_bytes().hex())
def execute(m:[], function_name=None): sdk = OntologySdk() sdk.set_rpc(m["rpc_address"]) if m["func"] is "migrate": # 判断是否已经部署 code = sdk.rpc.get_smart_contract(m["contract_address"]) if code != "unknow contract": print("contract have been deployed") print("contract_address:", m["contract_address"]) return need_storage = False if m["need_storage"] is 'true': need_storage = True tx = sdk.neo_vm().make_deploy_transaction(m["code"], need_storage, m["name"], m["code_version"], m["author"] , m["email"], m["desp"], m["payer_address"], m["gas_limit"], m["gas_price"]) sdk.wallet_manager.open_wallet(m["wallet_file_path"]) acct = sdk.wallet_manager.get_account(m["payer_address"], m["payer_password"]) sdk.sign_transaction(tx, acct) sdk.set_rpc(m["rpc_address"]) try: print("deploying,please waiting ...") res = sdk.rpc.send_raw_transaction(tx) print("txhash:", res) for i in range(10): time.sleep(1) res = sdk.rpc.get_smart_contract(m["contract_address"]) if res == "unknow contract" or res == "": continue else: print("deploy success") save_file(m, "success") return print("deployed failed") save_file(m, "deployed failed") except Exception as e: print(e) save_file(m, e) elif m["func"] is "invoke": func_maps = {} for i in list(m["function"]): func_map = {} param_list = [] func_map["function_name"] = i.function_name func_map["pre_exec"] = i.pre_exec try: for j in list(i.function_param): param_list.append(j) func_map["param_list"] = param_list except Exception as e: pass if not i.pre_exec: try: func_map["signers"] = i.signers except AttributeError as e: func_map["signers"] = None func_maps[i.function_name] = func_map with open(str(m["abi_path"]), "r") as f: abi = json.loads(f.read(), object_hook=lambda d: namedtuple('X', d.keys())(*d.values())) abi_info = AbiInfo(abi.hash, abi.entrypoint, abi.functions, abi.events) contract_address = bytearray.fromhex(str(abi.hash)[2:]) m["contract_address"] = contract_address.hex() contract_address.reverse() sdk.wallet_manager.open_wallet(m["wallet_file_path"]) payer = sdk.wallet_manager.get_account(m["payer_address"], m["payer_password"]) func_l = [] no = 0 for func_map in func_maps.values(): if function_name is not None: if function_name != func_map["function_name"]: continue func = abi_info.get_function(func_map["function_name"]) func_map["return_type"] = func.return_type params = [] l = [] l.append(no) no = no + 1 l.append(func_map["function_name"]) l.append(func_map["pre_exec"]) temp_l = "" # 用来放参数 for i in range(len(func_map["param_list"])): temp_l = "" if type(func_map["param_list"][i]) is int: temp_l += str(func_map["param_list"][i]) + ":" else: temp_l += func_map["param_list"][i] + ":" if func.parameters[i].type == "String": params.append(str(func_map["param_list"][i])) if func.parameters[i].type == "ByteArray": if func_map["param_list"][i].startswith("A"): params.append(Address.b58decode(func_map["param_list"][i], False).to_array()) else: params.append(bytearray(func_map["param_list"][i].encode())) if func.parameters[i].type == "Integer": params.append(func_map["param_list"][i]) l.append(temp_l[:len(temp_l) - 1]) if len(params) == 1: func.set_params_value(params[0]) elif len(params) == 2: func.set_params_value(params[0], params[1]) elif len(params) == 3: func.set_params_value(params[0], params[1], params[2]) elif len(params) == 4: func.set_params_value(params[0], params[1], params[2], params[3]) elif len(params) == 5: func.set_params_value(params[0], params[1], params[2], params[3], params[4]) elif len(params) == 6: func.set_params_value(params[0], params[1], params[2], params[3], params[4], params[5]) elif len(params) == 7: func.set_params_value(params[0], params[1], params[2], params[3], params[4], params[5], params[6]) try: print("") print("invoking, please waiting ...") print("method: " + func_map["function_name"]) if func_map["pre_exec"]: res = sdk.neo_vm().send_transaction(contract_address, None, None, 0, 0, func, True) if res["error"] != 0: print(res["desc"]) l.append(res["desc"]) else: if res["result"]["Result"] == None or res["result"]["Result"] == "": print("res:", res["result"]["Result"]) l.append("") else: if func_map["return_type"] == "Integer": value = bytearray.fromhex(res["result"]["Result"]) value.reverse() print("res:", int(value.hex(), 16)) l.append(int(value.hex(), 16)) else: print("res:", (bytearray.fromhex(res["result"]["Result"])).decode('utf-8')) l.append((bytearray.fromhex(res["result"]["Result"])).decode('utf-8')) else: res = "" if func_map["signers"] != None: wm = WalletManager() wm.open_wallet(func_map["signers"].signer.walletpath) signer = wm.get_account(func_map["signers"].signer.address, func_map["signers"].signer.password) print(wm.wallet_in_mem.accounts[0].address) print(signer) res = sdk.neo_vm().send_transaction(contract_address, signer, payer, m["gas_limit"], m["gas_price"], func, False) else: res = sdk.neo_vm().send_transaction(contract_address, payer, payer, m["gas_limit"], m["gas_price"], func, False) for i in range(10): time.sleep(1) event = sdk.rpc.get_smart_contract_event_by_tx_hash(res) if event != None: print("txhash:", res) print("event:", event) break l.append(res) except Exception as e: print("Error:", e) l.append(e) func_l.append(l) save_file(m, "", func_l) else: print("only support migrate and invoke")
def test_open_wallet_account_from_path(self): ''' Open wallet and get account''' wallet_path = "C:\\Go_WorkSpace\\src\\github.com\\ontio\\ontology\\_Wallet_\\wallet.dat" sdk.wallet_manager.open_wallet(wallet_path) acct1_addr = "AQf4Mzu1YJrhz9f3aRkkwSm9n3qhXGSh4p" acct2_addr = "ASUwFccvYFrrWR6vsZhhNszLFNvCLA5qS6" acct3_addr = "AWf8NiLzXSDf1JB2Ae6YUKSHke4yLHMVCm" acct1_pwd = "xinhao" acct1 = sdk.wallet_manager.get_account(acct1_addr, acct1_pwd) acct2 = sdk.wallet_manager.get_account(acct2_addr, acct1_pwd) acct3 = sdk.wallet_manager.get_account(acct3_addr, acct1_pwd) '''export several keys''' account = acct3 wif_key = account.export_wif() print("wif_key is ", wif_key) private_key_bytes = account.get_privatekey_from_wif(wif_key) print("private_key_bytes is ", private_key_bytes, type(private_key_bytes)) private_key_str = private_key_bytes.hex() print("private_key_str is ", private_key_str, type(private_key_str)) pwd = acct1_pwd addr = "ANjLDUU9htLKe41yxzVKpiPmFNseA3N9gc" salt = "XeK1Nkv8F8qKxXtLEPSbRw==" nounce = 16384 scheme = SignatureScheme.SHA256withECDSA private_key_str = private_key_bytes.hex() print("private_key_str is ", private_key_str, type(private_key_str)) ''' send transaction without signer''' version = 0 tx_type = 0xd1 unix_time_now = int(time.time()) nonce = unix_time_now gas_price = 0 gas_limit = 20000 payer = None payload = None attributes = None sigs = None hash = None ''' contract_address_str = "749a701ae89c0dbdab9b4b660ba84ee478004219" contract_address_bytearray = bytearray.fromhex(contract_address_str) contract_address = contract_address_bytearray contract_address.reverse() print('contract_address is ', contract_address) ''' ''' contract_address = util.get_asset_address("ont") #state = [{"address": "ASUwFccvYFrrWR6vsZhhNszLFNvCLA5qS6", "to": "AQf4Mzu1YJrhz9f3aRkkwSm9n3qhXGSh4p", "amount": 10000}] b58_address = "ASUwFccvYFrrWR6vsZhhNszLFNvCLA5qS6" raw_address = Address.b58decode(b58_address) #sdk.neo_vm().send_transaction(contract_address, acct1,[],20000, 0, ) invoke_code = build_native_invoke_code(contract_address, bytes([0]), "balanceOf", raw_address) payer = raw_address tx = Transaction(0, 0xd1, unix_time_now, gas_price, gas_limit, payer, invoke_code, bytearray(), [], bytearray()) #Transaction(0, 0xd1, unix_time_now, 0, 0, payer, invoke_code, bytearray(), [], bytearray()) res = sdk.rpc.send_raw_transaction_pre_exec(tx) print('res is ', res) ''' # Check balanceOf through NeoVm.make_invoke_transaction contract_address_str = "f328cb02bb1bd3a25c32f3db9b5f20b6fc4e04ea" contract_address_bytearray = bytearray.fromhex(contract_address_str) contract_address = contract_address_bytearray contract_address.reverse() print('contract_address is ', contract_address) params_list = [] params_list.append(str("BalanceOf").encode()) param = [] b58_address = "AQf4Mzu1YJrhz9f3aRkkwSm9n3qhXGSh4p" param.append(Address.b58decode(b58_address).to_array()) params_list.append(param) params = BuildParams.create_code_params_script(params_list) # when pre-execute, don't use 0x67 tx = NeoVm.make_invoke_transaction(bytearray(contract_address), bytearray(params), b'', 20000, 0) res = sdk.rpc.send_raw_transaction_pre_exec(tx) print("BalanceOf is ", res) # # Check totalsupply # params_list = [] # params_list.append(str("totalSupply").encode()) # param = [10] # params_list.append(param) # params = BuildParams.create_code_params_script(params_list) # # when pre-execute, don't use 0x67 # tx = NeoVm.make_invoke_transaction(bytearray(contract_address), bytearray(params), b'', 20000, 0) # res = sdk.rpc.send_raw_transaction_pre_exec(tx) # print('totalsupply is ', res) # # # Transfer through Transaction, send_raw_transaction # params_list = [] # params_list.append(str("transfer").encode()) # from_addr = "ASUwFccvYFrrWR6vsZhhNszLFNvCLA5qS6" # to_addr = "AQf4Mzu1YJrhz9f3aRkkwSm9n3qhXGSh4p" # value = 100 # param = [] # param.append(Address.b58decode(from_addr).to_array()) # param.append(Address.b58decode(to_addr).to_array()) # param.append(value) # params_list.append(param) # params = BuildParams.create_code_params_script(params_list) # # when execute, use 0x67, then add the contract_address # params.append(0x67) # for i in contract_address: # params.append(i) # payer_raw_address = acct2.get_address().to_array() # payer_acct = acc2 # unix_time_now = int(time.time()) # tx = Transaction(0, 0xd1, unix_time_now, gas_price, gas_limit, payer_raw_address, params, bytearray(), [], bytearray()) # sdk.sign_transaction(tx, acct2) # #sdk.add_sign_transaction(tx, payer_acct) # sdk.rpc.send_raw_transaction(tx) # # # Transfer through send_Transaction # # balance_Of_Addr = "ASUwFccvYFrrWR6vsZhhNszLFNvCLA5qS6" # # func = AbiFunction("balanceOf", "Integer", []) # # func.set_params_value((binascii.a2b_hex(balance_Of_Addr))) # # balance = sdk.neo_vm().send_transaction(contract_address, None, None, 0, 0, func, True) # # Transfer through Transaction, send_raw_transaction ### check balance before transferMulti### print('### check balance Before transferMulti ###') params_list = [] params_list.append(str("BalanceOf").encode()) param = [] b58_address = "AQf4Mzu1YJrhz9f3aRkkwSm9n3qhXGSh4p" param.append(Address.b58decode(b58_address).to_array()) params_list.append(param) params = BuildParams.create_code_params_script(params_list) # when pre-execute, don't use 0x67 tx = NeoVm.make_invoke_transaction(bytearray(contract_address), bytearray(params), b'', 20000, 0) res = sdk.rpc.send_raw_transaction_pre_exec(tx) print("before TransferMulti, the balance is ", res) ### transferMulti params_list = [] params_list.append(str("TransferMulti").encode()) from_addr1 = "AQf4Mzu1YJrhz9f3aRkkwSm9n3qhXGSh4p" from_addr2 = "AQf4Mzu1YJrhz9f3aRkkwSm9n3qhXGSh4p" to_addr1 = "ASUwFccvYFrrWR6vsZhhNszLFNvCLA5qS6" to_addr2 = "AWf8NiLzXSDf1JB2Ae6YUKSHke4yLHMVCm" value1 = 10000 value2 = 10000 param1 = [] param1.append(Address.b58decode(from_addr1).to_array()) param1.append(Address.b58decode(to_addr1).to_array()) param1.append(value1) param2 = [] param2.append(Address.b58decode(from_addr2).to_array()) param2.append(Address.b58decode(to_addr2).to_array()) param2.append(value2) params_list_tmp = [] params_list_tmp.append(param1) params_list_tmp.append(param2) params_list.append(params_list_tmp) # params_list.append(param1) # params_list.append(param2) print(" params_list is ", params_list) print(" contract_address is ", contract_address) params = BuildParams.create_code_params_script(params_list) # when execute, use 0x67, then add the contract_address params.append(0x67) for i in contract_address: params.append(i) payer_raw_address = acct1.get_address().to_array() unix_time_now = int(time.time()) tx = Transaction(0, 0xd1, unix_time_now, gas_price, gas_limit, payer_raw_address, params, bytearray(), [], bytearray()) tx = sdk.sign_transaction(tx, acct1) # sdk.add_sign_transaction(tx, payer_acct) tx_hash = sdk.rpc.send_raw_transaction(tx) print('tx_hash is ', tx_hash) time.sleep(12) event = sdk.rpc.get_smart_contract_event_by_tx_hash(tx_hash) # event = sdk.rpc.get_block_by_hash(tx_hash) print("event is ", event) # print("tx_hash is ", tx_hash) # event = sdk.rpc.get_smart_contract_event_by_tx_hash(tx_hash) # print("event is ", event) #check balance After transferMulti print('### check balance After transferMulti ###') params_list = [] params_list.append(str("BalanceOf").encode()) param = [] b58_address = "AQf4Mzu1YJrhz9f3aRkkwSm9n3qhXGSh4p" param.append(Address.b58decode(b58_address).to_array()) params_list.append(param) params = BuildParams.create_code_params_script(params_list) # when pre-execute, don't use 0x67 tx = NeoVm.make_invoke_transaction(bytearray(contract_address), bytearray(params), b'', 20000, 0) res = sdk.rpc.send_raw_transaction_pre_exec(tx) print("After TransferMulti, the balance is ", res)
import base64 import unittest from ontology.utils import util from ontology.account.account import Account from ontology.wallet.wallet import WalletData from ontology.wallet.account import AccountData from ontology.crypto.signature_scheme import SignatureScheme from ontology.common.address import Address private_key = "8b6bb2bebb27f3e2c24cc8a3febb413c1ef98bd2481e2292ada6d90f9a5f5ec9" if __name__ == '__main__': account = Account(private_key) publickey = account.serialize_public_key() wif = account.export_wif() privatekey = account.get_privatekey_from_wif(wif) print("public key is ", publickey, type(publickey)) print("private key is ", privatekey) print("...", account.serialize_private_key()) address = Address(publickey) addr = address.b58decode() print("address is ", addr)
import requests from datetime import datetime from ontology.smart_contract.neo_vm import NeoVm from ontology.crypto.digest import Digest from ontology.utils.util import bigint_to_neo_bytes rpc_address = 'http://127.0.0.1:20336' sdk = OntologySdk() sdk.rpc.set_address(rpc_address) wallet_path = "D:\\test-python-sdk\\wallet.dat" sdk.wallet_manager.open_wallet(wallet_path) admin_addr = "ASwaf8mj2E3X18MHvcJtXoDsMqUjJswRWS" admin_pwd = "123123" adminAcct = sdk.wallet_manager.get_account(admin_addr, admin_pwd) ad = Address.b58decode(admin_addr).to_array() toAccount = "ARDskfQuvTa7TvbCVNX8MP5zjg7SUdDgSa" toAcct = Address.b58decode(toAccount).to_array() ContractAddress = "491b4c202b1f83a6f0d609b1680dc66b0590260e" contract_address_str = ContractAddress contract_address = bytearray.fromhex(contract_address_str) contract_address.reverse() DNA1 = 111101666666104 class Test(unittest.TestCase): def test_createProperty(self):