def tiat_create_txns(contract, src_acc, dest_accs, amount): # Clear any cached sessions. This is needed to ensure multiple processes # don't try to reuse the same TCP connection, which would lead to havoc LocalNet = chain.BlockChain(API_ENDPOINT, version=1, network_id=0) chain.set_active_chain(LocalNet) src_acc = Account(private_key=src_acc.private_key) contract = Contract.load_from_address(contract.address, load_state=False) txn_info_list = [] contract.account = src_acc src_addr = src_acc.bech32_address orig_nonce = nonces.get(src_addr, src_acc.get_nonce()) for dest_acc in dest_accs: try: dest = dest_acc.address0x txn_info = contract.call( method="Transfer", params=[ Contract.value_dict("to", "ByStr20", dest), Contract.value_dict("tokens", "Uint128", str(amount)) ], nonce=new_nonce(src_acc), confirm=False) txn_info_list.append(txn_info) print(json.dumps(src_acc.last_params), file=sys.stderr) print("Created {} transactions".format(len(txn_info_list))) except Exception as e: print("Could not send from {} to {}: {}".format( src_acc.address0x, dest, e)) nonce_now = nonces.get(src_addr, src_acc.get_nonce()) # print("{}: created {} transactions; nonce went from {} to {}".format(src_acc.bech32_address, len(txn_info_list), orig_nonce, nonce_now)) return txn_info_list, src_acc, nonce_now
def test_batch_transfer(self): chain.set_active_chain(chain.TestNet) account = Account.from_keystore("zxcvbnm,", path_join("crypto", "zilliqa_keystore.json")) print(account) balance = account.get_balance() print("Account balance", balance) assert balance > 0 batch = [] for i in range(10): batch.append(BatchTransfer( "b50c2404e699fd985f71b2c3f032059f13d6543b", Zil(i * 0.1)) ) pprint(batch) txn_infos = account.transfer_batch(batch) pprint(txn_infos) txn_details = account.wait_txn_confirm(txn_infos[0]["TranID"], timeout=120) pprint(txn_details) assert txn_details for txn_info in txn_infos: txn_details = account.wait_txn_confirm(txn_info["TranID"]) pprint(txn_details) balance2 = account.get_balance() print("Account1 balance", balance2)
def test_transfer(self): chain.set_active_chain(chain.TestNet) account = Account(address="b50c2404e699fd985f71b2c3f032059f13d6543b") print(account) balance1 = account.get_balance() print("Account1 balance", balance1) with pytest.raises(RuntimeError): account.transfer("to_addr", 1) account2 = Account.from_keystore("zxcvbnm,", path_join("crypto", "zilliqa_keystore.json")) print(account2) balance = account2.get_balance() print("Account2 balance", balance) assert balance > 0 to_addr = account.address with pytest.raises(ValueError): account2.transfer(to_addr, 50000) txn_info = account2.transfer(to_addr, Zil(10.3)) pprint(txn_info) txn_details = account2.wait_txn_confirm(txn_info["TranID"], timeout=120) pprint(txn_details) assert txn_details balance2 = account.get_balance() print("Account1 balance", balance2) assert balance2 >= balance1 + 10.3
def iat_create_txns(src_acc, dest_accs, zils): # Clear any cached sessions. This is needed to ensure multiple processes # don't try to reuse the same TCP connection, which would lead to havoc LocalNet = chain.BlockChain(API_ENDPOINT, version=1, network_id=0) chain.set_active_chain(LocalNet) src_acc = Account(private_key=src_acc.private_key) txn_info_list = [] src_addr = src_acc.bech32_address orig_nonce = nonces.get(src_addr, src_acc.get_nonce()) for dest_acc in dest_accs: try: dest = dest_acc.bech32_address txn_info = src_acc.transfer(to_addr=dest, zils=zils, nonce=new_nonce(src_acc), gas_price=100) txn_info_list.append(txn_info) print(json.dumps(src_acc.last_params), file=sys.stderr) print("Created {} transactions".format(len(txn_info_list))) except Exception as e: print("Could not send from {} to {}: {}".format(src_addr, dest, e)) nonce_now = nonces.get(src_addr, src_acc.get_nonce()) # print("{}: created {} transactions; nonce went from {} to {}".format(src_acc.bech32_address, len(txn_info_list), orig_nonce, nonce_now)) return txn_info_list, src_acc, nonce_now
def _test_transfer_qa(self): chain.set_active_chain(chain.TestNet) account = Account(address="b50c2404e699fd985f71b2c3f032059f13d6543b") print(account) print("Account1 balance", repr(account.get_balance())) account2 = Account.from_keystore( "zxcvbnm,", path_join("crypto", "zilliqa_keystore.json")) print(account2) balance = account2.get_balance() print("Account2 balance", repr(balance)) assert balance > 0 txn_info = account2.transfer(account.bech32_address, Qa(123456789)) pprint(txn_info) txn_details = account2.wait_txn_confirm(txn_info["TranID"], timeout=240) pprint(txn_details) assert txn_details print("Account1 balance", repr(account.get_balance())) print("Account1 balance", repr(account.get_balance_qa())) account = Account( private_key= "d0b47febbef2bd0c4a4ee04aa20b60d61eb02635e8df5e7fd62409a2b1f5ddf8") txn_info = account.transfer(account2.checksum_address, Qa(123456789), confirm=True) pprint(txn_info)
def main(): args = parse_arguments() pprint(args) frequency = int(args['frequency']) * 60 # Set active chain chain.set_active_chain( chain.BlockChain(args['apiurl'], version=65537, network_id=1)) while True: print('Check started at: ' + str(datetime.datetime.now())) global ERROR_MESSAGE ERROR_MESSAGE = '' try: test_txn(args) except Exception as e: ERROR_MESSAGE = '[' + os.path.basename( __file__) + '] Error: ' + str(e) if (ERROR_MESSAGE != ''): print(ERROR_MESSAGE) if args['webhook'] != '': send_report(ERROR_MESSAGE, args['webhook']) sys.stdout.flush() if frequency == 0: break time.sleep(frequency)
def launch(config): ''' The main procedure of a worker client. Args: config: Returns: None Note: The '--config' option is prior than others. It means if '--config' is set, other options will be ignored even if the config file is incomplete. ''' cfg = _parse_config(config) #Logging Config log_file = "" if cfg["log-file"] == "stdout" else cfg["log-file"] log_level = _log_level_map[cfg["log-level"]] os.environ['Tora-log-level'] = str(log_level) logger = logging.getLogger(__name__) logger.setLevel(log_level) coloredlogs.install(logger=logger) # set the active chain local_chain = BlockChain(cfg["baseChainServer"], int(cfg["baseChainversion"]), int(cfg["baseChainID"])) chain.set_active_chain(local_chain) KMSConnector.rpcserver = cfg["baseChainServer"] KMSConnector.version = cfg["baseChainversion"] KMSConnector.networkid = cfg["baseChainID"] KMSConnector.host = str(cfg["KMS_HOST"]) KMSConnector.port = int(cfg["KMS_PORT"]) KMSConnector.oracle_owner_address = cfg["oracleAddress"] general_monitor = ZilliqaMonitor(url=cfg["baseChainServer"], contract_addr=cfg["generalContract"]) swap_monitor = ZilliqaMonitor(url=cfg["baseChainServer"], contract_addr=cfg["swapContract"]) resolver = Resolver([general_monitor, swap_monitor], cfg) logger.info("Monitor lanuched~") logger.info("BaseChain: Zilliqa") logger.info("RPC-server: " + cfg["baseChainServer"]) logger.info("Tora Contract Address: " + cfg["generalContract"] + ", " + cfg["swapContract"]) logger.info("Oracle Account: " + cfg["oracleAddress"] + " " + cfg["oracleSK"]) general_monitor.start() swap_monitor.start() resolver.start() general_monitor.join() swap_monitor.join() resolver.join()
def withdraw(config, gas_price, gas_limit, contract): ''' This function will generate a transaction to transfer the token from TEE accoount to the worker's account. ''' cfg = _parse_config(config) # set the active chain local_chain = BlockChain(cfg["baseChainServer"], int(cfg["baseChainversion"]), int(cfg["baseChainID"])) chain.set_active_chain(local_chain) KMSConnector.rpcserver = cfg["baseChainServer"] KMSConnector.version = cfg["baseChainversion"] KMSConnector.networkid = cfg["baseChainID"] KMSConnector.host = str(cfg["KMS_HOST"]) KMSConnector.port = int(cfg["KMS_PORT"]) contract_addr = cfg[contract] contract = Contract.load_from_address(contract_addr) account = Account(private_key=cfg["oracleSK"]) contract.account = account resp = contract.call(method="get_reward_balance", params=[ Contract.value_dict( 'oracle_owner_address', 'ByStr20', zilkey.normalise_address( cfg['oracleAddress']).lower()) ], gas_price=gas_price, gas_limit=gas_limit) if (resp is not None) and (not resp['receipt']['success']): print("Network error") else: if (resp['receipt']['event_logs'][0]['params'][0]['value']['arguments'] == []) or (resp['receipt']['event_logs'][0]['params'][0] ['value']['arguments'] == ['0']): print("No money") else: money = int(resp['receipt']['event_logs'][0]['params'][0]['value'] ['arguments'][0]) / 1000000000000.0 print("Have money: " + str(money)) kms = KMSConnector() if kms.withdraw( zilkey.normalise_address(cfg['oracleAddress'].lower()), money, cfg[contract]) == "success": print("Withdraw submit success") time.sleep(300) print("Withdraw success") elif kms.withdraw( zilkey.normalise_address(cfg['oracleAddress'].lower()), money, cfg[contract]) is None: print("KMS server has no response") else: print("Withdraw submit fail")
def test_transfer(self): chain.set_active_chain(chain.TestNet) account = Account(address="b50c2404e699fd985f71b2c3f032059f13d6543b") print(account) balance1 = account.get_balance() print("Account1 balance", balance1) with pytest.raises(RuntimeError): account.transfer("to_addr", 1) account2 = Account.from_keystore( "zxcvbnm,", path_join("crypto", "zilliqa_keystore.json")) print(account2) balance = account2.get_balance() print("Account2 balance", balance) assert balance > 0 # check address format with pytest.raises(ValueError): account2.transfer(account.address, Zil(10.3)) with pytest.raises(ValueError): account2.transfer(account.address0x, Zil(10.3)) # checksum address # check insufficient balance with pytest.raises(ValueError): account2.transfer(account.checksum_address, 50000) txn_info = account2.transfer(account.checksum_address, Zil(10.3)) pprint(txn_info) txn_details = account2.wait_txn_confirm(txn_info["TranID"], timeout=240) pprint(txn_details) assert txn_details balance2 = account.get_balance() print("Account1 balance", balance2) assert balance2 >= balance1 + 10.299 account = Account( private_key= "d0b47febbef2bd0c4a4ee04aa20b60d61eb02635e8df5e7fd62409a2b1f5ddf8") # bech32 address txn_info = account.transfer(account2.bech32_address, 10.3, confirm=True) pprint(txn_info)
def contract_create_txns(contract, src_accs, method): # Clear any cached sessions. This is needed to ensure multiple processes # don't try to reuse the same TCP connection, which would lead to havoc LocalNet = chain.BlockChain(API_ENDPOINT, version=1, network_id=0) chain.set_active_chain(LocalNet) contract = Contract.load_from_address(contract.address, load_state=False) txn_info_list = [] for src_acc in src_accs: contract.account = src_acc src_addr = src_acc.bech32_address try: txn_info = None if method == 'registerOwnership': txn_info = contract.call(method="registerOwnership", params=[ Contract.value_dict( "ipfs_cid", "String", src_addr) ], nonce=1, confirm=False) elif method == 'configureResolver': label = src_addr txn_info = contract.call( method="configureResolver", params=[ Contract.value_dict("recordOwner", "ByStr20", src_acc.address0x), Contract.value_dict("node", "ByStr32", parentLabelToNode(rootNode, label)), Contract.value_dict("resolver", "ByStr20", src_acc.address0x) ], nonce=1, confirm=False) txn_info_list.append(txn_info) print(json.dumps(src_acc.last_params), file=sys.stderr) print("Created {} transactions".format(len(txn_info_list))) except Exception as e: print("Crowdfund exception: {}".format(e)) # nonce_now = nonces.get(src_addr, src_acc.get_nonce()) return txn_info_list, src_acc, None
def nft_create_txns(contract, src_acc, dest_accs, type='mint'): # Clear any cached sessions. This is needed to ensure multiple processes # don't try to reuse the same TCP connection, which would lead to havoc LocalNet = chain.BlockChain(API_ENDPOINT, version=1, network_id=0) chain.set_active_chain(LocalNet) src_acc = Account(private_key=src_acc.private_key) contract = Contract.load_from_address(contract.address, load_state=False) txn_info_list = [] contract.account = src_acc src_addr = src_acc.bech32_address for dest_acc in dest_accs: try: src = src_acc.address0x dest = dest_acc.address0x txn_info = None if type == 'mint': txn_info = contract.call( method="mint", params=[ Contract.value_dict("to", "ByStr20", dest), Contract.value_dict("tokenId", "Uint256", get_token_id(dest)) ], nonce=1, confirm=False) elif type == 'transfer': txn_info = contract.call( method="transfer", params=[ Contract.value_dict("tokenOwner", "ByStr20", src), Contract.value_dict("to", "ByStr20", dest), Contract.value_dict("tokenId", "Uint256", get_token_id(src)) ], nonce=1, confirm=False) txn_info_list.append(txn_info) print(json.dumps(src_acc.last_params), file=sys.stderr) print("Created {} transactions".format(len(txn_info_list))) except Exception as e: print("Could not send from {} to {}: {}".format( src_acc.address0x, dest, e)) return txn_info_list, src_acc, None
def _test_transfer_confirm(self): chain.set_active_chain(chain.TestNet) account = Account(address="b50c2404e699fd985f71b2c3f032059f13d6543b") print(account) balance1 = account.get_balance() print("Account1 balance", balance1) with pytest.raises(RuntimeError): account.transfer("to_addr", 1) account2 = Account.from_keystore( "zxcvbnm,", path_join("crypto", "zilliqa_keystore.json")) print(account2) balance = account2.get_balance() print("Account2 balance", balance) assert balance > 0 result = account2.transfer(account.checksum_address, Zil(10.3), confirm=True, timeout=300, sleep=20) print("Transfer Result", result) pprint(account2.last_params) pprint(account2.last_txn_info) pprint(account2.last_txn_details) balance2 = account.get_balance() print("Account1 balance", balance2) assert balance2 >= balance1 + 10.299 account = Account( private_key= "d0b47febbef2bd0c4a4ee04aa20b60d61eb02635e8df5e7fd62409a2b1f5ddf8") result = account.transfer(account2.bech32_address, 10.3, confirm=True, timeout=600, sleep=20) print("Transfer Result", result) pprint(account2.last_params) pprint(account2.last_txn_info) pprint(account2.last_txn_details)
def test_balance(self): account = Account(address="b50c2404e699fd985f71b2c3f032059f13d6543b") print("set active chain to TestNet") chain.set_active_chain(chain.TestNet) balance = account.get_balance() print("balance", balance) assert balance > 0 nonce = account.get_nonce() print("nonce", nonce) assert nonce >= 3 account2 = Account(address="b50c2404e699fd985f71b2c3f032059f13d65432") balance = account2.get_balance() print("balance", balance) assert balance == 0 account3 = Account.from_keystore("zxcvbnm,", path_join("crypto", "zilliqa_keystore.json")) balance = account3.get_balance() print("balance", balance) assert balance > 0
def contract_create_multidest_txns(contract, src_acc, dest_accs, method): # Clear any cached sessions. This is needed to ensure multiple processes # don't try to reuse the same TCP connection, which would lead to havoc LocalNet = chain.BlockChain(API_ENDPOINT, version=1, network_id=0) chain.set_active_chain(LocalNet) src_acc = Account(private_key=src_acc.private_key) contract = Contract.load_from_address(contract.address, load_state=False) txn_info_list = [] contract.account = src_acc src_addr = src_acc.bech32_address for dest_acc in dest_accs: try: dest = dest_acc.address0x txn_info = None if method == 'bestow': label = dest_acc.bech32_address txn_info = contract.call( method="bestow", params=[ Contract.value_dict("node", "ByStr32", parentLabelToNode(rootNode, label)), Contract.value_dict("label", "String", label), Contract.value_dict("owner", "ByStr20", dest), Contract.value_dict( "resolver", "ByStr20", "0x0000000000000000000000000000000000000000") ], nonce=1, confirm=False) txn_info_list.append(txn_info) print(json.dumps(src_acc.last_params), file=sys.stderr) print("Created {} transactions".format(len(txn_info_list))) except Exception as e: print("Could not send from {} to {}: {}".format( src_acc.address0x, dest, e)) return txn_info_list, src_acc, None
def test_batch_transfer(self): chain.set_active_chain(chain.TestNet) account = Account.from_keystore( "zxcvbnm,", path_join("crypto", "zilliqa_keystore.json")) print(account) balance = account.get_balance() print("Account balance", balance) assert balance > 0 batch = [] for i in range(10): batch.append( BatchTransfer("b50c2404e699fd985f71b2c3f032059f13d6543b", Zil(i * 0.1))) pprint(batch) txn_infos = account.transfer_batch(batch) pprint(txn_infos) txn_details = account.wait_txn_confirm(txn_infos[0]["TranID"], timeout=120) pprint(txn_details) assert txn_details for txn_info in txn_infos: txn_details = account.wait_txn_confirm(txn_info["TranID"]) pprint(txn_details) balance2 = account.get_balance() print("Account1 balance", balance2) account2 = Account( private_key= "d0b47febbef2bd0c4a4ee04aa20b60d61eb02635e8df5e7fd62409a2b1f5ddf8") txn_info = account2.transfer(account.address, sum([b.zils for b in batch])) pprint(txn_info)
def test_transfer_qa(self): chain.set_active_chain(chain.TestNet) account = Account(address="b50c2404e699fd985f71b2c3f032059f13d6543b") print(account) print("Account1 balance", repr(account.get_balance())) account2 = Account.from_keystore("zxcvbnm,", path_join("crypto", "zilliqa_keystore.json")) print(account2) balance = account2.get_balance() print("Account2 balance", repr(balance)) assert balance > 0 to_addr = account.address txn_info = account2.transfer(to_addr, Qa(123456789)) pprint(txn_info) txn_details = account2.wait_txn_confirm(txn_info["TranID"], timeout=120) pprint(txn_details) assert txn_details print("Account1 balance", repr(account.get_balance())) print("Account1 balance", repr(account.get_balance_qa()))
def __init__(self, account): # Set mainnet chain.set_active_chain(chain.MainNet) # Set contract _addr = "zil1hgg7k77vpgpwj3av7q7vv5dl4uvunmqqjzpv2w" self.contract = Contract.load_from_address(_addr, load_state=True) # Set account self.contract.account = account # Set Zilliqa API self.api = ZilliqaAPI("https://api.zilliqa.com/") # Load Zilgraph JSON fp_json = open("zilgraph.json") self.tokens = json.load(fp_json)["tokens"] # Setup dictionaries self.token = {} self.decimals = {"zil": 12} for tok in self.tokens: self.token[tok] = Account(address=self.tokens[tok]["addr"]) self.decimals[tok] = self.tokens[tok]["decimals"]
def crowd_create_txns(contract, src_accs, amount): # Clear any cached sessions. This is needed to ensure multiple processes # don't try to reuse the same TCP connection, which would lead to havoc LocalNet = chain.BlockChain(API_ENDPOINT, version=1, network_id=0) chain.set_active_chain(LocalNet) contract = Contract.load_from_address(contract.address, load_state=False) txn_info_list = [] for src_acc in src_accs: contract.account = src_acc src_addr = src_acc.bech32_address try: txn_info = contract.call(method="Donate", params=[], zils=amount, nonce=1, confirm=False) txn_info_list.append(txn_info) print(json.dumps(src_acc.last_params), file=sys.stderr) print("Created {} transactions".format(len(txn_info_list))) except Exception as e: print("Crowdfund exception: {}".format(e)) # nonce_now = nonces.get(src_addr, src_acc.get_nonce()) return txn_info_list, src_acc, None
def test_active_chain(self): chain.set_active_chain(None) with pytest.raises(chain.BlockChainError): active_chain.api.GetCurrentDSEpoch() chain.set_active_chain(chain.MainNet) print(active_chain) chain.set_active_chain(chain.TestNet) print(active_chain) resp = active_chain.api.GetCurrentDSEpoch() pprint(resp) assert resp
import time sys.path.append( os.path.abspath(os.path.join(os.path.dirname(__file__), "../../"))) sys.path.append( os.path.abspath(os.path.join(os.path.dirname(__file__), "../lib"))) from pprint import pprint from pyzil.crypto import zilkey from pyzil.zilliqa import chain from pyzil.account import Account from pyzil.contract import Contract from pyzil.zilliqa.api import ZilliqaAPI chain.set_active_chain(chain.TestNet) # user account account = Account( private_key= "919457fa2d81c0b7f1f1918683b1ff6b459c444aefec494c92f34d746ebb6b73") balance = account.get_balance() print("{}: {}".format(account, balance)) contract_addr = "zil1cfq4we3nmf2t7687qjvdwlz89qw2gzy700qwff" contract = Contract.load_from_address(contract_addr) contract.account = account def new_swap_request_test(swap_chain, initial_money, swap_money, target_addr, swap_chain_initial_addr, swap_chain_target_addr):
class TestAccount: chain.set_active_chain(chain.TestNet) account = Account.from_keystore("zxcvbnm,", path_join("crypto", "zilliqa_keystore.json")) def test_new_contract(self): print("Account balance", self.account.get_balance()) code = open(path_join("contracts", "HelloWorld.scilla")).read() contract = Contract.new_from_code(code) print(contract) with pytest.raises(ValueError, match=".+set account.+"): contract.deploy() contract.account = self.account contract.deploy(timeout=300, sleep=10) print(contract) assert contract.status == Contract.Status.Deployed def test_from_address_hello(self): address = "45dca9586598c8af78b191eaa28daf2b0a0b4f43" contract = Contract.load_from_address(address, load_state=True) print(contract) pprint(contract.get_state(get_code=True, get_init=True)) print(contract.status) print(contract.code) pprint(contract.init) pprint(contract.state) def test_from_address_test(self): address = "2d3195fbfbe0442556c9613e539a0b62a64f2402" contract = Contract.load_from_address(address, load_state=True) print(contract) pprint(contract.get_state(get_code=True, get_init=True)) print(contract.status) print(contract.code) pprint(contract.init) pprint(contract.state) def test_get_contracts(self): owner_addr = self.account.address contracts = Contract.get_contracts(owner_addr) pprint(contracts) contracts2 = self.account.get_contracts() pprint(contracts2) assert contracts == contracts2 def test_call(self): contract = Contract.load_from_address("2d3195fbfbe0442556c9613e539a0b62a64f2402") print(contract) contract.get_state(get_init=True, get_code=True) print(contract.status) print(contract.code) pprint(contract.init) pprint(contract.state) contract.account = self.account resp = contract.call(method="getMessage", params=[]) print(resp) pprint(contract.last_receipt) assert contract.last_receipt["success"] assert contract.last_receipt["event_logs"][0]["params"][0]["vname"] == "msg" assert contract.last_receipt["event_logs"][0]["params"][0]["value"] == "Test Message" def test_call_hello(self): contract = Contract.load_from_address("45dca9586598c8af78b191eaa28daf2b0a0b4f43") print(contract) print(contract.status) print(contract.code) pprint(contract.init) pprint(contract.state) contract.account = self.account resp = contract.call(method="contrAddr", params=[]) print(resp) pprint(contract.last_receipt) assert contract.last_receipt["success"] assert contract.last_receipt["event_logs"][0]["params"][0]["vname"] == "addr" assert contract.last_receipt["event_logs"][0]["params"][0]["value"] == contract.address0x resp = contract.call(method="setHello", params=[Contract.value_dict("msg", "String", "hi contract.")]) print(resp) pprint(contract.last_receipt) assert contract.last_receipt["success"] assert contract.last_receipt["event_logs"][0]["params"][0]["vname"] == "code" assert contract.last_receipt["event_logs"][0]["params"][0]["type"] == "Int32" assert contract.last_receipt["event_logs"][0]["params"][0]["value"] == "2" resp = contract.call(method="getHello", params=[]) print(resp) pprint(contract.last_receipt) assert contract.last_receipt["success"] assert contract.last_receipt["event_logs"][0]["_eventname"] == "getHello()" assert contract.last_receipt["event_logs"][0]["params"][0]["vname"] == "msg" assert contract.last_receipt["event_logs"][0]["params"][0]["type"] == "String" assert contract.last_receipt["event_logs"][0]["params"][0]["value"] == "hi contract." def test_call_other_account(self): contract = Contract.load_from_address("45dca9586598c8af78b191eaa28daf2b0a0b4f43") print(contract) print(contract.status) print(contract.code) pprint(contract.init) pprint(contract.state) account2 = Account(private_key="d0b47febbef2bd0c4a4ee04aa20b60d61eb02635e8df5e7fd62409a2b1f5ddf8") print("Account2 balance", account2.get_balance()) contract.account = account2 resp = contract.call(method="setHello", params=[ Contract.value_dict("msg", "String", "hello from another account") ]) print(resp) pprint(contract.last_receipt) assert contract.last_receipt["success"] assert contract.last_receipt["event_logs"][0]["params"][0]["vname"] == "code" assert contract.last_receipt["event_logs"][0]["params"][0]["value"] == "1" resp = contract.call(method="getHello", params=[]) print(resp) pprint(contract.last_receipt) assert contract.last_receipt["success"] assert contract.last_receipt["event_logs"][0]["_eventname"] == "getHello()" assert contract.last_receipt["event_logs"][0]["params"][0]["vname"] == "msg" assert contract.last_receipt["event_logs"][0]["params"][0]["type"] == "String" assert contract.last_receipt["event_logs"][0]["params"][0]["value"] == "hi contract."
def setup_method(self, method): print("set active chain to IsolatedServer") chain.set_active_chain(chain.IsolatedServer)
def _test_batch_transfer(self): chain.set_active_chain(chain.TestNet) account = Account.from_keystore( "zxcvbnm,", path_join("crypto", "zilliqa_keystore.json")) print(account) balance = account.get_balance() print("Account balance", balance) assert balance > 0 to_account = Account( address="b50c2404e699fd985f71b2c3f032059f13d6543b") # check address format with pytest.raises(ValueError): account.transfer_batch([ BatchTransfer(to_account.checksum_address, 0.001), BatchTransfer("wrong_address", 0.001) ]) with pytest.raises(ValueError): account.transfer_batch([ BatchTransfer(to_account.address, 0.001), ]) with pytest.raises(ValueError): account.transfer_batch([ BatchTransfer(to_account.address0x, 0.001), ]) batch = [] total_zils = 0 for i in range(10): batch.append( BatchTransfer(to_account.checksum_address, Zil(i * 0.1))) total_zils += (i * 0.1) batch.append(BatchTransfer(to_account.bech32_address, Zil(i * 0.1))) total_zils += (i * 0.1) pprint(batch) txn_infos = account.transfer_batch(batch) pprint(txn_infos) txn_details = account.wait_txn_confirm(txn_infos[0]["TranID"], timeout=240) pprint(txn_details) assert txn_details for txn_info in txn_infos: if not txn_info: print("Failed to create txn") else: txn_details = account.wait_txn_confirm(txn_info["TranID"]) pprint(txn_details) if txn_details and txn_details["receipt"]["success"]: print("Txn success") else: print("Txn failed") balance2 = account.get_balance() print("Account1 balance", balance2) account2 = Account( private_key= "d0b47febbef2bd0c4a4ee04aa20b60d61eb02635e8df5e7fd62409a2b1f5ddf8") txn_info = account2.transfer(account.bech32_address, total_zils, confirm=True) pprint(txn_info)
from pprint import pprint from pyzil.zilliqa.api import ZilliqaAPI, APIError from pyzil.zilliqa import chain from pyzil.account import Account import json import sys import datetime import math from concurrent import futures from concurrent.futures import ProcessPoolExecutor API_ENDPOINT = "http://localhost:4201" LocalNet = chain.BlockChain(API_ENDPOINT, version=1, network_id=0) chain.set_active_chain(LocalNet) MAX_NUM_WORKERS = 100 TARGET_BUCKET_SIZE = 1000 GET_CHAIN_NONCE = False nonces = {} def partition(list, num_buckets): part = {} for b in range(num_buckets): part[b] = [] for i, val in enumerate(list): part[i % num_buckets].append(val)
def setup_method(self, method): chain.set_active_chain(chain.IsolatedServer)