ethereum

package module
v0.0.5 Latest Latest
Warning

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

Go to latest
Published: Apr 17, 2025 License: MIT Imports: 23 Imported by: 0

README

ethereum-sdk

Ethereum SDK is used to interact with the Ethereum blockchain or Evm blockchains, it contains various functions can be used to web3 wallet.

Installation

go get

To obtain the latest version, simply require the project using :

go get -u github.com/sonr-io/coins/ethereum

Usage

New Address
	p, _ := hex.DecodeString("559376194bb4c9a9dfb33fde4a2ab15daa8a899a3f43dee787046f57d5f7b10a")
	prvKey, _ := btcec.PrivKeyFromBytes(p)
	address := GetNewAddress(prvKey.PubKey())
	addr, err := PubKeyToAddr(prvKey.PubKey().SerializeUncompressed())
	if err != nil {
		// todo
	}
Transfer
	transaction := NewEthTransaction(
		big.NewInt(int64(00)),
		big.NewInt(int64(420000)),
		big.NewInt(int64(200000000000)),
		big.NewInt(int64(100000000000000000)),
		"0x1ca96f8cfe7276bb053b25e57188f1b5ec6a4728", "0x",
	)
	hash, raw, _ := transaction.GetSigningHash(big.NewInt(int64(10)))
	tx, err := transaction.SignTransaction(big.NewInt(int64(10)), prvKey)
	if err != nil {
		// todo
	}
Transfer Token
	transfer, _ := token.Transfer("0x1ca96f8cfe7276bb053b25e57188f1b5ec6a4728", big.NewInt(int64(100000000000000000)))
	transaction := NewEthTransaction(
		big.NewInt(int64(00)),
		big.NewInt(int64(420000)),
		big.NewInt(int64(200000000000)),
		big.NewInt(int64(0)),
		"0x1ca96f8cfe7276bb053b25e57188f1b5ec6a4728", hex.EncodeToString(transfer),
	)
	tx, err := transaction.SignTransaction(big.NewInt(int64(10)), prvKey)
	if err != nil {
		// todo
	}
Sign message

    prv := "49c0722d56d6bac802bdf5c480a17c870d1d18bc4355d8344aa05390eb778280"
    prvB, err := hex.DecodeString(prv)
    assert.NoError(t, err)
    msg := "0x49c0722d56d6bac802bdf5c480a17c870d1d18bc4355d8344aa05390eb778280"
    prvKey, pub := btcec.PrivKeyFromBytes(prvB)
    sig, err := SignEthTypeMessage(msg, prvKey, true)   //true means using the format "\x19Ethereum Signed Message:\n%d%s"
	if err != nil {
	// todo
	}

Verify Signed message
    sig:="d87758593e0b89f8a2deef5e053ce484fe971a75124bf5d89d6f4d4f586604120d0110d03c91260fec9ec917354caae50c1744d246e30ff48def277d7d9aec831b"
    msg:="0x49c0722d56d6bac802bdf5c480a17c870d1d18bc4355d8344aa05390eb778280"
    addr:="0xd74c65ad81aa8537327e9ba943011a8cec7a7b6b"
    err := VerifySignMsg(sig, msg, addr, true) //true means using the format "\x19Ethereum Signed Message:\n%d%s"
    if err != nil {
        // todo
    }

EIP712
    var typedData TypedData
    str := `{"domain":{"name":"AuthTransfer","chainId":1,"verifyingContract":"0x1243C09717e4441341472c4b142B8ac0B71F7672"},"message":{"details":[{"token":"0x0000000000000000000000000000000000000000","expiration":1853395200}],"spenders":["0x1B256B89462710a6b459540B999AbE5771d45A6e"],"nonce":0},"primaryType":"Permits","types":{"EIP712Domain":[{"name":"name","type":"string"},{"name":"chainId","type":"uint256"},{"name":"verifyingContract","type":"address"}],"Permits":[{"name":"details","type":"PermitDetails[]"},{"name":"spenders","type":"address[]"},{"name":"nonce","type":"uint256"}],"PermitDetails":[{"name":"token","type":"address"},{"name":"expiration","type":"uint256"}]}}`
    err := json.Unmarshal([]byte(str), &typedData)
    assert.NoError(t, err)
    hash, str2, err := TypedDataAndHash(typedData)
	if err != nil {
	// todo
	}
Dynamic Fee Tx
	tx := NewEthDynamicFeeTx(big.NewInt(int64(11155111)),
        16,
        big.NewInt(int64(420000)),
        big.NewInt(int64(20000000000)),
        420000,
        big.NewInt(int64(1234)), "2de4898dd458d6dce097e29026d446300e3815fa", "", AccessList{})
    p, _ := hex.DecodeString("5dfce364a4e9020d1bc187c9c14060e1a2f8815b3b0ceb40f45e7e39eb122103")
    prvKey, _ := btcec.PrivKeyFromBytes(p)
    txStr, err := tx.SignTransaction(prvKey)
    if err != nil {
        // todo
    }

Credits This project includes code adapted from the following sources:

If you are the original author and would like credit adjusted, please contact us.

License

Most packages or folder are MIT licensed, see package or folder for the respective license.

Documentation

Index

Constants

View Source
const AddressLength = 20
View Source
const DynamicFeeTxType = 0x02
View Source
const MessagePrefixTmp = "\u0019Ethereum Signed Message:\n%d"

Variables

View Source
var (
	ErrEmptyString   = &decError{"empty hex string"}
	ErrSyntax        = &decError{"invalid hex string"}
	ErrMissingPrefix = &decError{"hex string without 0x prefix"}
	ErrOddLength     = &decError{"hex string of odd length"}
	ErrUint64Range   = &decError{"hex number > 64 bits"}
)

Errors

View Source
var (
	ErrInvalidParam = errors.New("invalid param")
)
View Source
var (
	ErrInvalidSignature = errors.New("invalid signature")
)

Functions

func BigPow

func BigPow(a, b int64) *big.Int

BigPow returns a ** b as a big integer.

func CalTxHash

func CalTxHash(signedTxHex string) (string, error)

func Decode

func Decode(input string) ([]byte, error)

func DecodeTx

func DecodeTx(rawTx string) (string, error)

func DecodeTxNonce

func DecodeTxNonce(signedTxHex string) (uint64, error)

func EIP712Hash

func EIP712Hash(typedData TypedData) string

func EIP712HashWithTypedDataHash

func EIP712HashWithTypedDataHash(domainSeparatorHex, typedDataHashHex string) string

func EIP712ParamsHash

func EIP712ParamsHash(typedData TypedData) string

func EcRecover

func EcRecover(signature, message string, addPrefix bool) (string, error)

func EcRecoverPubKey

func EcRecoverPubKey(signature, message string, addPrefix bool) (*btcec.PublicKey, error)

func FromHex

func FromHex(s string) []byte

FromHex returns the bytes represented by the hexadecimal string s. s may be prefixed with "0x".

func GenerateRawTransactionWithSignature

func GenerateRawTransactionWithSignature(txType int, chainId, unsignedRawTx, r, s, v string) (string, error)

GenerateRawTransactionWithSignature Generate the transaction to be broadcast based on the unsigned transaction and the signature result

func GetAddress

func GetAddress(pubkeyHex string) string

func GetEthGroupAddress

func GetEthGroupAddress(prefix string, pubKey *btcec.PublicKey) string

func GetEthGroupPubHash

func GetEthGroupPubHash(pubKey *btcec.PublicKey) []byte

func GetEthereumMessagePrefix

func GetEthereumMessagePrefix(message string) string

func GetNewAddress

func GetNewAddress(pubKey *btcec.PublicKey) string

func GetNewAddressBytes

func GetNewAddressBytes(pubKey *btcec.PublicKey) []byte

func HasHexPrefix

func HasHexPrefix(str string) bool

func Hex2Bytes

func Hex2Bytes(str string) []byte

Hex2Bytes returns the bytes represented by the hexadecimal string str.

func IsEthHexAddress

func IsEthHexAddress(s string) bool

func IsHex

func IsHex(str string) bool

func IsHexAddress

func IsHexAddress(s string) bool

IsHexAddress verifies whether a string can represent a valid hex-encoded Ethereum address or not.

func MessageHash

func MessageHash(data string) string

func NewEip1559Transaction

func NewEip1559Transaction(
	chainId *big.Int,
	nonce uint64,
	maxPriorityFeePerGas *big.Int,
	maxFeePerGas *big.Int,
	gasLimit uint64,
	to *common.Address,
	value *big.Int,
	data []byte) *types.Transaction

func OnlyRemovePrefix

func OnlyRemovePrefix(s string) string

func PaddedBigBytes

func PaddedBigBytes(bigint *big.Int, n int) []byte

PaddedBigBytes encodes a big integer as a big-endian byte slice. The length of the slice is at least n bytes.

func PubKeyToAddr

func PubKeyToAddr(publicKey []byte) (string, error)

func ReadBits

func ReadBits(bigint *big.Int, buf []byte)

ReadBits encodes the absolute value of bigint as big-endian bytes. Callers must ensure that buf has enough space. If buf is too short the result will be incomplete.

func SignEthTypeMessage

func SignEthTypeMessage(message string, prvKey *btcec.PrivateKey, addPrefix bool) (string, error)

func TypedDataAndHash

func TypedDataAndHash(typedData TypedData) ([]byte, string, error)

TypedDataAndHash is a helper function that calculates a hash for typed data conforming to EIP-712. This hash can then be safely used to calculate a signature.

See https://eips.ethereum.org/EIPS/eip-712 for the full specification.

This gives context to the signed typed data and prevents signing of transactions.

func U256

func U256(x *big.Int) *big.Int

U256 encodes as a 256 bit two's complement number. This operation is destructive.

func U256Bytes

func U256Bytes(n *big.Int) []byte

U256Bytes converts a big Int into a 256bit EVM number. This operation is destructive.

func ValidateAddress

func ValidateAddress(address string) bool

func VerifySignMsg

func VerifySignMsg(signature, message, address string, addPrefix bool) error

Types

type AccessList

type AccessList []AccessTuple

type AccessTuple

type AccessTuple struct {
	Address     []byte `json:"address"     gencodec:"required"`
	StorageKeys []Hash `json:"storageKeys" gencodec:"required"`
}

AccessTuple is the element type of an access list.

type Address

type Address [20]byte

Address represents the 20 byte address of an Ethereum account.

func BigToAddress

func BigToAddress(b *big.Int) Address

BigToAddress returns Address with byte values of b. If b is larger than len(h), b will be cropped from the left.

func BytesToAddress

func BytesToAddress(b []byte) Address

BytesToAddress returns Address with value b. If b is larger than len(h), b will be cropped from the left.

func HexToAddress

func HexToAddress(s string) Address

HexToAddress returns Address with byte values of s. If s is larger than len(h), s will be cropped from the left.

func (Address) Bytes

func (a Address) Bytes() []byte

Bytes gets the string representation of the underlying address.

func (Address) Hex

func (a Address) Hex() string

Hex returns an EIP55-compliant hex string representation of the address.

func (*Address) SetBytes

func (a *Address) SetBytes(b []byte)

func (Address) String

func (a Address) String() string

String implements fmt.Stringer.

type DynamicFeeTx

type DynamicFeeTx struct {
	ChainID    *big.Int `json:"chainId"`
	Nonce      uint64   `json:"nonce"`
	GasTipCap  *big.Int `json:"gasTipCap"` // a.k.a. maxPriorityFeePerGas
	GasFeeCap  *big.Int `json:"gasFeeCap"` // a.k.a. maxFeePerGas
	Gas        uint64   `json:"gas"`
	To         *Address `json:"to"` // nil means contract creation
	Value      *big.Int `json:"value"`
	Data       []byte   `json:"data"`
	AccessList AccessList

	// Signature values
	V *big.Int `json:"v" gencodec:"required"`
	R *big.Int `json:"r" gencodec:"required"`
	S *big.Int `json:"s" gencodec:"required"`
}

DynamicFeeTx represents an EIP-1559 transaction.

func NewEthDynamicFeeTx

func NewEthDynamicFeeTx(chainId *big.Int, nonce uint64, gasTipCap, gasFeeCap *big.Int, gas uint64, value *big.Int, to,
	data string, accessList AccessList) *DynamicFeeTx

func (*DynamicFeeTx) Hash

func (tx *DynamicFeeTx) Hash() (string, error)

func (*DynamicFeeTx) SignTransaction

func (tx *DynamicFeeTx) SignTransaction(prvKey *btcec.PrivateKey) (string, error)

type EIP1559Transaction

type EIP1559Transaction struct {
	Transaction
	TxType               int    `json:"txType"`
	MaxFeePerGas         string `json:"maxFeePerGas"`
	MaxPriorityFeePerGas string `json:"maxPriorityFeePerGas"`
}

type Eip1559Token

type Eip1559Token struct {
	EIP1559Transaction
	ContractAddress string `json:"contract_address"`
	Amount          string `json:"amount"`
}

type Eip1559Transaction

type Eip1559Transaction struct {
	ChainId    *big.Int         `json:"chainId"`
	Nonce      uint64           `json:"nonce"`
	GasTipCap  *big.Int         `json:"gasTipCap"`
	GasFeeCap  *big.Int         `json:"gasFeeCap"`
	Gas        uint64           `json:"gas"`
	To         *common.Address  `json:"to"`
	Value      *big.Int         `json:"value"`
	Data       []byte           `json:"data"`
	AccessList types.AccessList `json:"accessList"`
}

type EthTransaction

type EthTransaction struct {
	Nonce    *big.Int `json:"nonce"`
	GasPrice *big.Int `json:"gasPrice"`
	GasLimit *big.Int `json:"gas"`
	To       []byte   `json:"to"`
	Value    *big.Int `json:"value"`
	Data     []byte   `json:"data"`
	// Signature values
	V *big.Int `json:"v"`
	R *big.Int `json:"r"`
	S *big.Int `json:"s"`
}

func NewEthTransaction

func NewEthTransaction(nonce, gasLimit, gasPrice, value *big.Int, to, data string) *EthTransaction

func NewTransactionFromRaw

func NewTransactionFromRaw(raw string) (*EthTransaction, error)

func (*EthTransaction) GetSigningHash

func (tx *EthTransaction) GetSigningHash(chainId *big.Int) (string, string, error)

func (*EthTransaction) Hash

func (tx *EthTransaction) Hash() (string, error)

func (*EthTransaction) SignTransaction

func (tx *EthTransaction) SignTransaction(chainId *big.Int, prvKey *btcec.PrivateKey) (string, error)

func (*EthTransaction) SignedTx

func (tx *EthTransaction) SignedTx(chainId *big.Int, sig *SignatureData) (string, error)

func (*EthTransaction) UnSignedTx

func (tx *EthTransaction) UnSignedTx(chainId *big.Int) (string, error)

type Hash

type Hash [32]byte

type NameValueType

type NameValueType struct {
	Name  string      `json:"name"`
	Value interface{} `json:"value"`
	Typ   string      `json:"type"`
}

NameValueType is a very simple struct with Name, Value and Type. It's meant for simple json structures used to communicate signing-info about typed data with the UI

func (*NameValueType) Pprint

func (nvt *NameValueType) Pprint(depth int) string

Pprint returns a pretty-printed version of nvt

type SignatureData

type SignatureData struct {
	V *big.Int
	R *big.Int
	S *big.Int

	ByteV byte
	ByteR []byte
	ByteS []byte
}

func NewSignatureData

func NewSignatureData(msgHash []byte, publicKey string, r, s *big.Int) (*SignatureData, error)

func SignAsRecoverable

func SignAsRecoverable(value []byte, prvKey *btcec.PrivateKey) (*SignatureData, error)

func SignMessage

func SignMessage(message []byte, prvKey *btcec.PrivateKey) (*SignatureData, error)

func SignMessageEIP1559

func SignMessageEIP1559(message []byte, prvKey *btcec.PrivateKey) (*SignatureData, error)

func (SignatureData) ToBytes

func (sd SignatureData) ToBytes() []byte

func (*SignatureData) ToHex

func (sd *SignatureData) ToHex() string

type Transaction

type Transaction struct {
	Nonce    string `json:"nonce"`
	GasLimit string `json:"gasLimit"`
	GasPrice string `json:"gasPrice"`
	From     string `json:"from"`
	To       string `json:"to"`
	Value    string `json:"value"`
	Data     string `json:"data"`
	Fee      string `json:"fee"`
	ChainId  string `json:"chainId"`
}

type Type

type Type struct {
	Name string `json:"name"`
	Type string `json:"type"`
}

type TypePriority

type TypePriority struct {
	Type  string
	Value uint
}

type TypedData

type TypedData struct {
	Types       Types            `json:"types"`
	PrimaryType string           `json:"primaryType"`
	Domain      TypedDataDomain  `json:"domain"`
	Message     TypedDataMessage `json:"message"`
}

func (*TypedData) Dependencies

func (typedData *TypedData) Dependencies(primaryType string, found []string) []string

Dependencies returns an array of custom types ordered by their hierarchical reference tree

func (*TypedData) EncodeData

func (typedData *TypedData) EncodeData(primaryType string, data map[string]interface{}, depth int) ([]byte, error)

EncodeData generates the following encoding: `enc(value₁) ‖ enc(value₂) ‖ … ‖ enc(valueₙ)`

each encoded member is 32-byte long

func (*TypedData) EncodePrimitiveValue

func (typedData *TypedData) EncodePrimitiveValue(encType string, encValue interface{}, depth int) ([]byte, error)

EncodePrimitiveValue deals with the primitive values found while searching through the typed data

func (*TypedData) EncodeType

func (typedData *TypedData) EncodeType(primaryType string) hexutil.Bytes

EncodeType generates the following encoding: `name ‖ "(" ‖ member₁ ‖ "," ‖ member₂ ‖ "," ‖ … ‖ memberₙ ")"`

each member is written as `type ‖ " " ‖ name` encodings cascade down and are sorted by name

func (*TypedData) Format

func (typedData *TypedData) Format() ([]*NameValueType, error)

Format returns a representation of typedData, which can be easily displayed by a user-interface without in-depth knowledge about 712 rules

func (*TypedData) HashStruct

func (typedData *TypedData) HashStruct(primaryType string, data TypedDataMessage) ([]byte, error)

HashStruct generates a keccak256 hash of the encoding of the provided data

func (*TypedData) Map

func (typedData *TypedData) Map() map[string]interface{}

Map generates a map version of the typed data

func (*TypedData) TypeHash

func (typedData *TypedData) TypeHash(primaryType string) []byte

TypeHash creates the keccak256 hash of the data

type TypedDataDomain

type TypedDataDomain struct {
	Name              string   `json:"name"`
	Version           string   `json:"version"`
	ChainId           *big.Int `json:"chainId"`
	VerifyingContract string   `json:"verifyingContract"`
	Salt              string   `json:"salt"`
}

func (*TypedDataDomain) Map

func (domain *TypedDataDomain) Map() map[string]interface{}

Map is a helper function to generate a map version of the domain

type TypedDataMessage

type TypedDataMessage = map[string]interface{}

type Types

type Types map[string][]Type

type UnsignedTx

type UnsignedTx struct {
	Tx   string `json:"tx"`
	Hash string `json:"hash"`
}

func GenerateTxWithJSON

func GenerateTxWithJSON(message string, chainId *big.Int, isToken bool) (*UnsignedTx, error)

generate tx with json param

func NewUnsignedTx

func NewUnsignedTx(nonce, gasLimit, gasPrice, value, chainId *big.Int, to, data string) (*UnsignedTx, error)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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