starknet

package module
v0.0.0-...-61460eb Latest Latest
Warning

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

Go to latest
Published: Apr 12, 2024 License: MIT Imports: 17 Imported by: 0

README

starknet-sdk

Starknet SDK is used to interact with the Starknet blockchain, 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/okx/go-wallet-sdk/coins/starknet

Usage

New Address
	curve := SC()
	starkPub, _ := GetPubKey(curve, "0x01651242558d251b0daa72cdf11feb1713e47eb88fb55d0978a2625445a771ac")
	calculateAddress, err := CalculateContractAddressFromHash(starkPub)
	if err != nil {
		// todo
	}
	preAddress := BigToHexWithPadding(calculateAddress)
Transfer
	curve := SC()
	contractAddr := ETHBridge
	from := "0x076a18ceb1638b364b2bccd7652b3d024b0192b6cd97932d7a25638cd0c38cc3"
	maxFee := big.NewInt(1864315586779310)
	nonce := big.NewInt(2)
	functionName := "initiate_withdraw"
	calldata := []string{"0x62e206b4ddd402056d881ded58c0bd87193d2913", "0x38d7ea4c68000"}
	tx, err := CreateSignedContractTx(curve, contractAddr, from, functionName, calldata, nonce, maxFee, MAINNET_ID, "0x01651242558d251b0daa72cdf11feb1713e47eb88fb55d0978a2625445a771ac")
	if err != nil {
		// todo
	}

License

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

Documentation

Index

Constants

View Source
const (
	//todo put your account class hash
	AccountClassHash = "0x309c042d3729173c7f2f91a34f04d8c509c1b292d334679ef1aabf8da0899cc"
	//todo put your proxy account class hash
	ProxyAccountClassHash = "0x3530cc4759d78042f1b543bf797f5f3d647cde0388c33734cf91b7f7b9314a9"
)
View Source
const (
	TransactionTypeDeploy        = "DEPLOY"
	TransactionTypeInvoke        = "INVOKE_FUNCTION"
	TransactionTypeDeployAccount = "DEPLOY_ACCOUNT"

	GOERLI_ID  = "SN_GOERLI"
	MAINNET_ID = "SN_MAIN"

	EXECUTE_SELECTOR = "__execute__"

	TRANSACTION_PREFIX  string = "invoke"
	DEPLOY_ACCOUNT      string = "deploy_account"
	TRANSACTION_VERSION int64  = 1
)
View Source
const ETH = "0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7"
View Source
const ETHBridge = "0x073314940630fd6dcda0d772d4c972c4e0a9946bef9dabf4ef84eda8ef542b82"
View Source
const PEDERSEN_PARAMS string = `` /* 102707-byte string literal not displayed */

* https://github.com/NethermindEth/starknet.go/blob/main/LICENSE

MIT License

Copyright (c) 2021 Don't Panic DAO

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Although the library adheres to the 'elliptic/curve' interface.
All testing has been done against library function explicity.
It is recommended to use in the same way(i.e. `curve.Sign` and not `ecdsa.Sign`).
View Source
const USDT = "0x068f5c6a61780768455de69077e07e89787839bf8166decfbf92b645209c0fb8"

Variables

This section is empty.

Functions

func BigToHex

func BigToHex(in *big.Int) string

convert big int to hexidecimal string

func BigToHexWithPadding

func BigToHexWithPadding(in *big.Int) string

func BytesToBig

func BytesToBig(bytes []byte) *big.Int

func CalculateContractAddressFromHash

func CalculateContractAddressFromHash(starkPub string) (hash *big.Int, err error)

func CompressCompiledContract

func CompressCompiledContract(program map[string]interface{}) (string, error)

func ComputeFact

func ComputeFact(programHash *big.Int, programOutputs []*big.Int) *big.Int

func ComputeHashOnElements

func ComputeHashOnElements(elems []*big.Int) (hash *big.Int, err error)

func DivMod

func DivMod(n, m, p *big.Int) *big.Int

Finds a nonnegative integer 0 <= x < p such that (m * x) % p == n

(ref: https://github.com/starkware-libs/cairo-lang/blob/master/src/starkware/crypto/starkware/crypto/signature/math_utils.py)

func FmtExecuteCalldata

func FmtExecuteCalldata(txs []Transaction) (calldataArray []*big.Int)

func FmtExecuteCalldataStrings

func FmtExecuteCalldataStrings(txs []Transaction) (calldataStrings []string)

func FmtKecBytes

func FmtKecBytes(in *big.Int, rolen int) (buf []byte)

func GetPubKey

func GetPubKey(curve StarkCurve, privKey string) (string, error)

func GetPubKeyPoint

func GetPubKeyPoint(curve StarkCurve, privKey string) (string, error)

func GetSelectorFromName

func GetSelectorFromName(funcName string) *big.Int

func GetTxHash

func GetTxHash(txStr string) (string, error)

func HexToBN

func HexToBN(hexString string) (*big.Int, error)

trim "0x" prefix(if exists) and converts hexidecimal string to big int

func HexToBig

func HexToBig(in string) *big.Int

convert hexidecimal string to big int

func HexToBytes

func HexToBytes(hexString string) ([]byte, error)

trim "0x" prefix(if exists) and converts hexidecimal string to byte slice

func HexToShortStr

func HexToShortStr(hexStr string) string

func InitCurve

func InitCurve()

Not all operations require a stark curve initialization including the provided constant points. Here you can initialize the curve without the constant points

func InitWithConstants

func InitWithConstants(path string) error

Various starknet functions require constant points be initialized. In this case use 'InitWithConstants'. Given an empty string this will init the curve by pulling the 'pedersen_params.json' file from Starkware official github repository. For production deployments it is recommended to have the file stored locally.

func Keccak256

func Keccak256(data ...[]byte) []byte

Keccak256 calculates and returns the Keccak256 hash of the input data. (ref: https://github.com/ethereum/go-ethereum/blob/master/crypto/crypto.go)

func MaskBits

func MaskBits(mask, wordSize int, slice []byte) (ret []byte)

func NewKeyPair

func NewKeyPair(curve StarkCurve) (priv, pub string, err error)

func OldFmtExecuteCalldata

func OldFmtExecuteCalldata(nonce *big.Int, txs []Transaction) (calldataArray []*big.Int)

func SignMsg

func SignMsg(curve StarkCurve, msg string, privKey string) (string, error)

func SignTx

func SignTx(curve StarkCurve, tx signTx, privKeyHex string) error

func SplitFactStr

func SplitFactStr(fact string) (fact_low, fact_high string)

func StrToBig

func StrToBig(str string) *big.Int

convert decimal string to big int

func UTF8StrToBig

func UTF8StrToBig(str string) *big.Int

convert utf8 string to big int

func ValidAddress

func ValidAddress(address string) bool

Types

type ABI

type ABI struct {
	Members []struct {
		Name   string `json:"name"`
		Offset int    `json:"offset"`
		Type   string `json:"type"`
	} `json:"members,omitempty"`
	Inputs []struct {
		Name string `json:"name"`
		Type string `json:"type"`
	} `json:"inputs"`
	Name    string `json:"name"`
	Outputs []struct {
		Name string `json:"name"`
		Type string `json:"type"`
	} `json:"outputs"`
	Type            string `json:"type"`
	Size            int    `json:"size,omitempty"`
	StateMutability string `json:"stateMutability,omitempty"`
}

type Calls

type Calls struct {
	ContractAddress string   `json:"contract_address"`
	Entrypoint      string   `json:"entry_point_selector"`
	Calldata        []string `json:"calldata"`
}

type ContractDefinition

type ContractDefinition struct {
	ABI               []ABI                  `json:"abi"`
	EntryPointsByType EntryPointsByType      `json:"entry_points_by_type"`
	Program           map[string]interface{} `json:"program"`
}

type DeployTransaction

type DeployTransaction struct {
	Type                string     `json:"type"`
	ContractAddressSalt *big.Int   `json:"contract_address_salt"`
	ConstructorCalldata []*big.Int `json:"constructor_calldata"`
	ClassHash           *big.Int   `json:"class_hash"`
	MaxFee              *big.Int   `json:"max_fee"`
	Version             *big.Int   `json:"version"`
	Nonce               *big.Int   `json:"nonce"`
	Signature           []*big.Int `json:"signature"`
	TransactionHash     *big.Int   `json:"-"`
}

func CreateDeployAccountTx

func CreateDeployAccountTx(starkPub string, nonce, maxFee *big.Int, chainId string) (*DeployTransaction, error)

func CreateSignedDeployAccountTx

func CreateSignedDeployAccountTx(curve StarkCurve, starkPub string, nonce, maxFee *big.Int, chainId string, privateKey string) (*DeployTransaction, error)

func (*DeployTransaction) GetDeployAccountReq

func (d *DeployTransaction) GetDeployAccountReq() DeployTransactionReq

func (*DeployTransaction) GetDeployAccountReqWithOutSign

func (d *DeployTransaction) GetDeployAccountReqWithOutSign() DeployTransactionReq

func (*DeployTransaction) GetTxHash

func (d *DeployTransaction) GetTxHash() *big.Int

func (*DeployTransaction) SetSignature

func (d *DeployTransaction) SetSignature(x, y *big.Int)

func (*DeployTransaction) UnmarshalJSON

func (d *DeployTransaction) UnmarshalJSON(data []byte) error

type DeployTransactionReq

type DeployTransactionReq struct {
	Type                string   `json:"type"`
	ContractAddressSalt string   `json:"contract_address_salt"`
	ConstructorCalldata []string `json:"constructor_calldata"`
	ClassHash           string   `json:"class_hash"`
	MaxFee              string   `json:"max_fee"`
	Version             string   `json:"version"`
	Nonce               string   `json:"nonce"`
	Signature           []string `json:"signature"`
}

type EntryPointsByType

type EntryPointsByType struct {
	Constructor []struct {
		Offset   string `json:"offset"`
		Selector string `json:"selector"`
	} `json:"CONSTRUCTOR"`
	External []struct {
		Offset   string `json:"offset"`
		Selector string `json:"selector"`
	} `json:"EXTERNAL"`
	L1Handler []interface{} `json:"L1_HANDLER"`
}

type FunctionInvocation

type FunctionInvocation struct {
	ContractAddress    string   `json:"contract_address"`
	Calldata           []string `json:"calldata"`
	EntryPointSelector string   `json:"entry_point_selector"`
}

type KeccakState

type KeccakState interface {
	hash.Hash
	Read([]byte) (int, error)
}

KeccakState wraps sha3.state. In addition to the usual hash methods, it also supports Read to get a variable amount of data from the hash state. Read is faster than Sum because it doesn't copy the internal state, but also modifies the internal state.

func NewKeccakState

func NewKeccakState() KeccakState

NewKeccakState creates a new KeccakState (ref: https://github.com/ethereum/go-ethereum/blob/master/crypto/crypto.go)

type OldTransactionRequest

type OldTransactionRequest struct {
	Type               string   `json:"type"`
	ContractAddress    string   `json:"contract_address"`
	Calldata           []string `json:"calldata"`
	EntryPointSelector string   `json:"entry_point_selector"`
	MaxFee             string   `json:"max_fee"`
	Signature          []string `json:"signature,omitempty"`
}

type Params

type Params struct {
	FunctionInvocation FunctionInvocation `json:"function_invocation"`
	Signature          []string           `json:"signature"`
	MaxFee             string             `json:"max_fee"`
	Version            string             `json:"version"`
}

type StarkCurve

type StarkCurve struct {
	*elliptic.CurveParams
	EcGenX           *big.Int
	EcGenY           *big.Int
	MinusShiftPointX *big.Int
	MinusShiftPointY *big.Int
	Max              *big.Int
	Alpha            *big.Int
	ConstantPoints   [][]*big.Int
}

Returned stark curve includes several values above and beyond what the 'elliptic' interface calls for to facilitate common starkware functions

func SC

func SC() StarkCurve

func SCWithConstants

func SCWithConstants(path string) (StarkCurve, error)

func (StarkCurve) Add

func (sc StarkCurve) Add(x1, y1, x2, y2 *big.Int) (x, y *big.Int)

Gets two points on an elliptic curve mod p and returns their sum. Assumes affine form (x, y) is spread (x1 *big.Int, y1 *big.Int)

(ref: https://github.com/starkware-libs/cairo-lang/blob/master/src/starkware/crypto/starkware/crypto/signature/math_utils.py)

func (StarkCurve) Double

func (sc StarkCurve) Double(x1, y1 *big.Int) (x, y *big.Int)

Doubles a point on an elliptic curve with the equation y^2 = x^3 + alpha*x + beta mod p. Assumes affine form (x, y) is spread (x1 *big.Int, y1 *big.Int)

(ref: https://github.com/starkware-libs/cairo-lang/blob/master/src/starkware/crypto/starkware/crypto/signature/math_utils.py)

func (StarkCurve) EcMult

func (sc StarkCurve) EcMult(m, x1, y1 *big.Int) (x, y *big.Int)

Multiplies by m a point on the elliptic curve with equation y^2 = x^3 + alpha*x + beta mod p. Assumes affine form (x, y) is spread (x1 *big.Int, y1 *big.Int) and that 0 < m < order(point).

(ref: https://github.com/starkware-libs/cairo-lang/blob/master/src/starkware/crypto/starkware/crypto/signature/math_utils.py)

func (StarkCurve) GenerateSecret

func (sc StarkCurve) GenerateSecret(msgHash, privKey, seed *big.Int) (secret *big.Int)

implementation based on https://github.com/codahale/rfc6979/blob/master/rfc6979.go

func (StarkCurve) GetRandomPrivateKey

func (sc StarkCurve) GetRandomPrivateKey() (priv *big.Int, err error)

obtain random primary key on stark curve NOTE: to be used for testing purposes

func (StarkCurve) GetYCoordinate

func (sc StarkCurve) GetYCoordinate(starkX *big.Int) *big.Int

Given the x coordinate of a stark_key, returns a possible y coordinate such that together the point (x,y) is on the curve. Note: the real y coordinate is either y or -y.

(ref: https://github.com/starkware-libs/cairo-lang/blob/master/src/starkware/crypto/starkware/crypto/signature/signature.py)

func (StarkCurve) HashElements

func (sc StarkCurve) HashElements(elems []*big.Int) (hash *big.Int, err error)

Hashes the contents of a given array using a golang Pedersen Hash implementation.

(ref: https://github.com/seanjameshan/starknet.js/blob/main/src/utils/ellipticCurve.ts)

func (StarkCurve) HashMsg

func (sc StarkCurve) HashMsg(addr *big.Int, tx Transaction) (hash *big.Int, err error)

Adheres to 'starknet.js' hash non typedData

func (StarkCurve) HashMulticall

func (sc StarkCurve) HashMulticall(addr, nonce, maxFee, chainId *big.Int, txs []Transaction) (hash *big.Int, err error)

func (StarkCurve) HashTx

func (sc StarkCurve) HashTx(addr *big.Int, tx Transaction) (hash *big.Int, err error)

Adheres to 'starknet.js' hash non typedData

func (StarkCurve) IsOnCurve

func (sc StarkCurve) IsOnCurve(x, y *big.Int) bool

func (StarkCurve) MimicEcMultAir

func (sc StarkCurve) MimicEcMultAir(mout, x1, y1, x2, y2 *big.Int) (x *big.Int, y *big.Int, err error)

Computes m * point + shift_point using the same steps like the AIR and throws an exception if and only if the AIR errors.

(ref: https://github.com/starkware-libs/cairo-lang/blob/master/src/starkware/crypto/starkware/crypto/signature/signature.py)

func (StarkCurve) OldHashMulticall

func (sc StarkCurve) OldHashMulticall(addr, nonce, maxFee, chainId *big.Int, txs []Transaction) (hash *big.Int, err error)

func (StarkCurve) Params

func (sc StarkCurve) Params() *elliptic.CurveParams

func (StarkCurve) PedersenHash

func (sc StarkCurve) PedersenHash(elems []*big.Int) (hash *big.Int, err error)

Provides the pedersen hash of given array of big integers. NOTE: This function assumes the curve has been initialized with contant points

(ref: https://github.com/seanjameshan/starknet.js/blob/main/src/utils/ellipticCurve.ts)

func (StarkCurve) PrivateToPoint

func (sc StarkCurve) PrivateToPoint(privKey *big.Int) (x, y *big.Int, err error)

obtain public key coordinates from stark curve given the private key

func (StarkCurve) PrivateToPublic

func (sc StarkCurve) PrivateToPublic(privKey *big.Int) (pubKey *big.Int, err error)

func (StarkCurve) ScalarBaseMult

func (sc StarkCurve) ScalarBaseMult(k []byte) (x, y *big.Int)

func (StarkCurve) ScalarMult

func (sc StarkCurve) ScalarMult(x1, y1 *big.Int, k []byte) (x, y *big.Int)

func (StarkCurve) Sign

func (sc StarkCurve) Sign(msgHash, privKey *big.Int, seed ...*big.Int) (x, y *big.Int, err error)

Signs the hash value of contents with the provided private key. Secret is generated using a golang implementation of RFC 6979. Implementation does not yet include "extra entropy" or "retry gen".

(ref: https://datatracker.ietf.org/doc/html/rfc6979)

func (StarkCurve) XToPubKey

func (sc StarkCurve) XToPubKey(x string) (*big.Int, *big.Int)

given x will find corresponding public key coordinate on curve

type StarkCurvePayload

type StarkCurvePayload struct {
	License        []string     `json:"_license"`
	Comment        string       `json:"_comment"`
	FieldPrime     *big.Int     `json:"FIELD_PRIME"`
	FieldGen       int          `json:"FIELD_GEN"`
	EcOrder        *big.Int     `json:"EC_ORDER"`
	Alpha          int64        `json:"ALPHA"`
	Beta           *big.Int     `json:"BETA"`
	ConstantPoints [][]*big.Int `json:"CONSTANT_POINTS"`
}

struct definition for parsing 'pedersen_params.json'

type Transaction

type Transaction struct {
	Type               string     `json:"type"`
	ContractAddress    *big.Int   `json:"contract_address"`
	Calldata           []*big.Int `json:"calldata"`
	EntryPointSelector *big.Int   `json:"entry_point_selector"`
	Nonce              *big.Int   `json:"nonce,omitempty"`
	TransactionHash    *big.Int   `json:"transaction_hash"`
	MaxFee             *big.Int   `json:"max_fee"`
	Signature          []*big.Int `json:"signature"`
	SenderAddress      string     `json:"sender_address"`
}

func CreateContractTx

func CreateContractTx(curve StarkCurve, contractAddr, from, functionName string, callData []string, nonce, maxFee *big.Int, chainId string) (*Transaction, error)

func CreateSignedContractTx

func CreateSignedContractTx(curve StarkCurve, contractAddr, from, functionName string, callData []string, nonce, maxFee *big.Int, chainId string, privateKey string) (*Transaction, error)

func CreateSignedMultiContractTx

func CreateSignedMultiContractTx(curve StarkCurve, from string, calls []Calls, nonce, maxFee *big.Int, chainId string, privateKey string) (*Transaction, error)

func CreateSignedTransferTx

func CreateSignedTransferTx(curve StarkCurve, contractAddr, from, to string, amount, nonce, maxFee *big.Int, chainId string, privKeyHex string) (*Transaction, error)

func CreateSignedUpgradeTx

func CreateSignedUpgradeTx(curve StarkCurve, from string, nonce, maxFee *big.Int, chainId string, privateKey string) (*Transaction, error)

func CreateTransferTx

func CreateTransferTx(curve StarkCurve, contractAddr, from, to string, amount, nonce, maxFee *big.Int, chainId string) (*Transaction, error)

func (Transaction) GetOldTxRequest

func (tx Transaction) GetOldTxRequest() *OldTransactionRequest

func (*Transaction) GetTxHash

func (tx *Transaction) GetTxHash() *big.Int

func (*Transaction) GetTxRequest

func (tx *Transaction) GetTxRequest() *TransactionRequest

func (*Transaction) GetTxRequestWithOutSign

func (tx *Transaction) GetTxRequestWithOutSign() *TransactionRequest

func (*Transaction) SetSignature

func (tx *Transaction) SetSignature(x, y *big.Int)

func (*Transaction) ToJsonRpcParams

func (tx *Transaction) ToJsonRpcParams() string

func (*Transaction) UnmarshalJSON

func (t *Transaction) UnmarshalJSON(data []byte) error

type TransactionJsonRpc

type TransactionJsonRpc struct {
	Jsonrpc string `json:"jsonrpc"`
	Method  string `json:"method"`
	Params  struct {
		FunctionInvocation FunctionInvocation `json:"function_invocation"`
		Signature          []string           `json:"signature"`
		MaxFee             string             `json:"max_fee"`
		Version            string             `json:"version"`
	} `json:"params"`
	Id int `json:"id"`
}

type TransactionRequest

type TransactionRequest struct {
	Type          string   `json:"type"`
	SenderAddress string   `json:"sender_address"`
	Calldata      []string `json:"calldata"`
	MaxFee        string   `json:"max_fee"`
	Signature     []string `json:"signature,omitempty"`
	Version       string   `json:"version"`
	Nonce         string   `json:"nonce"`
}

Jump to

Keyboard shortcuts

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