domain

package
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Sep 15, 2023 License: MIT Imports: 12 Imported by: 0

Documentation

Index

Constants

View Source
const (
	StrategyTypeUndefined = iota
	StrategyTypePluggable
	StrategyTypeBalanced
	StrategyTypeUnbalanced
)
View Source
const (
	TradeStatusCodeUndefined = iota
	TradeStatusCodeProposal
	TradeStatusCodeAccepted
	TradeStatusCodeCompleted
	TradeStatusCodeSettled
	TradeStatusCodeExpired
)
View Source
const (
	MinPercentageFee = 0
	MaxPercentageFee = 9999

	FeeAccount              = "fee_account"
	FeeFragmenterAccount    = "fee_fragmenter_account"
	MarketFragmenterAccount = "market_fragmenter_account"
)

Variables

View Source
var (
	// ErrMarketFeeTooHigh ...
	ErrMarketInvalidPercentageFee = fmt.Errorf(
		"invalid market percentage fee, must be in range [%d, %d]",
		MinPercentageFee, MaxPercentageFee,
	)
	//ErrMarketIsClosed is thrown when a market requires being tradable for a change
	ErrMarketIsClosed = errors.New("the market is paused, please open it first")
	//ErrMarketMustBeClosed is thrown when a market requires being NOT tradable for a change
	ErrMarketIsOpen = errors.New("the market is active, please pause it first")
	//ErrMarketNotPriced is thrown when the price is still 0 (ie. not initialized)
	ErrMarketNotPriced = errors.New("the selected strategy mandates price to be updated manually")
	//ErrMarketInvalidBasePrice is thrown when the amount for Base price is an invalid satoshis value.
	ErrMarketInvalidBasePrice = errors.New("invalid base price amount, must be > 0")
	//ErrMarketInvalidQuotePrice is thrown when the amount for Quote price is an invalid satoshis value.
	ErrMarketInvalidQuotePrice = errors.New("invalid quote price amount, must be > 0")
	// ErrMarketInvalidBaseAsset is thrown when non valid base asset is given.
	ErrMarketInvalidBaseAsset = errors.New("invalid base asset")
	// ErrMarketInvalidQuoteAsset is thrown when non valid quote asset is given.
	ErrMarketInvalidQuoteAsset = errors.New("invalid quote asset")
	// ErrMarketInvalidBaseAssetPrecision is thrown when non valid quote asset precision is given.
	ErrMarketInvalidBaseAssetPrecision = errors.New("base asset precision must be in range [0, 8]")
	// ErrMarketInvalidQuoteAssetPrecision is thrown when non valid quote asset precision is given.
	ErrMarketInvalidQuoteAssetPrecision = errors.New("quote asset precision must be in range [0, 8]")
	// ErrInvalidFixedFee ...
	ErrMarketInvalidFixedFee = errors.New("invalid fixed fee amount")
	// ErrMarketPreviewAmountTooLow is returned when a preview fails because
	// the provided amount makes the previewed amount to be too low (lower than
	// the optional fixed fee).
	ErrMarketPreviewAmountTooLow = errors.New("provided amount is too low")
	// ErrMarketPreviewAmountTooBig is returned when a preview fails because
	// the provided amount makes the previewed amount to be too big (greater than
	// the overall balance).
	ErrMarketPreviewAmountTooBig = errors.New("provided amount is too big")
	// ErrMarketUnknownStrategy is thrown when an invalid strategy is given at
	// market creation.
	ErrMarketUnknownStrategy = errors.New("unknown market strategy")
)

Market errors

View Source
var (
	// ErrTradeUnknownType ...
	ErrTradeUnknownType = errors.New("unknown trade type")
	// ErrTradeMustBeProposal ...
	ErrTradeMustBeProposal = errors.New(
		"trade must be in proposal state for being accepted",
	)
	// ErrTradeMustBeAccepted ...
	ErrTradeMustBeAccepted = errors.New(
		"trade must be in accepted state for being completed",
	)
	// ErrTradeMustBeCompleted ...
	ErrTradeMustBeCompletedOrAccepted = errors.New(
		"trade must be in completed or accepted to be settled",
	)
	// ErrTradeInvalidExpiryTime ...
	ErrTradeInvalidExpiryTime = errors.New(
		"trade expiration date must be after proposal one",
	)
	// ErrTradeExpiryTimeNotReached ...
	ErrTradeExpiryTimeNotReached = errors.New(
		"trade must have reached the expiration date to be set expired",
	)
	// ErrTradeExpired ...
	ErrTradeExpired = errors.New("trade has expired")
	// ErrTradeNullExpiryTime ...
	ErrTradeNullExpiryTime = errors.New(
		"trade must have an expiration date set to be set expired",
	)
)

Trade errors

Functions

This section is empty.

Types

type Deposit added in v0.6.0

type Deposit struct {
	AccountName       string
	TxID              string
	TotAmountPerAsset map[string]uint64
	Timestamp         int64
}

Deposit holds info about txs with funds sent to some wallet account.

func (Deposit) Key added in v0.6.0

func (d Deposit) Key() string

type DepositRepository added in v0.6.0

type DepositRepository interface {
	// AddDeposits adds the provided deposits to the repository. Those already
	// existing won't be re-added.
	AddDeposits(ctx context.Context, deposits []Deposit) (int, error)
	// GetDepositsForAccount returns the deposits related to the given account.
	GetDepositsForAccount(
		ctx context.Context, accountName string, page Page,
	) ([]Deposit, error)
	// GetAllDeposits returns all deposits related to all markets.
	GetAllDeposits(ctx context.Context, page Page) ([]Deposit, error)
}

DepositRepository is the abstraction for any kind of database intended to persist Deposits.

type Market

type Market struct {
	// Base asset in hex format.
	BaseAsset string
	// Quote asset in hex format.
	QuoteAsset string
	// Name of the market.
	Name string
	// Precison of the base asset.
	BaseAssetPrecision uint
	// Precison of the quote asset.
	QuoteAssetPrecision uint
	// Percentage fee expressed in basis points for both assets.
	PercentageFee MarketFee
	// Fixed fee amount expressed in satoshis for both assets.
	FixedFee MarketFee
	// if curretly open for trades
	Tradable bool
	// Market Making strategy type
	StrategyType int
	// Pluggable Price of the asset pair.
	Price MarketPrice
}

Market defines the Market entity data structure for holding an asset pair state.

func NewMarket

func NewMarket(
	baseAsset, quoteAsset, name string,
	basePercentageFee, quotePercentageFee, baseFixedFee, quoteFixedFee uint64,
	baseAssetPrecision, quoteAssetPrecision, strategyType uint,
) (*Market, error)

NewMarket returns a new market with an account index, the asset pair and the percentage fee set.

func (*Market) ChangeAssetPrecision added in v0.9.0

func (m *Market) ChangeAssetPrecision(
	baseAssetPrecision, quoteAssetPrecision int,
) error

func (*Market) ChangeFixedFee added in v0.3.9

func (m *Market) ChangeFixedFee(baseFee, quoteFee int64) error

ChangeFixedFee updates market's fixed fee to those given.

func (*Market) ChangePercentageFee added in v1.0.0

func (m *Market) ChangePercentageFee(baseFee, quoteFee int64) error

ChangePercentageFee updates market's perentage fee to the given one.

func (*Market) ChangePrice added in v1.0.0

func (m *Market) ChangePrice(basePrice, quotePrice decimal.Decimal) error

ChangeBasePrice updates the price of market's base asset.

func (*Market) IsStrategyBalanced added in v0.8.1

func (m *Market) IsStrategyBalanced() bool

func (*Market) IsStrategyPluggable

func (m *Market) IsStrategyPluggable() bool

IsStrategyPluggable returns true if the strategy isn't automated.

func (*Market) IsTradable

func (m *Market) IsTradable() bool

IsTradable returns true if the market is available for trading

func (*Market) MakeNotTradable

func (m *Market) MakeNotTradable()

MakeNotTradable updates the status of the market to not tradable.

func (*Market) MakeStrategyBalanced

func (m *Market) MakeStrategyBalanced() error

MakeStrategyBalanced makes the current market using a balanced AMM formula 50/50

func (*Market) MakeStrategyPluggable

func (m *Market) MakeStrategyPluggable() error

MakeStrategyPluggable makes the current market using a given price (ie. set via UpdateMarketPrice rpc either manually or a price feed plugin)

func (*Market) MakeTradable

func (m *Market) MakeTradable() error

MakeTradable updates the status of the market to tradable.

func (*Market) Preview added in v0.4.4

func (m *Market) Preview(
	baseBalance, quoteBalance, amount uint64,
	asset, feeAsset string, isBuy bool,
) (*PreviewInfo, error)

func (*Market) SpotPrice added in v0.9.0

func (m *Market) SpotPrice(
	baseBalance, quoteBalance uint64,
) (MarketPrice, error)

type MarketFee added in v1.0.0

type MarketFee struct {
	BaseAsset  uint64
	QuoteAsset uint64
}

type MarketPrice added in v1.0.0

type MarketPrice struct {
	// how much 1 base asset is valued in quote asset.
	BasePrice string
	// how much 1 quote asset is valued in base asset
	QuotePrice string
}

MarketPrice represents base and quote market price

func (MarketPrice) GetBasePrice added in v1.0.0

func (mp MarketPrice) GetBasePrice() decimal.Decimal

func (MarketPrice) GetQuotePrice added in v1.0.0

func (mp MarketPrice) GetQuotePrice() decimal.Decimal

func (MarketPrice) IsZero added in v1.0.0

func (mp MarketPrice) IsZero() bool

type MarketRepository

type MarketRepository interface {
	// AddMarket adds a new market to the repository.
	AddMarket(ctx context.Context, market *Market) error
	// GetMarketByName returns the market with the given name.
	GetMarketByName(
		ctx context.Context, marketName string,
	) (*Market, error)
	// GetMarketByAssets returns the market with a given asset pair.
	GetMarketByAssets(
		ctx context.Context, baseAsset, quoteAsset string,
	) (*Market, error)
	// GetTradableMarkets returns all markets that are open for trading.
	GetTradableMarkets(ctx context.Context) ([]Market, error)
	// GetAllMarkets returns all markets.
	GetAllMarkets(ctx context.Context) ([]Market, error)
	// UpdateMarket updates the state of a market. The closure function let's to
	// commit multiple changes to a certain market in a transactional way.
	UpdateMarket(
		ctx context.Context,
		marketName string, updateFn func(m *Market) (*Market, error),
	) error
	// OpenMarket makes a market open for trading.
	OpenMarket(ctx context.Context, marketName string) error
	// CloseMarket puts a market in pause and not available for trading.
	CloseMarket(ctx context.Context, marketName string) error
	// DeleteMarket removes a market from the repository.
	DeleteMarket(ctx context.Context, marketName string) error
	// UpdateMarketPrice updates the price of a given market.
	UpdateMarketPrice(
		ctx context.Context, marketName string, price MarketPrice,
	) error
}

MarketRepository is the abstraction for any kind of database intended to persist Markets.

type Page added in v0.6.0

type Page interface {
	GetNumber() int64
	GetSize() int64
}

type PreviewInfo added in v0.4.4

type PreviewInfo struct {
	Price     MarketPrice
	Amount    uint64
	Asset     string
	FeeAsset  string
	FeeAmount uint64
}

PreviewInfo contains info about a price preview based on the market's current strategy.

type Swap

type Swap struct {
	Id        string
	Message   []byte
	Timestamp int64
}

Swap is the data structure that represents any of the above swaps.

type SwapAccept added in v0.3.0

type SwapAccept struct {
	Id              string
	RequestId       string
	Transaction     string
	UnblindedInputs []UnblindedInput
}

func (*SwapAccept) GetId added in v0.3.0

func (s *SwapAccept) GetId() string

func (*SwapAccept) GetRequestId added in v0.3.0

func (s *SwapAccept) GetRequestId() string

func (*SwapAccept) GetTransaction added in v0.3.0

func (s *SwapAccept) GetTransaction() string

func (*SwapAccept) GetUnblindedInputs added in v1.0.0

func (s *SwapAccept) GetUnblindedInputs() []UnblindedInput

type SwapComplete added in v0.3.0

type SwapComplete struct {
	Id          string
	AcceptId    string
	Transaction string
}

func (*SwapComplete) GetAcceptId added in v0.3.0

func (s *SwapComplete) GetAcceptId() string

func (*SwapComplete) GetId added in v0.3.0

func (s *SwapComplete) GetId() string

func (*SwapComplete) GetTransaction added in v0.3.0

func (s *SwapComplete) GetTransaction() string

type SwapFail added in v0.3.0

type SwapFail struct {
	Id             string
	MessageId      string
	FailureCode    uint32
	FailureMessage string
}

func (*SwapFail) GetFailureCode added in v0.3.0

func (s *SwapFail) GetFailureCode() uint32

func (*SwapFail) GetFailureMessage added in v0.3.0

func (s *SwapFail) GetFailureMessage() string

func (*SwapFail) GetId added in v0.3.0

func (s *SwapFail) GetId() string

func (*SwapFail) GetMessageId added in v0.3.0

func (s *SwapFail) GetMessageId() string

type SwapParser added in v0.3.0

type SwapParser interface {
	SerializeRequest(r SwapRequest) ([]byte, int)
	SerializeAccept(
		reqMsg []byte, tx string, unblindedIns []UnblindedInput,
	) (string, []byte, int)
	SerializeComplete(accMsg []byte, tx string) (string, []byte, int)
	SerializeFail(id string, code int) (string, []byte)

	DeserializeRequest(
		msg []byte, feeAsset string, feeAmount uint64,
	) *SwapRequest
	DeserializeAccept(msg []byte) *SwapAccept
	DeserializeComplete(msg []byte) *SwapComplete
	DeserializeFail(msg []byte) *SwapFail

	ParseSwapTransaction(tx string) (*SwapTransactionDetails, int)
}

SwapParser defines the required methods to override the default swap message parser, which is grpc-proto.

var (
	// SwapParserManager ...
	SwapParserManager SwapParser
)

type SwapRequest added in v0.3.0

type SwapRequest struct {
	Id              string
	AssetP          string
	AssetR          string
	AmountP         uint64
	AmountR         uint64
	Transaction     string
	FeeAsset        string
	FeeAmount       uint64
	UnblindedInputs []UnblindedInput
}

func (*SwapRequest) GetAmountP added in v0.3.0

func (s *SwapRequest) GetAmountP() uint64

func (*SwapRequest) GetAmountR added in v0.3.0

func (s *SwapRequest) GetAmountR() uint64

func (*SwapRequest) GetAssetP added in v0.3.0

func (s *SwapRequest) GetAssetP() string

func (*SwapRequest) GetAssetR added in v0.3.0

func (s *SwapRequest) GetAssetR() string

func (*SwapRequest) GetFeeAmount added in v1.0.0

func (s *SwapRequest) GetFeeAmount() uint64

func (*SwapRequest) GetFeeAsset added in v1.0.0

func (s *SwapRequest) GetFeeAsset() string

func (*SwapRequest) GetId added in v0.3.0

func (s *SwapRequest) GetId() string

func (*SwapRequest) GetTransaction added in v0.3.0

func (s *SwapRequest) GetTransaction() string

func (*SwapRequest) GetUnblindedInputs added in v1.0.0

func (s *SwapRequest) GetUnblindedInputs() []UnblindedInput

type SwapTransactionDetails added in v1.0.0

type SwapTransactionDetails struct {
	PsetBase64 string
	TxHex      string
	Txid       string
}

type Trade

type Trade struct {
	Id                  string
	Type                TradeType
	MarketName          string
	MarketBaseAsset     string
	MarketQuoteAsset    string
	MarketPrice         MarketPrice
	MarketPercentageFee MarketFee
	MarketFixedFee      MarketFee
	FeeAsset            string
	FeeAmount           uint64
	TraderPubkey        []byte
	Status              TradeStatus
	PsetBase64          string
	TxId                string
	TxHex               string
	ExpiryTime          int64
	SettlementTime      int64
	SwapRequest         *Swap
	SwapAccept          *Swap
	SwapComplete        *Swap
	SwapFail            *Swap
}

Trade is the data structure representing a trade entity.

func NewTrade

func NewTrade() *Trade

NewTrade returns a trade with a new id and Empty status.

func (*Trade) Accept

func (t *Trade) Accept(
	psetBase64 string, unblindedIns []UnblindedInput, expiryTime int64,
) (bool, error)

Accept brings a trade from the Proposal to the Accepted status by validating the provided argument against the SwapRequest message and sets its expiration time.

func (*Trade) Complete

func (t *Trade) Complete(tx string) (bool, error)

Complete brings a trade from the Accepted to the Completed status by checking that the given PSET completes the one of the SwapAccept message and by finalizing it and extracting the raw tx in hex format. Complete must be called before the trade expires, otherwise it won't be possible to actually complete an accepted trade.

func (*Trade) ContainsSwap

func (t *Trade) ContainsSwap(swapID string) bool

ContainsSwap returns whether a swap identified by its id belongs to the current trade.

func (*Trade) Expire added in v0.3.0

func (t *Trade) Expire() (bool, error)

Expire brings the trade to the Expired status if its expiration date was previosly set. This infers that it must be in any of the Accepted, Completed, or related failed statuses. This method makes also sure that the expiration date has passed before changing the status.

func (*Trade) Fail

func (t *Trade) Fail(swapID string, errCode int)

Fail marks the current status of the trade as Failed and adds the SwapFail message.

func (*Trade) IsAccepted

func (t *Trade) IsAccepted() bool

IsAccepted returns whether the trade is in Accepted status.

func (*Trade) IsCompleted

func (t *Trade) IsCompleted() bool

IsCompleted returns whether the trade is in Completed status.

func (*Trade) IsEmpty

func (t *Trade) IsEmpty() bool

IsEmpty returns whether the Trade is empty.

func (*Trade) IsExpired

func (t *Trade) IsExpired() bool

IsExpired returns whether the trade is in Expired status, or if its expiration date has passed.

func (*Trade) IsProposal

func (t *Trade) IsProposal() bool

IsProposal returns whether the trade is in Proposal status.

func (*Trade) IsRejected

func (t *Trade) IsRejected() bool

IsRejected returns whether the trade has failed.

func (*Trade) IsSettled added in v0.3.0

func (t *Trade) IsSettled() bool

IsSettled returns whether the trade is in Settled status.

func (*Trade) Propose

func (t *Trade) Propose(
	tradeType TradeType, swapRequest SwapRequest,
	mktName, mktBaseAsset, mktQuoteAsset string,
	mktPercentageFee, mktFixedFee MarketFee,
	traderPubkey []byte,
) (bool, error)

Propose brings an Empty trade to the Propose status by first validating the provided arguments.

func (*Trade) Settle added in v0.1.2

func (t *Trade) Settle(settlementTime int64) (bool, error)

Settle brings the trade from the Completed to the Settled status, unsets the expiration time and adds the timestamp of the settlement (it must be a blocktime).

func (*Trade) SwapAcceptMessage

func (t *Trade) SwapAcceptMessage() *SwapAccept

SwapAcceptMessage returns the deserialized swap accept message, if defined.

func (*Trade) SwapCompleteMessage

func (t *Trade) SwapCompleteMessage() *SwapComplete

SwapCompleteMessage returns the deserialized swap complete message, if defined.

func (*Trade) SwapFailMessage

func (t *Trade) SwapFailMessage() *SwapFail

SwapFailMessage returns the deserialized swap fail message, if defined.

func (*Trade) SwapRequestMessage

func (t *Trade) SwapRequestMessage() *SwapRequest

SwapRequestMessage returns the deserialized swap request message.

type TradeRepository

type TradeRepository interface {
	// AddTrade adds a new trade to the repository.
	AddTrade(ctx context.Context, trade *Trade) error
	// GetTradeById returns the trade with the given id if existing.
	GetTradeById(ctx context.Context, id string) (*Trade, error)
	// GetAllTrades returns all the trades stored in the repository.
	GetAllTrades(ctx context.Context, page Page) ([]Trade, error)
	// GetAllTradesByMarket returns all the trades filtered by a market
	// identified by its name.
	GetAllTradesByMarket(
		ctx context.Context, marketName string, page Page,
	) ([]Trade, error)
	// GetCompletedTradesByMarket returns all the Completed or Settled trades
	// for the provided market identified by its name.
	GetCompletedTradesByMarket(
		ctx context.Context, marketName string, page Page,
	) ([]Trade, error)
	// GetTradeBySwapAcceptId returns the trade that contains the SwapAccept
	// message matching the given id.
	GetTradeBySwapAcceptId(
		ctx context.Context, swapAcceptId string,
	) (*Trade, error)
	// GetTradeByTxid returns the trade which transaction matches the given
	// transaction id.
	GetTradeByTxId(ctx context.Context, txid string) (*Trade, error)
	// UpdateTrade allowa to commit multiple changes to the same trade in a
	// transactional way.
	UpdateTrade(
		ctx context.Context,
		tradeId string, updateFn func(t *Trade) (*Trade, error),
	) error
}

TradeRepository is the abstraction for any kind of database intended to persist Trades.

type TradeStatus added in v1.0.0

type TradeStatus struct {
	Code   int
	Failed bool
}

Status represents the different statuses that a trade can assume.

type TradeType added in v1.0.0

type TradeType int
const (
	TradeBuy TradeType = iota
	TradeSell
)

func (TradeType) String added in v1.0.0

func (t TradeType) String() string

type UnblindedInput added in v1.0.0

type UnblindedInput struct {
	Index         uint32
	Asset         string
	Amount        uint64
	AssetBlinder  string
	AmountBlinder string
}

func (UnblindedInput) GetAmount added in v1.0.0

func (i UnblindedInput) GetAmount() uint64

func (UnblindedInput) GetAmountBlinder added in v1.0.0

func (i UnblindedInput) GetAmountBlinder() string

func (UnblindedInput) GetAsset added in v1.0.0

func (i UnblindedInput) GetAsset() string

func (UnblindedInput) GetAssetBlinder added in v1.0.0

func (i UnblindedInput) GetAssetBlinder() string

func (UnblindedInput) GetIndex added in v1.0.0

func (i UnblindedInput) GetIndex() uint32

type Withdrawal added in v0.6.0

type Withdrawal struct {
	AccountName       string
	TxID              string
	TotAmountPerAsset map[string]uint64
	Timestamp         int64
}

Withdrawal holds info about txs with funds sent from a wallet account.

type WithdrawalRepository added in v0.6.0

type WithdrawalRepository interface {
	// AddWithdrawals adds the provided withdrawals to the repository. Those already
	// existing won't be re-added.
	AddWithdrawals(ctx context.Context, withdrawals []Withdrawal) (int, error)
	// GetWithdrawalsForAccount returns the list with the withdrawals related to
	// the given market.
	GetWithdrawalsForAccount(
		ctx context.Context, accountName string, page Page,
	) ([]Withdrawal, error)
	// GetAllWithdrawals returns all withdrawals related to all markets.
	GetAllWithdrawals(ctx context.Context, page Page) ([]Withdrawal, error)
}

WithdrawalRepository is the abstraction for any kind of database intended to persist Withdrawals.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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