ethereum_types.numeric

Numeric types (mostly integers.)

_BytesLike

26
_BytesLike: TypeAlias = Union[bytes, bytearray, memoryview]

_max_value

def _max_value(bits: int) -> int:
30
    assert bits >= 0
31
    value = (2**bits) - 1
32
    return cast("int", value)  # 2**-1 == 0.5

Unsigned

Base of integer types.

35
@mypyc_attr(acyclic=True)
class Unsigned:

__slots__

41
    __slots__ = ("_number",)

_number

42
    _number: Final[int]

__init__

def __init__(self, ​​value: SupportsInt) -> None:
45
        int_value = int(value)
46
        if not self._in_range(int_value):
47
            raise OverflowError
48
        self._number = int_value

__complex__

def __complex__(self) -> complex:
51
        return complex(self._number)

__bool__

def __bool__(self) -> bool:
54
        return bool(self._number)

real

56
    @property
def real(self) -> Self:
58
        return self

imag

60
    @property
def imag(self) -> Self:
62
        return type(self)(0)

conjugate

def conjugate(self) -> Self:
65
        return self

__float__

def __float__(self) -> float:
68
        return float(self._number)

numerator

70
    @property
def numerator(self) -> int:
72
        return self._number.numerator

denominator

74
    @property
def denominator(self) -> int:
76
        return 1

__index__

def __index__(self) -> int:
79
        return self._number

_in_range

81
    @abstractmethod
def _in_range(self, ​​value: int) -> bool:
83
        raise NotImplementedError

__abs__

def __abs__(self) -> Self:
86
        return type(self)(self)

__radd__

def __radd__(self, ​​left: Self) -> Self:
89
        return self.__add__(left)

__add__

def __add__(self, ​​right: Self) -> Self:
92
        class_ = type(self)
93
        if not isinstance(right, class_):
94
            return NotImplemented
95
        return class_(self._number + right._number)

__iadd__

def __iadd__(self, ​​right: Self) -> Self:
98
        class_ = type(self)
99
        if not isinstance(right, class_):
100
            return NotImplemented
101
        return class_(self._number + right._number)

__sub__

def __sub__(self, ​​right: Self) -> Self:
104
        class_ = type(self)
105
        if not isinstance(right, class_):
106
            return NotImplemented
107
108
        if self._number < right._number:
109
            raise OverflowError
110
111
        return class_(self._number - right._number)

__rsub__

def __rsub__(self, ​​left: Self) -> Self:
114
        class_ = type(self)
115
        if not isinstance(left, class_):
116
            return NotImplemented
117
118
        if self._number > left._number:
119
            raise OverflowError
120
121
        return class_(left._number - self._number)

__isub__

def __isub__(self, ​​right: Self) -> Self:
124
        class_ = type(self)
125
        if not isinstance(right, class_):
126
            return NotImplemented
127
        if right._number > self._number:
128
            raise OverflowError
129
        return class_(self._number - right._number)

__mul__

def __mul__(self, ​​right: Self) -> Self:
132
        class_ = type(self)
133
        if not isinstance(right, class_):
134
            return NotImplemented
135
        return class_(self._number * right._number)

__rmul__

def __rmul__(self, ​​left: Self) -> Self:
138
        return self.__mul__(left)

__imul__

def __imul__(self, ​​right: Self) -> Self:
141
        class_ = type(self)
142
        if not isinstance(right, class_):
143
            return NotImplemented
144
        return class_(self._number * right._number)

__truediv__

def __truediv__(self, ​​other: Self) -> float:
147
        class_ = type(self)
148
        if not isinstance(other, class_):
149
            return NotImplemented
150
        return self._number.__truediv__(other._number)

__rtruediv__

def __rtruediv__(self, ​​other: Self) -> float:
153
        class_ = type(self)
154
        if not isinstance(other, class_):
155
            return NotImplemented
156
        return self._number.__rtruediv__(other._number)

__floordiv__

def __floordiv__(self, ​​right: Self) -> Self:
159
        class_ = type(self)
160
        if not isinstance(right, class_):
161
            return NotImplemented
162
163
        return class_(self._number.__floordiv__(right._number))

__rfloordiv__

def __rfloordiv__(self, ​​left: Self) -> Self:
166
        class_ = type(self)
167
        if not isinstance(left, class_):
168
            return NotImplemented
169
170
        return class_(self._number.__rfloordiv__(left._number))

__ifloordiv__

def __ifloordiv__(self, ​​right: Self) -> Self:
173
        class_ = type(self)
174
        if not isinstance(right, class_):
175
            return NotImplemented
176
        return class_(self._number // right._number)

__mod__

def __mod__(self, ​​right: Self) -> Self:
179
        class_ = type(self)
180
        if not isinstance(right, class_):
181
            return NotImplemented
182
183
        return class_(self._number % right._number)

__rmod__

def __rmod__(self, ​​left: Self) -> Self:
186
        class_ = type(self)
187
        if not isinstance(left, class_):
188
            return NotImplemented
189
190
        return class_(self._number.__rmod__(left._number))

__imod__

def __imod__(self, ​​right: Self) -> Self:
193
        class_ = type(self)
194
        if not isinstance(right, class_):
195
            return NotImplemented
196
        return class_(self._number % right._number)

__divmod__

def __divmod__(self, ​​right: Self) -> Tuple[Self, Self]:
199
        class_ = type(self)
200
        if not isinstance(right, class_):
201
            return NotImplemented
202
203
        result = self._number.__divmod__(right._number)
204
        return (
205
            class_(result[0]),
206
            class_(result[1]),
207
        )

__rdivmod__

def __rdivmod__(self, ​​left: Self) -> Union[Tuple[Self, Self], NotImplementedType]:
212
        class_ = type(self)
213
        if not isinstance(left, class_):
214
            # No idea why mypy is assuming this is an Any...
215
            return NotImplemented  # type: ignore[no-any-return]
216
217
        result = self._number.__rdivmod__(left._number)
218
        return (
219
            class_(result[0]),
220
            class_(result[1]),
221
        )

__pow__

def __pow__(self, ​​right: Self, ​​modulo: Optional[Self]) -> Self:
224
        class_ = type(self)
225
        modulo_int = None
226
        if modulo is not None:
227
            if not isinstance(modulo, class_):
228
                return NotImplemented
229
            modulo_int = modulo._number
230
231
        if not isinstance(right, class_):
232
            return NotImplemented
233
234
        return class_(self._number.__pow__(right._number, modulo_int))

__rpow__

def __rpow__(self, ​​left: Self) -> Self:
237
        class_ = type(self)
238
        if not isinstance(left, class_):
239
            return NotImplemented
240
241
        return class_(self._number.__rpow__(left._number))

__ipow__

def __ipow__(self, ​​right: Self, ​​modulo: Optional[Self]) -> Self:
244
        class_ = type(self)
245
        modulo_int = None
246
        if modulo is not None:
247
            if not isinstance(modulo, class_):
248
                raise TypeError
249
            modulo_int = modulo._number
250
251
        if not isinstance(right, class_):
252
            return NotImplemented
253
254
        return class_(self._number.__pow__(right._number, modulo_int))

__xor__

def __xor__(self, ​​right: Self) -> Self:
257
        class_ = type(self)
258
        if not isinstance(right, class_):
259
            return NotImplemented
260
261
        return class_(self._number.__xor__(right._number))

__rxor__

def __rxor__(self, ​​left: Self) -> Self:
264
        class_ = type(self)
265
        if not isinstance(left, class_):
266
            return NotImplemented
267
268
        return class_(self._number.__rxor__(left._number))

__ixor__

def __ixor__(self, ​​right: Self) -> Self:
271
        class_ = type(self)
272
        if not isinstance(right, class_):
273
            return NotImplemented
274
275
        return class_(self._number.__xor__(right._number))

__and__

def __and__(self, ​​other: Self) -> Self:
278
        class_ = type(self)
279
        if not isinstance(other, class_):
280
            return NotImplemented
281
282
        return class_(self._number.__and__(other._number))

__rand__

def __rand__(self, ​​other: Self) -> Self:
285
        class_ = type(self)
286
        if not isinstance(other, class_):
287
            return NotImplemented
288
289
        return class_(self._number.__rand__(other._number))

__or__

def __or__(self, ​​other: Self) -> Self:
292
        class_ = type(self)
293
        if not isinstance(other, class_):
294
            return NotImplemented
295
296
        return class_(self._number.__or__(other._number))

__ror__

def __ror__(self, ​​other: Self) -> Self:
299
        class_ = type(self)
300
        if not isinstance(other, class_):
301
            return NotImplemented
302
303
        return class_(self._number.__ror__(other._number))

__neg__

def __neg__(self) -> int:
306
        return -self._number

__pos__

def __pos__(self) -> Self:
309
        return type(self)(self._number)

__invert__

def __invert__(self) -> Self:
312
        # TODO: How should this behave?
313
        raise NotImplementedError

__floor__

def __floor__(self) -> Self:
316
        return type(self)(self)

__ceil__

def __ceil__(self) -> Self:
319
        return type(self)(self)

__int__

def __int__(self) -> int:
322
        return self._number

__eq__

324
    @override
def __eq__(self, ​​other: object) -> bool:
326
        # Unlike the other comparison dunder methods (eg. `__lt__`, `__ge__`,
327
        # etc.), `__eq__` is expected to work with any object, so mypy doesn't
328
        # detect comparisons between `Uint` and `int` as errors. Instead of
329
        # throwing a `TypeError` at runtime, we try to behave sanely and
330
        # soundly by converting `other` to an integer if possible, then
331
        # comparing.
332
        if isinstance(other, Unsigned):
333
            return self._number == other._number
334
        elif isinstance(other, SupportsInt):
335
            other_int = int(other)
336
            if other != other_int:
337
                # If `other` doesn't equal `int(other)`, `self` definitely
338
                # doesn't equal `other` since `self` has to be an integer.
339
                return False
340
            return self._number == other_int
341
        return NotImplemented

__le__

def __le__(self, ​​other: Self) -> bool:
344
        class_ = type(self)
345
        if not isinstance(other, class_):
346
            return NotImplemented
347
348
        return self._number <= other._number

__ge__

def __ge__(self, ​​other: Self) -> bool:
351
        class_ = type(self)
352
        if not isinstance(other, class_):
353
            return NotImplemented
354
355
        return self._number >= other._number

__lt__

def __lt__(self, ​​other: Self) -> bool:
358
        class_ = type(self)
359
        if not isinstance(other, class_):
360
            return NotImplemented
361
362
        return self._number < other._number

__gt__

def __gt__(self, ​​other: Self) -> bool:
365
        class_ = type(self)
366
        if not isinstance(other, class_):
367
            return NotImplemented
368
369
        return self._number > other._number

__round__

def __round__(self, ​​ndigits: Optional[int]) -> Self:
372
        return type(self)(self)

__trunc__

def __trunc__(self) -> Self:
375
        return type(self)(self)

__rshift__

def __rshift__(self, ​​right: Self) -> Self:
378
        class_ = type(self)
379
        if not isinstance(right, class_):
380
            return NotImplemented
381
382
        return class_(self._number >> right._number)

__rrshift__

def __rrshift__(self, ​​left: Self) -> Self:
385
        class_ = type(self)
386
        if not isinstance(left, class_):
387
            return NotImplemented
388
389
        return class_(self._number.__rrshift__(left._number))

__lshift__

def __lshift__(self, ​​right: Self) -> Self:
392
        class_ = type(self)
393
        if not isinstance(right, class_):
394
            return NotImplemented
395
396
        return class_(self._number << right._number)

__rlshift__

def __rlshift__(self, ​​left: Self) -> Self:
399
        class_ = type(self)
400
        if not isinstance(left, class_):
401
            return NotImplemented
402
403
        return class_(self._number.__rlshift__(left._number))

__hash__

405
    @override
def __hash__(self) -> int:
407
        return hash(self._number)

__repr__

409
    @override
def __repr__(self) -> str:
411
        return f"{type(self).__name__}({self._number})"

__str__

413
    @override
def __str__(self) -> str:
415
        return str(self._number)

to_be_bytes64

Converts this unsigned integer into its big endian representation with exactly 64 bytes.

def to_be_bytes64(self) -> Bytes64:
418
        <snip>
422
        return Bytes64(self._number.to_bytes(64, "big"))

to_be_bytes32

Converts this unsigned integer into its big endian representation with exactly 32 bytes.

def to_be_bytes32(self) -> Bytes32:
425
        <snip>
429
        return Bytes32(self._number.to_bytes(32, "big"))

to_bytes1

Converts this unsigned integer into a byte sequence with exactly 1 bytes.

def to_bytes1(self) -> Bytes1:
432
        <snip>
436
        return Bytes1(self._number.to_bytes(1, "little"))

to_le_bytes4

Converts this unsigned integer into its little endian representation, with exactly 4 bytes.

def to_le_bytes4(self) -> "Bytes4":
439
        <snip>
443
        return Bytes4(self._number.to_bytes(4, "little"))

to_be_bytes4

Converts this unsigned integer into its big endian representation, with exactly 4 bytes.

def to_be_bytes4(self) -> "Bytes4":
446
        <snip>
450
        return Bytes4(self._number.to_bytes(4, "big"))

to_le_bytes8

Converts this fixed sized unsigned integer into its little endian representation, with exactly 8 bytes.

def to_le_bytes8(self) -> "Bytes8":
453
        <snip>
457
        return Bytes8(self._number.to_bytes(8, "little"))

to_be_bytes8

Converts this unsigned integer into its big endian representation, with exactly 8 bytes.

def to_be_bytes8(self) -> "Bytes8":
460
        <snip>
464
        return Bytes8(self._number.to_bytes(8, "big"))

to_bytes

Return an array of bytes representing an integer.

def to_bytes(self, ​​length: Optional[Self], ​​byteorder: Literal["big", "little"]) -> Bytes:
471
        <snip>
474
        length_int = 1 if length is None else int(length)
475
        return self._number.to_bytes(length=length_int, byteorder=byteorder)

to_be_bytes

Converts this unsigned integer into its big endian representation, without padding.

def to_be_bytes(self) -> "Bytes":
478
        <snip>
482
        bit_length = self._number.bit_length()
483
        byte_length = (bit_length + 7) // 8
484
        return self._number.to_bytes(byte_length, "big")

to_le_bytes

Converts this unsigned integer into its little endian representation, without padding.

def to_le_bytes(self) -> "Bytes":
487
        <snip>
491
        bit_length = self._number.bit_length()
492
        number_bytes = (bit_length + 7) // 8
493
        return self._number.to_bytes(number_bytes, "little")

to_le_bytes32

Converts this unsigned integer into its little endian representation with exactly 32 bytes.

def to_le_bytes32(self) -> Bytes32:
496
        <snip>
500
        return Bytes32(self._number.to_bytes(32, "little"))

to_le_bytes64

Converts this unsigned integer into its little endian representation with exactly 64 bytes.

def to_le_bytes64(self) -> Bytes64:
503
        <snip>
507
        return Bytes64(self._number.to_bytes(64, "little"))

bit_length

Minimum number of bits required to represent this number in binary.

def bit_length(self) -> "Uint":
510
        <snip>
513
        return Uint(self._number.bit_length())

Uint

Unsigned integer of arbitrary size.

516
@mypyc_attr(acyclic=True)
class Uint:

from_be_bytes

Converts a sequence of bytes into an arbitrarily sized unsigned integer from its big endian representation.

522
    @classmethod
def from_be_bytes(cls: Type[Self], ​​buffer: _BytesLike) -> Self:
524
        <snip>
528
        return cls(int.from_bytes(buffer, "big"))

from_le_bytes

Converts a sequence of bytes into an arbitrarily sized unsigned integer from its little endian representation.

530
    @classmethod
def from_le_bytes(cls: Type[Self], ​​buffer: _BytesLike) -> Self:
532
        <snip>
536
        return cls(int.from_bytes(buffer, "little"))

_in_range

538
    @override
def _in_range(self, ​​value: int) -> bool:
540
        return value >= 0

ulen

Return the number of items in a container, as a Uint.

def ulen(sized: Sized, ​​/) -> Uint:
547
    <snip>
550
    return Uint(len(sized))

FixedUnsigned

Superclass for fixed size unsigned integers. Not intended to be used directly, but rather to be subclassed.

553
@mypyc_attr(acyclic=True)
class FixedUnsigned:

MAX_VALUE

Largest value that can be represented by this integer type.

560
    MAX_VALUE: ClassVar[Self]

from_be_bytes

Converts a sequence of bytes into a fixed sized unsigned integer from its big endian representation.

565
    @classmethod
def from_be_bytes(cls: Type[Self], ​​buffer: _BytesLike) -> Self:
567
        <snip>
571
        bits = cls.MAX_VALUE._number.bit_length()
572
        byte_count = (bits + 7) // 8
573
        if len(buffer) > byte_count:
574
            message = f"expected at most {byte_count} but got {len(buffer)}"
575
            raise ValueError(message)
576
577
        return cls(int.from_bytes(buffer, "big"))

from_le_bytes

Converts a sequence of bytes into a fixed sized unsigned integer from its little endian representation.

579
    @classmethod
def from_le_bytes(cls: Type[Self], ​​buffer: _BytesLike) -> Self:
581
        <snip>
585
        bits = cls.MAX_VALUE._number.bit_length()
586
        byte_count = (bits + 7) // 8
587
        if len(buffer) > byte_count:
588
            message = f"expected at most {byte_count} but got {len(buffer)}"
589
            raise ValueError(message)
590
591
        return cls(int.from_bytes(buffer, "little"))

from_signed

Creates an unsigned integer representing value using two's complement.

593
    @classmethod
def from_signed(cls: Type[Self], ​​value: int) -> Self:
595
        <snip>
599
        if value >= (cls.MAX_VALUE._number // 2 + 1):
600
            raise OverflowError
601
602
        if value >= 0:
603
            return cls(value)
604
605
        if value < (-cls.MAX_VALUE // 2):
606
            raise OverflowError
607
608
        return cls(value & cls.MAX_VALUE._number)

_in_range

610
    @override
def _in_range(self, ​​value: int) -> bool:
612
        return value >= 0 and value <= self.MAX_VALUE._number

wrapping_add

Return a new instance containing self + right (mod N).

def wrapping_add(self, ​​right: Self) -> Self:
615
        <snip>
618
        class_ = type(self)
619
        if not isinstance(right, class_):
620
            raise TypeError
621
622
        # This is a fast way of ensuring that the result is < (2 ** 256)
623
        return class_((self._number + right._number) & self.MAX_VALUE._number)

wrapping_sub

Return a new instance containing self - right (mod N).

def wrapping_sub(self, ​​right: Self) -> Self:
626
        <snip>
629
        class_ = type(self)
630
        if not isinstance(right, class_):
631
            raise TypeError
632
633
        # This is a fast way of ensuring that the result is < (2 ** 256)
634
        return class_((self._number - right._number) & self.MAX_VALUE._number)

wrapping_mul

Return a new instance containing self * right (mod N).

def wrapping_mul(self, ​​right: Self) -> Self:
637
        <snip>
640
        class_ = type(self)
641
        if not isinstance(right, class_):
642
            raise TypeError
643
644
        # This is a fast way of ensuring that the result is < (2 ** 256)
645
        return class_((self._number * right._number) & self.MAX_VALUE._number)

wrapping_pow

Return a new instance containing self ** right (mod modulo).

If omitted, modulo defaults to Uint(self.MAX_VALUE) + 1.

def wrapping_pow(self, ​​right: Self, ​​modulo: Optional[Self]) -> Self:
648
        <snip>
653
        class_ = type(self)
654
        modulo_int = None
655
        if modulo is not None:
656
            if not isinstance(modulo, class_):
657
                raise TypeError
658
            modulo_int = modulo._number
659
660
        if not isinstance(right, class_):
661
            raise TypeError
662
663
        # This is a fast way of ensuring that the result is < (2 ** 256)
664
        return class_(
665
            self._number.__pow__(right._number, modulo_int)
666
            & self.MAX_VALUE._number
667
        )

__invert__

669
    @override
def __invert__(self: Self) -> Self:
671
        return type(self)(
672
            int.__invert__(self._number) & self.MAX_VALUE._number
673
        )

to_signed

Decodes a signed integer from its two's complement representation.

def to_signed(self) -> int:
676
        <snip>
679
        bits = self.MAX_VALUE._number.bit_length()
680
        bits = 8 * ((bits + 7) // 8)
681
        if self._number.bit_length() < bits:
682
            # This means that the sign bit is 0
683
            return int(self)
684
685
        # -1 * (2's complement of value)
686
        return int(self) - (self.MAX_VALUE._number + 1)

U256

Unsigned integer, which can represent 0 to 2 ** 256 - 1, inclusive.

689
@mypyc_attr(acyclic=True)
class U256:

Largest value that can be represented by this integer type.

695
    MAX_VALUE: ClassVar["U256"]

_U256

704
@mypyc_attr(acyclic=True)
class _U256:

_in_range

706
    @override
def _in_range(self, ​​value: int) -> bool:
708
        return True

U256.MAX_VALUE

711
U256.MAX_VALUE = _U256(_max_value(256))

U256.MAX_VALUE

712
U256.MAX_VALUE = U256(_max_value(256))

U8

Unsigned positive integer, which can represent 0 to 2 ** 8 - 1, inclusive.

715
@mypyc_attr(acyclic=True)
class U8:

Largest value that can be represented by this integer type.

722
    MAX_VALUE: ClassVar["U8"]

_U8

731
@mypyc_attr(acyclic=True)
class _U8:

_in_range

733
    @override
def _in_range(self, ​​value: int) -> bool:
735
        return True

U8.MAX_VALUE

738
U8.MAX_VALUE = _U8(_max_value(8))

U8.MAX_VALUE

739
U8.MAX_VALUE = U8(_max_value(8))

U16

Unsigned positive integer, which can represent 0 to 2 ** 16 - 1, inclusive.

742
@mypyc_attr(acyclic=True)
class U16:

Largest value that can be represented by this integer type.

749
    MAX_VALUE: ClassVar["U16"]

_U16

758
@mypyc_attr(acyclic=True)
class _U16:

_in_range

760
    @override
def _in_range(self, ​​value: int) -> bool:
762
        return True

U16.MAX_VALUE

765
U16.MAX_VALUE = _U16(_max_value(16))

U16.MAX_VALUE

766
U16.MAX_VALUE = U16(_max_value(16))

U32

Unsigned positive integer, which can represent 0 to 2 ** 32 - 1, inclusive.

769
@mypyc_attr(acyclic=True)
class U32:

Largest value that can be represented by this integer type.

776
    MAX_VALUE: ClassVar["U32"]

_U32

785
@mypyc_attr(acyclic=True)
class _U32:

_in_range

787
    @override
def _in_range(self, ​​value: int) -> bool:
789
        return True

U32.MAX_VALUE

792
U32.MAX_VALUE = _U32(_max_value(32))

U32.MAX_VALUE

793
U32.MAX_VALUE = U32(_max_value(32))

U64

Unsigned positive integer, which can represent 0 to 2 ** 64 - 1, inclusive.

796
@mypyc_attr(acyclic=True)
class U64:

Largest value that can be represented by this integer type.

803
    MAX_VALUE: ClassVar["U64"]

_U64

812
@mypyc_attr(acyclic=True)
class _U64:

_in_range

814
    @override
def _in_range(self, ​​value: int) -> bool:
816
        return True

U64.MAX_VALUE

819
U64.MAX_VALUE = _U64(_max_value(64))

U64.MAX_VALUE

820
U64.MAX_VALUE = U64(_max_value(64))