starkex

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jul 1, 2022 License: MIT, MIT Imports: 20 Imported by: 0

README

stark key authentication library, signature generator for dydx exchange

for the following operations:

  • Place an order
  • Withdraw funds

link : https://docs.dydx.exchange/#authentication

Installation
go get github.com/yanue/starkex
demos
order sign demo
    const MOCK_PRIVATE_KEY = "58c7d5a90b1776bde86ebac077e053ed85b0f7164f53b080304a531947f46e3"
    param := OrderSignParam{
		NetworkId:  NETWORK_ID_ROPSTEN,
		Market:     "ETH-USD",
		Side:       "BUY",
		PositionId: 12345,
		HumanSize:  "145.0005",
		HumanPrice: "350.00067",
		LimitFee:   "0.125",
		ClientId:   "This is an ID that the client came up with to describe this order",
		Expiration: "2020-09-17T04:15:55.028Z",
	}
	sign, err := OrderSign(MOCK_PRIVATE_KEY, param)
	// 00cecbe513ecdbf782cd02b2a5efb03e58d5f63d15f2b840e9bc0029af04e8dd0090b822b16f50b2120e4ea9852b340f7936ff6069d02acca02f2ed03029ace5
	fmt.Println("sign,err", sign, err)
withdraw sign demo
    const MOCK_PRIVATE_KEY = "58c7d5a90b1776bde86ebac077e053ed85b0f7164f53b080304a531947f46e3"
    param := WithdrawSignParam{
		NetworkId:   NETWORK_ID_ROPSTEN,
		PositionId:  12345,
		HumanAmount: "49.478023",
		ClientId:    "This is an ID that the client came up with to describe this withdrawal",
		Expiration:  "2020-09-17T04:15:55.028Z",
	}
	sign, err := WithdrawSign(MOCK_PRIVATE_KEY, param)
	// 05e48c33f8205a5359c95f1bd7385c1c1f587e338a514298c07634c0b6c952ba0687d6980502a5d7fa84ef6fdc00104db22c43c7fb83e88ca84f19faa9ee3de1
	fmt.Println("sign,err", sign, err)
transfer sign demo (fast_withdraw)
    const MOCK_PRIVATE_KEY = "58c7d5a90b1776bde86ebac077e053ed85b0f7164f53b080304a531947f46e3"
    param := TransferSignParam{
		NetworkId:          NETWORK_ID_MAINNET,
		CreditAmount:       "1",
		DebitAmount:        "2",
		SenderPositionId:   12345,
		ReceiverPositionId: 67890,
		ReceiverPublicKey:  "04a9ecd28a67407c3cff8937f329ca24fd631b1d9ca2b9f2df47c7ebf72bf0b0",
		ReceiverAddress:    "0x1234567890123456789012345678901234567890",
		Expiration:         "2020-09-17T04:15:55.028Z",
		ClientId:           "This is an ID that the client came up with to describe this transfer",
	}
	sign, err := TransferSign(MOCK_PRIVATE_KEY, param)
	// 0278aeb361938d4c377950487bb770fc9464bf5352e19117c03243efad4e10a302bb3983e05676c7952caa4acdc1a83426d5c8cb8c56d7f6c477cfdafd37718a
	fmt.Println("sign,err", sign, err)
inspired by

https://github.com/dydxprotocol/dydx-v3-python

https://github.com/starkware-libs/starkex-resources

Documentation

Overview

starkex provides signing and other algorithms for starkex (https://starkware.co/starkex/).

Index

Constants

View Source
const (
	ORDER_PREFIX                = 3
	CONDITIONAL_TRANSFER_PREFIX = 5
	WITHDRAWAL_PREFIX           = 6
)
View Source
const (
	ORDER_PADDING_BITS                = 17
	WITHDRAWAL_PADDING_BITS           = 49
	CONDITIONAL_TRANSFER_PADDING_BITS = 81
)
View Source
const (
	CONDITIONAL_TRANSFER_FEE_ASSET_ID   = 0
	CONDITIONAL_TRANSFER_MAX_AMOUNT_FEE = 0
)
View Source
const (
	NETWORK_ID_MAINNET = 1
	NETWORK_ID_ROPSTEN = 3
)
View Source
const (
	ONE_HOUR_IN_SECONDS                     = 60 * 60
	ORDER_SIGNATURE_EXPIRATION_BUFFER_HOURS = 24 * 7 // Seven days.
)
View Source
const (
	ASSET_ID_MAINNET = "0x02893294412a4c8f915f75892b395ebbf6859ec246ec365c3b1f56f47c3a0a5d"
	ASSET_ID_ROPSTEN = "0x02c04d8b650f44092278a7cb1e1028c82025dff622db96c934b611b84cc8de5a"
)
View Source
const COLLATERAL_ASSET = "USDC"
View Source
const COLLATERAL_TOKEN_DECIMALS = 6
View Source
const (
	// HashLength is the expected length of the hash
	HashLength = 32
)

Lengths of hashes and addresses in bytes.

View Source
const NONCE_UPPER_BOUND_EXCLUSIVE = 1 << 32 // 1 << ORDER_FIELD_BIT_LENGTHS['nonce']

Variables

View Source
var (
	EC_ORDER    = new(big.Int)
	FIELD_PRIME = new(big.Int)
)
View Source
var ASSET_RESOLUTION = map[string]int64{
	"USDC":    1e6,
	"BTC":     1e10,
	"ETH":     1e9,
	"LINK":    1e7,
	"AAVE":    1e8,
	"UNI":     1e7,
	"SUSHI":   1e7,
	"SOL":     1e7,
	"YFI":     1e10,
	"ONEINCH": 1e7,
	"AVAX":    1e7,
	"SNX":     1e7,
	"CRV":     1e6,
	"UMA":     1e7,
	"DOT":     1e7,
	"DOGE":    1e5,
	"MATIC":   1e6,
	"MKR":     1e9,
	"FIL":     1e7,
	"ADA":     1e6,
	"ATOM":    1e7,
	"COMP":    1e8,
	"BCH":     1e8,
	"LTC":     1e8,
	"EOS":     1e6,
	"ALGO":    1e6,
	"ZRX":     1e6,
	"XMR":     1e8,
	"ZEC":     1e8,
}
View Source
var BIT_MASK_250 = big.NewInt(0).Sub(big.NewInt(0).Exp(big.NewInt(2), big.NewInt(250), nil), one)

BIT_MASK_250 (2 ** 250) - 1

View Source
var COLLATERAL_ASSET_ID_BY_NETWORK_ID = map[int]*big.Int{
	NETWORK_ID_MAINNET: mainNet,
	NETWORK_ID_ROPSTEN: ropstenNet,
}
View Source
var CONDITIONAL_TRANSFER_FIELD_BIT_LENGTHS = map[string]uint{
	"asset_id":               250,
	"receiver_public_key":    251,
	"position_id":            64,
	"condition":              251,
	"quantums_amount":        64,
	"nonce":                  32,
	"expiration_epoch_hours": 32,
}
View Source
var FACT_REGISTRY_CONTRACT = map[int]string{
	NETWORK_ID_MAINNET: "0xBE9a129909EbCb954bC065536D2bfAfBd170d27A",
	NETWORK_ID_ROPSTEN: "0x8Fb814935f7E63DEB304B500180e19dF5167B50e",
}
View Source
var N_ELEMENT_BITS_ECDSA = big.NewInt(251)

N_ELEMENT_BITS_ECDSA math.floor(math.log(FIELD_PRIME, 2))

View Source
var ORDER_FIELD_BIT_LENGTHS = map[string]uint{
	"asset_id_synthetic":     128,
	"asset_id_collateral":    250,
	"asset_id_fee":           250,
	"quantums_amount":        64,
	"nonce":                  32,
	"position_id":            64,
	"expiration_epoch_hours": 32,
}
View Source
var SYNTHETIC_ID_MAP = map[string]string{
	"BTC":     "0x4254432d3130000000000000000000",
	"ETH":     "0x4554482d3900000000000000000000",
	"LINK":    "0x4c494e4b2d37000000000000000000",
	"AAVE":    "0x414156452d38000000000000000000",
	"UNI":     "0x554e492d3700000000000000000000",
	"SUSHI":   "0x53555348492d370000000000000000",
	"SOL":     "0x534f4c2d3700000000000000000000",
	"YFI":     "0x5946492d3130000000000000000000",
	"ONEINCH": "0x31494e43482d370000000000000000",
	"AVAX":    "0x415641582d37000000000000000000",
	"SNX":     "0x534e582d3700000000000000000000",
	"CRV":     "0x4352562d3600000000000000000000",
	"UMA":     "0x554d412d3700000000000000000000",
	"DOT":     "0x444f542d3700000000000000000000",
	"DOGE":    "0x444f47452d35000000000000000000",
	"MATIC":   "0x4d415449432d360000000000000000",
	"MKR":     "0x4d4b522d3900000000000000000000",
	"FIL":     "0x46494c2d3700000000000000000000",
	"ADA":     "0x4144412d3600000000000000000000",
	"ATOM":    "0x41544f4d2d37000000000000000000",
	"COMP":    "0x434f4d502d38000000000000000000",
	"BCH":     "0x4243482d3800000000000000000000",
	"LTC":     "0x4c54432d3800000000000000000000",
	"EOS":     "0x454f532d3600000000000000000000",
	"ALGO":    "0x414c474f2d36000000000000000000",
	"ZRX":     "0x5a52582d3600000000000000000000",
	"XMR":     "0x584d522d3800000000000000000000",
	"ZEC":     "0x5a45432d3800000000000000000000",
}
View Source
var TOKEN_CONTRACTS = map[string]map[int]string{
	COLLATERAL_ASSET: {
		NETWORK_ID_MAINNET: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
		NETWORK_ID_ROPSTEN: "0x8707A5bf4C2842d46B31A405Ba41b858C0F876c4",
	},
}
View Source
var WITHDRAWAL_FIELD_BIT_LENGTHS = map[string]uint{
	"asset_id":               250,
	"position_id":            64,
	"nonce":                  32,
	"quantums_amount":        64,
	"expiration_epoch_hours": 32,
}

Functions

func FactToCondition

func FactToCondition(factRegistryAddress string, fact string) *big.Int

FactToCondition Generate the condition, signed as part of a conditional transfer.

func GenerateKRfc6979

func GenerateKRfc6979(msgHash, priKey *big.Int, seed int) *big.Int

func GetTransferErc20Fact

func GetTransferErc20Fact(recipient string, tokenDecimals int, humanAmount, tokenAddress, salt string) (string, error)

GetTransferErc20Fact get erc20 fact tokenDecimals is COLLATERAL_TOKEN_DECIMALS This is taken from the orignal code below: ```

func GetTransferErc20FactOld(recipient string, tokenDecimals int, humanAmount, tokenAddress, salt string) (string, error) {
	fmt.Println("GetTransferErc20Fact", recipient, tokenDecimals, humanAmount, tokenAddress, salt)
	// token_amount = float(human_amount) * (10 ** token_decimals)
	amount, err := decimal.NewFromString(humanAmount)
	if err != nil {
		return "", err
	}
	saltInt, ok := big.NewInt(0).SetString(salt, 0) // with prefix: 0x
	if !ok {
		return "", fmt.Errorf("invalid salt: %v,can not parse to big.Int", salt)
	}
	tokenAmount := amount.Mul(decimal.New(10, int32(tokenDecimals-1)))
	fact := solsha3.SoliditySHA3(
		// types
		[]string{"address", "uint256", "address", "uint256"},
		// values
		[]interface{}{recipient, tokenAmount.String(), tokenAddress, saltInt.String()},
	)
	return hex.EncodeToString(fact), nil
}

```

func IntToHex32

func IntToHex32(x *big.Int) string

IntToHex32 Normalize to a 32-byte hex string without 0x prefix.

func NonceByClientId

func NonceByClientId(clientId string) *big.Int

NonceByClientId generate nonce by clientId

func OrderSign

func OrderSign(starkPrivateKey string, param OrderSignParam) (string, error)

func PedersenHash

func PedersenHash(str ...string) string

func PrivateKeyToEcPointOnStarkCurv

func PrivateKeyToEcPointOnStarkCurv(priv_key *big.Int) (*big.Int, *big.Int, error)

func SerializeSignature

func SerializeSignature(r, s *big.Int) string

SerializeSignature Convert a Sign from an r, s pair to a 32-byte hex string.

func ToJsonString

func ToJsonString(input interface{}) string

func TransferSign

func TransferSign(starkPrivateKey string, param TransferSignParam) (string, error)

func WithdrawSign

func WithdrawSign(starkPrivateKey string, param WithdrawSignParam) (string, error)

Types

type Hash

type Hash [HashLength]byte

Hash represents the 32 byte Keccak256 hash of arbitrary data.

func (Hash) Big

func (h Hash) Big() *big.Int

Big converts a hash to a big integer.

type OrderSignParam

type OrderSignParam struct {
	NetworkId  int    `json:"network_id"` // 1 MAINNET 3 ROPSTEN
	PositionId int64  `json:"position_id"`
	Market     string `json:"market"`
	Side       string `json:"side"`
	HumanSize  string `json:"human_size"`
	HumanPrice string `json:"human_price"`
	LimitFee   string `json:"limit_fee"`
	ClientId   string `json:"clientId"`
	Expiration string `json:"expiration"` // 2006-01-02T15:04:05.000Z
}

type OrderSigner

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

type PedersenCfg

type PedersenCfg struct {
	Comment        string        `json:"_comment"`
	FieldPrime     *big.Int      `json:"FIELD_PRIME"`
	FieldGen       int           `json:"FIELD_GEN"`
	EcOrder        *big.Int      `json:"EC_ORDER"`
	ALPHA          int           `json:"ALPHA"`
	BETA           *big.Int      `json:"BETA"`
	ConstantPoints [][2]*big.Int `json:"CONSTANT_POINTS"`
}

type Signable

type Signable interface {
	// contains filtered or unexported methods
}

type Signer

type Signer struct {
	NetworkId int
	// contains filtered or unexported fields
}

func NewSigner

func NewSigner(starkPrivateKey string) *Signer

func (*Signer) SetNetworkId

func (s *Signer) SetNetworkId(networkId int) *Signer

func (*Signer) SetSigner

func (s *Signer) SetSigner(signer Signable) *Signer

func (*Signer) Sign

func (s *Signer) Sign() (string, error)

func (*Signer) SignOrder

func (s *Signer) SignOrder(param OrderSignParam) (string, error)

func (*Signer) SignTransfer

func (s *Signer) SignTransfer(param TransferSignParam) (string, error)

func (*Signer) SignWithdraw

func (s *Signer) SignWithdraw(param WithdrawSignParam) (string, error)

type TransferSignParam

type TransferSignParam struct {
	NetworkId          int    `json:"network_id"` // 1 MAINNET 3 ROPSTEN
	SenderPositionId   int64  `json:"sender_position_id"`
	ReceiverPositionId int64  `json:"receiver_position_id"`
	ReceiverPublicKey  string `json:"receiver_public_key"`
	ReceiverAddress    string `json:"receiver_address"`
	CreditAmount       string `json:"credit_amount"`
	DebitAmount        string `json:"debit_amount"`
	Expiration         string `json:"expiration"`
	ClientId           string `json:"client_id"`
}

type TransferSigner

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

type WithdrawSignParam

type WithdrawSignParam struct {
	NetworkId   int    `json:"network_id"` // 1 MAINNET 3 ROPSTEN
	PositionId  int64  `json:"position_id"`
	HumanAmount string `json:"human_amount"`
	ClientId    string `json:"clientId"`
	Expiration  string `json:"expiration"` // 2006-01-02T15:04:05.000Z
}

type WithdrawSigner

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

Jump to

Keyboard shortcuts

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