eth-portfolio-temp 0.2.12__cp313-cp313-win32.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.

Potentially problematic release.


This version of eth-portfolio-temp might be problematic. Click here for more details.

Files changed (83) hide show
  1. eth_portfolio/__init__.py +25 -0
  2. eth_portfolio/_argspec.cp313-win32.pyd +0 -0
  3. eth_portfolio/_argspec.py +42 -0
  4. eth_portfolio/_cache.py +121 -0
  5. eth_portfolio/_config.cp313-win32.pyd +0 -0
  6. eth_portfolio/_config.py +4 -0
  7. eth_portfolio/_db/__init__.py +0 -0
  8. eth_portfolio/_db/decorators.py +147 -0
  9. eth_portfolio/_db/entities.py +311 -0
  10. eth_portfolio/_db/utils.py +604 -0
  11. eth_portfolio/_decimal.py +156 -0
  12. eth_portfolio/_decorators.py +84 -0
  13. eth_portfolio/_exceptions.py +67 -0
  14. eth_portfolio/_ledgers/__init__.py +0 -0
  15. eth_portfolio/_ledgers/address.py +938 -0
  16. eth_portfolio/_ledgers/portfolio.py +327 -0
  17. eth_portfolio/_loaders/__init__.py +33 -0
  18. eth_portfolio/_loaders/_nonce.cp313-win32.pyd +0 -0
  19. eth_portfolio/_loaders/_nonce.py +196 -0
  20. eth_portfolio/_loaders/balances.cp313-win32.pyd +0 -0
  21. eth_portfolio/_loaders/balances.py +94 -0
  22. eth_portfolio/_loaders/token_transfer.py +217 -0
  23. eth_portfolio/_loaders/transaction.py +240 -0
  24. eth_portfolio/_loaders/utils.cp313-win32.pyd +0 -0
  25. eth_portfolio/_loaders/utils.py +68 -0
  26. eth_portfolio/_shitcoins.cp313-win32.pyd +0 -0
  27. eth_portfolio/_shitcoins.py +329 -0
  28. eth_portfolio/_stableish.cp313-win32.pyd +0 -0
  29. eth_portfolio/_stableish.py +42 -0
  30. eth_portfolio/_submodules.py +73 -0
  31. eth_portfolio/_utils.py +225 -0
  32. eth_portfolio/_ydb/__init__.py +0 -0
  33. eth_portfolio/_ydb/token_transfers.py +145 -0
  34. eth_portfolio/address.py +397 -0
  35. eth_portfolio/buckets.py +194 -0
  36. eth_portfolio/constants.cp313-win32.pyd +0 -0
  37. eth_portfolio/constants.py +82 -0
  38. eth_portfolio/portfolio.py +661 -0
  39. eth_portfolio/protocols/__init__.py +67 -0
  40. eth_portfolio/protocols/_base.py +108 -0
  41. eth_portfolio/protocols/convex.py +17 -0
  42. eth_portfolio/protocols/dsr.py +51 -0
  43. eth_portfolio/protocols/lending/README.md +6 -0
  44. eth_portfolio/protocols/lending/__init__.py +50 -0
  45. eth_portfolio/protocols/lending/_base.py +57 -0
  46. eth_portfolio/protocols/lending/compound.py +187 -0
  47. eth_portfolio/protocols/lending/liquity.py +110 -0
  48. eth_portfolio/protocols/lending/maker.py +104 -0
  49. eth_portfolio/protocols/lending/unit.py +46 -0
  50. eth_portfolio/protocols/liquity.py +16 -0
  51. eth_portfolio/py.typed +0 -0
  52. eth_portfolio/structs/__init__.py +43 -0
  53. eth_portfolio/structs/modified.py +69 -0
  54. eth_portfolio/structs/structs.py +637 -0
  55. eth_portfolio/typing/__init__.py +1447 -0
  56. eth_portfolio/typing/balance/single.py +176 -0
  57. eth_portfolio__mypyc.cp313-win32.pyd +0 -0
  58. eth_portfolio_scripts/__init__.py +20 -0
  59. eth_portfolio_scripts/_args.py +26 -0
  60. eth_portfolio_scripts/_logging.py +15 -0
  61. eth_portfolio_scripts/_portfolio.py +194 -0
  62. eth_portfolio_scripts/_utils.py +106 -0
  63. eth_portfolio_scripts/balances.cp313-win32.pyd +0 -0
  64. eth_portfolio_scripts/balances.py +52 -0
  65. eth_portfolio_scripts/docker/.grafana/dashboards/Portfolio/Balances.json +1962 -0
  66. eth_portfolio_scripts/docker/.grafana/dashboards/dashboards.yaml +10 -0
  67. eth_portfolio_scripts/docker/.grafana/datasources/datasources.yml +11 -0
  68. eth_portfolio_scripts/docker/__init__.cp313-win32.pyd +0 -0
  69. eth_portfolio_scripts/docker/__init__.py +16 -0
  70. eth_portfolio_scripts/docker/check.cp313-win32.pyd +0 -0
  71. eth_portfolio_scripts/docker/check.py +56 -0
  72. eth_portfolio_scripts/docker/docker-compose.yaml +61 -0
  73. eth_portfolio_scripts/docker/docker_compose.cp313-win32.pyd +0 -0
  74. eth_portfolio_scripts/docker/docker_compose.py +78 -0
  75. eth_portfolio_scripts/main.py +119 -0
  76. eth_portfolio_scripts/py.typed +1 -0
  77. eth_portfolio_scripts/victoria/__init__.py +73 -0
  78. eth_portfolio_scripts/victoria/types.py +38 -0
  79. eth_portfolio_temp-0.2.12.dist-info/METADATA +25 -0
  80. eth_portfolio_temp-0.2.12.dist-info/RECORD +83 -0
  81. eth_portfolio_temp-0.2.12.dist-info/WHEEL +5 -0
  82. eth_portfolio_temp-0.2.12.dist-info/entry_points.txt +2 -0
  83. eth_portfolio_temp-0.2.12.dist-info/top_level.txt +3 -0
@@ -0,0 +1,1447 @@
1
+ """
2
+ This module defines a set of classes to represent and manipulate various levels of balance structures
3
+ within an Ethereum portfolio. The focus of these classes is on reading, aggregating, and summarizing
4
+ balances, including the value in both tokens and their equivalent in USD.
5
+
6
+ The main classes and their purposes are as follows:
7
+
8
+ - :class:`~eth_portfolio.typing.Balance`: Represents the balance of a single token, including its token amount and equivalent USD value.
9
+ - :class:`~eth_portfolio.typing.TokenBalances`: Manages a collection of :class:`~eth_portfolio.typing.Balance` objects for multiple tokens, providing operations
10
+ such as summing balances across tokens.
11
+ - :class:`~eth_portfolio.typing.RemoteTokenBalances`: Extends :class:`~eth_portfolio.typing.TokenBalances` to manage balances across different protocols, enabling
12
+ aggregation and analysis of balances by protocol.
13
+ - :class:`~eth_portfolio.typing.WalletBalances`: Organizes token balances into categories such as assets, debts, and external balances
14
+ for a single wallet. It combines :class:`~eth_portfolio.typing.TokenBalances` and :class:`~eth_portfolio.typing.RemoteTokenBalances` to provide a complete view
15
+ of a wallet's balances.
16
+ - :class:`~eth_portfolio.typing.PortfolioBalances`: Aggregates :class:`~eth_portfolio.typing.WalletBalances` for multiple wallets, providing operations to sum
17
+ balances across an entire portfolio.
18
+ - :class:`~eth_portfolio.typing.WalletBalancesRaw`: Similar to :class:`~eth_portfolio.typing.WalletBalances`, but with a key structure optimized for accessing
19
+ balances directly by wallet and token.
20
+ - :class:`~eth_portfolio.typing.PortfolioBalancesByCategory`: Provides an inverted view of :class:`~eth_portfolio.typing.PortfolioBalances`, allowing access
21
+ by category first, then by wallet and token.
22
+
23
+ These classes are designed for efficient parsing, manipulation, and summarization of portfolio data,
24
+ without managing or altering any underlying assets.
25
+ """
26
+
27
+ from functools import cached_property
28
+ from typing import (
29
+ Any,
30
+ Callable,
31
+ DefaultDict,
32
+ Dict,
33
+ Final,
34
+ Iterable,
35
+ List,
36
+ Literal,
37
+ Optional,
38
+ Tuple,
39
+ TypedDict,
40
+ TypeVar,
41
+ Union,
42
+ final,
43
+ )
44
+
45
+ from checksum_dict import DefaultChecksumDict
46
+ from eth_typing import BlockNumber, HexAddress
47
+ from pandas import DataFrame, concat
48
+ from typing_extensions import ParamSpec, Self
49
+ from y import Contract, ERC20
50
+ from y.datatypes import Address
51
+
52
+ from eth_portfolio._decimal import Decimal
53
+ from eth_portfolio.typing.balance.single import Balance
54
+
55
+
56
+ _T = TypeVar("_T")
57
+ _I = TypeVar("_I")
58
+ _P = ParamSpec("_P")
59
+
60
+ Fn = Callable[_P, _T]
61
+
62
+
63
+ ProtocolLabel = str
64
+
65
+ Addresses = Union[Address, Iterable[Address]]
66
+ TokenAddress = TypeVar("TokenAddress", bound=Address)
67
+
68
+
69
+ class _SummableNonNumericMixin:
70
+ """
71
+ Mixin class for non-numeric summable objects.
72
+
73
+ This class provides an interface for objects that can be used with `sum` but are not necessarily numeric.
74
+ """
75
+
76
+ def __add__(self, other: Self) -> Self:
77
+ """
78
+ Abstract method for adding two objects of the same type.
79
+
80
+ Args:
81
+ other: Another object of the same type.
82
+
83
+ Raises:
84
+ NotImplementedError: If no `__add__` method was defined on the subclass.
85
+
86
+ Returns:
87
+ A new object representing the sum.
88
+ """
89
+ raise NotImplementedError
90
+
91
+ def __radd__(self, other: Union[Self, Literal[0]]) -> Self:
92
+ """
93
+ Supports the addition operation from the right side to enable use of `sum`.
94
+
95
+ Args:
96
+ other: Another object of the same type or zero.
97
+
98
+ Returns:
99
+ A new object representing the sum.
100
+
101
+ Example:
102
+ >>> class Summable(_SummableNonNumeric):
103
+ ... def __init__(self, value: int):
104
+ ... self.value = value
105
+ ... def __add__(self, other):
106
+ ... return Summable(self.value + other.value)
107
+ ... def __radd__(self, other):
108
+ ... return self.__add__(other)
109
+ >>> a = Summable(10)
110
+ >>> b = Summable(20)
111
+ >>> sum_result = a + b
112
+ >>> sum_result.value
113
+ 30
114
+ """
115
+ return self if other == 0 else self.__add__(other) # type: ignore
116
+
117
+
118
+ _TBSeed = Union[Dict[Address, Balance], Iterable[Tuple[Address, Balance]]]
119
+
120
+
121
+ @final
122
+ class TokenBalances(DefaultChecksumDict[Balance], _SummableNonNumericMixin): # type: ignore [misc]
123
+ """
124
+ A specialized defaultdict subclass made for holding a mapping of ``token -> balance``.
125
+
126
+ Manages a collection of :class:`~eth_portfolio.typing.Balance` objects for multiple tokens, allowing for operations
127
+ such as summing balances across tokens.
128
+
129
+ The class uses token addresses as keys and :class:`~eth_portfolio.typing.Balance` objects as values. It supports
130
+ arithmetic operations like addition and subtraction of token balances.
131
+
132
+ Token addresses are checksummed automatically when adding items to the dict, and the default value for a token not present is an empty :class:`~eth_portfolio.typing.Balance` object.
133
+
134
+ Args:
135
+ seed: An initial seed of token balances, either as a dictionary or an iterable of tuples.
136
+
137
+ Example:
138
+ >>> token_balances = TokenBalances({'0x123': Balance(Decimal('100'), Decimal('2000'))})
139
+ >>> token_balances['0x123'].balance
140
+ Decimal('100')
141
+ """
142
+
143
+ def __init__(
144
+ self, seed: Optional[_TBSeed] = None, *, block: Optional[BlockNumber] = None
145
+ ) -> None:
146
+ super().__init__(Balance)
147
+ self.block: Final = block
148
+ if seed is None:
149
+ return
150
+ if isinstance(seed, dict):
151
+ seed = seed.items()
152
+ if not isinstance(seed, Iterable):
153
+ raise TypeError(f"{seed} is not a valid input for TokenBalances")
154
+ for token, balance in seed: # type: ignore [misc]
155
+ try:
156
+ self[token] += balance
157
+ except AttributeError:
158
+ if not isinstance(token, (ERC20, Contract)):
159
+ raise
160
+ self[token.address] += balance
161
+
162
+ def __getitem__(self, key: HexAddress) -> Balance:
163
+ return super().__getitem__(key) if key in self else Balance(token=key, block=self.block)
164
+
165
+ def __setitem__(self, key: HexAddress, value: Balance) -> None:
166
+ """
167
+ Sets the balance for a given token address.
168
+
169
+ Args:
170
+ key: The token address.
171
+ value: The balance to set for the token.
172
+
173
+ Raises:
174
+ TypeError: If the value is not a :class:`~eth_portfolio.typing.Balance` object.
175
+
176
+ Example:
177
+ >>> token_balances = TokenBalances()
178
+ >>> token_balances['0x123'] = Balance(Decimal('100'), Decimal('2000'))
179
+ >>> token_balances['0x123'].balance
180
+ Decimal('100')
181
+ """
182
+ if not isinstance(value, Balance):
183
+ raise TypeError(f"value must be a `Balance` object. You passed {value}") from None
184
+ return super().__setitem__(key, value)
185
+
186
+ @property
187
+ def dataframe(self) -> DataFrame:
188
+ """
189
+ Converts the token balances into a pandas DataFrame.
190
+
191
+ Returns:
192
+ A DataFrame representation of the token balances.
193
+ """
194
+ df = DataFrame(
195
+ {
196
+ token: {"balance": balance.balance, "usd_value": balance.usd_value}
197
+ for token, balance in dict.items(self)
198
+ }
199
+ ).T
200
+ df.reset_index(inplace=True)
201
+ df.rename(columns={"index": "token"}, inplace=True)
202
+ return df
203
+
204
+ def sum_usd(self) -> Decimal:
205
+ """
206
+ Sums the USD values of all token balances.
207
+
208
+ Returns:
209
+ The total USD value of all token balances.
210
+
211
+ Example:
212
+ >>> token_balances = TokenBalances({'0x123': Balance(Decimal('100'), Decimal('2000'))})
213
+ >>> total_usd = token_balances.sum_usd()
214
+ >>> total_usd
215
+ Decimal('2000')
216
+ """
217
+ return Decimal(sum(balance.usd for balance in dict.values(self)))
218
+
219
+ def __bool__(self) -> bool:
220
+ """
221
+ Evaluates the truth value of the :class:`~eth_portfolio.typing.TokenBalances` object.
222
+
223
+ Returns:
224
+ True if any token has a non-zero balance, otherwise False.
225
+
226
+ Example:
227
+ >>> token_balances = TokenBalances()
228
+ >>> bool(token_balances)
229
+ False
230
+ """
231
+ return any(dict.values(self))
232
+
233
+ def __repr__(self) -> str:
234
+ """
235
+ Returns a string representation of the :class:`~eth_portfolio.typing.TokenBalances` object.
236
+
237
+ Returns:
238
+ The string representation of the token balances.
239
+ """
240
+ return f"TokenBalances{dict(self)}"
241
+
242
+ def __add__(self, other: "TokenBalances") -> "TokenBalances":
243
+ """
244
+ Adds another :class:`~eth_portfolio.typing.TokenBalances` object to this one.
245
+
246
+ Args:
247
+ other: Another :class:`~eth_portfolio.typing.TokenBalances` object.
248
+
249
+ Returns:
250
+ A new :class:`~eth_portfolio.typing.TokenBalances` object with the combined balances.
251
+
252
+ Raises:
253
+ TypeError: If the other object is not a :class:`~eth_portfolio.typing.TokenBalances`.
254
+
255
+ Example:
256
+ >>> tb1 = TokenBalances({'0x123': Balance(Decimal('100'), Decimal('2000'))})
257
+ >>> tb2 = TokenBalances({'0x123': Balance(Decimal('50'), Decimal('1000'))})
258
+ >>> combined_tb = tb1 + tb2
259
+ >>> combined_tb['0x123'].balance
260
+ Decimal('150')
261
+ """
262
+ if not isinstance(other, TokenBalances):
263
+ raise TypeError(f"{other} is not a TokenBalances object")
264
+
265
+ block = self.block
266
+ if block != other.block:
267
+ raise ValueError(
268
+ f"These TokenBalances objects are not from the same block ({block} and {other.block})"
269
+ )
270
+
271
+ combined: TokenBalances = TokenBalances(block=block)
272
+ for token, balance in dict.items(self):
273
+ if balance:
274
+ DefaultChecksumDict._setitem_nochecksum(
275
+ combined,
276
+ token,
277
+ Balance(balance.balance, balance.usd_value, token=token, block=block),
278
+ )
279
+ for token, balance in dict.items(other):
280
+ if balance:
281
+ if token in combined:
282
+ DefaultChecksumDict._setitem_nochecksum(
283
+ combined, token, combined._getitem_nochecksum(token) + balance
284
+ )
285
+ else:
286
+ DefaultChecksumDict._setitem_nochecksum(
287
+ combined,
288
+ token,
289
+ Balance(balance.balance, balance.usd_value, token=token, block=block),
290
+ )
291
+ return combined
292
+
293
+ def __iadd__(self, other: "TokenBalances") -> "TokenBalances":
294
+ if not isinstance(other, TokenBalances):
295
+ raise TypeError(f"{other} is not a TokenBalances object")
296
+
297
+ block = self.block
298
+ if block != other.block:
299
+ raise ValueError(
300
+ f"These TokenBalances objects are not from the same block ({block} and {other.block})"
301
+ )
302
+
303
+ for token, balance in dict.items(other):
304
+ if not balance:
305
+ continue
306
+ if token in self:
307
+ DefaultChecksumDict._setitem_nochecksum(
308
+ self,
309
+ token,
310
+ self._getitem_nochecksum(token) + balance,
311
+ )
312
+ else:
313
+ balance = Balance(balance.balance, balance.usd_value, token=token, block=block)
314
+ DefaultChecksumDict._setitem_nochecksum(self, token, balance)
315
+ return self
316
+
317
+ def __sub__(self, other: "TokenBalances") -> "TokenBalances":
318
+ """
319
+ Subtracts another :class:`~eth_portfolio.typing.TokenBalances` object from this one.
320
+
321
+ Args:
322
+ other: Another :class:`~eth_portfolio.typing.TokenBalances` object.
323
+
324
+ Returns:
325
+ A new :class:`~eth_portfolio.typing.TokenBalances` object with the subtracted balances.
326
+
327
+ Raises:
328
+ TypeError: If the other object is not a :class:`~eth_portfolio.typing.TokenBalances`.
329
+
330
+ Example:
331
+ >>> tb1 = TokenBalances({'0x123': Balance(Decimal('100'), Decimal('2000'))})
332
+ >>> tb2 = TokenBalances({'0x123': Balance(Decimal('50'), Decimal('1000'))})
333
+ >>> result_tb = tb1 - tb2
334
+ >>> result_tb['0x123'].balance
335
+ Decimal('50')
336
+ """
337
+ if not isinstance(other, TokenBalances):
338
+ raise TypeError(f"{other} is not a TokenBalances object")
339
+ if self.block != other.block:
340
+ raise ValueError(
341
+ f"These TokenBalances objects are not from the same block ({self.block} and {other.block})"
342
+ )
343
+ # NOTE We need a new object to avoid mutating the inputs
344
+ subtracted: TokenBalances = TokenBalances(self, block=self.block)
345
+ for token, balance in dict.items(other):
346
+ subtracted[token] -= balance
347
+ for token, balance in dict(subtracted).items():
348
+ if not balance:
349
+ del subtracted[token]
350
+ return subtracted
351
+
352
+ __slots__ = ("block",)
353
+
354
+
355
+ _RTBSeed = Dict[ProtocolLabel, TokenBalances]
356
+
357
+
358
+ @final
359
+ class RemoteTokenBalances(DefaultDict[ProtocolLabel, TokenBalances], _SummableNonNumericMixin):
360
+ """
361
+ Manages token balances across different protocols, extending the :class:`~eth_portfolio.typing.TokenBalances` functionality
362
+ to multiple protocols.
363
+
364
+ The class uses protocol labels as keys and :class:`~eth_portfolio.typing.TokenBalances` objects as values.
365
+
366
+ Args:
367
+ seed: An initial seed of remote token balances, either as a dictionary
368
+ or an iterable of tuples.
369
+
370
+ Example:
371
+ >>> remote_balances = RemoteTokenBalances({'protocol1': TokenBalances({'0x123': Balance(Decimal('100'), Decimal('2000'))})})
372
+ >>> remote_balances['protocol1']['0x123'].balance
373
+ Decimal('100')
374
+ """
375
+
376
+ __slots__ = ("block",)
377
+
378
+ def __init__(
379
+ self, seed: Optional[_RTBSeed] = None, *, block: Optional[BlockNumber] = None
380
+ ) -> None:
381
+ super().__init__(lambda: TokenBalances(block=block))
382
+ self.block: Final = block
383
+ if seed is None:
384
+ return
385
+ if isinstance(seed, dict):
386
+ seed = seed.items() # type: ignore [assignment]
387
+ if not isinstance(seed, Iterable):
388
+ raise TypeError(f"{seed} is not a valid input for TokenBalances")
389
+ for remote, token_balances in seed: # type: ignore [misc]
390
+ if self.block != token_balances.block:
391
+ raise ValueError(
392
+ f"These objects are not from the same block ({self.block} and {token_balances.block})"
393
+ )
394
+ self[remote] += token_balances # type: ignore [has-type]
395
+
396
+ def __setitem__(self, protocol: str, value: TokenBalances) -> None:
397
+ """
398
+ Sets the token balances for a given protocol.
399
+
400
+ Args:
401
+ key: The protocol label.
402
+ value: The token balances to set for the protocol.
403
+
404
+ Raises:
405
+ TypeError: If the value is not a :class:`~eth_portfolio.typing.TokenBalances` object.
406
+
407
+ Example:
408
+ >>> remote_balances = RemoteTokenBalances()
409
+ >>> remote_balances['protocol1'] = TokenBalances({'0x123': Balance(Decimal('100'), Decimal('2000'))})
410
+ >>> remote_balances['protocol1']['0x123'].balance
411
+ Decimal('100')
412
+ """
413
+ if not isinstance(value, TokenBalances):
414
+ raise TypeError(f"value must be a `TokenBalances` object. You passed {value}") from None
415
+ return super().__setitem__(protocol, value)
416
+
417
+ @property
418
+ def dataframe(self) -> DataFrame:
419
+ """
420
+ Converts the remote token balances into a pandas DataFrame.
421
+
422
+ Returns:
423
+ A DataFrame representation of the remote token balances.
424
+ """
425
+ dfs: List[DataFrame] = []
426
+ for protocol, balances in dict.items(self):
427
+ df = balances.dataframe
428
+ df["protocol"] = protocol
429
+ dfs.append(df)
430
+ return concat(dfs).reset_index(drop=True) if dfs else DataFrame()
431
+
432
+ def sum_usd(self) -> Decimal:
433
+ """
434
+ Sums the USD values of all token balances across all protocols.
435
+
436
+ Returns:
437
+ The total USD value of all remote token balances.
438
+
439
+ Example:
440
+ >>> remote_balances = RemoteTokenBalances({'protocol1': TokenBalances({'0x123': Balance(Decimal('100'), Decimal('2000'))})})
441
+ >>> total_usd = remote_balances.sum_usd()
442
+ >>> total_usd
443
+ Decimal('2000')
444
+ """
445
+ return Decimal(sum(balance.sum_usd() for balance in dict.values(self)))
446
+
447
+ def __bool__(self) -> bool:
448
+ """
449
+ Evaluates the truth value of the :class:`~eth_portfolio.typing.RemoteTokenBalances` object.
450
+
451
+ Returns:
452
+ True if any protocol has a non-zero balance, otherwise False.
453
+
454
+ Example:
455
+ >>> remote_balances = RemoteTokenBalances()
456
+ >>> bool(remote_balances)
457
+ False
458
+ """
459
+ return any(dict.values(self))
460
+
461
+ def __repr__(self) -> str:
462
+ """
463
+ Returns a string representation of the :class:`~eth_portfolio.typing.RemoteTokenBalances` object.
464
+
465
+ Returns:
466
+ The string representation of the remote token balances.
467
+ """
468
+ return f"RemoteTokenBalances{dict(self)}"
469
+
470
+ def __add__(self, other: "RemoteTokenBalances") -> "RemoteTokenBalances":
471
+ """
472
+ Adds another :class:`~eth_portfolio.typing.RemoteTokenBalances` object to this one.
473
+
474
+ Args:
475
+ other: Another :class:`~eth_portfolio.typing.RemoteTokenBalances` object.
476
+
477
+ Returns:
478
+ A new :class:`~eth_portfolio.typing.RemoteTokenBalances` object with the combined balances.
479
+
480
+ Raises:
481
+ TypeError: If the other object is not a :class:`~eth_portfolio.typing.RemoteTokenBalances`.
482
+
483
+ Example:
484
+ >>> rb1 = RemoteTokenBalances({'protocol1': TokenBalances({'0x123': Balance(Decimal('100'), Decimal('2000'))})})
485
+ >>> rb2 = RemoteTokenBalances({'protocol1': TokenBalances({'0x123': Balance(Decimal('50'), Decimal('1000'))})})
486
+ >>> combined_rb = rb1 + rb2
487
+ >>> combined_rb['protocol1']['0x123'].balance
488
+ Decimal('150')
489
+ """
490
+ if not isinstance(other, RemoteTokenBalances):
491
+ raise TypeError(f"{other} is not a RemoteTokenBalances object")
492
+
493
+ block = self.block
494
+ if block != other.block:
495
+ raise ValueError(
496
+ f"These RemoteTokenBalances objects are not from the same block ({block} and {other.block})"
497
+ )
498
+
499
+ combined: RemoteTokenBalances = RemoteTokenBalances(block=block)
500
+ for protocol, token_balances in dict.items(self):
501
+ if token_balances:
502
+ combined[protocol] += token_balances
503
+ for protocol, token_balances in dict.items(other):
504
+ if token_balances:
505
+ combined[protocol] += token_balances
506
+ return combined
507
+
508
+ def __iadd__(self, other: "RemoteTokenBalances") -> "RemoteTokenBalances":
509
+ if not isinstance(other, RemoteTokenBalances):
510
+ raise TypeError(f"{other} is not a RemoteTokenBalances object")
511
+
512
+ if self.block != other.block:
513
+ raise ValueError(
514
+ f"These RemoteTokenBalances objects are not from the same block ({self.block} and {other.block})"
515
+ )
516
+
517
+ for protocol, token_balances in dict.items(other):
518
+ if token_balances:
519
+ self[protocol] += token_balances
520
+ return self
521
+
522
+ def __sub__(self, other: "RemoteTokenBalances") -> "RemoteTokenBalances":
523
+ """
524
+ Subtracts another :class:`~eth_portfolio.typing.RemoteTokenBalances` object from this one.
525
+
526
+ Args:
527
+ other: Another :class:`~eth_portfolio.typing.RemoteTokenBalances` object.
528
+
529
+ Returns:
530
+ A new :class:`~eth_portfolio.typing.RemoteTokenBalances` object with the subtracted balances.
531
+
532
+ Raises:
533
+ TypeError: If the other object is not a :class:`~eth_portfolio.typing.RemoteTokenBalances`.
534
+
535
+ Example:
536
+ >>> rb1 = RemoteTokenBalances({'protocol1': TokenBalances({'0x123': Balance(Decimal('100'), Decimal('2000'))})})
537
+ >>> rb2 = RemoteTokenBalances({'protocol1': TokenBalances({'0x123': Balance(Decimal('50'), Decimal('1000'))})})
538
+ >>> result_rb = rb1 - rb2
539
+ >>> result_rb['protocol1']['0x123'].balance
540
+ Decimal('50')
541
+ """
542
+ if not isinstance(other, RemoteTokenBalances):
543
+ raise TypeError(f"{other} is not a RemoteTokenBalances object")
544
+ if self.block != other.block:
545
+ raise ValueError(
546
+ f"These RemoteTokenBalances objects are not from the same block ({self.block} and {other.block})"
547
+ )
548
+ # NOTE We need a new object to avoid mutating the inputs
549
+ subtracted: RemoteTokenBalances = RemoteTokenBalances(self, block=self.block)
550
+ for protocol, token_balances in dict.items(other):
551
+ subtracted[protocol] -= token_balances
552
+ for protocol, token_balances in dict(subtracted).items():
553
+ if not token_balances:
554
+ del subtracted[protocol]
555
+ return subtracted
556
+
557
+
558
+ CategoryLabel = Literal["assets", "debt", "external"]
559
+
560
+ _WalletBalancesTD = TypedDict(
561
+ "_WalletBalancesTD",
562
+ {
563
+ "assets": TokenBalances,
564
+ "debt": TokenBalances,
565
+ "external": RemoteTokenBalances,
566
+ },
567
+ )
568
+
569
+ _WBSeed = Union[_WalletBalancesTD, Iterable[Tuple[CategoryLabel, TokenBalances]]]
570
+
571
+
572
+ @final
573
+ class WalletBalances(
574
+ Dict[CategoryLabel, Union[TokenBalances, RemoteTokenBalances]], _SummableNonNumericMixin
575
+ ):
576
+ """
577
+ Organizes token balances into categories such as assets, debts, and external balances for a single wallet.
578
+
579
+ The class uses categories as keys (`assets`, `debt`, `external`) and :class:`~eth_portfolio.typing.TokenBalances` or :class:`~eth_portfolio.typing.RemoteTokenBalances`
580
+ objects as values.
581
+
582
+ Args:
583
+ seed: An initial seed of wallet balances, either as a dictionary or an iterable of tuples.
584
+
585
+ Example:
586
+ >>> wallet_balances = WalletBalances({'assets': TokenBalances({'0x123': Balance(Decimal('100'), Decimal('2000'))})})
587
+ >>> wallet_balances['assets']['0x123'].balance
588
+ Decimal('100')
589
+ """
590
+
591
+ def __init__(
592
+ self,
593
+ seed: Optional[Union["WalletBalances", _WBSeed]] = None,
594
+ *,
595
+ block: Optional[BlockNumber] = None,
596
+ ) -> None:
597
+ self.block: Final = block
598
+ self._keys = "assets", "debt", "external"
599
+ self["assets"] = TokenBalances(block=block)
600
+ self["debt"] = RemoteTokenBalances(block=block)
601
+ self["external"] = RemoteTokenBalances(block=block)
602
+
603
+ if seed is None:
604
+ return
605
+ if isinstance(seed, dict):
606
+ seed = seed.items() # type: ignore
607
+ if not isinstance(seed, Iterable):
608
+ raise TypeError(f"{seed} is not a valid input for WalletBalances")
609
+ for key, balances in seed: # type: ignore
610
+ if self.block != balances.block:
611
+ raise ValueError(
612
+ f"These objects are not from the same block ({self.block} and {balances.block})"
613
+ )
614
+ self.__validateitem(key, balances)
615
+ self[key] += balances # type: ignore [operator]
616
+
617
+ @property
618
+ def assets(self) -> TokenBalances:
619
+ """
620
+ Returns the assets held by the wallet.
621
+
622
+ Returns:
623
+ :class:`~eth_portfolio.typing.TokenBalances`: The :class:`~eth_portfolio.typing.TokenBalances` object representing the wallet's assets.
624
+ """
625
+ return self["assets"] # type: ignore
626
+
627
+ @property
628
+ def debt(self) -> RemoteTokenBalances:
629
+ """
630
+ Returns the debts associated with the wallet.
631
+
632
+ Returns:
633
+ :class:`~eth_portfolio.typing.RemoteTokenBalances`: The :class:`~eth_portfolio.typing.RemoteTokenBalances` object representing the wallet's debts.
634
+ """
635
+ return self["debt"]
636
+
637
+ @property
638
+ def external(self) -> RemoteTokenBalances:
639
+ """
640
+ Returns the external balances associated with the wallet.
641
+
642
+ Returns:
643
+ :class:`~eth_portfolio.typing.RemoteTokenBalances`: The :class:`~eth_portfolio.typing.RemoteTokenBalances` object representing the wallet's external balances.
644
+ """
645
+ return self["external"]
646
+
647
+ @property
648
+ def dataframe(self) -> DataFrame:
649
+ """
650
+ Converts the wallet balances into a pandas DataFrame.
651
+
652
+ Returns:
653
+ A DataFrame representation of the wallet balances.
654
+ """
655
+ dfs: List[DataFrame] = []
656
+ for category, category_bals in dict.items(self):
657
+ df = category_bals.dataframe
658
+ df["category"] = category
659
+ dfs.append(df)
660
+ return concat(dfs).reset_index(drop=True) if dfs else DataFrame()
661
+
662
+ def sum_usd(self) -> Decimal:
663
+ """
664
+ Sums the USD values of the wallet's assets, debts, and external balances.
665
+
666
+ Returns:
667
+ The total USD value of the wallet's net assets (assets - debt + external).
668
+
669
+ Example:
670
+ >>> wallet_balances = WalletBalances({'assets': TokenBalances({'0x123': Balance(Decimal('100'), Decimal('2000'))})})
671
+ >>> total_usd = wallet_balances.sum_usd()
672
+ >>> total_usd
673
+ Decimal('2000')
674
+ """
675
+ return self.assets.sum_usd() - self.debt.sum_usd() + self.external.sum_usd()
676
+
677
+ def __bool__(self) -> bool:
678
+ """
679
+ Evaluates the truth value of the :class:`~eth_portfolio.typing.WalletBalances` object.
680
+
681
+ Returns:
682
+ True if any category has a non-zero balance, otherwise False.
683
+
684
+ Example:
685
+ >>> wallet_balances = WalletBalances()
686
+ >>> bool(wallet_balances)
687
+ False
688
+ """
689
+ return any(dict.values(self))
690
+
691
+ def __repr__(self) -> str:
692
+ """
693
+ Returns a string representation of the :class:`~eth_portfolio.typing.WalletBalances` object.
694
+
695
+ Returns:
696
+ The string representation of the wallet balances.
697
+ """
698
+ return f"WalletBalances {dict(self)}"
699
+
700
+ def __add__(self, other: "WalletBalances") -> "WalletBalances":
701
+ """
702
+ Adds another :class:`~eth_portfolio.typing.WalletBalances` object to this one.
703
+
704
+ Args:
705
+ other: Another :class:`~eth_portfolio.typing.WalletBalances` object.
706
+
707
+ Returns:
708
+ A new :class:`~eth_portfolio.typing.WalletBalances` object with the combined balances.
709
+
710
+ Raises:
711
+ TypeError: If the other object is not a :class:`~eth_portfolio.typing.WalletBalances`.
712
+
713
+ Example:
714
+ >>> wb1 = WalletBalances({'assets': TokenBalances({'0x123': Balance(Decimal('100'), Decimal('2000'))})})
715
+ >>> wb2 = WalletBalances({'assets': TokenBalances({'0x123': Balance(Decimal('50'), Decimal('1000'))})})
716
+ >>> combined_wb = wb1 + wb2
717
+ >>> combined_wb['assets']['0x123'].balance
718
+ Decimal('150')
719
+ """
720
+ if not isinstance(other, WalletBalances):
721
+ raise TypeError(f"{other} is not a WalletBalances object")
722
+
723
+ block = self.block
724
+ if block != other.block:
725
+ raise ValueError(
726
+ f"These WalletBalances objects are not from the same block ({block} and {other.block})"
727
+ )
728
+
729
+ combined: WalletBalances = WalletBalances(block=block)
730
+ for category, balances in dict.items(self):
731
+ if balances:
732
+ combined[category] += balances # type: ignore [operator]
733
+ for category, balances in dict.items(other):
734
+ if balances:
735
+ combined[category] += balances # type: ignore [operator]
736
+ return combined
737
+
738
+ def __iadd__(self, other: "WalletBalances") -> "WalletBalances":
739
+ if not isinstance(other, WalletBalances):
740
+ raise TypeError(f"{other} is not a WalletBalances object")
741
+
742
+ if self.block != other.block:
743
+ raise ValueError(
744
+ f"These WalletBalances objects are not from the same block ({self.block} and {other.block})"
745
+ )
746
+
747
+ for category, balances in dict.items(other):
748
+ if balances:
749
+ self[category] += balances # type: ignore [operator]
750
+ return self
751
+
752
+ def __sub__(self, other: "WalletBalances") -> "WalletBalances":
753
+ """
754
+ Subtracts another :class:`~eth_portfolio.typing.WalletBalances` object from this one.
755
+
756
+ Args:
757
+ other: Another :class:`~eth_portfolio.typing.WalletBalances` object.
758
+
759
+ Returns:
760
+ A new :class:`~eth_portfolio.typing.WalletBalances` object with the subtracted balances.
761
+
762
+ Raises:
763
+ TypeError: If the other object is not a :class:`~eth_portfolio.typing.WalletBalances`.
764
+
765
+ Example:
766
+ >>> wb1 = WalletBalances({'assets': TokenBalances({'0x123': Balance(Decimal('100'), Decimal('2000'))})})
767
+ >>> wb2 = WalletBalances({'assets': TokenBalances({'0x123': Balance(Decimal('50'), Decimal('1000'))})})
768
+ >>> result_wb = wb1 - wb2
769
+ >>> result_wb['assets']['0x123'].balance
770
+ Decimal('50')
771
+ """
772
+ if not isinstance(other, WalletBalances):
773
+ raise TypeError(f"{other} is not a WalletBalances object")
774
+ if self.block != other.block:
775
+ raise ValueError(
776
+ f"These WalletBalances objects are not from the same block ({self.block} and {other.block})"
777
+ )
778
+ # We need a new object to avoid mutating the inputs
779
+ subtracted: WalletBalances = WalletBalances(self, block=self.block)
780
+ for category, balances in dict.items(other):
781
+ subtracted[category] -= balances # type: ignore
782
+ for category, balances in dict(subtracted).items():
783
+ if not balances:
784
+ del subtracted[category]
785
+ return subtracted
786
+
787
+ def __getitem__(self, key: CategoryLabel) -> Union[TokenBalances, RemoteTokenBalances]:
788
+ """
789
+ Retrieves the balance associated with the given category key.
790
+
791
+ Args:
792
+ key: The category label (`assets`, `debt`, or `external`).
793
+
794
+ Returns:
795
+ The balances associated with the category.
796
+
797
+ Raises:
798
+ KeyError: If the key is not a valid category.
799
+
800
+ Example:
801
+ >>> wallet_balances = WalletBalances({'assets': TokenBalances({'0x123': Balance(Decimal('100'), Decimal('2000'))})})
802
+ >>> assets_balances = wallet_balances['assets']
803
+ >>> assets_balances['0x123'].balance
804
+ Decimal('100')
805
+ """
806
+ self.__validatekey(key)
807
+ return super().__getitem__(key)
808
+
809
+ def __setitem__(
810
+ self, key: CategoryLabel, value: Union[TokenBalances, RemoteTokenBalances]
811
+ ) -> None:
812
+ """
813
+ Sets the balance associated with the given category key.
814
+
815
+ Args:
816
+ key: The category label (`assets`, `debt`, or `external`).
817
+ value: The balance to associate with the category.
818
+
819
+ Raises:
820
+ KeyError: If the key is not a valid category.
821
+ TypeError: If the value is not a valid balance type for the category.
822
+
823
+ Example:
824
+ >>> wallet_balances = WalletBalances()
825
+ >>> wallet_balances['assets'] = TokenBalances({'0x123': Balance(Decimal('100'), Decimal('2000'))})
826
+ >>> wallet_balances['assets']['0x123'].balance
827
+ Decimal('100')
828
+ """
829
+ self.__validateitem(key, value)
830
+ return super().__setitem__(key, value)
831
+
832
+ def __validatekey(self, key: CategoryLabel) -> None:
833
+ """
834
+ Validates that the given key is a valid category.
835
+
836
+ Valid keys: "assets", "debt", "external"
837
+
838
+ Args:
839
+ key: The category label to validate.
840
+
841
+ Raises:
842
+ KeyError: If the key is not a valid category.
843
+ """
844
+ if key not in self._keys:
845
+ raise KeyError(
846
+ f"{key} is not a valid key for WalletBalances. Valid keys are: {self._keys}"
847
+ )
848
+
849
+ def __validateitem(self, key: CategoryLabel, item: Any) -> None:
850
+ """
851
+ Validates that the given item is a valid balance type for the category.
852
+
853
+ Args:
854
+ key: The category label.
855
+ item: The balance item to validate.
856
+
857
+ Raises:
858
+ KeyError: If the key is not a valid category.
859
+ TypeError: If the item is not a valid balance type for the category.
860
+ """
861
+ self.__validatekey(key)
862
+ if key == "assets":
863
+ if not isinstance(item, TokenBalances):
864
+ raise TypeError(
865
+ f'{item} is not a valid value for "{key}". Must be a TokenBalances object.'
866
+ )
867
+ elif key in {"debt", "external"}:
868
+ if not isinstance(item, RemoteTokenBalances):
869
+ raise TypeError(
870
+ f'{item} is not a valid value for "{key}". Must be a RemoteTokenBalances object.'
871
+ )
872
+ else:
873
+ raise NotImplementedError(f"key {key} is not yet implemented.")
874
+
875
+
876
+ _PBSeed = Union[Dict[Address, WalletBalances], Iterable[Tuple[Address, WalletBalances]]]
877
+
878
+
879
+ @final
880
+ class PortfolioBalances(DefaultChecksumDict[WalletBalances], _SummableNonNumericMixin): # type: ignore [misc]
881
+ """
882
+ Aggregates :class:`~eth_portfolio.typing.WalletBalances` for multiple wallets, providing operations to sum
883
+ balances across an entire portfolio.
884
+
885
+ The class uses wallet addresses as keys and :class:`~eth_portfolio.typing.WalletBalances` objects as values.
886
+
887
+ Args:
888
+ seed: An initial seed of portfolio balances, either as a dictionary or an iterable of tuples.
889
+
890
+ Example:
891
+ >>> portfolio_balances = PortfolioBalances({'0x123': WalletBalances({'assets': TokenBalances({'0x456': Balance(Decimal('100'), Decimal('2000'))})})})
892
+ >>> portfolio_balances['0x123']['assets']['0x456'].balance
893
+ Decimal('100')
894
+ """
895
+
896
+ def __init__(
897
+ self, seed: Optional[_PBSeed] = None, *, block: Optional[BlockNumber] = None
898
+ ) -> None:
899
+ super().__init__(lambda: WalletBalances(block=block))
900
+ self.block: Final = block
901
+ if seed is None:
902
+ return
903
+ if isinstance(seed, dict):
904
+ seed = seed.items()
905
+ if not isinstance(seed, Iterable):
906
+ raise TypeError(f"{seed} is not a valid input for PortfolioBalances")
907
+ for wallet, balances in seed:
908
+ if self.block != balances.block:
909
+ raise ValueError(
910
+ f"These objects are not from the same block ({self.block} and {balances.block})"
911
+ )
912
+ self[wallet] += balances
913
+
914
+ def __setitem__(self, key: HexAddress, value: WalletBalances) -> None:
915
+ if not isinstance(value, WalletBalances):
916
+ raise TypeError(
917
+ f"value must be a `WalletBalances` object. You passed {value}"
918
+ ) from None
919
+ return super().__setitem__(key, value)
920
+
921
+ @property
922
+ def dataframe(self) -> DataFrame:
923
+ """
924
+ Converts the portfolio balances into a pandas DataFrame.
925
+
926
+ Returns:
927
+ A DataFrame representation of the portfolio balances.
928
+ """
929
+ dfs: List[DataFrame] = []
930
+ for wallet, balances in dict.items(self):
931
+ df = balances.dataframe
932
+ df["wallet"] = wallet
933
+ dfs.append(df)
934
+ return concat(dfs).reset_index(drop=True) if dfs else DataFrame()
935
+
936
+ def sum_usd(self) -> Decimal:
937
+ """
938
+ Sums the USD values of all wallet balances in the portfolio.
939
+
940
+ Returns:
941
+ The total USD value of all wallet balances in the portfolio.
942
+
943
+ Example:
944
+ >>> portfolio_balances = PortfolioBalances({'0x123': WalletBalances({'assets': TokenBalances({'0x123': Balance(Decimal('100'), Decimal('2000'))})})})
945
+ >>> total_usd = portfolio_balances.sum_usd()
946
+ >>> total_usd
947
+ Decimal('2000')
948
+ """
949
+ return sum(balances.sum_usd() for balances in dict.values(self)) # type: ignore
950
+
951
+ @cached_property
952
+ def inverted(self) -> "PortfolioBalancesByCategory":
953
+ """
954
+ Returns an inverted view of the portfolio balances, grouped by category first.
955
+
956
+ Returns:
957
+ :class:`~eth_portfolio.typing.PortfolioBalancesByCategory`: The inverted portfolio balances, grouped by category.
958
+
959
+ Example:
960
+ >>> portfolio_balances = PortfolioBalances({'0x123': WalletBalances({'assets': TokenBalances({'0x123': Balance(Decimal('100'), Decimal('2000'))})})})
961
+ >>> inverted_pb = portfolio_balances.inverted
962
+ >>> inverted_pb['assets']['0x123'].balance
963
+ Decimal('100')
964
+ """
965
+ inverted = PortfolioBalancesByCategory()
966
+ for wallet, wbalances in dict.items(self):
967
+ for label, tbalances in wbalances.items():
968
+ if tbalances:
969
+ inverted[label][wallet] += tbalances # type: ignore [operator]
970
+ return inverted
971
+
972
+ def __bool__(self) -> bool:
973
+ """
974
+ Evaluates the truth value of the :class:`~eth_portfolio.typing.PortfolioBalances` object.
975
+
976
+ Returns:
977
+ True if any wallet has a non-zero balance of any token, otherwise False.
978
+
979
+ Example:
980
+ >>> portfolio_balances = PortfolioBalances()
981
+ >>> bool(portfolio_balances)
982
+ False
983
+ """
984
+ return any(dict.values(self))
985
+
986
+ def __repr__(self) -> str:
987
+ """
988
+ Returns a string representation of the :class:`~eth_portfolio.typing.PortfolioBalances` object.
989
+
990
+ Returns:
991
+ The string representation of the portfolio balances.
992
+ """
993
+ return f"WalletBalances{dict(self)}"
994
+
995
+ def __add__(self, other: "PortfolioBalances") -> "PortfolioBalances":
996
+ """
997
+ Adds another :class:`~eth_portfolio.typing.PortfolioBalances` object to this one.
998
+
999
+ Args:
1000
+ other: Another :class:`~eth_portfolio.typing.PortfolioBalances` object.
1001
+
1002
+ Returns:
1003
+ A new :class:`~eth_portfolio.typing.PortfolioBalances` object with the combined balances.
1004
+
1005
+ Raises:
1006
+ TypeError: If the other object is not a :class:`~eth_portfolio.typing.PortfolioBalances`.
1007
+
1008
+ Example:
1009
+ >>> pb1 = PortfolioBalances({'0x123': WalletBalances({'assets': TokenBalances({'0x123': Balance(Decimal('100'), Decimal('2000'))})})})
1010
+ >>> pb2 = PortfolioBalances({'0x123': WalletBalances({'assets': TokenBalances({'0x123': Balance(Decimal('50'), Decimal('1000'))})})})
1011
+ >>> combined_pb = pb1 + pb2
1012
+ >>> combined_pb['0x123']['assets']['0x123'].balance
1013
+ Decimal('150')
1014
+ """
1015
+ if not isinstance(other, PortfolioBalances):
1016
+ raise TypeError(f"{other} is not a PortfolioBalances object")
1017
+
1018
+ block = self.block
1019
+ if block != other.block:
1020
+ raise ValueError(
1021
+ f"These PortfolioBalances objects are not from the same block ({block} and {other.block})"
1022
+ )
1023
+ # NOTE We need a new object to avoid mutating the inputs
1024
+ combined: PortfolioBalances = PortfolioBalances(block=block)
1025
+ for wallet, balance in dict.items(self):
1026
+ if balance:
1027
+ DefaultChecksumDict._setitem_nochecksum(
1028
+ combined, wallet, combined._getitem_nochecksum(wallet) + balance
1029
+ )
1030
+ for wallet, balance in dict.items(other):
1031
+ if balance:
1032
+ DefaultChecksumDict._setitem_nochecksum(
1033
+ combined, wallet, combined._getitem_nochecksum(wallet) + balance
1034
+ )
1035
+ return combined
1036
+
1037
+ def __iadd__(self, other: "PortfolioBalances") -> "PortfolioBalances":
1038
+ if not isinstance(other, PortfolioBalances):
1039
+ raise TypeError(f"{other} is not a PortfolioBalances object")
1040
+
1041
+ if self.block != other.block:
1042
+ raise ValueError(
1043
+ f"These PortfolioBalances objects are not from the same block ({self.block} and {other.block})"
1044
+ )
1045
+
1046
+ for wallet, balance in dict.items(other):
1047
+ if balance:
1048
+ DefaultChecksumDict._setitem_nochecksum(
1049
+ self, wallet, self._getitem_nochecksum(wallet) + balance
1050
+ )
1051
+ return self
1052
+
1053
+ def __sub__(self, other: "PortfolioBalances") -> "PortfolioBalances":
1054
+ """
1055
+ Subtracts another :class:`~eth_portfolio.typing.PortfolioBalances` object from this one.
1056
+
1057
+ Args:
1058
+ other: Another :class:`~eth_portfolio.typing.PortfolioBalances` object.
1059
+
1060
+ Returns:
1061
+ A new :class:`~eth_portfolio.typing.PortfolioBalances` object with the subtracted balances.
1062
+
1063
+ Raises:
1064
+ TypeError: If the other object is not a :class:`~eth_portfolio.typing.PortfolioBalances`.
1065
+
1066
+ Example:
1067
+ >>> pb1 = PortfolioBalances({'0x123': WalletBalances({'assets': TokenBalances({'0x123': Balance(Decimal('100'), Decimal('2000'))})})})
1068
+ >>> pb2 = PortfolioBalances({'0x123': WalletBalances({'assets': TokenBalances({'0x123': Balance(Decimal('50'), Decimal('1000'))})})})
1069
+ >>> result_pb = pb1 - pb2
1070
+ >>> result_pb['0x123']['assets']['0x123'].balance
1071
+ Decimal('50')
1072
+ """
1073
+ if not isinstance(other, PortfolioBalances):
1074
+ raise TypeError(f"{other} is not a PortfolioBalances object")
1075
+ if self.block != other.block:
1076
+ raise ValueError(
1077
+ f"These PortfolioBalances objects are not from the same block ({self.block} and {other.block})"
1078
+ )
1079
+ # We need a new object to avoid mutating the inputs
1080
+ subtracted: PortfolioBalances = PortfolioBalances(self, block=self.block)
1081
+ for protocol, balances in dict.items(other):
1082
+ subtracted[protocol] -= balances
1083
+ for protocol, balances in subtracted.items():
1084
+ if not balances:
1085
+ del subtracted[protocol]
1086
+ return subtracted
1087
+
1088
+ __slots__ = ("block",)
1089
+
1090
+
1091
+ _WTBInput = Union[Dict[Address, TokenBalances], Iterable[Tuple[Address, TokenBalances]]]
1092
+
1093
+
1094
+ @final
1095
+ class WalletBalancesRaw(DefaultChecksumDict[TokenBalances], _SummableNonNumericMixin): # type: ignore [misc]
1096
+ # Since PortfolioBalances key lookup is: ``wallet -> category -> token -> balance``
1097
+ # We need a new structure for key pattern: ``wallet -> token -> balance``
1098
+
1099
+ # WalletBalancesRaw fills this role.
1100
+ """
1101
+ A structure for key pattern `wallet -> token -> balance`.
1102
+
1103
+ This class is similar to :class:`~eth_portfolio.typing.WalletBalances` but optimized for key lookups by wallet and token directly.
1104
+ It manages :class:`~eth_portfolio.typing.TokenBalances` objects for multiple wallets.
1105
+
1106
+ Args:
1107
+ seed: An initial seed of wallet balances, either as a dictionary or an iterable of tuples.
1108
+
1109
+ Example:
1110
+ >>> raw_balances = WalletBalancesRaw({'0x123': TokenBalances({'0x456': Balance(Decimal('100'), Decimal('2000'))})})
1111
+ >>> raw_balances['0x123']['0x456'].balance
1112
+ Decimal('100')
1113
+ """
1114
+
1115
+ def __init__(
1116
+ self, seed: Optional[_WTBInput] = None, *, block: Optional[BlockNumber] = None
1117
+ ) -> None:
1118
+ super().__init__(lambda: TokenBalances(block=block))
1119
+ self.block: Final = block
1120
+ if seed is None:
1121
+ return
1122
+ if isinstance(seed, dict):
1123
+ seed = seed.items()
1124
+ if not isinstance(seed, Iterable):
1125
+ raise TypeError(f"{seed} is not a valid input for WalletBalancesRaw")
1126
+ for wallet, balances in seed:
1127
+ if self.block != balances.block:
1128
+ raise ValueError(
1129
+ f"These objects are not from the same block ({self.block} and {balances.block})"
1130
+ )
1131
+ self[wallet] += balances
1132
+
1133
+ def __bool__(self) -> bool:
1134
+ """
1135
+ Evaluates the truth value of the :class:`~eth_portfolio.typing.WalletBalancesRaw` object.
1136
+
1137
+ Returns:
1138
+ True if any wallet has a non-zero balance, otherwise False.
1139
+
1140
+ Example:
1141
+ >>> raw_balances = WalletBalancesRaw()
1142
+ >>> bool(raw_balances)
1143
+ False
1144
+ """
1145
+ return any(dict.values(self))
1146
+
1147
+ def __repr__(self) -> str:
1148
+ """
1149
+ Returns a string representation of the :class:`~eth_portfolio.typing.WalletBalancesRaw` object.
1150
+
1151
+ Returns:
1152
+ The string representation of the raw wallet balances.
1153
+ """
1154
+ return f"WalletBalances{dict(self)}"
1155
+
1156
+ def __add__(self, other: "WalletBalancesRaw") -> "WalletBalancesRaw":
1157
+ """
1158
+ Adds another :class:`~eth_portfolio.typing.WalletBalancesRaw` object to this one.
1159
+
1160
+ Args:
1161
+ other: Another :class:`~eth_portfolio.typing.WalletBalancesRaw` object.
1162
+
1163
+ Returns:
1164
+ A new :class:`~eth_portfolio.typing.WalletBalancesRaw` object with the combined balances.
1165
+
1166
+ Raises:
1167
+ TypeError: If the other object is not a :class:`~eth_portfolio.typing.WalletBalancesRaw`.
1168
+
1169
+ Example:
1170
+ >>> raw_balances1 = WalletBalancesRaw({'0x123': TokenBalances({'0x123': Balance(Decimal('100'), Decimal('2000'))})})
1171
+ >>> raw_balances2 = WalletBalancesRaw({'0x123': TokenBalances({'0x123': Balance(Decimal('50'), Decimal('1000'))})})
1172
+ >>> combined_raw = raw_balances1 + raw_balances2
1173
+ >>> combined_raw['0x123']['0x123'].balance
1174
+ Decimal('150')
1175
+ """
1176
+ if not isinstance(other, WalletBalancesRaw):
1177
+ raise TypeError(f"{other} is not a WalletBalancesRaw object")
1178
+
1179
+ block = self.block
1180
+ if block != other.block:
1181
+ raise ValueError(
1182
+ f"These WalletBalancesRaw objects are not from the same block ({block} and {other.block})"
1183
+ )
1184
+
1185
+ combined: WalletBalancesRaw = WalletBalancesRaw(block=block)
1186
+ for wallet, balance in dict.items(self):
1187
+ if balance:
1188
+ DefaultChecksumDict._setitem_nochecksum(
1189
+ combined, wallet, combined._getitem_nochecksum(wallet) + balance
1190
+ )
1191
+ for wallet, balance in dict.items(other):
1192
+ if balance:
1193
+ DefaultChecksumDict._setitem_nochecksum(
1194
+ combined, wallet, combined._getitem_nochecksum(wallet) + balance
1195
+ )
1196
+ return combined
1197
+
1198
+ def __iadd__(self, other: "WalletBalancesRaw") -> "WalletBalancesRaw":
1199
+ if not isinstance(other, WalletBalancesRaw):
1200
+ raise TypeError(f"{other} is not a WalletBalancesRaw object")
1201
+
1202
+ if self.block != other.block:
1203
+ raise ValueError(
1204
+ f"These WalletBalancesRaw objects are not from the same block ({self.block} and {other.block})"
1205
+ )
1206
+
1207
+ for wallet, balance in dict.items(other):
1208
+ if balance:
1209
+ DefaultChecksumDict._setitem_nochecksum(
1210
+ self, wallet, self._getitem_nochecksum(wallet) + balance
1211
+ )
1212
+ return self
1213
+
1214
+ def __sub__(self, other: "WalletBalancesRaw") -> "WalletBalancesRaw":
1215
+ """
1216
+ Subtracts another :class:`~eth_portfolio.typing.WalletBalancesRaw` object from this one.
1217
+
1218
+ Args:
1219
+ other: Another :class:`~eth_portfolio.typing.WalletBalancesRaw` object.
1220
+
1221
+ Returns:
1222
+ A new :class:`~eth_portfolio.typing.WalletBalancesRaw` object with the subtracted balances.
1223
+
1224
+ Raises:
1225
+ TypeError: If the other object is not a :class:`~eth_portfolio.typing.WalletBalancesRaw`.
1226
+
1227
+ Example:
1228
+ >>> raw_balances1 = WalletBalancesRaw({'0x123': TokenBalances({'0x123': Balance(Decimal('100'), Decimal('2000'))})})
1229
+ >>> raw_balances2 = WalletBalancesRaw({'0x123': TokenBalances({'0x123': Balance(Decimal('50'), Decimal('1000'))})})
1230
+ >>> result_raw = raw_balances1 - raw_balances2
1231
+ >>> result_raw['0x123']['0x123'].balance
1232
+ Decimal('50')
1233
+ """
1234
+ if not isinstance(other, WalletBalancesRaw):
1235
+ raise TypeError(f"{other} is not a WalletBalancesRaw object")
1236
+ if self.block != other.block:
1237
+ raise ValueError(
1238
+ f"These WalletBalancesRaw objects are not from the same block ({self.block} and {other.block})"
1239
+ )
1240
+ # NOTE We need a new object to avoid mutating the inputs
1241
+ subtracted: WalletBalancesRaw = WalletBalancesRaw(self, block=other.block)
1242
+ for wallet, balances in dict.items(other):
1243
+ if balances:
1244
+ subtracted[wallet] -= balances
1245
+ for wallet, balances in subtracted.items():
1246
+ if not balances:
1247
+ del subtracted[wallet]
1248
+ return subtracted
1249
+
1250
+ __slots__ = ("block",)
1251
+
1252
+
1253
+ _CBInput = Union[
1254
+ Dict[CategoryLabel, WalletBalancesRaw], Iterable[Tuple[CategoryLabel, WalletBalancesRaw]]
1255
+ ]
1256
+
1257
+
1258
+ @final
1259
+ class PortfolioBalancesByCategory(
1260
+ DefaultDict[CategoryLabel, WalletBalancesRaw], _SummableNonNumericMixin
1261
+ ):
1262
+ """
1263
+ Provides an inverted view of :class:`~eth_portfolio.typing.PortfolioBalances`, allowing access by category first,
1264
+ then by wallet and token.
1265
+
1266
+ The class uses category labels as keys (`assets`, `debt`, `external`) and :class:`~eth_portfolio.typing.WalletBalancesRaw`
1267
+ objects as values.
1268
+
1269
+ Args:
1270
+ seed: An initial seed of portfolio balances by category, either as a dictionary or an iterable of tuples.
1271
+
1272
+ Example:
1273
+ >>> pb_by_category = PortfolioBalancesByCategory({'assets': WalletBalancesRaw({'0x123': TokenBalances({'0x456': Balance(Decimal('100'), Decimal('2000'))})})})
1274
+ >>> pb_by_category['assets']['0x123']['0x456'].balance
1275
+ Decimal('100')
1276
+ """
1277
+
1278
+ def __init__(
1279
+ self, seed: Optional[_CBInput] = None, *, block: Optional[BlockNumber] = None
1280
+ ) -> None:
1281
+ super().__init__(lambda: WalletBalancesRaw(block=block))
1282
+ self.block: Final = block
1283
+ if seed is None:
1284
+ return
1285
+ if isinstance(seed, dict):
1286
+ seed = seed.items()
1287
+ if not isinstance(seed, Iterable):
1288
+ raise TypeError(f"{seed} is not a valid input for PortfolioBalancesByCategory")
1289
+ for label, balances in seed: # type: ignore
1290
+ if self.block != balances.block:
1291
+ raise ValueError(
1292
+ f"These objects are not from the same block ({self.block} and {balances.block})"
1293
+ )
1294
+ self[label] += balances
1295
+
1296
+ @property
1297
+ def assets(self) -> WalletBalancesRaw:
1298
+ """
1299
+ Returns the asset balances across all wallets.
1300
+
1301
+ Returns:
1302
+ :class:`~eth_portfolio.typing.WalletBalancesRaw`: The :class:`~eth_portfolio.typing.WalletBalancesRaw` object representing the asset balances.
1303
+ """
1304
+ return self["assets"]
1305
+
1306
+ @property
1307
+ def debt(self) -> WalletBalancesRaw:
1308
+ """
1309
+ Returns the debt balances across all wallets.
1310
+
1311
+ Returns:
1312
+ :class:`~eth_portfolio.typing.WalletBalancesRaw`: The :class:`~eth_portfolio.typing.WalletBalancesRaw` object representing the debt balances.
1313
+ """
1314
+ return self["debt"]
1315
+
1316
+ def invert(self) -> "PortfolioBalances":
1317
+ """
1318
+ Inverts the portfolio balances by category to group by wallet first.
1319
+
1320
+ Returns:
1321
+ :class:`~eth_portfolio.typing.PortfolioBalances`: The inverted portfolio balances, grouped by wallet first.
1322
+
1323
+ Example:
1324
+ >>> pb_by_category = PortfolioBalancesByCategory({'assets': WalletBalancesRaw({'0x123': TokenBalances({'0x123': Balance(Decimal('100'), Decimal('2000'))})})})
1325
+ >>> inverted_pb = pb_by_category.invert()
1326
+ >>> inverted_pb['0x123']['assets']['0x123'].balance
1327
+ Decimal('100')
1328
+ """
1329
+ inverted = PortfolioBalances()
1330
+ for label, wtbalances in dict.items(self):
1331
+ for wallet, tbalances in wtbalances.items():
1332
+ if tbalances:
1333
+ inverted[wallet][label] += tbalances # type: ignore [operator]
1334
+ return inverted
1335
+
1336
+ def __bool__(self) -> bool:
1337
+ """
1338
+ Evaluates the truth value of the :class:`~eth_portfolio.typing.PortfolioBalancesByCategory` object.
1339
+
1340
+ Returns:
1341
+ True if any category has a non-zero balance, otherwise False.
1342
+
1343
+ Example:
1344
+ >>> pb_by_category = PortfolioBalancesByCategory()
1345
+ >>> bool(pb_by_category)
1346
+ False
1347
+ """
1348
+ return any(dict.values(self))
1349
+
1350
+ def __repr__(self) -> str:
1351
+ """
1352
+ Returns a string representation of the :class:`~eth_portfolio.typing.PortfolioBalancesByCategory` object.
1353
+
1354
+ Returns:
1355
+ The string representation of the portfolio balances by category.
1356
+ """
1357
+ return f"PortfolioBalancesByCategory{dict(self)}"
1358
+
1359
+ def __add__(self, other: "PortfolioBalancesByCategory") -> "PortfolioBalancesByCategory":
1360
+ """
1361
+ Adds another :class:`~eth_portfolio.typing.PortfolioBalancesByCategory` object to this one.
1362
+
1363
+ Args:
1364
+ other: Another :class:`~eth_portfolio.typing.PortfolioBalancesByCategory` object.
1365
+
1366
+ Returns:
1367
+ A new :class:`~eth_portfolio.typing.PortfolioBalancesByCategory` object with the combined balances.
1368
+
1369
+ Raises:
1370
+ TypeError: If the other object is not a :class:`~eth_portfolio.typing.PortfolioBalancesByCategory`.
1371
+
1372
+ Example:
1373
+ >>> pb_by_category1 = PortfolioBalancesByCategory({'assets': WalletBalancesRaw({'0x123': TokenBalances({'0x123': Balance(Decimal('100'), Decimal('2000'))})})})
1374
+ >>> pb_by_category2 = PortfolioBalancesByCategory({'assets': WalletBalancesRaw({'0x123': TokenBalances({'0x123': Balance(Decimal('50'), Decimal('1000'))})})})
1375
+ >>> combined_pb_by_category = pb_by_category1 + pb_by_category2
1376
+ >>> combined_pb_by_category['assets']['0x123']['0x123'].balance
1377
+ Decimal('150')
1378
+ """
1379
+ if not isinstance(other, PortfolioBalancesByCategory):
1380
+ raise TypeError(f"{other} is not a PortfolioBalancesByCategory object")
1381
+
1382
+ block = self.block
1383
+ if block != other.block:
1384
+ raise ValueError(
1385
+ f"These PortfolioBalancesByCategory objects are not from the same block ({block} and {other.block})"
1386
+ )
1387
+
1388
+ combined: PortfolioBalancesByCategory = PortfolioBalancesByCategory(block=block)
1389
+ for protocol, balances in dict.items(self):
1390
+ if balances:
1391
+ combined[protocol] += balances
1392
+ for protocol, balances in dict.items(other):
1393
+ if balances:
1394
+ combined[protocol] += balances
1395
+ return combined
1396
+
1397
+ def __iadd__(self, other: "PortfolioBalancesByCategory") -> "PortfolioBalancesByCategory":
1398
+
1399
+ if not isinstance(other, PortfolioBalancesByCategory):
1400
+ raise TypeError(f"{other} is not a PortfolioBalancesByCategory object")
1401
+
1402
+ if self.block != other.block:
1403
+ raise ValueError(
1404
+ f"These PortfolioBalancesByCategory objects are not from the same block ({self.block} and {other.block})"
1405
+ )
1406
+
1407
+ for protocol, balances in dict.items(other):
1408
+ if balances:
1409
+ self[protocol] += balances
1410
+ return self
1411
+
1412
+ def __sub__(self, other: "PortfolioBalancesByCategory") -> "PortfolioBalancesByCategory":
1413
+ """
1414
+ Subtracts another :class:`~eth_portfolio.typing.PortfolioBalancesByCategory` object from this one.
1415
+
1416
+ Args:
1417
+ other: Another :class:`~eth_portfolio.typing.PortfolioBalancesByCategory` object.
1418
+
1419
+ Returns:
1420
+ A new :class:`~eth_portfolio.typing.PortfolioBalancesByCategory` object with the subtracted balances.
1421
+
1422
+ Raises:
1423
+ TypeError: If the other object is not a :class:`~eth_portfolio.typing.PortfolioBalancesByCategory`.
1424
+
1425
+ Example:
1426
+ >>> pb_by_category1 = PortfolioBalancesByCategory({'assets': WalletBalancesRaw({'0x123': TokenBalances({'0x123': Balance(Decimal('100'), Decimal('2000'))})})})
1427
+ >>> pb_by_category2 = PortfolioBalancesByCategory({'assets': WalletBalancesRaw({'0x123': TokenBalances({'0x123': Balance(Decimal('50'), Decimal('1000'))})})})
1428
+ >>> result_pb_by_category = pb_by_category1 - pb_by_category2
1429
+ >>> result_pb_by_category['assets']['0x123']['0x123'].balance
1430
+ Decimal('50')
1431
+ """
1432
+ if not isinstance(other, PortfolioBalancesByCategory):
1433
+ raise TypeError(f"{other} is not a PortfolioBalancesByCategory object")
1434
+ if self.block != other.block:
1435
+ raise ValueError(
1436
+ f"These PortfolioBalancesByCategory objects are not from the same block ({self.block} and {other.block})"
1437
+ )
1438
+ # NOTE We need a new object to avoid mutating the inputs
1439
+ subtracted: PortfolioBalancesByCategory = PortfolioBalancesByCategory(
1440
+ self, block=self.block
1441
+ )
1442
+ for protocol, balances in dict.items(other):
1443
+ subtracted[protocol] -= balances
1444
+ for protocol, balances in subtracted.items():
1445
+ if not balances:
1446
+ del subtracted[protocol]
1447
+ return subtracted