domain

package
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Mar 19, 2021 License: MIT Imports: 25 Imported by: 0

Documentation

Index

Constants

View Source
const (
	FeeAccount = iota
	WalletAccount
	UnusedAccount1
	UnusedAccount2
	UnusedAccount3
	MarketAccountStart

	ExternalChain = 0
	InternalChain = 1

	MinMilliSatPerByte = 100

	StrategyTypePluggable  StrategyType = 0
	StrategyTypeBalanced   StrategyType = 1
	StrategyTypeUnbalanced StrategyType = 2
)

Variables

View Source
var (
	// ErrInvalidBaseAsset is thrown when non valid base asset is given
	ErrInvalidBaseAsset = errors.New("invalid base asset")
	// ErrInvalidQuoteAsset is thrown when non valid quote asset is given
	ErrInvalidQuoteAsset = errors.New("invalid quote asset")
	// ErrMustBeLocked is thrown when trying to change the passphrase with an unlocked wallet
	ErrMustBeLocked = errors.New("wallet must be locked to perform this operation")
	// ErrMustBeUnlocked is thrown when trying to make an operation that requires the wallet to be unlocked
	ErrMustBeUnlocked = errors.New("wallet must be unlocked to perform this operation")
	// ErrInvalidPassphrase ...
	ErrInvalidPassphrase = errors.New("passphrase is not valid")
	// ErrVaultAlreadyInitialized ...
	ErrVaultAlreadyInitialized = errors.New("vault is already initialized")
	// ErrNullMnemonicOrPassphrase ...
	ErrNullMnemonicOrPassphrase = errors.New("mnemonic and/or passphrase must not be null")
	//ErrNotFunded is thrown when a market requires being funded for a change
	ErrNotFunded = errors.New("market must be funded")
	//ErrMarketIsClosed is thrown when a market requires being tradable for a change
	ErrMarketIsClosed = errors.New("market is closed")
	//ErrMarketMustBeClose is thrown when a market requires being NOT tradable for a change
	ErrMarketMustBeClose = errors.New("market must be closed")
	//ErrPriceExists is thrown when a price for that given timestamp already exists
	ErrPriceExists = errors.New("price has been inserted already")
	//ErrNotPriced is thrown when the price is still 0 (ie. not initialized)
	ErrNotPriced = errors.New("price must be inserted")
	//ErrInvalidBasePrice is thrown when the amount for Base price is an invalid satoshis value.
	ErrInvalidBasePrice = errors.New("the amount for base price is invalid")
	//ErrInvalidQuotePrice is thrown when the amount for Quote price is an invalid satoshis value.
	ErrInvalidQuotePrice = errors.New("the amount for base price is invalid")
	// ErrMustBeEmpty ...
	ErrMustBeEmpty = errors.New(
		"trade must be empty for parsing a proposal",
	)
	// ErrMustBeProposal ...
	ErrMustBeProposal = errors.New(
		"trade must be in proposal state for being accepted",
	)
	// ErrMustBeAccepted ...
	ErrMustBeAccepted = errors.New(
		"trade must be in accepted state for being completed",
	)
	// ErrMustBeCompleted ...
	ErrMustBeCompleted = errors.New(
		"trade must be in completed state to add txid",
	)
	// ErrExpirationDateNotReached ...
	ErrExpirationDateNotReached = errors.New(
		"trade did not reached expiration date yet and cannot be set expired",
	)
	// ErrMarketNotExist ...
	ErrMarketNotExist = errors.New("market does not exists")
)
View Source
var (
	// EmptyStatus represent the status of an empty trade
	EmptyStatus = Status{
		Code: pb.SwapStatus_UNDEFINED,
	}
	// ProposalStatus represent the status of a trade presented by some trader to
	// the daemon and not yet processed
	ProposalStatus = Status{
		Code: pb.SwapStatus_REQUEST,
	}
	// ProposalRejectedStatus represents the status of a trade presented by some
	// trader to the daemon and rejected for some reason
	ProposalRejectedStatus = Status{
		Code:   pb.SwapStatus_REQUEST,
		Failed: true,
	}
	// AcceptedStatus represents the status of a trade proposal that has been
	// accepted by the daemon
	AcceptedStatus = Status{
		Code: pb.SwapStatus_ACCEPT,
	}
	// FailedToCompleteStatus represents the status of a trade that failed to be
	// be completed for some reason
	FailedToCompleteStatus = Status{
		Code:   pb.SwapStatus_ACCEPT,
		Failed: true,
	}
	// CompletedStatus represents the status of a trade that has been completed
	// and accepted in mempool, waiting for being published on the blockchain
	CompletedStatus = Status{
		Code: pb.SwapStatus_COMPLETE,
	}
)

Functions

This section is empty.

Types

type Account

type Account struct {
	AccountIndex           int
	LastExternalIndex      int
	LastInternalIndex      int
	DerivationPathByScript map[string]string
}

Account defines the entity data struture for a derived account of the daemon's HD wallet

func NewAccount

func NewAccount(positiveAccountIndex int) (*Account, error)

NewAccount returns an empty Account instance

type AccountAndKey

type AccountAndKey struct {
	AccountIndex int
	BlindingKey  []byte
}

type AddressInfo

type AddressInfo struct {
	AccountIndex   int
	Address        string
	BlindingKey    []byte
	DerivationPath string
}

type BalanceInfo

type BalanceInfo struct {
	TotalBalance       uint64
	ConfirmedBalance   uint64
	UnconfirmedBalance uint64
}

type CompleteResult

type CompleteResult struct {
	OK    bool
	TxHex string
	TxID  string
}

CompleteResult is return type of Complete method

type Market

type Market struct {
	// AccountIndex links a market to a HD wallet account derivation.
	AccountIndex int
	BaseAsset    string
	QuoteAsset   string
	// Each Market has a different fee expressed in basis point of each swap
	Fee int64
	// if curretly open for trades
	Tradable bool
	// Market Making strategy
	Strategy mm.MakingStrategy
	//Pluggable Price of the asset pair.
	Price Prices
}

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

func NewMarket

func NewMarket(positiveAccountIndex int) (*Market, error)

NewMarket returns an empty market with a reference to an account index

func (*Market) BaseAssetPrice

func (m *Market) BaseAssetPrice() decimal.Decimal

BaseAssetPrice returns the latest price for the base asset

func (*Market) ChangeBasePrice

func (m *Market) ChangeBasePrice(price decimal.Decimal) error

ChangeBasePrice ...

func (*Market) ChangeFee

func (m *Market) ChangeFee(fee int64) error

ChangeFee ...

func (*Market) ChangeQuotePrice

func (m *Market) ChangeQuotePrice(price decimal.Decimal) error

ChangeQuotePrice ...

func (*Market) FundMarket

func (m *Market) FundMarket(fundingTxs []OutpointWithAsset) error

FundMarket adds the assets of market from the given array of outpoints. Since the list of outpoints can contain an infinite number of utxos with different assets, they're fistly indexed by their asset, then the market's base asset is updated if found in the list, otherwise only the very first asset type is used as the market's quote asset, discarding the others that should be manually transferred to some other address because they won't be used by the daemon.

func (*Market) IsFunded

func (m *Market) IsFunded() bool

IsFunded method returns true if the market contains a non empty funding tx outpoint for each asset

func (*Market) IsStrategyPluggable

func (m *Market) IsStrategyPluggable() bool

IsStrategyPluggable returns true if the the startegy isn't automated.

func (*Market) IsStrategyPluggableInitialized

func (m *Market) IsStrategyPluggableInitialized() bool

IsStrategyPluggableInitialized returns true if the prices have been set.

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() error

MakeNotTradable ...

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 ...

func (*Market) QuoteAssetPrice

func (m *Market) QuoteAssetPrice() decimal.Decimal

QuoteAssetPrice returns the latest price for the quote asset

type MarketRepository

type MarketRepository interface {

	// Retrieves a market with a given account index.
	GetMarketByAccount(ctx context.Context, accountIndex int) (market *Market, err error)

	// Retrieves a market with a given a quote asset hash.
	GetMarketByAsset(ctx context.Context, quoteAsset string) (market *Market, accountIndex int, err error)

	// Retrieves the latest market sorted by account index
	GetLatestMarket(ctx context.Context) (market *Market, accountIndex int, err error)

	// Retrieves a market with the given account index. If not found, a new entry shall be created.
	GetOrCreateMarket(ctx context.Context, accountIndex int) (market *Market, err error)

	// Retrieves all the markets that are open for trading
	GetTradableMarkets(ctx context.Context) ([]Market, error)

	// Retrieves all the markets
	GetAllMarkets(ctx context.Context) ([]Market, error)

	// Updates the state of a market. In order to be flexible for many use case and to manage
	// at an higher level the possible errors, an update closure function shall be passed
	UpdateMarket(
		ctx context.Context,
		accountIndex int,
		updateFn func(m *Market) (*Market, error),
	) error

	// Open and close trading activities for a market with the given quote asset hash
	OpenMarket(ctx context.Context, quoteAsset string) error
	CloseMarket(ctx context.Context, quoteAsset string) error

	// Update only the price without touching market details
	UpdatePrices(ctx context.Context, accountIndex int, prices Prices) error
}

MarketRepository defines the abstraction for Market

type OutpointWithAsset

type OutpointWithAsset struct {
	Asset string
	Txid  string
	Vout  int
}

OutpointWithAsset contains the transaction outpoint (tx hash and vout) along with the asset hash

type Prices

type Prices struct {
	// how much 1 base asset is valued in quote asset.
	BasePrice decimal.Decimal
	// how much 1 quote asset is valued in base asset
	QuotePrice decimal.Decimal
}

Prices ...

func (Prices) AreZero

func (p Prices) AreZero() bool

AreZero ...

func (Prices) IsZero

func (p Prices) IsZero() bool

IsZero ...

type Status

type Status struct {
	Code   pb.SwapStatus
	Failed bool
}

Status represents the different statuses that a trade between a trader and a provider can assume

type StrategyType

type StrategyType int32

StrategyType is the Market making strategy type

type Swap

type Swap struct {
	ID      string
	Message []byte
}

type Timestamp

type Timestamp struct {
	Request  uint64
	Accept   uint64
	Complete uint64
	Expiry   uint64
}

type Trade

type Trade struct {
	ID               uuid.UUID
	MarketQuoteAsset string
	MarketPrice      Prices
	MarketFee        int64
	TraderPubkey     []byte
	Status           Status
	PsetBase64       string
	TxID             string
	TxHex            string
	Timestamp        Timestamp
	SwapRequest      Swap
	SwapAccept       Swap
	SwapComplete     Swap
	SwapFail         Swap
}

Trade defines the Trade entity data structure for holding swap transactions

func NewTrade

func NewTrade() *Trade

NewTrade returns an empty trade

func (*Trade) Accept

func (t *Trade) Accept(
	psetBase64 string,
	inputBlindingKeys,
	outputBlindingKeys map[string][]byte,
) (bool, error)

Accept attempts to accept a trade proposal. The trade must be in Proposal status to be accepted, otherwise an error is thrown

func (*Trade) AddBlocktime

func (t *Trade) AddBlocktime(blocktime uint64) error

AddBlocktime sets the timestamp for a completed trade to the given blocktime. If the trade is not in Complete status, an error is thrown

func (*Trade) Complete

func (t *Trade) Complete(psetBase64 string) (*CompleteResult, error)

Complete sets the status of the trade to Complete by adding the txID of the tx in the blockchain. The trade must be in Accepted or FailedToComplete status for being completed, otherwise an error is thrown

func (*Trade) ContainsSwap

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

ContainsSwap returns whether some swap identified by an id belongs to the current trade

func (*Trade) Fail

func (t *Trade) Fail(swapID string, tradeStatus Status, errCode pkgswap.ErrCode, errMsg string)

Fail sets the status of the trade to the provided status and creates the serialized SwapFail message and id for the given swap, errCode and errMsg

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 has reached the expiration date, ie if now is after the expriation date and the trade is not in Complete status

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 is in ProposalRejected status

func (*Trade) Propose

func (t *Trade) Propose(
	swapRequest *pb.SwapRequest,
	marketQuoteAsset string,
	marketFeeBasisPoint int64,
	traderPubkey []byte,
) (bool, error)

Propose returns a new trade proposal for the given trader and market

func (*Trade) Settle added in v0.1.2

func (t *Trade) Settle(settlementTime uint64) error

func (*Trade) SwapAcceptMessage

func (t *Trade) SwapAcceptMessage() *pb.SwapAccept

SwapAcceptMessage returns the swap accept made for the trade

func (*Trade) SwapAcceptTime

func (t *Trade) SwapAcceptTime() uint64

SwapAcceptTime returns the timestamp of when the trade proposal has been accepted

func (*Trade) SwapCompleteMessage

func (t *Trade) SwapCompleteMessage() *pb.SwapComplete

SwapCompleteMessage returns the swap complete message for the trade if existing

func (*Trade) SwapCompleteTime

func (t *Trade) SwapCompleteTime() uint64

SwapCompleteTime returns the timestamp of when the accepted trade has been completed

func (*Trade) SwapExpiryTime

func (t *Trade) SwapExpiryTime() uint64

SwapExpiryTime returns the timestamp of when the current trade will expire

func (*Trade) SwapFailMessage

func (t *Trade) SwapFailMessage() *pb.SwapFail

SwapFailMessage returns the swap fail message for the trade if existing

func (*Trade) SwapRequestMessage

func (t *Trade) SwapRequestMessage() *pb.SwapRequest

SwapRequestMessage returns the swap request made for the trade

func (*Trade) SwapRequestTime

func (t *Trade) SwapRequestTime() uint64

SwapRequestTime returns the timestamp of the proposal of the current trade

type TradeRepository

type TradeRepository interface {
	GetOrCreateTrade(ctx context.Context, tradeID *uuid.UUID) (*Trade, error)
	GetAllTrades(ctx context.Context) ([]*Trade, error)
	GetAllTradesByMarket(ctx context.Context, marketQuoteAsset string) ([]*Trade, error)
	GetTradeBySwapAcceptID(ctx context.Context, swapAcceptID string) (*Trade, error)
	UpdateTrade(
		ctx context.Context,
		tradeID *uuid.UUID,
		updateFn func(t *Trade) (*Trade, error),
	) error
	GetCompletedTradesByMarket(
		ctx context.Context,
		marketQuoteAsset string,
	) ([]*Trade, error)
	GetTradeByTxID(ctx context.Context, txID string) (*Trade, error)
}

TradeRepository defines the abstraction for Trade

type Unspent

type Unspent struct {
	TxID            string
	VOut            uint32
	Value           uint64
	AssetHash       string
	ValueCommitment string
	AssetCommitment string
	ValueBlinder    []byte
	AssetBlinder    []byte
	ScriptPubKey    []byte
	Nonce           []byte
	RangeProof      []byte
	SurjectionProof []byte
	Address         string
	Spent           bool
	Locked          bool
	LockedBy        *uuid.UUID
	Confirmed       bool
}

func (*Unspent) Confirm

func (u *Unspent) Confirm()

func (*Unspent) IsConfirmed

func (u *Unspent) IsConfirmed() bool

func (*Unspent) IsKeyEqual

func (u *Unspent) IsKeyEqual(key UnspentKey) bool

func (*Unspent) IsLocked

func (u *Unspent) IsLocked() bool

func (*Unspent) IsSpent

func (u *Unspent) IsSpent() bool

func (*Unspent) Key

func (u *Unspent) Key() UnspentKey

func (*Unspent) Lock

func (u *Unspent) Lock(tradeID *uuid.UUID)

func (*Unspent) Spend

func (u *Unspent) Spend()

func (*Unspent) ToUtxo

func (u *Unspent) ToUtxo() explorer.Utxo

func (*Unspent) UnLock

func (u *Unspent) UnLock()

type UnspentKey

type UnspentKey struct {
	TxID string
	VOut uint32
}

type UnspentRepository

type UnspentRepository interface {
	AddUnspents(ctx context.Context, unspents []Unspent) error
	GetAllUnspents(ctx context.Context) []Unspent
	GetBalance(
		ctx context.Context,
		addresses []string,
		assetHash string,
	) (uint64, error)
	GetAvailableUnspents(ctx context.Context) ([]Unspent, error)
	GetAllUnspentsForAddresses(
		ctx context.Context,
		addresses []string,
	) ([]Unspent, error)
	GetUnspentsForAddresses(
		ctx context.Context,
		addresses []string,
	) ([]Unspent, error)
	GetAvailableUnspentsForAddresses(
		ctx context.Context,
		addresses []string,
	) ([]Unspent, error)
	GetUnlockedBalance(
		ctx context.Context,
		addresses []string,
		assetHash string,
	) (uint64, error)
	SpendUnspents(
		ctx context.Context,
		unspentKeys []UnspentKey,
	) error
	ConfirmUnspents(
		ctx context.Context,
		unspentKeys []UnspentKey,
	) error
	LockUnspents(
		ctx context.Context,
		unspentKeys []UnspentKey,
		tradeID uuid.UUID,
	) error
	UnlockUnspents(ctx context.Context, unspentKeys []UnspentKey) error
	GetUnspentForKey(
		ctx context.Context,
		unspentKey UnspentKey,
	) (*Unspent, error)
}

type Vault

type Vault struct {
	//Mnemonic               []string
	EncryptedMnemonic      string
	PassphraseHash         []byte
	Accounts               map[int]*Account
	AccountAndKeyByAddress map[string]AccountAndKey
}

func NewVault

func NewVault(mnemonic []string, passphrase string) (*Vault, error)

NewVault encrypts the provided mnemonic with the passhrase and returns a new Vault initialized with the encrypted mnemonic and the hash of the passphrase. The Vault is locked by default since it is initialized without the mnemonic in plain text

func (*Vault) AccountByAddress

func (v *Vault) AccountByAddress(addr string) (*Account, int, error)

AccountByAddress returns the account to which the provided address belongs

func (*Vault) AccountByIndex

func (v *Vault) AccountByIndex(accountIndex int) (*Account, error)

AccountByIndex returns the account with the given index

func (*Vault) AllDerivedAddressesAndBlindingKeysForAccount

func (v *Vault) AllDerivedAddressesAndBlindingKeysForAccount(accountIndex int) ([]string, [][]byte, error)

AllDerivedAddressesAndBlindingKeysForAccount returns all the external and internal addresses derived for the provided account along with the respective private blinding keys

func (*Vault) AllDerivedAddressesInfo

func (v *Vault) AllDerivedAddressesInfo() []AddressInfo

AllDerivedAddressesInfo returns the info of all the external and internal addresses derived by the daemon. This method does not require the Vault to be unlocked since it does not make use of the mnemonic in plain text. The info returned for each address are the account index, the derivation path, and the private blinding key.

func (*Vault) AllDerivedExternalAddressesForAccount

func (v *Vault) AllDerivedExternalAddressesForAccount(accountIndex int) (
	[]string,
	error,
)

AllDerivedExternalAddressesForAccount returns all the external derived for the provided account

func (*Vault) ChangePassphrase

func (v *Vault) ChangePassphrase(currentPassphrase, newPassphrase string) error

ChangePassphrase attempts to unlock the

func (*Vault) DeriveNextExternalAddressForAccount

func (v *Vault) DeriveNextExternalAddressForAccount(accountIndex int) (address string, script string, blindingPrivateKey []byte, err error)

DeriveNextExternalAddressForAccount returns the next unused address, the corresponding output script, the blinding key.

func (*Vault) DeriveNextInternalAddressForAccount

func (v *Vault) DeriveNextInternalAddressForAccount(accountIndex int) (address string, script string, blindingPrivateKey []byte, err error)

DeriveNextInternalAddressForAccount returns the next unused change address for the provided account and the corresponding output script

func (*Vault) GetMnemonicSafe

func (v *Vault) GetMnemonicSafe() ([]string, error)

GetMnemonicSafe is getter for Vault's mnemonic in plain text

func (*Vault) InitAccount

func (v *Vault) InitAccount(accountIndex int)

InitAccount creates a new account in the current Vault if not existing

func (*Vault) IsZero

func (v *Vault) IsZero() bool

IsZero returns whether the Vault is initialized without holding any data

func (*Vault) Lock

func (v *Vault) Lock() error

Lock locks the Vault by wiping its mnemonic field

func (*Vault) Unlock

func (v *Vault) Unlock(passphrase string) error

Unlock attempts to decrypt the mnemonic with the provided passphrase

type VaultRepository

type VaultRepository interface {
	GetOrCreateVault(
		ctx context.Context,
		mnemonic []string,
		passphrase string,
	) (*Vault, error)
	UpdateVault(
		ctx context.Context,
		mnemonic []string,
		passphrase string,
		updateFn func(v *Vault) (*Vault, error),
	) error
	GetAccountByIndex(ctx context.Context, accountIndex int) (*Account, error)
	GetAccountByAddress(ctx context.Context, addr string) (*Account, int, error)
	GetAllDerivedAddressesAndBlindingKeysForAccount(
		ctx context.Context,
		accountIndex int,
	) ([]string, [][]byte, error)
	GetDerivationPathByScript(
		ctx context.Context,
		accountIndex int,
		scripts []string,
	) (map[string]string, error)
	GetAllDerivedExternalAddressesForAccount(
		ctx context.Context,
		accountIndex int,
	) ([]string, error)
}

Jump to

Keyboard shortcuts

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