viz-python-lib 1.0.2__py3-none-any.whl → 1.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
viz/__init__.py CHANGED
@@ -1,13 +1,3 @@
1
- # -*- coding: utf-8 -*-
2
- from .viz import Client # noqa: F401
1
+ from .viz import Client
3
2
 
4
- __all__ = [
5
- "viz",
6
- "account",
7
- "amount",
8
- "block",
9
- "blockchain",
10
- "storage",
11
- "utils",
12
- "wallet",
13
- ]
3
+ __all__ = ["Client"]
viz/account.py CHANGED
@@ -1,5 +1,7 @@
1
- from typing import TYPE_CHECKING, Generator, List, Optional, Union
1
+ from collections.abc import Generator
2
+ from typing import TYPE_CHECKING, Optional
2
3
  from warnings import warn
4
+
3
5
  from graphenecommon.exceptions import AccountDoesNotExistsException
4
6
  from toolz import dissoc
5
7
 
@@ -11,7 +13,7 @@ from .utils import json_expand, parse_time, time_elapsed
11
13
  if TYPE_CHECKING:
12
14
  from .viz import Client # noqa: F401
13
15
 
14
- HistoryGenerator = Generator[Union[dict, list], None, int]
16
+ HistoryGenerator = Generator[dict | list, None, int]
15
17
 
16
18
 
17
19
  class Account(dict):
@@ -23,11 +25,16 @@ class Account(dict):
23
25
  instance
24
26
  """
25
27
 
26
- def __init__(self, account_name: str, blockchain_instance: Optional['Client'] = None) -> None:
28
+ def __init__(
29
+ self,
30
+ account_name: str,
31
+ blockchain_instance: Optional["Client"] = None,
32
+ protocol: str = "",
33
+ ) -> None:
27
34
  self.blockchain_instance = blockchain_instance or shared_blockchain_instance()
28
35
  self.name = account_name
29
36
 
30
- self.refresh()
37
+ self.refresh(protocol)
31
38
 
32
39
  @property
33
40
  def balances(self):
@@ -38,18 +45,18 @@ class Account(dict):
38
45
  def energy(self):
39
46
  """Account energy at the moment of last use (stale)"""
40
47
  cfg = self.blockchain_instance.rpc.config
41
- return self['energy'] / cfg['CHAIN_1_PERCENT']
48
+ return self["energy"] / cfg["CHAIN_1_PERCENT"]
42
49
 
43
- def refresh(self):
50
+ def refresh(self, protocol: str = "") -> None:
44
51
  """Loads account object from blockchain."""
45
52
  try:
46
- account = self.blockchain_instance.rpc.get_accounts([self.name])[0]
47
- except IndexError:
48
- raise AccountDoesNotExistsException
53
+ account = self.blockchain_instance.rpc.get_account(self.name, protocol)
54
+ except Exception as err:
55
+ raise AccountDoesNotExistsException from err
49
56
 
50
57
  # load json_metadata
51
58
  account = json_expand(account, "json_metadata")
52
- super(Account, self).__init__(account)
59
+ super().__init__(account)
53
60
 
54
61
  def get_balances(self) -> dict:
55
62
  """
@@ -65,14 +72,14 @@ class Account(dict):
65
72
  def current_energy(self) -> float:
66
73
  """Returns current account energy (actual data, counts regenerated energy)"""
67
74
  self.refresh()
68
- last_vote_time = parse_time(self['last_vote_time'])
75
+ last_vote_time = parse_time(self["last_vote_time"])
69
76
  elapsed_time = time_elapsed(last_vote_time)
70
77
  cfg = self.blockchain_instance.rpc.config
71
78
  regenerated_energy = (
72
- cfg['CHAIN_100_PERCENT'] * elapsed_time.total_seconds() / cfg['CHAIN_ENERGY_REGENERATION_SECONDS']
79
+ cfg["CHAIN_100_PERCENT"] * elapsed_time.total_seconds() / cfg["CHAIN_ENERGY_REGENERATION_SECONDS"]
73
80
  )
74
- current_energy = self['energy'] + regenerated_energy
75
- energy = min(current_energy, cfg['CHAIN_100_PERCENT']) / cfg['CHAIN_1_PERCENT']
81
+ current_energy = self["energy"] + regenerated_energy
82
+ energy = min(current_energy, cfg["CHAIN_100_PERCENT"]) / cfg["CHAIN_1_PERCENT"]
76
83
 
77
84
  return energy
78
85
 
@@ -85,7 +92,7 @@ class Account(dict):
85
92
  else:
86
93
  return last_item
87
94
 
88
- def get_withdraw_routes(self, type_: str = 'all') -> dict:
95
+ def get_withdraw_routes(self, type_: str = "all") -> dict:
89
96
  """
90
97
  Get vesting withdraw routes.
91
98
 
@@ -111,10 +118,10 @@ class Account(dict):
111
118
  self,
112
119
  index: int,
113
120
  limit: int,
114
- start: Optional[int] = None,
115
- stop: Optional[int] = None,
121
+ start: int | None = None,
122
+ stop: int | None = None,
116
123
  order: int = -1,
117
- filter_by: Optional[Union[str, List[str]]] = None,
124
+ filter_by: str | list[str] | None = None,
118
125
  raw_output: bool = False,
119
126
  ) -> HistoryGenerator:
120
127
  """
@@ -155,7 +162,7 @@ class Account(dict):
155
162
  # removes specified key from dict
156
163
  block_props = dissoc(event, "op")
157
164
 
158
- def construct_op(account_name):
165
+ def construct_op(account_name, index, op_type, block_props, op, item):
159
166
  # verbatim output from steemd
160
167
  if raw_output:
161
168
  return item
@@ -170,14 +177,14 @@ class Account(dict):
170
177
  return immutable
171
178
 
172
179
  if filter_by is None or op_type in filter_by:
173
- yield construct_op(self.name)
180
+ yield construct_op(self.name, index, op_type, block_props, op, item)
174
181
  op_count += 1
175
182
 
176
183
  return op_count
177
184
 
178
185
  def history(
179
186
  self,
180
- filter_by: Optional[Union[str, List[str]]] = None,
187
+ filter_by: str | list[str] | None = None,
181
188
  start: int = 0,
182
189
  batch_size: int = 1000,
183
190
  raw_output: bool = False,
@@ -186,7 +193,7 @@ class Account(dict):
186
193
  """
187
194
  THIS FUNCTION IS DEPRECATED. PLEASE USE :py:func:`history_reverse` INSTEAD.
188
195
 
189
- Stream account history in chronological order.
196
+ Stream account history in chronological order.
190
197
 
191
198
  This generator yields history items which may be in list or dict form depending on ``raw_output``.
192
199
  Output is similar to :py:func:`history_reverse`.
@@ -200,7 +207,11 @@ class Account(dict):
200
207
  This is a rough limit, actual results could be a bit longer
201
208
  :return: number of ops
202
209
  """
203
- warn("Function `history` is not recommened. Use `history_reverse` instead.", DeprecationWarning, stacklevel=2)
210
+ warn(
211
+ "Function `history` is not recommened. Use `history_reverse` instead.",
212
+ DeprecationWarning,
213
+ stacklevel=2,
214
+ )
204
215
 
205
216
  op_count = 0
206
217
 
@@ -230,7 +241,7 @@ class Account(dict):
230
241
 
231
242
  def history_reverse(
232
243
  self,
233
- filter_by: Optional[Union[str, List[str]]] = None,
244
+ filter_by: str | list[str] | None = None,
234
245
  batch_size: int = 1000,
235
246
  raw_output: bool = False,
236
247
  limit: int = -1,
@@ -297,7 +308,11 @@ class Account(dict):
297
308
  if i - batch_size < 0:
298
309
  batch_size = i
299
310
  count = yield from self.get_account_history(
300
- index=i, limit=batch_size, order=-1, filter_by=filter_by, raw_output=raw_output,
311
+ index=i,
312
+ limit=batch_size,
313
+ order=-1,
314
+ filter_by=filter_by,
315
+ raw_output=raw_output,
301
316
  )
302
317
  i -= batch_size + 1
303
318
  op_count += count
viz/block.py CHANGED
@@ -1,4 +1,3 @@
1
- # -*- coding: utf-8 -*-
2
1
  from graphenecommon.block import Block as GrapheneBlock
3
2
  from graphenecommon.block import BlockHeader as GrapheneBlockHeader
4
3
 
viz/blockchain.py CHANGED
@@ -1,8 +1,7 @@
1
- # -*- coding: utf-8 -*-
2
1
  import hashlib
3
2
  import json
4
3
  import time
5
- from typing import Iterator, List, Optional, Union
4
+ from collections.abc import Iterator
6
5
 
7
6
  from graphenecommon.blockchain import Blockchain as GrapheneBlockchain
8
7
 
@@ -43,8 +42,8 @@ class Blockchain(GrapheneBlockchain):
43
42
 
44
43
  def stream_from(
45
44
  self,
46
- start_block: Optional[int] = None,
47
- end_block: Optional[int] = None,
45
+ start_block: int | None = None,
46
+ end_block: int | None = None,
48
47
  batch_operations: bool = False,
49
48
  full_blocks: bool = False,
50
49
  only_virtual_ops: bool = False,
@@ -109,9 +108,9 @@ class Blockchain(GrapheneBlockchain):
109
108
 
110
109
  def stream(
111
110
  self,
112
- filter_by: Optional[Union[str, List[str]]] = None,
113
- start_block: Optional[int] = None,
114
- end_block: Optional[int] = None,
111
+ filter_by: str | list[str] | None = None,
112
+ start_block: int | None = None,
113
+ end_block: int | None = None,
115
114
  raw_output: bool = False,
116
115
  ) -> Iterator[dict]:
117
116
  """
@@ -201,7 +200,6 @@ class Blockchain(GrapheneBlockchain):
201
200
  for op in self.stream_from(
202
201
  full_blocks=False, only_virtual_ops=only_virtual_ops, start_block=start_block, end_block=end_block
203
202
  ):
204
-
205
203
  if not filter_by or op["op"][0] in filter_by:
206
204
  if raw_output:
207
205
  yield op
viz/blockchainobject.py CHANGED
@@ -1,4 +1,3 @@
1
- # -*- coding: utf-8 -*-
2
1
  from graphenecommon.blockchainobject import BlockchainObject as GrapheneBlockchainObject
3
2
  from graphenecommon.blockchainobject import Object as GrapheneChainObject
4
3
 
viz/converter.py CHANGED
@@ -2,7 +2,7 @@ from .amount import Amount
2
2
  from .instance import shared_blockchain_instance
3
3
 
4
4
 
5
- class Converter(object):
5
+ class Converter:
6
6
  """
7
7
  Converter simplifies the handling of different metrics of the blockchain.
8
8
 
viz/exceptions.py CHANGED
@@ -1,4 +1,3 @@
1
- # -*- coding: utf-8 -*-
2
1
  class BaseException(Exception):
3
2
  """Base excepsion class."""
4
3
 
viz/instance.py CHANGED
@@ -1,4 +1,3 @@
1
- # -*- coding: utf-8 -*-
2
1
  from graphenecommon.instance import AbstractBlockchainInstanceProvider
3
2
 
4
3
 
viz/memo.py CHANGED
@@ -1,4 +1,3 @@
1
- # -*- coding: utf-8 -*-
2
1
  import secrets
3
2
 
4
3
  from graphenecommon.exceptions import KeyNotFound, MissingKeyError
@@ -76,9 +75,9 @@ class Memo(GrapheneMemo):
76
75
  "Memo private key {} for {} could not be found".format(
77
76
  self.from_account["memo_key"], self.from_account["name"]
78
77
  )
79
- )
78
+ ) from None
80
79
  if not memo_wif:
81
- raise MissingKeyError("Memo key for %s missing!" % self.from_account["name"])
80
+ raise MissingKeyError("Memo key for {} missing!".format(self.from_account["name"]))
82
81
 
83
82
  if not hasattr(self, "chain_prefix"):
84
83
  self.chain_prefix = self.blockchain.prefix
@@ -105,10 +104,10 @@ class Memo(GrapheneMemo):
105
104
  keys = memo.involved_keys(message)
106
105
  wif = None
107
106
  for key in keys:
108
- try:
107
+ try:
109
108
  wif = self.blockchain.wallet.getPrivateKeyForPublicKey(str(key))
110
109
  break
111
- except:
110
+ except Exception:
112
111
  continue
113
112
  if not wif:
114
113
  raise MissingKeyError("None of the required memo keys are installed!")
viz/storage.py CHANGED
@@ -1,12 +1,6 @@
1
- # -*- coding: utf-8 -*-
2
1
  from graphenestorage import (
3
- InRamConfigurationStore,
4
- InRamEncryptedKeyStore,
5
- InRamPlainKeyStore,
6
2
  SqliteConfigurationStore,
7
3
  SqliteEncryptedKeyStore,
8
- SQLiteFile,
9
- SqlitePlainKeyStore,
10
4
  )
11
5
 
12
6
  from vizbase.chains import DEFAULT_PREFIX
viz/transactionbuilder.py CHANGED
@@ -1,4 +1,3 @@
1
- # -*- coding: utf-8 -*-
2
1
  # We don't have own Asset class because it is unneeded
3
2
  import struct
4
3
  from binascii import unhexlify
@@ -39,9 +38,9 @@ class ProposalBuilder(GrapheneProposalBuilder):
39
38
  self, author, title, memo, proposal_expiration=None, proposal_review=None, parent=None, *args, **kwargs
40
39
  ):
41
40
  self.define_classes()
42
- assert self.operation_class
43
- assert self.operations
44
- assert self.account_class
41
+ assert self.operation_class is not None
42
+ assert self.operations is not None
43
+ assert self.account_class is not None
45
44
 
46
45
  self.proposal_expiration = proposal_expiration or 2 * 24 * 60 * 60
47
46
  self.proposal_review = proposal_review
@@ -62,12 +61,12 @@ class ProposalBuilder(GrapheneProposalBuilder):
62
61
  return
63
62
  ops = [self.operations.Op_wrapper(op=o) for o in list(self.ops)]
64
63
  data = {
65
- 'author': self.proposer,
66
- 'title': self.title,
67
- 'memo': self.memo,
68
- 'proposed_operations': [o.json() for o in ops],
69
- 'expiration_time': formatTimeFromNow(self.proposal_expiration),
70
- 'extensions': [],
64
+ "author": self.proposer,
65
+ "title": self.title,
66
+ "memo": self.memo,
67
+ "proposed_operations": [o.json() for o in ops],
68
+ "expiration_time": formatTimeFromNow(self.proposal_expiration),
69
+ "extensions": [],
71
70
  }
72
71
  if self.proposal_review:
73
72
  data.update({"review_period_time": formatTimeFromNow(self.proposal_review)})
@@ -123,7 +122,7 @@ class TransactionBuilder(GrapheneTransactionBuilder):
123
122
  else:
124
123
  accountObj = self.account_class(account, blockchain_instance=self.blockchain) # noqa: N806
125
124
  # TODO: method overriden because of _authority
126
- field = "{}_authority".format(permission)
125
+ field = f"{permission}_authority"
127
126
  required_treshold = accountObj[field]["weight_threshold"]
128
127
  keys = self._fetchkeys(accountObj, field, required_treshold=required_treshold)
129
128
  # If we couldn't find an active key, let's try overwrite it
viz/utils.py CHANGED
@@ -1,13 +1,12 @@
1
- # -*- coding: utf-8 -*-
2
1
  import json
3
- from datetime import datetime
2
+ from datetime import datetime, timezone
4
3
 
5
4
  from toolz import assoc, update_in
6
5
 
7
6
 
8
7
  def json_expand(json_op, key_name="json"):
9
8
  """Convert a string json object to Python dict in an op."""
10
- if type(json_op) == dict and key_name in json_op and json_op[key_name]:
9
+ if isinstance(json_op, dict) and key_name in json_op and json_op[key_name]:
11
10
  try:
12
11
  return update_in(json_op, [key_name], json.loads)
13
12
  except json.JSONDecodeError:
@@ -20,12 +19,14 @@ def time_elapsed(event_time):
20
19
  """Takes a string time from blockchain event, and returns a time delta from now."""
21
20
  if isinstance(event_time, str):
22
21
  event_time = parse_time(event_time)
23
- return datetime.utcnow() - event_time
22
+ if event_time.tzinfo is None:
23
+ event_time = event_time.replace(tzinfo=timezone.utc)
24
+ return datetime.now(timezone.utc) - event_time
24
25
 
25
26
 
26
27
  def parse_time(event_time):
27
28
  """Take a string representation of time from the blockchain, and parse it into datetime object."""
28
- return datetime.strptime(event_time, '%Y-%m-%dT%H:%M:%S')
29
+ return datetime.strptime(event_time, "%Y-%m-%dT%H:%M:%S")
29
30
 
30
31
 
31
32
  def time_diff(time1, time2):