int256

package module
v0.0.0-alpha Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 21, 2026 License: BSD-3-Clause Imports: 6 Imported by: 0

README

int256

Fixed-size signed integer math library represented as a 256-bit absolute value plus a sign bit.

This package wraps uint256 to support arithmetic on negative values while keeping a fixed-size 256-bit magnitude.

Values are stored in signed-magnitude form:

type Int struct {
    abs uint256.Int
    neg bool
}

Operations are defined on the signed integer value. Bitwise operations and arithmetic right shift follow math/big signed integer semantics, not raw bitwise operations on abs.

This is not Solidity/EVM int256 two's-complement arithmetic: bit 255 is not the sign bit, values are not interpreted as 256-bit EVM words, and the sign is stored separately in neg.

Example usage:

Expanding a number to 18 decimals
x := int256.NewInt(123)
decimal18 := int256.MustFromDecimal("1000000000000000000")
xExpanded := new(int256.Int).Mul(x, decimal18)

fmt.Printf("%s expanded to 18 decimals is: %s", x.String(), xExpanded.String())
Mostly correct implementation of UniSwap V3 getTickAtSqrtRatio using both uint256 and int256
var (
    ErrInvalidSqrtRatio = errors.New("invalid sqrt ratio")
    MinSqrtRatio        = uint256.MustFromDecimal("4295128739")
    MaxSqrtRatio        = uint256.MustFromDecimal("1461446703485210103287273052203988822378723970342")
    magicSqrt10001      = int256.MustFromDecimal("255738958999603826347141")
    magicTickLow        = int256.MustFromDecimal("3402992956809132418596140100660247210")
    magicTickHigh       = int256.MustFromDecimal("291339464771989622907027621153398088495")
)

func GetTickAtSqrtRatio(sqrtPriceX96 *uint256.Int) (tick int, err error) {
    if sqrtPriceX96.Cmp(MinSqrtRatio) < 0 || sqrtPriceX96.Cmp(MaxSqrtRatio) >= 0 {
        return 0, fmt.Errorf("%w: %v", ErrInvalidSqrtRatio, sqrtPriceX96)
    }
    ratio := new(int256.Int).Lsh(int256.MustFromBig(sqrtPriceX96.ToBig()), 32)

    msb := ratio.MostSignificantBit()
    var r *int256.Int
    if msb >= 128 {
        r = new(int256.Int).Rsh(ratio, uint(msb-127))
    } else {
        r = new(int256.Int).Lsh(ratio, uint(127-msb))
    }
    log2 := new(int256.Int).Lsh(int256.NewInt(int64(int(msb)-128)), 64)

    for i := 0; i < 14; i++ {
        r = new(int256.Int).Rsh(new(int256.Int).Mul(r, r), 127)
        f := new(int256.Int).Rsh(r, 128)
        log2 = new(int256.Int).Or(log2, new(int256.Int).Lsh(f, uint(63-i)))
        r = new(int256.Int).Rsh(r, uint(f.Int64()))
    }

    logSqrt10001 := new(int256.Int).Mul(log2, magicSqrt10001)

    tickLow := new(int256.Int).Rsh(new(int256.Int).Sub(logSqrt10001, magicTickLow), 128).Int64()
    tickHigh := new(int256.Int).Rsh(new(int256.Int).Add(logSqrt10001, magicTickHigh), 128).Int64()

    if tickLow == tickHigh {
        return int(tickLow), nil
    }
	
    // GetSqrtRatioAtTick to be implemented by the user
    sqrtRatio, err := GetSqrtRatioAtTick(int(tickHigh))
    if err != nil {
        return 0, err
    }
    if sqrtRatio.Cmp(sqrtPriceX96) <= 0 {
        return int(tickHigh), nil
    } else {
        return int(tickLow), nil
    }
}
Json Marshaling/UnMarshaling example
type TickInfo struct {
    Initialized  bool
    LiquidityNet *int256.Int
}

type Pool struct {
    PoolAddress *common.Address
    Ticks       map[int]*TickInfo
}

func main() {
    tick1Info := &TickInfo{
        Initialized:  true,
        LiquidityNet: int256.MustFromDecimal("-111000000000000000000000000000000000099990"),
    }

    tick2Info := &TickInfo{
        Initialized:  true,
        LiquidityNet: int256.MustFromDecimal("1110000000000440000000000000000000000099990"),
    }
    ticks := make(map[int]*TickInfo)
    ticks[100] = tick2Info
    ticks[-100] = tick1Info
    poolAddr := common.HexToAddress("0x0000000000000000000000000000000000000000")
    pool := &Pool{
        PoolAddress: &poolAddr,
        Ticks:       ticks,
    }
    data, err := json.Marshal(pool)
    if err != nil {
        fmt.Println(err)
    } else {
        // {"PoolAddress":"0x0000000000000000000000000000000000000000","Ticks":{"-100":{"Initialized":true,"LiquidityNet":"-111000000000000000000000000000000000099990"},"100":{"Initialized":true,"LiquidityNet":"1110000000000440000000000000000000000099990"}}}
        fmt.Println(string(data))
    }
    newPool := &Pool{}
    poolData := "{\"PoolAddress\":\"0x0000000000000000000000000000000000000000\",\"Ticks\":{\"-100\":{\"Initialized\":true,\"LiquidityNet\":\"-111000000000000000000000000000000000099990\"},\"100\":{\"Initialized\":true,\"LiquidityNet\":\"1110000000000440000000000000000000000099990\"}}}"
    err = json.Unmarshal([]byte(poolData), &newPool)
    if err != nil {
        fmt.Println(err)
    } else {
		// -111000000000000000000000000000000000099990
        fmt.Println(newPool.Ticks[-100].LiquidityNet.String())
		// 1110000000000440000000000000000000000099990
        fmt.Println(newPool.Ticks[100].LiquidityNet.String())
    }
}

License

This project is licensed under the BSD-3-Clause license.

Portions are derived from linhbkhn95/int256, licensed under MIT, and holiman/uint256, licensed under BSD-3-Clause. See THIRD_PARTY_NOTICES.md.

Documentation

Overview

Package int256: Fixed-size signed integer math library represented as a 256-bit absolute value plus a sign bit. Copyright (c) 2023 Trịnh Đức Bảo Linh(Kevin) Copyright 2018-2020 uint256 Authors Copyright (c) 2026 0xsimulacra SPDX-License-Identifier: MIT AND BSD-3-Clause

Package int256: Fixed-size signed integer math library represented as a 256-bit absolute value plus a sign bit. Copyright 2018-2020 uint256 Authors Copyright (c) 2026 0xsimulacra SPDX-License-Identifier: BSD-3-Clause

Package int256: Fixed-size signed integer math library represented as a 256-bit absolute value plus a sign bit. Copyright (c) 2023 Trịnh Đức Bảo Linh(Kevin) Copyright 2018-2020 uint256 Authors Copyright (c) 2026 0xsimulacra SPDX-License-Identifier: MIT AND BSD-3-Clause

Package int256: Fixed-size signed integer math library represented as a 256-bit absolute value plus a sign bit. Copyright (c) 2023 Trịnh Đức Bảo Linh(Kevin) Copyright (c) 2026 0xsimulacra SPDX-License-Identifier: MIT AND BSD-3-Clause

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrMultipleSignAtStart = errors.New("multiple sign at the beginning")
)

Functions

This section is empty.

Types

type Int

type Int struct {
	// contains filtered or unexported fields
}

Int Fixed-size signed integer math library represented as a 256-bit absolute value plus a sign bit.

This is not Solidity/EVM int256 two's-complement arithmetic: bit 255 is not the sign bit, values are not interpreted as 256-bit EVM words, and the sign is stored separately in neg.

func CondRef

func CondRef(c bool, x, y *Int) *Int

CondRef return either x or y based on the condition c (c ? x : y)

func FromBig

func FromBig(x *big.Int) (*Int, bool)

func FromDecimal

func FromDecimal(decimal string) (*Int, error)

FromDecimal is a convenience-constructor to create an Int from a decimal (base 10) string. Numbers larger than 256 bits are not accepted.

func FromHex

func FromHex(hex string) (*Int, error)

FromHex is a convenience-constructor to create an Int from a hexadecimal string. The string is required to be '0x' or "-0x"-prefixed Numbers larger than 256 bits are not accepted.

func FromUInt256

func FromUInt256(x *uint256.Int) *Int

FromUInt256 create a int256.Int from a uint256.Int

func MustFromBig

func MustFromBig(x *big.Int) *Int

func MustFromDecimal

func MustFromDecimal(decimal string) *Int

MustFromDecimal is a convenience-constructor to create an Int from a decimal (base 10) string. Returns a new Int and panics if any error occurred.

func MustFromHex

func MustFromHex(hex string) *Int

MustFromHex is a convenience-constructor to create an Int from a hexadecimal string. Returns a new Int and panics if any error occurred.

func New

func New() *Int

func NewInt

func NewInt(x int64) *Int

NewInt allocates and returns a new Int set to x.

func (*Int) Abs

func (z *Int) Abs() *uint256.Int

Abs Absolute value of z having the type uint256.Int

func (*Int) AbsInt

func (z *Int) AbsInt() *Int

AbsInt Absolute value of z having the same type int256.Int

func (*Int) Add

func (z *Int) Add(x, y *Int) *Int

func (*Int) And

func (z *Int) And(x, y *Int) *Int

And sets z = x & y and returns z.

func (*Int) Clone

func (z *Int) Clone() *Int

Clone method creates a deep copy of Int

func (*Int) Cmp

func (z *Int) Cmp(x *Int) (r int)

Cmp compares x and y and returns:

-1 if x <  y
 0 if x == y
+1 if x >  y

func (*Int) CmpU

func (z *Int) CmpU(x *uint256.Int) int

CmpU compares z (Int) and x(Uint) and returns:

-1 if z <  x
 0 if z == x
+1 if z >  x

func (*Int) Dec

func (z *Int) Dec() string

Dec returns the decimal representation of z.

func (*Int) Div

func (z *Int) Div(x, y *Int) *Int

func (*Int) Eq

func (z *Int) Eq(x *Int) bool

Eq returns true if z == x

func (*Int) Exp

func (z *Int) Exp(x, y, m *Int) *Int

Exp sets z = x**y mod |m| (i.e. the sign of m is ignored), and returns z. If m == nil or m == 0, z = x**y unless y <= 0 then z = 1. If m != 0, y < 0, and x and m are not relatively prime, z is unchanged and nil is returned.

Modular exponentiation of inputs of a particular size is not a cryptographically constant-time operation.

func (*Int) Hex

func (z *Int) Hex() string

Hex encodes z in 0x-prefixed or -0x-prefixed hexadecimal form.

func (*Int) InPlaceNegate

func (z *Int) InPlaceNegate() *Int

InPlaceNegate transform the sign of z to its opposite

func (*Int) Int64

func (z *Int) Int64() int64

func (*Int) IsZero

func (z *Int) IsZero() bool

IsZero returns true if z == 0

func (*Int) Lsh

func (z *Int) Lsh(x *Int, n uint) *Int

Lsh sets z = x << n and returns z.

func (*Int) MarshalJSON

func (z *Int) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler. MarshalJSON marshals using the 'decimal string' representation. This is _not_ compatible with big.Int: big.Int marshals into JSON 'native' numeric format.

The JSON native format is, on some platforms, (e.g. javascript), limited to 53-bit large integer space. Thus, U256 uses string-format, which is not compatible with big.int (big.Int refuses to unmarshal a string representation).

func (*Int) MarshalText

func (z *Int) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler MarshalText marshals using the decimal representation

func (*Int) MostSignificantBit

func (z *Int) MostSignificantBit() uint8

MostSignificantBit return the most significant bit of z, ignoring the bit or the sign

func (*Int) Mul

func (z *Int) Mul(x, y *Int) *Int

Mul sets z to the product x*y and returns z.

func (*Int) MulDivOverflow

func (z *Int) MulDivOverflow(x, y, d *Int) (*Int, bool)

MulDivOverflow calculates (x*y)/d with full precision, returns z and whether overflow occurred in multiply process (result does not fit to 256-bit). computes 512-bit multiplication and 512 by 256 division.

func (*Int) Negate

func (z *Int) Negate() *Int

Negate return a new int256.Int equal to the negative of z

func (*Int) Or

func (z *Int) Or(x, y *Int) *Int

Or sets z = x | y and returns z.

func (*Int) Quo

func (z *Int) Quo(x, y *Int) *Int

Quo sets z to the quotient x/y for y != 0 and returns z. If y == 0, a division-by-zero run-time panic occurs. Quo implements truncated division (like Go); see QuoRem for more details.

func (*Int) Relu

func (z *Int) Relu() *Int

Relu function (x > 0 ? x : 0)

func (*Int) Rem

func (z *Int) Rem(x, y *Int) *Int

Rem sets z to the remainder x%y for y != 0 and returns z. If y == 0, a division-by-zero run-time panic occurs. Rem implements truncated modulus (like Go); see QuoRem for more details.

func (*Int) Rsh

func (z *Int) Rsh(x *Int, n uint) *Int

Rsh sets z = x >> n and returns z.

func (*Int) Set

func (z *Int) Set(x *Int) *Int

Set sets z to x and returns z

func (*Int) SetFromDecimal

func (z *Int) SetFromDecimal(decimal string) (err error)

SetFromDecimal sets z from the given string, interpreted as a decimal number. OBS! This method is _not_ strictly identical to the (*big.Int).SetString(..., 10) method. Notable differences: - This method does not accept underscore input, e.g. "100_000"

func (*Int) SetFromHex

func (z *Int) SetFromHex(hex string) error

SetFromHex sets z from the given string, interpreted as a hexadecimal number. OBS! This method is _not_ strictly identical to the (*big.Int).SetString(..., 16) method. Notable differences: - This method _require_ "0x", "0X", "-0x" or "-0X" prefix. - This method does not accept zero-prefixed hex, e.g. "0x0001" - This method does not accept underscore input, e.g. "100_000", - negative value should be prefixed with "-" like "-0x0"

func (*Int) SetInt64

func (z *Int) SetInt64(x int64) *Int

SetInt64 sets z to x and returns z.

func (*Int) SetString

func (z *Int) SetString(s string) (*Int, error)

func (*Int) SetUint64

func (z *Int) SetUint64(x uint64) *Int

SetUint64 sets z to x and returns z.

func (*Int) Sign

func (z *Int) Sign() int

Sign returns:

-1 if x <  0
 0 if x == 0
+1 if x >  0

func (*Int) Signed

func (z *Int) Signed(a, b *Int) *Int

Signed z with the value equal to a but the sign of b

func (*Int) SignedMaxAbs

func (z *Int) SignedMaxAbs(a, b, c *Int) *Int

SignedMaxAbs take the maximum of abs of a and b and return z with that value but the sign of c

func (*Int) Sqrt

func (z *Int) Sqrt(x *Int) *Int

Sqrt sets z to ⌊√x⌋, the largest integer such that z² ≤ x, and returns z. It panics if x is negative.

func (*Int) String

func (z *Int) String() string

String returns the decimal encoding of z

func (*Int) Sub

func (z *Int) Sub(x, y *Int) *Int

Sub sets z to the difference x-y and returns z.

func (*Int) TempAbs

func (z *Int) TempAbs() *uint256.Int

TempAbs Absolute value of z having the type uint256.Int without cloning it

func (*Int) ToBig

func (z *Int) ToBig() *big.Int

func (*Int) UnmarshalJSON

func (z *Int) UnmarshalJSON(input []byte) error

UnmarshalJSON implements json.Unmarshaler. UnmarshalJSON accepts either - Quoted string: either hexadecimal OR decimal - For hexadecimal, the input _must_ be prefixed with -0x, -0X, 0x or 0X - Not quoted string: only decimal

func (*Int) UnmarshalText

func (z *Int) UnmarshalText(input []byte) error

UnmarshalText implements encoding.TextUnmarshaler. This method can unmarshal either hexadecimal or decimal. - For hexadecimal, the input _must_ be prefixed with -0x, -0X, 0x or 0X

func (*Int) Value

func (z *Int) Value() (driver.Value, error)

Value implements the database/sql/driver Valuer interface. It encodes a base 10 string. In Postgres, this will work with both integer and the Numeric/Decimal types In MariaDB/MySQL, this will work with the Numeric/Decimal types up to 65 digits, however any more and you should use either VarChar or Char(79) In SqLite, use TEXT

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL