eth-portfolio 0.5.4__cp310-cp310-macosx_11_0_arm64.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 might be problematic. Click here for more details.

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