Example #1
0
    def buy_gzil(self, amount, max_price=2000):
        # Buy gZIL
        _min_token_amount = str(int(amount * 1e15))
        _deadline_block = str(int(self.api.GetCurrentMiniEpoch()) + 15)

        _params = [
            Contract.value_dict("token_address", "ByStr20",
                                self.token["gzil"].address0x),
            Contract.value_dict("min_token_amount", "Uint128",
                                _min_token_amount),
            Contract.value_dict("deadline_block", "BNum", _deadline_block),
            Contract.value_dict("recipient_address", "ByStr20",
                                self.contract.account.address0x)
        ]

        pprint(_params)

        _zils = Zil(max_price * amount)

        resp = self.contract.call(method="SwapExactZILForTokens",
                                  params=_params,
                                  amount=_zils,
                                  gas_limit=30000)
        pprint(resp)
        pprint(self.contract.last_receipt)
Example #2
0
    def test_call_other_account(self):
        address = self.contracts["hello"]
        contract = Contract.load_from_address(address)
        print(contract)
        print(contract.status)

        account2 = Account(private_key="d0b47febbef2bd0c4a4ee04aa20b60d61eb02635e8df5e7fd62409a2b1f5ddf8")
        print("Account2 balance", account2.get_balance())

        contract.account = account2
        resp = contract.call(gas_price=1000000000, 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(gas_price=1000000000, 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."
Example #3
0
def commit_verify_result_test(verify_request_id, result, oracle_owner_address):
    resp = contract.call(method="commit_verify_result", params=[
        Contract.value_dict('id', 'Uint32', verify_request_id),
        Contract.value_dict('result', 'String', result),
        Contract.value_dict('oracle_owner_address', 'ByStr20', oracle_owner_address)
    ])
    pprint(resp)
Example #4
0
    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."
Example #5
0
    def test_call_hello(self):
        address = self.contracts["hello"]
        contract = Contract.load_from_address(address)
        print(contract)
        print(contract.status)
        pprint(contract.state)

        contract.account = self.account
        resp = contract.call(gas_price=1000000000, 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(gas_price=1000000000, 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(gas_price=1000000000, 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."
Example #6
0
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
Example #7
0
def register_test(owner_addr, pk, proof):
    resp = contract.call(method="register", params=[
        Contract.value_dict("owner_address", "ByStr20", owner_addr),
        Contract.value_dict("pk", "ByStr33", pk),
        Contract.value_dict("proof", "ByStr64", proof)])
    pprint(resp)
    pprint(contract.last_receipt)
Example #8
0
def commit_swap_hash_test(swap_request_id, user_addr, tx_hash, gas_price,
                          gas_limit):
    print("Waiting the request published on chain...")
    resp = contract.call(method="commit_swap_hash",
                         params=[
                             Contract.value_dict("swap_request_id", "Uint32",
                                                 swap_request_id),
                             Contract.value_dict("user_addr", "ByStr20",
                                                 user_addr),
                             Contract.value_dict("tx_hash", "String", tx_hash),
                             Contract.value_dict("gas_price", "Uint128",
                                                 gas_price),
                             Contract.value_dict("gas_limit", "Uint128",
                                                 gas_limit)
                         ],
                         amount=20)
    if resp['receipt']['success']:
        event_logs = resp['receipt']['event_logs']
        if event_logs[0]['_eventname'] == 'verifyrequest':
            print("Commit hash successfully, please wait for the response...")
            monitor_swap_success_event(account.address0x)
        else:
            print("Commit fail, please see the event log")
            pprint(event_logs)
    else:
        print("Commit fail")
        pprint(resp)
Example #9
0
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")
Example #10
0
def response_string(result, gas_price, gas_limit, oracle_owner_address):
    resp = contract.call(method="responseString",
                         params=[
                             Contract.value_dict('id', 'Uint32', '1'),
                             Contract.value_dict('result', 'String', result),
                             Contract.value_dict('oracle_owner_address',
                                                 'ByStr20',
                                                 oracle_owner_address)
                         ],
                         gas_price=gas_price,
                         gas_limit=gas_limit)
    pprint(resp)
    pprint(contract.last_receipt)
Example #11
0
def appeal_test(swap_request_id):
    resp = contract.call(method="appeal",
                         params=[
                             Contract.value_dict("swap_request_id", "Uint32",
                                                 swap_request_id)
                         ])
    pprint(resp)
Example #12
0
def deploy_execution_script(exprs):
    contract_addr = "zil1mejpsqd5cw589xyq3llzvrk0nvetm9v0l5kcn7"
    contract = Contract.load_from_address(contract_addr)
    contract.account = account
    resp = contract.call(method="deployScript", params=[
        Contract.value_dict('exprs', "String", exprs)], priority=True)
    if resp['receipt']['success']:
        event_logs = resp['receipt']['event_logs']
        if event_logs[0]['_eventname'] == 'Script Deploy':
            print("Script committed successfully, the script id is " + event_logs[0]['params'][1]['value'])
        else:
            print("Commit fail, please see the event log")
            pprint(event_logs)
    else:
        print("Commit fail")
        pprint(resp)
 def register_to_process(self, sk, request_id):
     account = Account(private_key=sk)
     contract = Contract.load_from_address(self.contract_addr)
     contract.account = account
     resp = contract.call(method="register_to_process", params=[
         Contract.value_dict("verify_request_id", "Uint32", request_id)
     ], amount=DEFAULT_REGISTER_STAKE)
     if not resp:
         return False
     if resp['receipt']['success']:
         if "event_logs" in resp['receipt']:
             event_logs = resp['receipt']["event_logs"]
             for event_log in event_logs:
                 if event_log['_eventname'] == 'register success':
                     return True
     return False
Example #14
0
 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)
Example #15
0
 def test_from_address_test(self):
     address = self.contracts["test"]
     contract = Contract.load_from_address(address, load_state=True)
     print(contract)
     pprint(contract.get_state(get_code=True, get_init=False))
     print(contract.status)
     print(contract.code)
     pprint(contract.init)
     pprint(contract.state)
Example #16
0
 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)
Example #17
0
    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
Example #18
0
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
Example #19
0
def get_reward_balance(oracle_owner_address, gas_price, gas_limit):
    resp = contract.call(method="get_reward_balance",
                         params=[
                             Contract.value_dict('oracle_owner_address',
                                                 'ByStr20',
                                                 oracle_owner_address)
                         ],
                         gas_price=gas_price,
                         gas_limit=gas_limit)
    pprint(resp)
    pprint(contract.last_receipt)
Example #20
0
def withdraw_reward(oracle_owner_address, money, gas_price, gas_limit):
    resp = contract.call(method="withdraw_reward",
                         params=[
                             Contract.value_dict('oracle_owner_address',
                                                 'ByStr20',
                                                 oracle_owner_address)
                         ],
                         gas_price=gas_price,
                         gas_limit=gas_limit,
                         amount=money)
    pprint(resp)
    pprint(contract.last_receipt)
Example #21
0
def deploy_contract(acc, file, init_params=[]):
    print("Deploying {} contract".format(file), flush=True)
    code = open(os.path.join(CONTRACTS_PATH, file)).read()
    contract = Contract.new_from_code(code)
    contract.account = acc
    txn_info = contract.deploy(timeout=TX_TIMEOUT,
                               sleep=10,
                               confirm=True,
                               init_params=init_params,
                               gas_limit=20000)
    print(json.dumps(acc.last_params), file=sys.stderr, flush=True)
    pprint(contract)
    return contract
Example #22
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
Example #23
0
def register_to_process_test(verify_request_id):
    resp = contract.call(method="register_to_process", params=[
        Contract.value_dict("verify_request_id", "Uint32", verify_request_id)
    ], amount=2)
    pprint(resp)
    if not resp:
        pprint("Register fail")
    if resp['receipt']['success']:
        if "event_logs" in resp['receipt']:
            event_logs = resp['receipt']["event_logs"]
            for event_log in event_logs:
                if event_log['_eventname'] == 'register success':
                    pprint('Verify the request...')
                    return
        pprint('Register fail')
Example #24
0
    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 deploy_contract(contract_file, account_sk):
    # deploy the contract
    code = open(contract_file).read()
    contract = Contract.new_from_code(code)
    print(contract)

    account = Account(private_key=account_sk)
    balance = account.get_balance()
    print("{}: {}".format(account, balance))

    # set account before deploy
    contract.account = account

    contract.deploy(timeout=300, sleep=10, priority=True)
    assert contract.status == Contract.Status.Deployed
Example #26
0
def new_swap_request_test(swap_chain, initial_money, swap_money, target_addr, swap_chain_initial_addr, swap_chain_target_addr):
    resp = contract.call(method="request_swap", params=[
        Contract.value_dict("swap_chain", "String", swap_chain),
        Contract.value_dict("initial_money", "Uint128", str(initial_money)),
        Contract.value_dict("swap_money", "Uint128", str(swap_money)),
        Contract.value_dict("target_addr", "ByStr20", target_addr),
        Contract.value_dict("swap_chain_initial_addr", "ByStr20", swap_chain_initial_addr),
        Contract.value_dict("swap_chain_target_addr", "ByStr20", swap_chain_target_addr)
    ], amount=initial_money/1000000000000, priority=True)
    pprint(resp)
Example #27
0
    def test_call(self):
        address = self.contracts["test"]
        contract = Contract.load_from_address(address)
        print(contract)
        contract.get_state(get_init=True, get_code=False)
        print(contract.status)
        pprint(contract.init)
        pprint(contract.state)

        contract.account = self.account
        resp = contract.call(gas_price=1000000000, 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"
Example #28
0
    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"
Example #29
0
def test_executor():
    # request contract address
    contract_addr = "zil1phx2r986z4hr3rcpk0ztnxfaqvw4je5e2ek2w8"
    contract = Contract.load_from_address(contract_addr)
    contract.account = account
    print("Waiting for the request published on chain...")
    resp = contract.call(method="request", params=[], amount=25, priority=True)
    if resp['receipt']['success']:
        event_logs = resp['receipt']['event_logs']
        if event_logs[0]['_eventname'] == 'request':
            print("Request committed successfully, waiting the response...")
            get_response_event(contract_addr)
        else:
            print("Commit fail, please see the event log")
            pprint(event_logs)
    else:
        print("Commit fail")
        pprint(resp)
def test_cross_chain_info():
    # request contract address
    contract_addr = "zil1wazvqe0pl3qwnd7hcjw6yqaqy7say2a4qkhkzj"
    contract = Contract.load_from_address(contract_addr)
    contract.account = account
    print("Waiting for the request published on chain...")
    resp = contract.call(method="request", params=[], amount=25, priority=True)
    if resp['receipt']['success']:
        event_logs = resp['receipt']['event_logs']
        if event_logs[0]['_eventname'] == 'request':
            print("Request committed successfully, waiting the response...")
            get_response_event(contract_addr)
        else:
            print("Commit fail, please see the event log")
            pprint(event_logs)
    else:
        print("Commit fail")
        pprint(resp)