Exemple #1
0
    def transfer_batch(self, batch: List[BatchTransfer],
                       gas_price: Optional[int]=None, gas_limit=1,
                       max_workers=200, timeout=None):
        """Batch Transfer zils to addresses."""
        if not self.zil_key or not self.zil_key.encoded_private_key:
            raise RuntimeError("can not create transaction without private key")

        # check address format
        for to_addr, zils in batch:
            to_addr = zilkey.normalise_address(to_addr)
            if not to_addr:
                raise ValueError("invalid to address")

        if gas_price is None:
            gas_price = self.get_min_gas_price(refresh=False)

        resp = self.get_balance_nonce()
        batch_nonce = resp["nonce"] + 1

        txn_params = []
        for to_addr, zils in batch:
            to_addr = zilkey.normalise_address(to_addr)
            if not to_addr:
                raise ValueError("invalid to address")

            if isinstance(zils, Qa):
                amount = zils
            else:
                if not isinstance(zils, Zil):
                    zils = Zil(zils)
                amount = zils.toQa()

            params = active_chain.build_transaction_params(
                self.zil_key, to_addr,
                amount, batch_nonce,
                gas_price, gas_limit
            )
            txn_params.append(params)
            batch_nonce += 1

        def create_txn(p):
            try:
                txn_info = active_chain.api.CreateTransaction(p)
            except Exception as e:
                print("Error in CreateTransaction: {}".format(e))
                txn_info = None
            return txn_info

        txn_results = []
        with ThreadPoolExecutor(max_workers=max_workers) as pool:
            all_tasks = [pool.submit(create_txn, p) for p in txn_params]

            for future in futures.as_completed(all_tasks, timeout=timeout):
                try:
                    txn_results.append(future.result())
                except Exception as e:
                    print("Error: {}".format(e))
                    txn_results.append(None)

        return txn_results
Exemple #2
0
    def test_batch_transfer(self):
        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(2):
            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)

        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)
Exemple #3
0
    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)
Exemple #4
0
    def test_transfer_confirm(self):
        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)
Exemple #5
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)
Exemple #6
0
    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
Exemple #7
0
    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)
Exemple #8
0
    def transfer(self, to_addr: str,
                 zils: Union[str, float, Zil, Qa],
                 nonce: Optional[int]=None,
                 gas_price: Optional[int]=None, gas_limit=1,
                 code="", data="", priority=False,
                 confirm=False, timeout=300, sleep=20, hit_chain=False):
        """Transfer zils to another address."""
        if not self.zil_key or not self.zil_key.encoded_private_key:
            raise RuntimeError("can not create transaction without private key")

        to_addr = zilkey.normalise_address(to_addr)
        if not to_addr:
            raise ValueError("invalid to address")

        if isinstance(zils, Qa):
            amount = zils
        else:
            if not isinstance(zils, Zil):
                zils = Zil(zils)
            amount = zils.toQa()

        if gas_price is None:
            if hit_chain:
                gas_price = self.get_min_gas_price(refresh=False)
            else:
                gas_price = 100

        if nonce is None:
            resp = self.get_balance_nonce()
            if amount > Qa(resp["balance"]):
                raise ValueError("insufficient balance to send")
            nonce = resp["nonce"] + 1

        params = active_chain.build_transaction_params(
            self.zil_key, to_addr,
            amount, nonce,
            gas_price, gas_limit,
            code, data, priority
        )
        self.last_params = params

        if not hit_chain:
            return None
        else:
            txn_info = active_chain.api.CreateTransaction(params)
            self.last_txn_info = txn_info
            if not confirm:
                return txn_info

            if not txn_info:
                return None

            txn_details = Account.wait_txn_confirm(
                txn_info["TranID"],
                timeout=timeout, sleep=sleep
            )
            self.last_txn_details = txn_details
            return txn_details
Exemple #9
0
    def transfer_batch(self, batch: BatchTransfer,
                       gas_price: Optional[int]=None, gas_limit=1):
        """Batch Transfer zils to addresses."""
        if not self.zil_key or not self.zil_key.encoded_private_key:
            raise RuntimeError("can not create transaction without private key")

        if gas_price is None:
            gas_price = self.get_min_gas_price(refresh=False)

        resp = self.get_balance_nonce()
        batch_nonce = resp["nonce"] + 1

        txn_params = []
        for to_addr, zils in batch:
            to_addr = zilkey.to_checksum_address(to_addr)
            if not to_addr:
                raise ValueError("invalid to address")

            if isinstance(zils, Qa):
                amount = zils
            else:
                if not isinstance(zils, Zil):
                    zils = Zil(zils)
                amount = zils.toQa()

            params = active_chain.build_transaction_params(
                self.zil_key, to_addr,
                amount, batch_nonce,
                gas_price, gas_limit
            )
            txn_params.append(params)
            batch_nonce += 1

        return [
            active_chain.api.CreateTransaction(params)
            for params in txn_params
        ]
Exemple #10
0
    def call(self,
             method: str,
             params: Optional[List[Dict]],
             zils: Union[str, float, Zil, Qa] = 0,
             nonce: Optional[int] = None,
             gas_price: Optional[int] = None,
             gas_limit=10000,
             priority=False,
             confirm=True,
             timeout=300,
             sleep=10) -> Optional[Dict]:
        if not self.address:
            raise ValueError("invalid contract address")
        if self.status != Contract.Status.Deployed:
            raise ValueError("contract has not been deployed")

        call_data = json.dumps({"_tag": method, "params": params})

        if isinstance(zils, Qa):
            amount = zils
        else:
            if not isinstance(zils, Zil):
                zils = Zil(zils)
            amount = zils.toQa()

        txn_info = self.account.transfer(to_addr=self.checksum_address,
                                         zils=amount,
                                         nonce=nonce,
                                         gas_price=gas_price,
                                         gas_limit=gas_limit,
                                         data=call_data,
                                         priority=priority,
                                         hit_chain=False)
        if not confirm:
            return txn_info

        call_txn_id = txn_info["TranID"]

        txn_details = self.account.wait_txn_confirm(call_txn_id,
                                                    timeout=timeout,
                                                    sleep=sleep)
        self.last_receipt = txn_details and txn_details["receipt"]
        return txn_details
Exemple #11
0
    def transfer(self, to_addr: str,
                 zils: Union[str, float, Zil, Qa],
                 nonce: Optional[int]=None,
                 gas_price: Optional[int]=None, gas_limit=1,
                 code="", data="", priority=False):
        """Transfer zils to another address."""
        if not self.zil_key or not self.zil_key.encoded_private_key:
            raise RuntimeError("can not create transaction without private key")

        to_addr = zilkey.to_checksum_address(to_addr)
        if not to_addr:
            raise ValueError("invalid to address")

        if isinstance(zils, Qa):
            amount = zils
        else:
            if not isinstance(zils, Zil):
                zils = Zil(zils)
            amount = zils.toQa()

        if gas_price is None:
            gas_price = self.get_min_gas_price(refresh=False)

        if nonce is None:
            resp = self.get_balance_nonce()
            if amount > Qa(resp["balance"]):
                raise ValueError("insufficient balance to send")
            nonce = resp["nonce"] + 1

        params = active_chain.build_transaction_params(
            self.zil_key, to_addr,
            amount, nonce,
            gas_price, gas_limit,
            code, data, priority
        )

        txn_info = active_chain.api.CreateTransaction(params)
        return txn_info
Exemple #12
0
    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)