lendingstate

package
v0.0.0-...-7037f4e Latest Latest
Warning

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

Go to latest
Published: Jul 25, 2021 License: GPL-3.0 Imports: 23 Imported by: 0

Documentation

Overview

Package state provides a caching layer atop the Ethereum state trie.

Index

Constants

View Source
const (
	LiquidatedByTime  = uint64(0)
	LiquidatedByPrice = uint64(1)
)

liquidation reasons

View Source
const (
	Investing                  = "INVEST"
	Borrowing                  = "BORROW"
	TopUp                      = "TOPUP"
	Repay                      = "REPAY"
	Recall                     = "RECALL"
	LendingStatusNew           = "NEW"
	LendingStatusOpen          = "OPEN"
	LendingStatusReject        = "REJECTED"
	LendingStatusFilled        = "FILLED"
	LendingStatusPartialFilled = "PARTIAL_FILLED"
	LendingStatusCancelled     = "CANCELLED"
	Market                     = "MO"
	Limit                      = "LO"
)
View Source
const (
	TradeStatusOpen       = "OPEN"
	TradeStatusClosed     = "CLOSED"
	TradeStatusLiquidated = "LIQUIDATED"
)
View Source
const DefaultFeeRate = 100 // 100 / SdxXBaseFee = 100 / 10000 = 1%

Variables

View Source
var (
	EmptyAddress = "0x0000000000000000000000000000000000000000"
	EmptyRoot    = common.HexToHash("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421")
)
View Source
var (
	TokenMappingSlot = map[string]uint64{
		"balances": 0,
	}
	RelayerMappingSlot = map[string]uint64{
		"CONTRACT_OWNER":       0,
		"MaximumRelayers":      1,
		"MaximumTokenList":     2,
		"RELAYER_LIST":         3,
		"RELAYER_COINBASES":    4,
		"RESIGN_REQUESTS":      5,
		"RELAYER_ON_SALE_LIST": 6,
		"RelayerCount":         7,
		"MinimumDeposit":       8,
	}
	RelayerStructMappingSlot = map[string]*big.Int{
		"_deposit":    big.NewInt(0),
		"_fee":        big.NewInt(1),
		"_fromTokens": big.NewInt(2),
		"_toTokens":   big.NewInt(3),
		"_index":      big.NewInt(4),
		"_owner":      big.NewInt(5),
	}
)
View Source
var (
	LendingRelayerListSlot    = uint64(0)
	CollateralMapSlot         = uint64(1)
	DefaultCollateralSlot     = uint64(2)
	SupportedBaseSlot         = uint64(3)
	SupportedTermSlot         = uint64(4)
	ILOCollateralSlot         = uint64(5)
	LendingRelayerStructSlots = map[string]*big.Int{
		"fee":         big.NewInt(0),
		"bases":       big.NewInt(1),
		"terms":       big.NewInt(2),
		"collaterals": big.NewInt(3),
	}
	CollateralStructSlots = map[string]*big.Int{
		"depositRate":     big.NewInt(0),
		"liquidationRate": big.NewInt(1),
		"recallRate":      big.NewInt(2),
		"price":           big.NewInt(3),
	}
	PriceStructSlots = map[string]*big.Int{
		"price":       big.NewInt(0),
		"blockNumber": big.NewInt(1),
	}
)
View Source
var (
	ErrQuantityTradeTooSmall  = errors.New("quantity trade too small")
	ErrInvalidCollateralPrice = errors.New("unable to retrieve price of this collateral. Please try another collateral")
)
View Source
var EmptyHash = common.Hash{}
View Source
var EmptyLendingOrder = LendingItem{
	Quantity: Zero,
}
View Source
var EmptyLendingTrade = LendingTrade{
	Amount: big.NewInt(0),
}
View Source
var MaxTrieCacheGen = uint16(120)

Trie cache generation limit after which to evic trie nodes from memory.

View Source
var One = big.NewInt(1)
View Source
var ValidInputLendingStatus = map[string]bool{
	LendingStatusNew:       true,
	LendingStatusCancelled: true,
}
View Source
var ValidInputLendingType = map[string]bool{
	Market: true,
	Limit:  true,
	Repay:  true,
	TopUp:  true,
	Recall: true,
}
View Source
var Zero = big.NewInt(0)

Functions

func Add

func Add(x, y *big.Int) *big.Int

func AddTokenBalance

func AddTokenBalance(addr common.Address, value *big.Int, token common.Address, statedb *state.StateDB) error

func CalculateInterestRate

func CalculateInterestRate(finalizeTime, liquidationTime, term uint64, apr uint64) *big.Int

apr: annual percentage rate this function returns actual interest rate base on borrowing time and apr I = APR *(T + T1) / 2 / 365 T: term T1: borrowingTime

func CalculateTotalRepayValue

func CalculateTotalRepayValue(finalizeTime, liquidationTime, term uint64, apr uint64, tradeAmount *big.Int) *big.Int

func CheckAddTokenBalance

func CheckAddTokenBalance(addr common.Address, value *big.Int, token common.Address, statedb *state.StateDB, mapBalances map[common.Address]map[common.Address]*big.Int) (*big.Int, error)

func CheckRelayerFee

func CheckRelayerFee(relayer common.Address, fee *big.Int, statedb *state.StateDB) error

func CheckSubRelayerFee

func CheckSubRelayerFee(relayer common.Address, fee *big.Int, statedb *state.StateDB, mapBalances map[common.Address]*big.Int) (*big.Int, error)

func CheckSubTokenBalance

func CheckSubTokenBalance(addr common.Address, value *big.Int, token common.Address, statedb *state.StateDB, mapBalances map[common.Address]map[common.Address]*big.Int) (*big.Int, error)

func CloneBigInt

func CloneBigInt(bigInt *big.Int) *big.Int

func Div

func Div(x, y *big.Int) *big.Int

func EncodeFinalizedResult

func EncodeFinalizedResult(liquidatedTrades, autoRepayTrades, autoTopUpTrades, autoRecallTrades []*LendingTrade) ([]byte, error)

func EncodeTxLendingBatch

func EncodeTxLendingBatch(batch TxLendingBatch) ([]byte, error)

func EtherToWei

func EtherToWei(amount *big.Int) *big.Int

func Exp

func Exp(x, y *big.Int) *big.Int

func GetAllCollateral

func GetAllCollateral(statedb *state.StateDB) []common.Address

@function GetAllCollateral @param statedb : current state @return: list of address of collateral token

func GetAllLendingBooks

func GetAllLendingBooks(statedb *state.StateDB) (mapLendingBook map[common.Hash]bool, err error)

@function GetAllLendingBooks @param statedb : current state @return: a map to specify whether lendingBook (combination of baseToken and term) is valid or not

func GetBaseList

func GetBaseList(statedb *state.StateDB, coinbase common.Address) []common.Address

@function GetBaseList @param statedb : current state @param coinbase: coinbase address of relayer @return: list of base tokens

func GetBaseTokenAtIndex

func GetBaseTokenAtIndex(relayer common.Address, statedb *state.StateDB, index uint64) common.Address

func GetBaseTokenLength

func GetBaseTokenLength(relayer common.Address, statedb *state.StateDB) uint64

func GetCollateralDetail

func GetCollateralDetail(statedb *state.StateDB, token common.Address) (depositRate, liquidationRate, recallRate *big.Int)

@function GetCollateralDetail @param statedb : current state @param token: address of collateral token @return: depositRate, liquidationRate, price of collateral

func GetCollateralPrice

func GetCollateralPrice(statedb *state.StateDB, collateralToken common.Address, lendingToken common.Address) (price, blockNumber *big.Int)

func GetCollaterals

func GetCollaterals(statedb *state.StateDB, coinbase common.Address, baseToken common.Address, term uint64) (collaterals []common.Address, isSpecialCollateral bool)

@function GetCollaterals @param statedb : current state @param coinbase: coinbase address of relayer @param baseToken: address of baseToken @param terms: term @return:

  • collaterals []common.Address : list of addresses of collateral
  • isSpecialCollateral : TRUE if collateral is a token which is NOT available for trading in SdxX, otherwise FALSE

func GetExRelayerFee

func GetExRelayerFee(relayer common.Address, statedb *state.StateDB) *big.Int

func GetFee

func GetFee(statedb *state.StateDB, coinbase common.Address) *big.Int

@function GetFee @param statedb : current state @param coinbase: coinbase address of relayer @return: feeRate of lending

func GetLendingCacheKey

func GetLendingCacheKey(item *LendingItem) common.Hash

func GetLendingItemHistoryKey

func GetLendingItemHistoryKey(lendingToken, collateralToken common.Address, lendingItemHash common.Hash) common.Hash

use orderHash instead of tradeId because both takerOrders don't have tradeId

func GetLendingOrderBookHash

func GetLendingOrderBookHash(lendingToken common.Address, term uint64) common.Hash

func GetLocMappingAtKey

func GetLocMappingAtKey(key common.Hash, slot uint64) *big.Int

func GetQuoteTokenAtIndex

func GetQuoteTokenAtIndex(relayer common.Address, statedb *state.StateDB, index uint64) common.Address

func GetQuoteTokenLength

func GetQuoteTokenLength(relayer common.Address, statedb *state.StateDB) uint64

func GetRelayerOwner

func GetRelayerOwner(relayer common.Address, statedb *state.StateDB) common.Address

func GetSupportedBaseToken

func GetSupportedBaseToken(statedb *state.StateDB) []common.Address

@function GetSupportedBaseToken @param statedb : current state @return: list of tokens which are available for lending

func GetSupportedTerms

func GetSupportedTerms(statedb *state.StateDB) []uint64

@function GetSupportedTerms @param statedb : current state @return: list of terms which sdxxlending supports

func GetTerms

func GetTerms(statedb *state.StateDB, coinbase common.Address) []uint64

@function GetTerms @param statedb : current state @param coinbase: coinbase address of relayer @return: list of supported terms of the given relayer

func GetTokenBalance

func GetTokenBalance(addr common.Address, token common.Address, statedb *state.StateDB) *big.Int

func IsResignedRelayer

func IsResignedRelayer(relayer common.Address, statedb *state.StateDB) bool

return true if relayer request to resign and have not withdraw locked fund

func IsValidPair

func IsValidPair(statedb *state.StateDB, coinbase common.Address, baseToken common.Address, term uint64) (valid bool, pairIndex uint64)

@function IsValidPair @param statedb : current state @param coinbase: coinbase address of relayer @param baseToken: address of baseToken @param terms: term @return: TRUE if the given baseToken, term organize a valid pair

func IsValidRelayer

func IsValidRelayer(statedb *state.StateDB, coinbase common.Address) bool

@function IsValidRelayer : return whether the given address is the coinbase of a valid relayer or not @param statedb : current state @param coinbase: coinbase address of relayer @return: true if it's a valid coinbase address of lending protocol, otherwise return false

func Max

func Max(a, b *big.Int) *big.Int

func Mul

func Mul(x, y *big.Int) *big.Int

func Neg

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

func SetSubRelayerFee

func SetSubRelayerFee(relayer common.Address, balance *big.Int, fee *big.Int, statedb *state.StateDB)

func SetTokenBalance

func SetTokenBalance(addr common.Address, balance *big.Int, token common.Address, statedb *state.StateDB) error

func Sub

func Sub(x, y *big.Int) *big.Int

func SubRelayerFee

func SubRelayerFee(relayer common.Address, fee *big.Int, statedb *state.StateDB) error

func SubTokenBalance

func SubTokenBalance(addr common.Address, value *big.Int, token common.Address, statedb *state.StateDB) error

func ToBigInt

func ToBigInt(s string) *big.Int

func ToJSON

func ToJSON(object interface{}, args ...string) string

ToJSON : log json string

func VerifyBalance

func VerifyBalance(isSdxXLendingFork bool, statedb *state.StateDB, lendingStateDb *LendingStateDB,
	orderType, side, status string, userAddress, relayer, lendingToken, collateralToken common.Address,
	quantity, lendingTokenDecimal, collateralTokenDecimal, lendTokenSDXPrice, collateralPrice *big.Int,
	term uint64, lendingId uint64, lendingTradeId uint64) error

func WeiToEther

func WeiToEther(amount *big.Int) *big.Int

Types

type Database

type Database interface {
	// OpenTrie opens the main account trie.
	OpenTrie(root common.Hash) (Trie, error)

	// OpenStorageTrie opens the storage trie of an account.
	OpenStorageTrie(addrHash, root common.Hash) (Trie, error)

	// CopyTrie returns an independent copy of the given trie.
	CopyTrie(Trie) Trie

	// ContractCode retrieves a particular contract's code.
	ContractCode(addrHash, codeHash common.Hash) ([]byte, error)

	// ContractCodeSize retrieves a particular contracts code's size.
	ContractCodeSize(addrHash, codeHash common.Hash) (int, error)

	// TrieDB retrieves the low level trie database used for data storage.
	TrieDB() *trie.Database
}

Database wraps access to tries and contract code.

func NewDatabase

func NewDatabase(db ethdb.Database) Database

NewDatabase creates a backing store for state. The returned database is safe for concurrent use and retains cached trie nodes in memory. The pool is an optional intermediate trie-node memory pool between the low level storage layer and the high level trie abstraction.

type DumpOrderBookInfo

type DumpOrderBookInfo struct {
	Nonce                 uint64
	TradeNonce            uint64
	BestInvesting         *big.Int
	BestBorrowing         *big.Int
	LowestLiquidationTime *big.Int
}

type DumpOrderList

type DumpOrderList struct {
	Volume *big.Int
	Orders map[*big.Int]*big.Int
}

type FinalizedResult

type FinalizedResult struct {
	Liquidated []common.Hash
	AutoRepay  []common.Hash
	AutoTopUp  []common.Hash
	AutoRecall []common.Hash
	TxHash     common.Hash
	Timestamp  int64
}

func DecodeFinalizedResult

func DecodeFinalizedResult(data []byte) (result FinalizedResult, err error)

type LendingItem

type LendingItem struct {
	Quantity        *big.Int       `bson:"quantity" json:"quantity"`
	Interest        *big.Int       `bson:"interest" json:"interest"`
	Side            string         `bson:"side" json:"side"` // INVESTING/BORROWING
	Type            string         `bson:"type" json:"type"` // LIMIT/MARKET
	LendingToken    common.Address `bson:"lendingToken" json:"lendingToken"`
	CollateralToken common.Address `bson:"collateralToken" json:"collateralToken"`
	AutoTopUp       bool           `bson:"autoTopUp" json:"autoTopUp"`
	FilledAmount    *big.Int       `bson:"filledAmount" json:"filledAmount"`
	Status          string         `bson:"status" json:"status"`
	Relayer         common.Address `bson:"relayer" json:"relayer"`
	Term            uint64         `bson:"term" json:"term"`
	UserAddress     common.Address `bson:"userAddress" json:"userAddress"`
	Signature       *Signature     `bson:"signature" json:"signature"`
	Hash            common.Hash    `bson:"hash" json:"hash"`
	TxHash          common.Hash    `bson:"txHash" json:"txHash"`
	Nonce           *big.Int       `bson:"nonce" json:"nonce"`
	CreatedAt       time.Time      `bson:"createdAt" json:"createdAt"`
	UpdatedAt       time.Time      `bson:"updatedAt" json:"updatedAt"`
	LendingId       uint64         `bson:"lendingId" json:"lendingId"`
	LendingTradeId  uint64         `bson:"tradeId" json:"tradeId"`
	ExtraData       string         `bson:"extraData" json:"extraData"`
}

func (*LendingItem) ComputeHash

func (l *LendingItem) ComputeHash() common.Hash

func (*LendingItem) EncodedSide

func (l *LendingItem) EncodedSide() *big.Int

func (*LendingItem) GetBSON

func (l *LendingItem) GetBSON() (interface{}, error)

func (*LendingItem) SetBSON

func (l *LendingItem) SetBSON(raw bson.Raw) error

func (*LendingItem) VerifyCollateral

func (l *LendingItem) VerifyCollateral(state *state.StateDB) error

func (*LendingItem) VerifyLendingInterest

func (l *LendingItem) VerifyLendingInterest() error

func (*LendingItem) VerifyLendingItem

func (l *LendingItem) VerifyLendingItem(state *state.StateDB) error

func (*LendingItem) VerifyLendingQuantity

func (l *LendingItem) VerifyLendingQuantity() error

func (*LendingItem) VerifyLendingSide

func (l *LendingItem) VerifyLendingSide() error

func (*LendingItem) VerifyLendingSignature

func (l *LendingItem) VerifyLendingSignature() error

verify signatures

func (*LendingItem) VerifyLendingStatus

func (l *LendingItem) VerifyLendingStatus() error

func (*LendingItem) VerifyLendingType

func (l *LendingItem) VerifyLendingType() error

type LendingItemBSON

type LendingItemBSON struct {
	Quantity        string           `bson:"quantity" json:"quantity"`
	Interest        string           `bson:"interest" json:"interest"`
	Side            string           `bson:"side" json:"side"` // INVESTING/BORROWING
	Type            string           `bson:"type" json:"type"` // LIMIT/MARKET
	LendingToken    string           `bson:"lendingToken" json:"lendingToken"`
	CollateralToken string           `bson:"collateralToken" json:"collateralToken"`
	AutoTopUp       bool             `bson:"autoTopUp" json:"autoTopUp"`
	FilledAmount    string           `bson:"filledAmount" json:"filledAmount"`
	Status          string           `bson:"status" json:"status"`
	Relayer         string           `bson:"relayer" json:"relayer"`
	Term            string           `bson:"term" json:"term"`
	UserAddress     string           `bson:"userAddress" json:"userAddress"`
	Signature       *SignatureRecord `bson:"signature" json:"signature"`
	Hash            string           `bson:"hash" json:"hash"`
	TxHash          string           `bson:"txHash" json:"txHash"`
	Nonce           string           `bson:"nonce" json:"nonce"`
	CreatedAt       time.Time        `bson:"createdAt" json:"createdAt"`
	UpdatedAt       time.Time        `bson:"updatedAt" json:"updatedAt"`
	LendingId       string           `bson:"lendingId" json:"lendingId"`
	LendingTradeId  string           `bson:"tradeId" json:"tradeId"`
	ExtraData       string           `bson:"extraData" json:"extraData"`
}

type LendingItemHistoryItem

type LendingItemHistoryItem struct {
	TxHash       common.Hash
	FilledAmount *big.Int
	Status       string
	UpdatedAt    time.Time
}

type LendingManagedState

type LendingManagedState struct {
	*LendingStateDB
	// contains filtered or unexported fields
}

func ManageState

func ManageState(statedb *LendingStateDB) *LendingManagedState

LendingManagedState returns a new managed state with the statedb as it's backing layer

func (*LendingManagedState) GetNonce

func (ms *LendingManagedState) GetNonce(addr common.Hash) uint64

GetNonce returns the canonical nonce for the managed or unmanaged tradeId.

Because GetNonce mutates the DB, we must take a write lock.

func (*LendingManagedState) HasAccount

func (ms *LendingManagedState) HasAccount(addr common.Hash) bool

HasAccount returns whether the given address is managed or not

func (*LendingManagedState) NewNonce

func (ms *LendingManagedState) NewNonce(addr common.Hash) uint64

NewNonce returns the new canonical nonce for the managed tradeId

func (*LendingManagedState) RemoveNonce

func (ms *LendingManagedState) RemoveNonce(addr common.Hash, n uint64)

RemoveNonce removed the nonce from the managed state and all future pending nonces

func (*LendingManagedState) SetNonce

func (ms *LendingManagedState) SetNonce(addr common.Hash, nonce uint64)

SetNonce sets the new canonical nonce for the managed state

func (*LendingManagedState) SetState

func (ms *LendingManagedState) SetState(statedb *LendingStateDB)

SetState sets the backing layer of the managed state

type LendingPair

type LendingPair struct {
	LendingToken    common.Address
	CollateralToken common.Address
}

func GetAllLendingPairs

func GetAllLendingPairs(statedb *state.StateDB) (allPairs []LendingPair, err error)

@function GetAllLendingPairs @param statedb : current state @return: list of lendingPair (combination of baseToken and collateralToken)

type LendingSettleBalance

type LendingSettleBalance struct {
	Taker                  TradeResult
	Maker                  TradeResult
	CollateralLockedAmount *big.Int
}

func GetSettleBalance

func GetSettleBalance(isSdxXLendingFork bool,
	takerSide string,
	lendTokenSDXPrice,
	collateralPrice,
	depositRate,
	borrowFeeRate *big.Int,
	lendingToken,
	collateralToken common.Address,
	lendTokenDecimal,
	collateralTokenDecimal *big.Int,
	quantityToLend *big.Int) (*LendingSettleBalance, error)

func (*LendingSettleBalance) String

func (settleBalance *LendingSettleBalance) String() string

type LendingStateDB

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

func New

func New(root common.Hash, db Database) (*LendingStateDB, error)

Create a new state from a given trie.

func (*LendingStateDB) CancelLendingOrder

func (self *LendingStateDB) CancelLendingOrder(orderBook common.Hash, order *LendingItem) error

func (*LendingStateDB) CancelLendingTrade

func (self *LendingStateDB) CancelLendingTrade(orderBook common.Hash, tradeId uint64) error

func (*LendingStateDB) Commit

func (s *LendingStateDB) Commit() (root common.Hash, err error)

Commit writes the state to the underlying in-memory trie database.

func (*LendingStateDB) Copy

func (self *LendingStateDB) Copy() *LendingStateDB

Copy creates a deep, independent copy of the state. Snapshots of the copied state cannot be applied to the copy.

func (*LendingStateDB) Database

func (self *LendingStateDB) Database() Database

Database retrieves the low level database supporting the lower level trie ops.

func (*LendingStateDB) DumpBorrowingTrie

func (self *LendingStateDB) DumpBorrowingTrie(orderBook common.Hash) (map[*big.Int]DumpOrderList, error)

func (*LendingStateDB) DumpInvestingTrie

func (self *LendingStateDB) DumpInvestingTrie(orderBook common.Hash) (map[*big.Int]DumpOrderList, error)

func (*LendingStateDB) DumpLendingOrderTrie

func (self *LendingStateDB) DumpLendingOrderTrie(orderBook common.Hash) (map[*big.Int]LendingItem, error)

func (*LendingStateDB) DumpLendingTradeTrie

func (self *LendingStateDB) DumpLendingTradeTrie(orderBook common.Hash) (map[*big.Int]LendingTrade, error)

func (*LendingStateDB) DumpLiquidationTimeTrie

func (self *LendingStateDB) DumpLiquidationTimeTrie(orderBook common.Hash) (map[*big.Int]DumpOrderList, error)

func (*LendingStateDB) DumpOrderBookInfo

func (self *LendingStateDB) DumpOrderBookInfo(orderBook common.Hash) (*DumpOrderBookInfo, error)

func (*LendingStateDB) Empty

func (self *LendingStateDB) Empty(addr common.Hash) bool

Empty returns whether the state object is either non-existent or empty according to the EIP161 specification (balance = nonce = code = 0)

func (*LendingStateDB) Error

func (self *LendingStateDB) Error() error

func (*LendingStateDB) Exist

func (self *LendingStateDB) Exist(addr common.Hash) bool

Exist reports whether the given tradeId address exists in the state. Notably this also returns true for suicided lenddinges.

func (*LendingStateDB) Finalise

func (s *LendingStateDB) Finalise()

Finalise finalises the state by removing the self destructed objects and clears the journal as well as the refunds.

func (*LendingStateDB) GetBestBorrowRate

func (self *LendingStateDB) GetBestBorrowRate(orderBook common.Hash) (*big.Int, *big.Int)

func (*LendingStateDB) GetBestInvestingRate

func (self *LendingStateDB) GetBestInvestingRate(orderBook common.Hash) (*big.Int, *big.Int)

func (*LendingStateDB) GetBestLendingIdAndAmount

func (self *LendingStateDB) GetBestLendingIdAndAmount(orderBook common.Hash, price *big.Int, side string) (common.Hash, *big.Int, error)

func (*LendingStateDB) GetBorrowings

func (self *LendingStateDB) GetBorrowings(orderBook common.Hash) (map[*big.Int]*big.Int, error)

func (*LendingStateDB) GetInvestings

func (self *LendingStateDB) GetInvestings(orderBook common.Hash) (map[*big.Int]*big.Int, error)

func (*LendingStateDB) GetLendingOrder

func (self *LendingStateDB) GetLendingOrder(orderBook common.Hash, orderId common.Hash) LendingItem

func (*LendingStateDB) GetLendingTrade

func (self *LendingStateDB) GetLendingTrade(orderBook common.Hash, tradeId common.Hash) LendingTrade

func (*LendingStateDB) GetLowestLiquidationTime

func (self *LendingStateDB) GetLowestLiquidationTime(lendingBook common.Hash, time *big.Int) (*big.Int, []common.Hash)

func (*LendingStateDB) GetNonce

func (self *LendingStateDB) GetNonce(addr common.Hash) uint64

func (*LendingStateDB) GetOrNewLendingExchangeObject

func (self *LendingStateDB) GetOrNewLendingExchangeObject(addr common.Hash) *lendingExchangeState

Retrieve a state object or create a new state object if nil.

func (*LendingStateDB) GetTradeNonce

func (self *LendingStateDB) GetTradeNonce(addr common.Hash) uint64

func (*LendingStateDB) InsertLendingItem

func (self *LendingStateDB) InsertLendingItem(orderBook common.Hash, orderId common.Hash, order LendingItem)

func (*LendingStateDB) InsertLiquidationTime

func (self *LendingStateDB) InsertLiquidationTime(lendingBook common.Hash, time *big.Int, tradeId uint64)

func (*LendingStateDB) InsertTradingItem

func (self *LendingStateDB) InsertTradingItem(orderBook common.Hash, tradeId uint64, order LendingTrade)

func (*LendingStateDB) IntermediateRoot

func (s *LendingStateDB) IntermediateRoot() common.Hash

IntermediateRoot computes the current root orderBook of the state trie. It is called in between transactions to get the root orderBook that goes into transaction receipts.

func (*LendingStateDB) MarkLendingExchangeObjectDirty

func (self *LendingStateDB) MarkLendingExchangeObjectDirty(addr common.Hash)

MarkStateLendObjectDirty adds the specified object to the dirty map to avoid costly state object cache iteration to find a handful of modified ones.

func (*LendingStateDB) RemoveLiquidationTime

func (self *LendingStateDB) RemoveLiquidationTime(lendingBook common.Hash, tradeId uint64, time uint64) error

func (*LendingStateDB) RevertToSnapshot

func (self *LendingStateDB) RevertToSnapshot(revid int)

RevertToSnapshot reverts all state changes made since the given revision.

func (*LendingStateDB) SetNonce

func (self *LendingStateDB) SetNonce(addr common.Hash, nonce uint64)

func (*LendingStateDB) SetTradeNonce

func (self *LendingStateDB) SetTradeNonce(addr common.Hash, nonce uint64)

func (*LendingStateDB) Snapshot

func (self *LendingStateDB) Snapshot() int

Snapshot returns an identifier for the current revision of the state.

func (*LendingStateDB) SubAmountLendingItem

func (self *LendingStateDB) SubAmountLendingItem(orderBook common.Hash, orderId common.Hash, price *big.Int, amount *big.Int, side string) error

func (*LendingStateDB) UpdateCollateralLockedAmount

func (self *LendingStateDB) UpdateCollateralLockedAmount(orderBook common.Hash, tradeId uint64, amount *big.Int)

func (*LendingStateDB) UpdateLiquidationPrice

func (self *LendingStateDB) UpdateLiquidationPrice(orderBook common.Hash, tradeId uint64, price *big.Int)

type LendingTrade

type LendingTrade struct {
	Borrower               common.Address `bson:"borrower" json:"borrower"`
	Investor               common.Address `bson:"investor" json:"investor"`
	LendingToken           common.Address `bson:"lendingToken" json:"lendingToken"`
	CollateralToken        common.Address `bson:"collateralToken" json:"collateralToken"`
	BorrowingOrderHash     common.Hash    `bson:"borrowingOrderHash" json:"borrowingOrderHash"`
	InvestingOrderHash     common.Hash    `bson:"investingOrderHash" json:"investingOrderHash"`
	BorrowingRelayer       common.Address `bson:"borrowingRelayer" json:"borrowingRelayer"`
	InvestingRelayer       common.Address `bson:"investingRelayer" json:"investingRelayer"`
	Term                   uint64         `bson:"term" json:"term"`
	Interest               uint64         `bson:"interest" json:"interest"`
	CollateralPrice        *big.Int       `bson:"collateralPrice" json:"collateralPrice"`
	LiquidationPrice       *big.Int       `bson:"liquidationPrice" json:"liquidationPrice"`
	CollateralLockedAmount *big.Int       `bson:"collateralLockedAmount" json:"collateralLockedAmount"`
	AutoTopUp              bool           `bson:"autoTopUp" json:"autoTopUp"`
	LiquidationTime        uint64         `bson:"liquidationTime" json:"liquidationTime"`
	DepositRate            *big.Int       `bson:"depositRate" json:"depositRate"`
	LiquidationRate        *big.Int       `bson:"liquidationRate" json:"liquidationRate"`
	RecallRate             *big.Int       `bson:"recallRate" json:"recallRate"`
	Amount                 *big.Int       `bson:"amount" json:"amount"`
	BorrowingFee           *big.Int       `bson:"borrowingFee" json:"borrowingFee"`
	InvestingFee           *big.Int       `bson:"investingFee" json:"investingFee"`
	Status                 string         `bson:"status" json:"status"`
	TakerOrderSide         string         `bson:"takerOrderSide" json:"takerOrderSide"`
	TakerOrderType         string         `bson:"takerOrderType" json:"takerOrderType"`
	MakerOrderType         string         `bson:"makerOrderType" json:"makerOrderType"`
	TradeId                uint64         `bson:"tradeId" json:"tradeId"`
	Hash                   common.Hash    `bson:"hash" json:"hash"`
	TxHash                 common.Hash    `bson:"txHash" json:"txHash"`
	ExtraData              string         `bson:"extraData" json:"extraData"`
	CreatedAt              time.Time      `bson:"createdAt" json:"createdAt"`
	UpdatedAt              time.Time      `bson:"updatedAt" json:"updatedAt"`
}

func (*LendingTrade) ComputeHash

func (t *LendingTrade) ComputeHash() common.Hash

func (*LendingTrade) GetBSON

func (t *LendingTrade) GetBSON() (interface{}, error)

func (*LendingTrade) SetBSON

func (t *LendingTrade) SetBSON(raw bson.Raw) error

type LendingTradeBSON

type LendingTradeBSON struct {
	Borrower               string    `bson:"borrower" json:"borrower"`
	Investor               string    `bson:"investor" json:"investor"`
	LendingToken           string    `bson:"lendingToken" json:"lendingToken"`
	CollateralToken        string    `bson:"collateralToken" json:"collateralToken"`
	BorrowingOrderHash     string    `bson:"borrowingOrderHash" json:"borrowingOrderHash"`
	InvestingOrderHash     string    `bson:"investingOrderHash" json:"investingOrderHash"`
	BorrowingRelayer       string    `bson:"borrowingRelayer" json:"borrowingRelayer"`
	InvestingRelayer       string    `bson:"investingRelayer" json:"investingRelayer"`
	Term                   string    `bson:"term" json:"term"`
	Interest               string    `bson:"interest" json:"interest"`
	CollateralPrice        string    `bson:"collateralPrice" json:"collateralPrice"`
	LiquidationPrice       string    `bson:"liquidationPrice" json:"liquidationPrice"`
	LiquidationTime        string    `bson:"liquidationTime" json:"liquidationTime"`
	CollateralLockedAmount string    `bson:"collateralLockedAmount" json:"collateralLockedAmount"`
	AutoTopUp              bool      `bson:"autoTopUp" json:"autoTopUp"`
	DepositRate            string    `bson:"depositRate" json:"depositRate"`
	LiquidationRate        string    `bson:"liquidationRate" json:"liquidationRate"`
	RecallRate             string    `bson:"recallRate" json:"recallRate"`
	Amount                 string    `bson:"amount" json:"amount"`
	BorrowingFee           string    `bson:"borrowingFee" json:"borrowingFee"`
	InvestingFee           string    `bson:"investingFee" json:"investingFee"`
	Status                 string    `bson:"status" json:"status"`
	TakerOrderSide         string    `bson:"takerOrderSide" json:"takerOrderSide"`
	TakerOrderType         string    `bson:"takerOrderType" json:"takerOrderType"`
	MakerOrderType         string    `bson:"makerOrderType" json:"makerOrderType"`
	TradeId                string    `bson:"tradeId" json:"tradeId"`
	Hash                   string    `bson:"hash" json:"hash"`
	TxHash                 string    `bson:"txHash" json:"txHash"`
	ExtraData              string    `bson:"extraData" json:"extraData"`
	UpdatedAt              time.Time `bson:"updatedAt" json:"updatedAt"`
}

type LendingTradeHistoryItem

type LendingTradeHistoryItem struct {
	TxHash                 common.Hash
	CollateralLockedAmount *big.Int
	LiquidationPrice       *big.Int
	Status                 string
	UpdatedAt              time.Time
}

type LiquidationData

type LiquidationData struct {
	RecallAmount      *big.Int
	LiquidationAmount *big.Int
	CollateralPrice   *big.Int
	Reason            uint64
}

type MatchingResult

type MatchingResult struct {
	Trades  []*LendingTrade
	Rejects []*LendingItem
}

type SdxXTrie

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

SdxXTrie wraps a trie with key hashing. In a secure trie, all access operations hash the key using keccak256. This prevents calling code from creating long chains of nodes that increase the access time.

Contrary to a regular trie, a SdxXTrie can only be created with New and must have an attached database. The database also stores the preimage of each key.

SdxXTrie is not safe for concurrent use.

func NewSdxXTrie

func NewSdxXTrie(root common.Hash, db *trie.Database) (*SdxXTrie, error)

NewSdxXTrie creates a trie with an existing root node from a backing database and optional intermediate in-memory node pool.

If root is the zero hash or the sha3 hash of an empty string, the trie is initially empty. Otherwise, New will panic if db is nil and returns MissingNodeError if the root node cannot be found.

Accessing the trie loads nodes from the database or node pool on demand. Loaded nodes are kept around until their 'cache generation' expires. A new cache generation is created by each call to Commit. cachelimit sets the number of past cache generations to keep.

func (*SdxXTrie) Commit

func (t *SdxXTrie) Commit(onleaf trie.LeafCallback) (root common.Hash, err error)

Commit writes all nodes and the secure hash pre-images to the trie's database. Nodes are stored with their sha3 hash as the key.

Committing flushes nodes from memory. Subsequent Get calls will load nodes from the database.

func (*SdxXTrie) Copy

func (t *SdxXTrie) Copy() *SdxXTrie

func (*SdxXTrie) Delete

func (t *SdxXTrie) Delete(key []byte)

Delete removes any existing value for key from the trie.

func (*SdxXTrie) Get

func (t *SdxXTrie) Get(key []byte) []byte

Get returns the value for key stored in the trie. The value bytes must not be modified by the caller.

func (*SdxXTrie) GetKey

func (t *SdxXTrie) GetKey(shaKey []byte) []byte

GetKey returns the sha3 preimage of a hashed key that was previously used to store a value.

func (*SdxXTrie) Hash

func (t *SdxXTrie) Hash() common.Hash

func (*SdxXTrie) NodeIterator

func (t *SdxXTrie) NodeIterator(start []byte) trie.NodeIterator

NodeIterator returns an iterator that returns nodes of the underlying trie. Iteration starts at the key after the given start key.

func (*SdxXTrie) Prove

func (t *SdxXTrie) Prove(key []byte, fromLevel uint, proofDb ethdb.KeyValueWriter) error

Prove constructs a merkle proof for key. The result contains all encoded nodes on the path to the value at key. The value itself is also included in the last node and can be retrieved by verifying the proof.

If the trie does not contain a value for key, the returned proof contains all nodes of the longest existing prefix of the key (at least the root node), ending with the node that proves the absence of the key.

func (*SdxXTrie) TryDelete

func (t *SdxXTrie) TryDelete(key []byte) error

TryDelete removes any existing value for key from the trie. If a node was not found in the database, a MissingNodeError is returned.

func (*SdxXTrie) TryGet

func (t *SdxXTrie) TryGet(key []byte) ([]byte, error)

TryGet returns the value for key stored in the trie. The value bytes must not be modified by the caller. If a node was not found in the database, a MissingNodeError is returned.

func (*SdxXTrie) TryGetBestLeftKeyAndValue

func (t *SdxXTrie) TryGetBestLeftKeyAndValue() ([]byte, []byte, error)

TryGetBestLeftKey returns the value of max left leaf If a node was not found in the database, a MissingNodeError is returned.

func (*SdxXTrie) TryGetBestRightKeyAndValue

func (t *SdxXTrie) TryGetBestRightKeyAndValue() ([]byte, []byte, error)

TryGetBestRightKey returns the value of max left leaf If a node was not found in the database, a MissingNodeError is returned.

func (*SdxXTrie) TryUpdate

func (t *SdxXTrie) TryUpdate(key, value []byte) error

TryUpdate associates key with value in the trie. Subsequent calls to Get will return value. If value has length zero, any existing value is deleted from the trie and calls to Get will return nil.

The value bytes must not be modified by the caller while they are stored in the trie.

If a node was not found in the database, a MissingNodeError is returned.

func (*SdxXTrie) Update

func (t *SdxXTrie) Update(key, value []byte)

Update associates key with value in the trie. Subsequent calls to Get will return value. If value has length zero, any existing value is deleted from the trie and calls to Get will return nil.

The value bytes must not be modified by the caller while they are stored in the trie.

type Signature

type Signature struct {
	V byte        `bson:"v" json:"v"`
	R common.Hash `bson:"r" json:"r"`
	S common.Hash `bson:"s" json:"s"`
}

Signature struct

type SignatureRecord

type SignatureRecord struct {
	V byte   `bson:"v" json:"v"`
	R string `bson:"r" json:"r"`
	S string `bson:"s" json:"s"`
}

type TradeResult

type TradeResult struct {
	Fee      *big.Int
	InToken  common.Address
	InTotal  *big.Int
	OutToken common.Address
	OutTotal *big.Int
}

type Trie

type Trie interface {
	TryGet(key []byte) ([]byte, error)
	TryGetBestLeftKeyAndValue() ([]byte, []byte, error)
	TryGetBestRightKeyAndValue() ([]byte, []byte, error)
	TryUpdate(key, value []byte) error
	TryDelete(key []byte) error
	Commit(onleaf trie.LeafCallback) (common.Hash, error)
	Hash() common.Hash
	NodeIterator(startKey []byte) trie.NodeIterator
	GetKey([]byte) []byte // TODO(fjl): remove this when SdxXTrie is removed
	Prove(key []byte, fromLevel uint, proofDb ethdb.KeyValueWriter) error
}

Trie is a Ethereum Merkle Trie.

type TxLendingBatch

type TxLendingBatch struct {
	Data      []*LendingItem
	Timestamp int64
	TxHash    common.Hash
}

func DecodeTxLendingBatch

func DecodeTxLendingBatch(data []byte) (TxLendingBatch, error)

Jump to

Keyboard shortcuts

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