ethereum_types.numeric

Numeric types (mostly integers.)

_BytesLike

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

Unsigned

Base of integer types.

class Unsigned:

__slots__

33
    __slots__ = ("_number",)

_number

34
    _number: Final[int]

__init__

def __init__(self, ​​value: SupportsInt) -> None:
37
        int_value = int(value)
38
        if not self._in_range(int_value):
39
            raise OverflowError()
40
        self._number = int_value

_in_range

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

__abs__

46
    @override
def __abs__(self) -> Self:
48
        return type(self)(self)

__radd__

50
    @override
def __radd__(self, ​​left: Self) -> Self:
52
        return self.__add__(left)

__add__

54
    @override
def __add__(self, ​​right: Self) -> Self:
56
        Class = type(self)
57
        if not isinstance(right, Class):
58
            return NotImplemented
59
        return Class(self._number + right._number)

__iadd__

def __iadd__(self, ​​right: Self) -> Self:
62
        Class = type(self)
63
        if not isinstance(right, Class):
64
            return NotImplemented
65
        return Class(self._number + right._number)

__sub__

67
    @override
def __sub__(self, ​​right: Self) -> Self:
69
        Class = type(self)
70
        if not isinstance(right, Class):
71
            return NotImplemented
72
73
        if self._number < right._number:
74
            raise OverflowError()
75
76
        return Class(self._number - right._number)

__rsub__

78
    @override
def __rsub__(self, ​​left: Self) -> Self:
80
        Class = type(self)
81
        if not isinstance(left, Class):
82
            return NotImplemented
83
84
        if self._number > left._number:
85
            raise OverflowError()
86
87
        return Class(left._number - self._number)

__isub__

def __isub__(self, ​​right: Self) -> Self:
90
        Class = type(self)
91
        if not isinstance(right, Class):
92
            return NotImplemented
93
        if right._number > self._number:
94
            raise OverflowError()
95
        return Class(self._number - right._number)

__mul__

97
    @override
def __mul__(self, ​​right: Self) -> Self:
99
        Class = type(self)
100
        if not isinstance(right, Class):
101
            return NotImplemented
102
        return Class(self._number * right._number)

__rmul__

104
    @override
def __rmul__(self, ​​left: Self) -> Self:
106
        return self.__mul__(left)

__imul__

def __imul__(self, ​​right: Self) -> Self:
109
        Class = type(self)
110
        if not isinstance(right, Class):
111
            return NotImplemented
112
        return Class(self._number * right._number)

__truediv__

114
    @override
def __truediv__(self, ​​other: Self) -> float:
116
        Class = type(self)
117
        if not isinstance(other, Class):
118
            return NotImplemented
119
        return self._number.__truediv__(other._number)

__rtruediv__

121
    @override
def __rtruediv__(self, ​​other: Self) -> float:
123
        Class = type(self)
124
        if not isinstance(other, Class):
125
            return NotImplemented
126
        return self._number.__rtruediv__(other._number)

__floordiv__

128
    @override
def __floordiv__(self, ​​right: Self) -> Self:
130
        Class = type(self)
131
        if not isinstance(right, Class):
132
            return NotImplemented
133
134
        return Class(self._number.__floordiv__(right._number))

__rfloordiv__

136
    @override
def __rfloordiv__(self, ​​left: Self) -> Self:
138
        Class = type(self)
139
        if not isinstance(left, Class):
140
            return NotImplemented
141
142
        return Class(self._number.__rfloordiv__(left._number))

__ifloordiv__

def __ifloordiv__(self, ​​right: Self) -> Self:
145
        Class = type(self)
146
        if not isinstance(right, Class):
147
            return NotImplemented
148
        return Class(self._number // right._number)

__mod__

150
    @override
def __mod__(self, ​​right: Self) -> Self:
152
        Class = type(self)
153
        if not isinstance(right, Class):
154
            return NotImplemented
155
156
        return Class(self._number % right._number)

__rmod__

158
    @override
def __rmod__(self, ​​left: Self) -> Self:
160
        Class = type(self)
161
        if not isinstance(left, Class):
162
            return NotImplemented
163
164
        return Class(self._number.__rmod__(left._number))

__imod__

def __imod__(self, ​​right: Self) -> Self:
167
        Class = type(self)
168
        if not isinstance(right, Class):
169
            return NotImplemented
170
        return Class(self._number % right._number)

__divmod__

172
    @override
def __divmod__(self, ​​right: Self) -> Tuple[Self, Self]:
174
        Class = type(self)
175
        if not isinstance(right, Class):
176
            return NotImplemented
177
178
        result = self._number.__divmod__(right._number)
179
        return (
180
            Class(result[0]),
181
            Class(result[1]),
182
        )

__rdivmod__

184
    @override
def __rdivmod__(self, ​​left: Self) -> Union[Tuple[Self, Self], NotImplementedType]:
188
        Class = type(self)
189
        if not isinstance(left, Class):
190
            # No idea why mypy is assuming this is an Any...
191
            return NotImplemented  # type: ignore[no-any-return]
192
193
        result = self._number.__rdivmod__(left._number)
194
        return (
195
            Class(result[0]),
196
            Class(result[1]),
197
        )

__pow__

199
    @override
def __pow__(self, ​​right: Self, ​​modulo: Optional[Self]) -> Self:
201
        Class = type(self)
202
        modulo_int = None
203
        if modulo is not None:
204
            if not isinstance(modulo, Class):
205
                return NotImplemented
206
            modulo_int = modulo._number
207
208
        if not isinstance(right, Class):
209
            return NotImplemented
210
211
        return Class(self._number.__pow__(right._number, modulo_int))

__rpow__

213
    @override
def __rpow__(self, ​​left: Self, ​​modulo: Optional[Self]) -> Self:
215
        Class = type(self)
216
        modulo_int = None
217
        if modulo is not None:
218
            if not isinstance(modulo, Class):
219
                raise TypeError()
220
            modulo_int = modulo._number
221
222
        if not isinstance(left, Class):
223
            return NotImplemented
224
225
        return Class(self._number.__rpow__(left._number, modulo_int))

__ipow__

def __ipow__(self, ​​right: Self, ​​modulo: Optional[Self]) -> Self:
228
        Class = type(self)
229
        modulo_int = None
230
        if modulo is not None:
231
            if not isinstance(modulo, Class):
232
                raise TypeError()
233
            modulo_int = modulo._number
234
235
        if not isinstance(right, Class):
236
            return NotImplemented
237
238
        return Class(self._number.__pow__(right._number, modulo_int))

__xor__

240
    @override
def __xor__(self, ​​right: Self) -> Self:
242
        Class = type(self)
243
        if not isinstance(right, Class):
244
            return NotImplemented
245
246
        return Class(self._number.__xor__(right._number))

__rxor__

248
    @override
def __rxor__(self, ​​left: Self) -> Self:
250
        Class = type(self)
251
        if not isinstance(left, Class):
252
            return NotImplemented
253
254
        return Class(self._number.__rxor__(left._number))

__ixor__

def __ixor__(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))

__and__

263
    @override
def __and__(self, ​​other: Self) -> Self:
265
        Class = type(self)
266
        if not isinstance(other, Class):
267
            return NotImplemented
268
269
        return Class(self._number.__and__(other._number))

__rand__

271
    @override
def __rand__(self, ​​other: Self) -> Self:
273
        Class = type(self)
274
        if not isinstance(other, Class):
275
            return NotImplemented
276
277
        return Class(self._number.__rand__(other._number))

__or__

279
    @override
def __or__(self, ​​other: Self) -> Self:
281
        Class = type(self)
282
        if not isinstance(other, Class):
283
            return NotImplemented
284
285
        return Class(self._number.__or__(other._number))

__ror__

287
    @override
def __ror__(self, ​​other: Self) -> Self:
289
        Class = type(self)
290
        if not isinstance(other, Class):
291
            return NotImplemented
292
293
        return Class(self._number.__ror__(other._number))

__neg__

295
    @override
def __neg__(self) -> int:
297
        return -self._number

__pos__

299
    @override
def __pos__(self) -> Self:
301
        return type(self)(self._number)

__invert__

303
    @override
def __invert__(self) -> Self:
306
        raise NotImplementedError()

__floor__

308
    @override
def __floor__(self) -> Self:
310
        return type(self)(self)

__ceil__

312
    @override
def __ceil__(self) -> Self:
314
        return type(self)(self)

__int__

316
    @override
def __int__(self) -> int:
318
        return self._number

__eq__

320
    @override
def __eq__(self, ​​other: object) -> bool:
328
        if isinstance(other, Unsigned):
329
            return self._number == other._number
330
        elif isinstance(other, SupportsInt):
331
            other_int = int(other)
332
            if other != other_int:
333
                # If `other` doesn't equal `int(other)`, `self` definitely
334
                # doesn't equal `other` since `self` has to be an integer.
335
                return False
336
            return self._number == other_int
337
        return NotImplemented

__le__

339
    @override
def __le__(self, ​​other: Self) -> bool:
341
        Class = type(self)
342
        if not isinstance(other, Class):
343
            return NotImplemented
344
345
        return self._number <= other._number

__ge__

def __ge__(self, ​​other: Self) -> bool:
348
        Class = type(self)
349
        if not isinstance(other, Class):
350
            return NotImplemented
351
352
        return self._number >= other._number

__lt__

354
    @override
def __lt__(self, ​​other: Self) -> bool:
356
        Class = type(self)
357
        if not isinstance(other, Class):
358
            return NotImplemented
359
360
        return self._number < other._number

__gt__

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

__round__

369
    @override
def __round__(self, ​​ndigits: Optional[int]) -> Self:
371
        return type(self)(self)

__trunc__

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

__rshift__

377
    @override
def __rshift__(self, ​​right: Self) -> Self:
379
        Class = type(self)
380
        if not isinstance(right, Class):
381
            return NotImplemented
382
383
        return Class(self._number >> right._number)

__rrshift__

385
    @override
def __rrshift__(self, ​​left: Self) -> Self:
387
        Class = type(self)
388
        if not isinstance(left, Class):
389
            return NotImplemented
390
391
        return Class(self._number.__rrshift__(left._number))

__lshift__

393
    @override
def __lshift__(self, ​​right: Self) -> Self:
395
        Class = type(self)
396
        if not isinstance(right, Class):
397
            return NotImplemented
398
399
        return Class(self._number << right._number)

__rlshift__

401
    @override
def __rlshift__(self, ​​left: Self) -> Self:
403
        Class = type(self)
404
        if not isinstance(left, Class):
405
            return NotImplemented
406
407
        return Class(self._number.__rlshift__(left._number))

__hash__

409
    @override
def __hash__(self) -> int:
412
        return hash((type(self), self._number))

__repr__

414
    @override
def __repr__(self) -> str:
416
        return "{}({})".format(type(self).__name__, self._number)

__str__

418
    @override
def __str__(self) -> str:
420
        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:
423
        """
424
        Converts this unsigned integer into its big endian representation with
425
        exactly 64 bytes.
426
        """
427
        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:
430
        """
431
        Converts this unsigned integer into its big endian representation
432
        with exactly 32 bytes.
433
        """
434
        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:
437
        """
438
        Converts this unsigned integer into a byte sequence with exactly 1
439
        bytes.
440
        """
441
        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":
444
        """
445
        Converts this unsigned integer into its little endian representation,
446
        with exactly 4 bytes.
447
        """
448
        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":
451
        """
452
        Converts this unsigned integer into its big endian representation, with
453
        exactly 4 bytes.
454
        """
455
        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":
458
        """
459
        Converts this fixed sized unsigned integer into its little endian
460
        representation, with exactly 8 bytes.
461
        """
462
        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":
465
        """
466
        Converts this unsigned integer into its big endian representation, with
467
        exactly 8 bytes.
468
        """
469
        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:
476
        """
477
        Return an array of bytes representing an integer.
478
        """
479
        if length is None:
480
            length_int = 1
481
        else:
482
            length_int = int(length)
483
        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":
486
        """
487
        Converts this unsigned integer into its big endian representation,
488
        without padding.
489
        """
490
        bit_length = self._number.bit_length()
491
        byte_length = (bit_length + 7) // 8
492
        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":
495
        """
496
        Converts this unsigned integer into its little endian representation,
497
        without padding.
498
        """
499
        bit_length = self._number.bit_length()
500
        number_bytes = (bit_length + 7) // 8
501
        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:
504
        """
505
        Converts this unsigned integer into its little endian representation
506
        with exactly 32 bytes.
507
        """
508
        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:
511
        """
512
        Converts this unsigned integer into its little endian representation
513
        with exactly 64 bytes.
514
        """
515
        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":
518
        """
519
        Minimum number of bits required to represent this number in binary.
520
        """
521
        return Uint(self._number.bit_length())

Uint

Unsigned integer of arbitrary size.

class Uint:

from_be_bytes

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

529
    @classmethod
def from_be_bytes(cls: Type[Self], ​​buffer: _BytesLike) -> Self:
531
        """
532
        Converts a sequence of bytes into an arbitrarily sized unsigned integer
533
        from its big endian representation.
534
        """
535
        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.

537
    @classmethod
def from_le_bytes(cls: Type[Self], ​​buffer: _BytesLike) -> Self:
539
        """
540
        Converts a sequence of bytes into an arbitrarily sized unsigned integer
541
        from its little endian representation.
542
        """
543
        return cls(int.from_bytes(buffer, "little"))

_in_range

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

ulen

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

def ulen(input: Sized, ​​/) -> Uint:
551
    """
552
    Return the number of items in a container, as a `Uint`.
553
    """
554
    return Uint(len(input))

FixedUnsigned

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

class FixedUnsigned:

MAX_VALUE

563
    MAX_VALUE: ClassVar[Self]

from_be_bytes

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

568
    @classmethod
def from_be_bytes(cls: Type[Self], ​​buffer: _BytesLike) -> Self:
570
        """
571
        Converts a sequence of bytes into a fixed sized unsigned integer
572
        from its big endian representation.
573
        """
574
        bits = cls.MAX_VALUE._number.bit_length()
575
        byte_count = (bits + 7) // 8
576
        if len(buffer) > byte_count:
577
            raise ValueError()
578
579
        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.

581
    @classmethod
def from_le_bytes(cls: Type[Self], ​​buffer: _BytesLike) -> Self:
583
        """
584
        Converts a sequence of bytes into a fixed sized unsigned integer
585
        from its little endian representation.
586
        """
587
        bits = cls.MAX_VALUE._number.bit_length()
588
        byte_count = (bits + 7) // 8
589
        if len(buffer) > byte_count:
590
            raise ValueError()
591
592
        return cls(int.from_bytes(buffer, "little"))

from_signed

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

594
    @classmethod
def from_signed(cls: Type[Self], ​​value: int) -> Self:
596
        """
597
        Creates an unsigned integer representing `value` using two's
598
        complement.
599
        """
600
        if value >= (cls.MAX_VALUE._number // 2 + 1):
601
            raise OverflowError
602
603
        if value >= 0:
604
            return cls(value)
605
606
        if value < (-cls.MAX_VALUE // 2):
607
            raise OverflowError
608
609
        return cls(value & cls.MAX_VALUE._number)

_in_range

611
    @override
def _in_range(self, ​​value: int) -> bool:
613
        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:
616
        """
617
        Return a new instance containing `self + right (mod N)`.
618
        """
619
        Class = type(self)
620
        if not isinstance(right, Class):
621
            raise TypeError()
622
623
        # This is a fast way of ensuring that the result is < (2 ** 256)
624
        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:
627
        """
628
        Return a new instance containing `self - right (mod N)`.
629
        """
630
        Class = type(self)
631
        if not isinstance(right, Class):
632
            raise TypeError()
633
634
        # This is a fast way of ensuring that the result is < (2 ** 256)
635
        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:
638
        """
639
        Return a new instance containing `self * right (mod N)`.
640
        """
641
        Class = type(self)
642
        if not isinstance(right, Class):
643
            raise TypeError
644
645
        # This is a fast way of ensuring that the result is < (2 ** 256)
646
        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:
649
        """
650
        Return a new instance containing `self ** right (mod modulo)`.
651
652
        If omitted, `modulo` defaults to `Uint(self.MAX_VALUE) + 1`.
653
        """
654
        Class = type(self)
655
        modulo_int = None
656
        if modulo is not None:
657
            if not isinstance(modulo, Class):
658
                raise TypeError()
659
            modulo_int = modulo._number
660
661
        if not isinstance(right, Class):
662
            raise TypeError()
663
664
        # This is a fast way of ensuring that the result is < (2 ** 256)
665
        return Class(
666
            self._number.__pow__(right._number, modulo_int)
667
            & self.MAX_VALUE._number
668
        )

__invert__

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

to_signed

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

def to_signed(self) -> int:
677
        """
678
        Decodes a signed integer from its two's complement representation.
679
        """
680
        bits = self.MAX_VALUE._number.bit_length()
681
        bits = 8 * ((bits + 7) // 8)
682
        if self._number.bit_length() < bits:
683
            # This means that the sign bit is 0
684
            return int(self)
685
686
        # -1 * (2's complement of value)
687
        return int(self) - (self.MAX_VALUE._number + 1)

_V

690
_V = TypeVar("_V", bound=FixedUnsigned)

_max_value

def _max_value(class_: Type[_V], ​​bits: int) -> _V:
694
    value = object.__new__(class_)
695
    value._number = (2**bits) - 1  # type: ignore[misc]
696
    return value

U256

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

class U256:

MAX_VALUE

704
    MAX_VALUE: ClassVar["U256"]

U256.MAX_VALUE

710
U256.MAX_VALUE = _max_value(U256, 256)

U8

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

class U8:

MAX_VALUE

719
    MAX_VALUE: ClassVar["U8"]

U8.MAX_VALUE

725
U8.MAX_VALUE = _max_value(U8, 8)

U32

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

class U32:

MAX_VALUE

734
    MAX_VALUE: ClassVar["U32"]

U32.MAX_VALUE

740
U32.MAX_VALUE = _max_value(U32, 32)

U64

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

class U64:

MAX_VALUE

749
    MAX_VALUE: ClassVar["U64"]

U64.MAX_VALUE

755
U64.MAX_VALUE = _max_value(U64, 64)