core

package
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2024 License: BlueOak-1.0.0 Imports: 51 Imported by: 12

Documentation

Index

Constants

View Source
const (
	NoteTypeFeePayment     = "feepayment"
	NoteTypeBondPost       = "bondpost"
	NoteTypeBondRefund     = "bondrefund"
	NoteTypeUnknownBond    = "unknownbond"
	NoteTypeSend           = "send"
	NoteTypeOrder          = "order"
	NoteTypeMatch          = "match"
	NoteTypeEpoch          = "epoch"
	NoteTypeConnEvent      = "conn"
	NoteTypeBalance        = "balance"
	NoteTypeSpots          = "spots"
	NoteTypeWalletConfig   = "walletconfig"
	NoteTypeWalletState    = "walletstate"
	NoteTypeWalletSync     = "walletsync"
	NoteTypeServerNotify   = "notify"
	NoteTypeSecurity       = "security"
	NoteTypeUpgrade        = "upgrade"
	NoteTypeBot            = "bot"
	NoteTypeDEXAuth        = "dex_auth"
	NoteTypeFiatRates      = "fiatrateupdate"
	NoteTypeCreateWallet   = "createwallet"
	NoteTypeLogin          = "login"
	NoteTypeWalletNote     = "walletnote"
	NoteTypeReputation     = "reputation"
	NoteTypeActionRequired = "actionrequired"
)

Notifications should use the following note type strings.

View Source
const (
	ActionIDRedeemRejected = "redeemRejected"
	TopicRedeemRejected    = "RedeemRejected"
)
View Source
const (
	FreshBookAction       = "book"
	FreshCandlesAction    = "candles"
	BookOrderAction       = "book_order"
	EpochOrderAction      = "epoch_order"
	UnbookOrderAction     = "unbook_order"
	UpdateRemainingAction = "update_remaining"
	CandleUpdateAction    = "candle_update"
	EpochMatchSummary     = "epoch_match_summary"
	EpochResolved         = "epoch_resolved"
)
View Source
const (
	// DefaultFiatCurrency is the currency for displaying assets fiat value.
	DefaultFiatCurrency = "USD"
)
View Source
const (
	DefaultResponseTimeout = comms.DefaultResponseTimeout
)

DefaultResponseTimeout is the default timeout for responses after a request is successfully sent.

View Source
const TopicReputationUpdate = "ReputationUpdate"
View Source
const TopicUnknownBondTierZero = "UnknownBondTierZero"
View Source
const TopicWalletSync = "WalletSync"

Variables

View Source
var (

	// ActiveOrdersLogoutErr is returned from logout when there are active
	// orders.
	ActiveOrdersLogoutErr = errors.New("cannot log out with active orders")
)
View Source
var CertStore = map[dex.Network]map[string][]byte{
	dex.Mainnet: {
		"dex.decred.org:7232": dexDotDecredCert,
	},
	dex.Testnet: {
		"bison.exchange:17232": nil,
	},
	dex.Simnet: {
		"127.0.0.1:17273": simnetHarnessCert,
	},
}
View Source
var (
	ErrAccountSuspended = errors.New("may not trade while account is suspended")
)

Functions

func AssetSeedAndPass added in v0.4.0

func AssetSeedAndPass(assetID uint32, appSeed []byte) ([]byte, []byte)

AssetSeedAndPass derives the wallet seed and password that would be used to create a native wallet for a particular asset and application seed. Depending on external wallet software and their key derivation paths, this seed may be usable for accessing funds outside of DEX applications, e.g. btcwallet.

func CheckTopicLangs added in v0.6.0

func CheckTopicLangs() (missingTranslations int)

CheckTopicLangs is used to report missing notification translations.

func FetchCoinpaprikaRates added in v1.0.0

func FetchCoinpaprikaRates(ctx context.Context, log dex.Logger, assets map[uint32]*SupportedAsset) map[uint32]float64

FetchCoinpaprikaRates retrieves and parses fiat rate data from the Coinpaprika API. See https://api.coinpaprika.com/#operation/getTickersById for sample request and response information.

func FetchDcrdataRates added in v1.0.0

func FetchDcrdataRates(ctx context.Context, log dex.Logger, assets map[uint32]*SupportedAsset) map[uint32]float64

FetchDcrdataRates retrieves and parses fiat rate data from dcrdata exchange rate API.

func FetchMessariRates added in v1.0.0

func FetchMessariRates(ctx context.Context, log dex.Logger, assets map[uint32]*SupportedAsset) map[uint32]float64

FetchMessariRates retrieves and parses fiat rate data from the Messari API. See https://messari.io/api/docs#operation/Get%20Asset%20Market%20Data for sample request and response information.

func RegisterTranslations added in v1.0.0

func RegisterTranslations()

RegisterTranslations registers translations with the init package for translator worksheet preparation.

func UnwrapErr added in v0.5.0

func UnwrapErr(err error) error

UnwrapErr returns the result of calling the Unwrap method on err, until it returns a non-wrapped error.

Types

type Account added in v0.2.0

type Account struct {
	Host      string `json:"host"`
	AccountID string `json:"accountID"`
	PrivKey   string `json:"privKey"`
	DEXPubKey string `json:"DEXPubKey"`
	Cert      string `json:"cert"`
}

Account holds data returned from AccountExport.

type ActionRequiredNote added in v1.0.0

type ActionRequiredNote WalletNote

ActionRequiredNote is structured like a WalletNote. The payload will be an *asset.ActionRequiredNote. This is done for compatibility reasons.

type BalanceNote

type BalanceNote struct {
	db.Notification
	AssetID uint32         `json:"assetID"`
	Balance *WalletBalance `json:"balance"`
}

BalanceNote is an update to a wallet's balance.

type BondAsset added in v0.6.0

type BondAsset struct {
	Version uint16 `json:"ver"`
	ID      uint32 `json:"id"`
	Confs   uint32 `json:"confs"`
	Amt     uint64 `json:"amount"`
}

BondAsset describes the bond asset in terms of it's BIP-44 coin type, required confirmations, and minimum bond amount. There is an analogous msgjson type for server providing supported bond assets.

type BondOptions added in v0.6.0

type BondOptions struct {
	BondAsset    uint32 `json:"bondAsset"`
	TargetTier   uint64 `json:"targetTier"`
	MaxBondedAmt uint64 `json:"maxBondedAmt"`
	PenaltyComps uint16 `json:"PenaltyComps"`
}

BondOptions are auto-bond maintenance settings for a particular DEX.

type BondOptionsForm added in v0.6.0

type BondOptionsForm struct {
	Host         string  `json:"host"`
	TargetTier   *uint64 `json:"targetTier,omitempty"`
	MaxBondedAmt *uint64 `json:"maxBondedAmt,omitempty"`
	PenaltyComps *uint16 `json:"penaltyComps,omitempty"`
	BondAssetID  *uint32 `json:"bondAssetID,omitempty"`
}

BondOptionsForm is used from the settings page to change the auto-bond maintenance setting for a DEX.

type BondPostNote added in v0.6.0

type BondPostNote struct {
	db.Notification
	Asset         *uint32       `json:"asset,omitempty"`
	Confirmations *int32        `json:"confirmations,omitempty"`
	BondedTier    *int64        `json:"bondedTier,omitempty"`
	CoinID        *string       `json:"coinID,omitempty"`
	Dex           string        `json:"dex,omitempty"`
	Auth          *ExchangeAuth `json:"auth,omitempty"`
}

BondPostNote is a notification regarding bond posting.

type BondRefundNote added in v0.6.0

type BondRefundNote struct {
	db.Notification
}

BondRefundNote is a notification regarding bond refunds.

type BookFeed

type BookFeed interface {
	Next() <-chan *BookUpdate
	Close()
	Candles(dur string) error
}

BookFeed manages a channel for receiving order book updates. It is imperative that the feeder (BookFeed).Close() when no longer using the feed.

type BookUpdate

type BookUpdate struct {
	Action   string `json:"action"`
	Host     string `json:"host"`
	MarketID string `json:"marketID"`
	Payload  any    `json:"payload"`
}

BookUpdate is an order book update.

type CandleUpdate added in v0.4.0

type CandleUpdate struct {
	Dur          string          `json:"dur"`
	DurMilliSecs uint64          `json:"ms"`
	Candle       *candles.Candle `json:"candle"`
}

type CandlesPayload added in v0.4.0

type CandlesPayload struct {
	Dur          string           `json:"dur"`
	DurMilliSecs uint64           `json:"ms"`
	Candles      []msgjson.Candle `json:"candles"`
}

type Coin added in v0.2.0

type Coin struct {
	ID       dex.Bytes `json:"id"`
	StringID string    `json:"stringID"`
	AssetID  uint32    `json:"assetID"`
	Symbol   string    `json:"symbol"`
	// Confs is populated only if this is a swap coin and we are waiting for
	// confirmations e.g. when this is the maker's swap and we're in
	// MakerSwapCast, or this is the takers swap, and we're in TakerSwapCast.
	Confs *Confirmations `json:"confs,omitempty"`
}

Coin encodes both the coin ID and the asset-dependent string representation of the coin ID.

func NewCoin added in v0.2.0

func NewCoin(assetID uint32, coinID []byte) *Coin

NewCoin constructs a new Coin.

func (*Coin) SetConfirmations added in v0.2.0

func (c *Coin) SetConfirmations(confs, confReq int64)

SetConfirmations sets the Confs field of the Coin.

type Config

type Config struct {
	// DBPath is a filepath to use for the client database. If the database does
	// not already exist, it will be created.
	DBPath string
	// Net is the current network.
	Net dex.Network
	// Logger is the Core's logger and is also used to create the sub-loggers
	// for the asset backends.
	Logger dex.Logger
	// Onion is the address (host:port) of a Tor proxy for use with DEX hosts
	// with a .onion address. To use Tor with regular DEX addresses as well, set
	// TorProxy.
	Onion string
	// TorProxy specifies the address of a Tor proxy server.
	TorProxy string
	// TorIsolation specifies whether to enable Tor circuit isolation.
	TorIsolation bool
	// Language. A BCP 47 language tag. Default is en-US.
	Language string

	// NoAutoWalletLock instructs Core to skip locking the wallet on shutdown or
	// logout. This can be helpful if the user wants the wallet to remain
	// unlocked. e.g. They started with the wallet unlocked, or they intend to
	// start Core again and wish to avoid the time to unlock a locked wallet on
	// startup.
	NoAutoWalletLock bool // zero value is legacy behavior
	// NoAutoDBBackup instructs the DB to skip the creation of a backup DB file
	// on shutdown. This is useful if the consumer is using the BackupDB method,
	// or simply creating manual backups of the DB file after shutdown.
	NoAutoDBBackup bool // zero value is legacy behavior
	// UnlockCoinsOnLogin indicates that on wallet connect during login, or on
	// creation of a new wallet, all coins with the wallet should be unlocked.
	UnlockCoinsOnLogin bool
	// ExtensionModeFile is the path to a file that specifies configuration
	// for running core in extension mode, which gives the caller options for
	// e.g. limiting the ability to configure wallets.
	ExtensionModeFile string
	// TheOneHost will run core with only the specified server.
	TheOneHost string
	// PruneArchive will prune the order archive to the specified number of
	// orders.
	PruneArchive uint64
}

Config is the configuration for the Core.

type Confirmations added in v0.2.0

type Confirmations struct {
	Count    int64 `json:"count"`
	Required int64 `json:"required"`
}

Confirmations is the confirmation count and confirmation requirement of a Coin.

type ConnEventNote

type ConnEventNote struct {
	db.Notification
	Host             string                 `json:"host"`
	ConnectionStatus comms.ConnectionStatus `json:"connectionStatus"`
}

ConnEventNote is a notification regarding individual DEX connection status.

type Core

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

Core is the core client application. Core manages DEX connections, wallets, database access, match negotiation and more.

func New

func New(cfg *Config) (*Core, error)

New is the constructor for a new Core.

func (*Core) AccelerateOrder added in v0.5.0

func (c *Core) AccelerateOrder(pw []byte, oidB dex.Bytes, newFeeRate uint64) (string, error)

AccelerateOrder will use the Child-Pays-For-Parent technique to accelerate the swap transactions in an order.

func (*Core) AccelerationEstimate added in v0.5.0

func (c *Core) AccelerationEstimate(oidB dex.Bytes, newFeeRate uint64) (uint64, error)

AccelerationEstimate returns the amount of funds that would be needed to accelerate the swap transactions in an order to a desired fee rate.

func (*Core) AccountExport added in v0.2.0

func (c *Core) AccountExport(pw []byte, host string) (*Account, []*db.Bond, error)

AccountExport is used to retrieve account by host for export.

func (*Core) AccountImport added in v0.2.0

func (c *Core) AccountImport(pw []byte, acct *Account, bonds []*db.Bond) error

AccountImport is used import an existing account into the db.

func (*Core) AckNotes

func (c *Core) AckNotes(ids []dex.Bytes)

AckNotes sets the acknowledgement field for the notifications.

func (*Core) Active added in v1.0.0

func (c *Core) Active() bool

Active indicates if there are any active orders across all configured accounts. This includes booked orders and trades that are settling.

func (*Core) ActiveOrders added in v1.0.0

func (c *Core) ActiveOrders() (map[string][]*Order, map[string][]*InFlightOrder, error)

ActiveOrders returns a map of host to all of their active orders from db if core is not yet logged in or from loaded trades map if core is logged in. Inflight orders are also returned for all dex servers if any.

func (*Core) AddDEX added in v0.6.0

func (c *Core) AddDEX(appPW []byte, dexAddr string, certI any) error

AddDEX configures a view-only DEX connection. This allows watching trade activity without setting up account keys or communicating account identity with the DEX. DiscoverAccount, PostBond may be used to set up a trading account for this DEX if required.

func (*Core) AddWalletPeer added in v0.6.0

func (c *Core) AddWalletPeer(assetID uint32, address string) error

AddWalletPeer connects the wallet to a new peer, and also persists this peer to be connected to on future startups.

func (*Core) ApproveToken added in v1.0.0

func (c *Core) ApproveToken(appPW []byte, assetID uint32, dexAddr string, onConfirm func()) (string, error)

ApproveToken calls a wallet's ApproveToken method. It approves the version of the token used by the dex at the specified address.

func (*Core) ApproveTokenFee added in v1.0.0

func (c *Core) ApproveTokenFee(assetID uint32, version uint32, approval bool) (uint64, error)

ApproveTokenFee returns the fee for a token approval/unapproval.

func (*Core) AssetBalance

func (c *Core) AssetBalance(assetID uint32) (*WalletBalance, error)

AssetBalance retrieves and updates the current wallet balance.

func (*Core) AutoWalletConfig

func (c *Core) AutoWalletConfig(assetID uint32, walletType string) (map[string]string, error)

AutoWalletConfig attempts to load setting from a wallet package's asset.WalletInfo.DefaultConfigPath. If settings are not found, an empty map is returned.

func (*Core) BackupDB added in v0.4.2

func (c *Core) BackupDB(dst string, overwrite, compact bool) error

BackupDB makes a backup of the database at the specified location, optionally overwriting any existing file and compacting the database.

func (*Core) BondsFeeBuffer added in v0.6.0

func (c *Core) BondsFeeBuffer(assetID uint32) (uint64, error)

BondsFeeBuffer suggests how much extra may be required for the transaction fees part of bond reserves when bond rotation is enabled. This may be used to inform the consumer how much extra (beyond double the bond amount) is required to facilitate uninterrupted maintenance of a target trading tier.

func (*Core) Book

func (c *Core) Book(dex string, base, quote uint32) (*OrderBook, error)

Book fetches the order book. If a subscription doesn't exist, one will be attempted and immediately closed.

func (*Core) Broadcast added in v1.0.0

func (c *Core) Broadcast(n Notification)

func (*Core) Cancel

func (c *Core) Cancel(oidB dex.Bytes) error

func (*Core) ChangeAppPass added in v0.2.0

func (c *Core) ChangeAppPass(appPW, newAppPW []byte) error

ChangeAppPass updates the application password to the provided new password after validating the current password.

func (*Core) CloseWallet

func (c *Core) CloseWallet(assetID uint32) error

CloseWallet closes the wallet for the specified asset. The wallet cannot be closed if there are active negotiations for the asset.

func (*Core) ConfigureFundsMixer added in v1.0.0

func (c *Core) ConfigureFundsMixer(pw []byte, assetID uint32, isMixerEnabled bool) error

ConfigureFundsMixer configures the wallet for funds mixing.

func (*Core) ConnectWallet

func (c *Core) ConnectWallet(assetID uint32) error

ConnectWallet connects to the wallet without unlocking.

func (*Core) CreateWallet

func (c *Core) CreateWallet(appPW, walletPW []byte, form *WalletForm) error

CreateWallet creates a new exchange wallet.

func (*Core) DeleteArchivedRecords added in v0.5.0

func (c *Core) DeleteArchivedRecords(olderThan *time.Time, matchesFile, ordersFile string) (int, error)

DeleteArchivedRecords deletes archived matches from the database and returns the total number of records deleted. Optionally set a time to delete older records and file paths to save deleted records as comma separated values. If a nil *time.Time is provided, current time is used.

func (*Core) DeleteArchivedRecordsWithBackup added in v0.6.0

func (c *Core) DeleteArchivedRecordsWithBackup(olderThan *time.Time, saveMatchesToFile, saveOrdersToFile bool) (string, int, error)

DeleteArchivedRecordsWithBackup is like DeleteArchivedRecords but the required filepaths are provided by Core and the path where archived records are stored is returned.

func (*Core) DiscoverAccount added in v0.4.0

func (c *Core) DiscoverAccount(dexAddr string, appPW []byte, certI any) (*Exchange, bool, error)

DiscoverAccount fetches the DEX server's config, and if the server supports the new deterministic account derivation scheme by providing its public key in the config response, DiscoverAccount also checks if the account is already paid. If the returned paid value is true, the account is ready for immediate use. If paid is false, Register should be used to complete the registration. For an older server that does not provide its pubkey in the config response, paid will always be false and the user should proceed to use Register.

The purpose of DiscoverAccount is existing account discovery when the client has been restored from seed. As such, DiscoverAccount is not strictly necessary to register on a DEX, and Register may be called directly, although it requires the expected fee amount as an additional input and it will pay the fee if the account is not discovered and paid.

The Tier and BondsPending fields may be consulted to determine if it is still necessary to PostBond (i.e. Tier == 0 && !BondsPending) before trading. The Connected field should be consulted first.

func (*Core) EstimateSendTxFee added in v0.6.0

func (c *Core) EstimateSendTxFee(address string, assetID uint32, amount uint64, subtract, maxWithdraw bool) (fee uint64, isValidAddress bool, err error)

EstimateSendTxFee returns an estimate of the tx fee needed to send or withdraw the specified amount.

func (*Core) Exchange added in v0.5.0

func (c *Core) Exchange(host string) (*Exchange, error)

Exchange returns an exchange with a certain host. It returns an error if no exchange exists at that host.

func (*Core) ExchangeMarket added in v1.0.0

func (c *Core) ExchangeMarket(host string, baseID, quoteID uint32) (*Market, error)

ExchangeMarket returns the market with the given base and quote assets at the given host. It returns an error if no market exists at that host.

func (*Core) Exchanges

func (c *Core) Exchanges() map[string]*Exchange

Exchanges creates a map of *Exchange keyed by host, including markets and orders.

func (*Core) ExportSeed added in v0.4.0

func (c *Core) ExportSeed(pw []byte) (seedStr string, err error)

ExportSeed exports the application seed.

func (*Core) ExtensionModeConfig added in v1.0.0

func (c *Core) ExtensionModeConfig() *ExtensionModeConfig

ExtensionModeConfig is the configuration parsed from the extension-mode file.

func (*Core) FiatConversionRates added in v1.0.0

func (c *Core) FiatConversionRates() map[uint32]float64

FiatConversionRates are the currently cached fiat conversion rates. Must have 1 or more fiat rate sources enabled.

func (*Core) FiatRateSources added in v0.5.0

func (c *Core) FiatRateSources() map[string]bool

FiatRateSources returns a list of fiat rate sources and their individual status.

func (*Core) FundsMixingStats added in v1.0.0

func (c *Core) FundsMixingStats(assetID uint32) (*asset.FundsMixingStats, error)

FundsMixingStats returns the current state of the wallet's funds mixer.

func (*Core) GenerateBCHRecoveryTransaction added in v1.0.0

func (c *Core) GenerateBCHRecoveryTransaction(appPW []byte, recipient string) ([]byte, error)

GenerateBCHRecoveryTransaction generates a tx that spends all inputs from the deprecated BCH wallet to the given recipient.

func (*Core) GetDEXConfig added in v0.2.0

func (c *Core) GetDEXConfig(dexAddr string, certI any) (*Exchange, error)

GetDEXConfig creates a temporary connection to the specified DEX Server and fetches the full exchange config. The connection is closed after the config is retrieved. An error is returned if user is already registered to the DEX since a DEX connection is already established and the config is accessible via the User or Exchanges methods. A TLS certificate, certI, can be provided as either a string filename, or []byte file contents.

func (*Core) InitializeClient

func (c *Core) InitializeClient(pw []byte, restorationSeed *string) (string, error)

InitializeClient sets the initial app-wide password and app seed for the client. The seed argument should be left nil unless restoring from seed.

func (*Core) IsInitialized

func (c *Core) IsInitialized() bool

IsInitialized checks if the app is already initialized.

func (*Core) Language added in v1.0.0

func (c *Core) Language() string

Language is the currently configured language.

func (*Core) ListVSPs added in v1.0.0

func (c *Core) ListVSPs(assetID uint32) ([]*asset.VotingServiceProvider, error)

ListVSPs lists known available voting service providers.

func (*Core) Login

func (c *Core) Login(pw []byte) error

Login logs the user in. On the first login after startup or after a logout, this function will connect wallets, resolve active trades, and decrypt account keys for all known DEXes. Otherwise, it will only check whether or not the app pass is correct.

func (*Core) Logout

func (c *Core) Logout() error

Logout logs the user out

func (*Core) MarketConfig added in v1.0.0

func (c *Core) MarketConfig(host string, baseID, quoteID uint32) (*msgjson.Market, error)

MarketConfig gets the configuration for the market.

func (*Core) MaxBuy added in v0.2.0

func (c *Core) MaxBuy(host string, baseID, quoteID uint32, rate uint64) (*MaxOrderEstimate, error)

MaxBuy is the maximum-sized *OrderEstimate for a buy order on the specified market. An order rate must be provided, since the number of lots available for trading will vary based on the rate for a buy order (unlike a sell order).

func (*Core) MaxFundingFees added in v1.0.0

func (c *Core) MaxFundingFees(fromAsset uint32, host string, numTrades uint32, options map[string]string) (uint64, error)

MaxFundingFees gives the max fees required to fund a Trade or MultiTrade. The host is needed to get the MaxFeeRate, which is used to calculate the funding fees.

func (*Core) MaxSell added in v0.2.0

func (c *Core) MaxSell(host string, base, quote uint32) (*MaxOrderEstimate, error)

MaxSell is the maximum-sized *OrderEstimate for a sell order on the specified market.

func (*Core) MultiTrade added in v1.0.0

func (c *Core) MultiTrade(pw []byte, form *MultiTradeForm) []*MultiTradeResult

MultiTrade is used to place multiple standing limit orders on the same side of the same market simultaneously.

func (*Core) Network

func (c *Core) Network() dex.Network

Network returns the current DEX network.

func (*Core) NetworkFeeRate added in v1.0.0

func (c *Core) NetworkFeeRate(assetID uint32) uint64

NetworkFeeRate generates a network tx fee rate for the specified asset. If the wallet implements FeeRater, the wallet will be queried for the fee rate. If the wallet is not a FeeRater, local book feed caches are checked. If no relevant books are synced, connected DCRDEX servers will be queried.

func (*Core) NewDepositAddress

func (c *Core) NewDepositAddress(assetID uint32) (string, error)

NewDepositAddress retrieves a new deposit address from the specified asset's wallet, saves it to the database, and emits a notification. If the wallet does not support generating new addresses, the current address will be returned.

func (*Core) NotificationFeed

func (c *Core) NotificationFeed() *NoteFeed

NotificationFeed returns a new receiving channel for notifications. The channel has capacity 1024, and should be monitored for the lifetime of the Core. Blocking channels are silently ignored.

func (*Core) Notifications added in v0.6.0

func (c *Core) Notifications(n int) (notes, pokes []*db.Notification, _ error)

Notifications loads the latest notifications from the db.

func (*Core) OpenWallet

func (c *Core) OpenWallet(assetID uint32, appPW []byte) error

OpenWallet opens (unlocks) the wallet for use.

func (*Core) Order

func (c *Core) Order(oidB dex.Bytes) (*Order, error)

Order fetches a single user order.

func (*Core) Orders

func (c *Core) Orders(filter *OrderFilter) ([]*Order, error)

Orders fetches a batch of user orders, filtered with the provided OrderFilter.

func (*Core) PostBond added in v0.6.0

func (c *Core) PostBond(form *PostBondForm) (*PostBondResult, error)

PostBond begins the process of posting a new bond for a new or existing DEX account. On return, the bond transaction will have been broadcast, and when the required number of confirmations is reached, Core will submit the bond for acceptance to the server. A TopicBondConfirmed is emitted when the fully-confirmed bond is accepted. Before the transaction is broadcasted, a prevalidatebond request is sent to ensure the transaction is compliant and (and that the intended server is actually online!). PostBond may be used to create a new account with a bond, or to top-up bond on an existing account. If the account is not yet configured in Core, account discovery will be performed prior to posting a new bond. If account discovery finds an existing account, the connection is established but no additional bond is posted. If no account is discovered on the server, the account is created locally and bond is posted to create the account.

Note that the FeeBuffer field of the form is optional, but it may be provided to ensure that the wallet reserves the amount reported by a preceding call to BondsFeeBuffer, such as during initial wallet funding.

func (*Core) PreAccelerateOrder added in v0.5.0

func (c *Core) PreAccelerateOrder(oidB dex.Bytes) (*PreAccelerate, error)

PreAccelerateOrder returns information the user can use to decide how much to accelerate stuck swap transactions in an order.

func (*Core) PreOrder added in v0.2.0

func (c *Core) PreOrder(form *TradeForm) (*OrderEstimate, error)

PreOrder calculates fee estimates for a trade.

func (*Core) PurchaseTickets added in v1.0.0

func (c *Core) PurchaseTickets(assetID uint32, pw []byte, n int) error

PurchaseTickets purchases n tickets. Returns the purchased ticket hashes if successful. Used for ticket purchasing.

func (*Core) Ready

func (c *Core) Ready() <-chan struct{}

Ready returns a channel that is closed when Run completes its initialization tasks and Core becomes ready for use.

func (*Core) ReconfigureWallet

func (c *Core) ReconfigureWallet(appPW, newWalletPW []byte, form *WalletForm) error

ReconfigureWallet updates the wallet configuration settings, it also updates the password if newWalletPW is non-nil. Do not make concurrent calls to ReconfigureWallet for the same asset.

func (*Core) RecoverWallet added in v0.5.0

func (c *Core) RecoverWallet(assetID uint32, appPW []byte, force bool) error

RecoverWallet will retrieve some recovery information from the wallet, which may not be possible if the wallet is too corrupted. Disconnect and destroy the old wallet, create a new one, and if the recovery information was retrieved from the old wallet, send this information to the new one. If force is false, this will check for active orders involving this asset before initiating a rescan. WARNING: It is ill-advised to initiate a wallet recovery with active orders unless the wallet db is definitely corrupted and even a rescan will not save it.

DO NOT MAKE CONCURRENT CALLS TO THIS FUNCTION WITH THE SAME ASSET.

func (*Core) RedeemGeocode added in v1.0.0

func (c *Core) RedeemGeocode(appPW, code []byte, msg string) (dex.Bytes, uint64, error)

RedeemGeocode redeems the provided game code with the wallet and redeems the prepaid bond (code is a prepaid bond). If the user is not registered with dex.decred.org yet, the dex will be added first.

func (*Core) RedeemPrepaidBond added in v1.0.0

func (c *Core) RedeemPrepaidBond(appPW []byte, code []byte, host string, certI any) (tier uint64, err error)

RedeemPrepaidBond redeems a pre-paid bond for a dcrdex host server.

func (*Core) RemoveWalletPeer added in v0.6.0

func (c *Core) RemoveWalletPeer(assetID uint32, address string) error

RemoveWalletPeer disconnects from a peer that the user previously added. It will no longer be guaranteed to connect to this peer in the future.

func (*Core) RescanWallet added in v0.4.1

func (c *Core) RescanWallet(assetID uint32, force bool) error

RescanWallet will issue a Rescan command to the wallet if supported by the wallet implementation. It is up to the underlying wallet backend if and how to implement this functionality. It may be asynchronous. Core will emit wallet state notifications until the rescan is complete. If force is false, this will check for active orders involving this asset before initiating a rescan. WARNING: It is ill-advised to initiate a wallet rescan with active orders unless as a last ditch effort to get the wallet to recognize a transaction needed to complete a swap.

func (*Core) ResetAppPass added in v1.0.0

func (c *Core) ResetAppPass(newPass []byte, seedStr string) (err error)

ResetAppPass resets the application password to the provided new password.

func (*Core) Run

func (c *Core) Run(ctx context.Context)

Run runs the core. Satisfies the runner.Runner interface.

func (*Core) Send added in v0.5.0

func (c *Core) Send(pw []byte, assetID uint32, value uint64, address string, subtract bool) (asset.Coin, error)

Send initiates either send or withdraw from an exchange wallet. if subtract is true, fees are subtracted from the value else fees are taken from the exchange wallet.

func (*Core) SetLanguage added in v1.0.0

func (c *Core) SetLanguage(lang string) error

SetLanguage sets the langauge used for notifications. The language set with SetLanguage persists through restarts and will override any language set in configuration.

func (*Core) SetVSP added in v1.0.0

func (c *Core) SetVSP(assetID uint32, addr string) error

SetVSP sets the VSP provider. Used for ticket purchasing.

func (*Core) SetVotingPreferences added in v1.0.0

func (c *Core) SetVotingPreferences(assetID uint32, choices, tSpendPolicy,
	treasuryPolicy map[string]string) error

SetVotingPreferences sets default voting settings for all active tickets and future tickets. Nil maps can be provided for no change. Used for ticket purchasing.

func (*Core) SetWalletPassword

func (c *Core) SetWalletPassword(appPW []byte, assetID uint32, newPW []byte) error

SetWalletPassword updates the (encrypted) password for the wallet. Returns passwordErr if provided newPW is nil. The wallet will be connected if it is not already.

func (*Core) SingleLotFees added in v1.0.0

func (c *Core) SingleLotFees(form *SingleLotFeesForm) (swapFees, redeemFees, refundFees uint64, err error)

SingleLotFees returns the estimated swap, refund, and redeem fees for a single lot trade.

func (*Core) StakeStatus added in v1.0.0

func (c *Core) StakeStatus(assetID uint32) (*asset.TicketStakingStatus, error)

StakeStatus returns current staking statuses such as currently owned tickets, ticket price, and current voting preferences. Used for ticket purchasing.

func (*Core) SupportedAssets

func (c *Core) SupportedAssets() map[uint32]*SupportedAsset

SupportedAssets returns a map of asset information for supported assets.

func (*Core) SyncBook

func (c *Core) SyncBook(host string, base, quote uint32) (*orderbook.OrderBook, BookFeed, error)

SyncBook subscribes to the order book and returns the book and a BookFeed to receive order book updates. The BookFeed must be Close()d when it is no longer in use.

func (*Core) TakeAction added in v1.0.0

func (c *Core) TakeAction(assetID uint32, actionID string, actionB json.RawMessage) (err error)

TakeAction is called in response to a ActionRequiredNote. The note may have come from core or from a wallet.

func (*Core) TicketPage added in v1.0.0

func (c *Core) TicketPage(assetID uint32, scanStart int32, n, skipN int) ([]*asset.Ticket, error)

TicketPage fetches a page of TicketBuyer tickets within a range of block numbers with a target page size and optional offset. scanStart it the block in which to start the scan. The scan progresses in reverse block number order, starting at scanStart and going to progressively lower blocks. scanStart can be set to -1 to indicate the current chain tip.

func (*Core) ToggleAccountStatus added in v1.0.1

func (c *Core) ToggleAccountStatus(pw []byte, host string, disable bool) error

ToggleAccountStatus is used to disable or enable an account by given host and application password.

func (*Core) ToggleRateSourceStatus added in v0.5.0

func (c *Core) ToggleRateSourceStatus(source string, disable bool) error

ToggleRateSourceStatus toggles a fiat rate source status. If disable is true, the fiat rate source is disabled, otherwise the rate source is enabled.

func (*Core) ToggleWalletStatus added in v0.6.0

func (c *Core) ToggleWalletStatus(assetID uint32, disable bool) error

ToggleWalletStatus changes a wallet's status to either disabled or enabled.

func (*Core) Trade

func (c *Core) Trade(pw []byte, form *TradeForm) (*Order, error)

Trade is used to place a market or limit order.

func (*Core) TradeAsync added in v0.6.0

func (c *Core) TradeAsync(pw []byte, form *TradeForm) (*InFlightOrder, error)

TradeAsync is like Trade but a temporary order is returned before order server validation. This helps handle some issues related to UI/UX where server response might take a fairly long time (15 - 20s).

func (*Core) TradingLimits added in v1.0.1

func (c *Core) TradingLimits(host string) (userParcels, parcelLimit uint32, err error)

TradingLimits returns the number of parcels the user can trade on an exchange and the amount that are currently being traded.

func (*Core) TxHistory added in v1.0.0

func (c *Core) TxHistory(assetID uint32, n int, refID *string, past bool) ([]*asset.WalletTransaction, error)

TxHistory returns all the transactions a wallet has made. If refID is nil, then transactions starting from the most recent are returned (past is ignored). If past is true, the transactions prior to the refID are returned, otherwise the transactions after the refID are returned. n is the number of transactions to return. If n is <= 0, all the transactions will be returned

func (*Core) UnapproveToken added in v1.0.0

func (c *Core) UnapproveToken(appPW []byte, assetID uint32, version uint32) (string, error)

UnapproveToken calls a wallet's UnapproveToken method for a specified version of the token.

func (*Core) UpdateBondOptions added in v0.6.0

func (c *Core) UpdateBondOptions(form *BondOptionsForm) error

UpdateBondOptions sets the bond rotation options for a DEX host, including the target trading tier, the preferred asset to use for bonds, and the maximum amount allowable to be locked in bonds.

func (*Core) UpdateCert added in v0.5.0

func (c *Core) UpdateCert(host string, cert []byte) error

UpdateCert attempts to connect to a server using a new TLS certificate. If the connection is successful, then the cert in the database is updated. Updating cert for already connected dex will return an error.

func (*Core) UpdateDEXHost added in v0.5.0

func (c *Core) UpdateDEXHost(oldHost, newHost string, appPW []byte, certI any) (*Exchange, error)

UpdateDEXHost updates the host for a connection to a dex. The dex at oldHost and newHost must be the same dex, which means that the dex at both hosts use the same public key.

func (*Core) User

func (c *Core) User() *User

User is a thread-safe getter for the User.

func (*Core) ValidateAddress added in v0.6.0

func (c *Core) ValidateAddress(address string, assetID uint32) (bool, error)

ValidateAddress checks that the provided address is valid.

func (*Core) WalletLogFilePath added in v0.4.1

func (c *Core) WalletLogFilePath(assetID uint32) (string, error)

WalletLogFilePath returns the path to the wallet's log file.

func (*Core) WalletPeers added in v0.6.0

func (c *Core) WalletPeers(assetID uint32) ([]*asset.WalletPeer, error)

WalletPeers returns a list of peers that a wallet is connected to. It also returns the user added peers that the wallet is not connected to.

func (*Core) WalletRestorationInfo added in v0.5.0

func (c *Core) WalletRestorationInfo(pw []byte, assetID uint32) ([]*asset.WalletRestoration, error)

WalletRestorationInfo returns information about how to restore the currently loaded wallet for assetID in various external wallet software. This function will return an error if the currently loaded wallet for assetID does not implement the WalletRestorer interface.

func (*Core) WalletSettings

func (c *Core) WalletSettings(assetID uint32) (map[string]string, error)

WalletSettings fetches the current wallet configuration details from the database.

func (*Core) WalletState

func (c *Core) WalletState(assetID uint32) *WalletState

WalletState returns the *WalletState for the asset ID.

func (*Core) WalletTraits added in v1.0.0

func (c *Core) WalletTraits(assetID uint32) (asset.WalletTrait, error)

WalletTraits gets the traits for the wallet.

func (*Core) WalletTransaction added in v1.0.0

func (c *Core) WalletTransaction(assetID uint32, txID string) (*asset.WalletTransaction, error)

WalletTransaction returns information about a transaction that the wallet has made or one in which that wallet received funds. This function supports both transaction ID and coin ID.

func (*Core) Wallets

func (c *Core) Wallets() []*WalletState

Wallets creates a slice of WalletState for all known wallets.

type DEXAuthNote

type DEXAuthNote struct {
	db.Notification
	Host          string `json:"host"`
	Authenticated bool   `json:"authenticated"`
}

DEXAuthNote is a notification regarding individual DEX authentication status.

type EpochMatchSummaryPayload added in v1.0.0

type EpochMatchSummaryPayload struct {
	MatchSummaries []*orderbook.MatchSummary `json:"matchSummaries"`
	Epoch          uint64                    `json:"epoch"`
}

type EpochNotification

type EpochNotification struct {
	db.Notification
	Host     string `json:"host"`
	MarketID string `json:"marketID"`
	Epoch    uint64 `json:"epoch"`
}

EpochNotification is a data notification that a new epoch has begun.

func (*EpochNotification) String

func (on *EpochNotification) String() string

String supplements db.Notification's Stringer with the Epoch index.

type Error

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

Error is an error code and a wrapped error.

func (*Error) Code added in v0.4.0

func (e *Error) Code() *int

Code returns the error code.

func (*Error) Error

func (e *Error) Error() string

Error returns the error string. Satisfies the error interface.

func (*Error) Unwrap added in v0.5.0

func (e *Error) Unwrap() error

Unwrap returns the underlying wrapped error.

type Exchange

type Exchange struct {
	Host             string                 `json:"host"`
	AcctID           string                 `json:"acctID"`
	Markets          map[string]*Market     `json:"markets"`
	Assets           map[uint32]*dex.Asset  `json:"assets"`
	BondExpiry       uint64                 `json:"bondExpiry"`
	BondAssets       map[string]*BondAsset  `json:"bondAssets"`
	ConnectionStatus comms.ConnectionStatus `json:"connectionStatus"`
	CandleDurs       []string               `json:"candleDurs"`
	ViewOnly         bool                   `json:"viewOnly"`
	Auth             ExchangeAuth           `json:"auth"`
	PenaltyThreshold uint32                 `json:"penaltyThreshold"`
	MaxScore         uint32                 `json:"maxScore"`
	Disabled         bool                   `json:"disabled"`
}

Exchange represents a single DEX with any number of markets.

type ExchangeAuth added in v1.0.0

type ExchangeAuth struct {
	// Rep is the user's Reputation as reported by the DEX server.
	Rep account.Reputation `json:"rep"`
	// BondAssetID is the user's currently configured bond asset.
	BondAssetID uint32 `json:"bondAssetID"`
	// PendingStrength counts how many tiers are in unconfirmed bonds.
	PendingStrength int64 `json:"pendingStrength"`
	// WeakStrength counts the number of tiers that are about to expire.
	WeakStrength int64 `json:"weakStrength"`
	// LiveStrength counts all active bond tiers, including weak.
	LiveStrength int64 `json:"liveStrength"`
	// TargetTier is the user's current configured tier level.
	TargetTier uint64 `json:"targetTier"`
	// EffectiveTier is the user's current tier, after considering reputation.
	EffectiveTier int64 `json:"effectiveTier"`
	// MaxBondedAmt is the maximum amount that can be locked in bonds at a given
	// time. If not provided, a default is calculated based on TargetTier and
	// PenaltyComps.
	MaxBondedAmt uint64 `json:"maxBondedAmt"`
	// PenaltyComps is the maximum number of penalized tiers to automatically
	// compensate.
	PenaltyComps uint16 `json:"penaltyComps"`
	// PendingBonds are currently pending bonds and their confirmation count.
	PendingBonds []*PendingBondState `json:"pendingBonds"`
	// ExpiredBonds are bonds that have expired but have not yet reached their
	// lock time for refunding.
	ExpiredBonds []*db.Bond `json:"expiredBonds"`
	// Compensation is the amount we have locked in bonds greater than what
	// is needed to maintain our target tier. This could be from penalty
	// compensation, or it could be due to the user lowering their target tier.
	Compensation int64 `json:"compensation"`
}

ExchangeAuth is data characterizing the state of client bonding.

type ExpirationErr

type ExpirationErr string

ExpirationErr indicates that the wait.TickerQueue has expired a waiter, e.g. a reported coin was not found before the set expiration time.

func (ExpirationErr) Error

func (err ExpirationErr) Error() string

Error satisfies the error interface for ExpirationErr.

type ExtensionModeConfig added in v0.6.3

type ExtensionModeConfig struct {
	// Name of embedding application. Used for messaging with disable features.
	Name string `json:"name"`
	// UseDEXBranding will tell the front end to use DCRDEX branding instead
	// of Bison Wallet branding where possible.
	UseDEXBranding bool `json:"useDEXBranding"`
	// RestrictedWallets are wallets that need restrictions on reconfiguration
	// options.
	RestrictedWallets map[string]struct {
		// HiddenFields are configuration fields (asset.ConfigOption.Key) that
		// should not be displayed to the user.
		HiddenFields []string `json:"hiddenFields"`
		// DisableWalletType indicates that we should not offer the user an
		// an option to change the wallet type.
		DisableWalletType bool `json:"disableWalletType"`
		// DisablePassword indicates that we should not offer the user an option
		// to change the wallet password.
		DisablePassword bool `json:"disablePassword"`
		// DisableStaking disables vsp configuration and ticket purchasing.
		DisableStaking bool `json:"disableStaking"`
		// DisablePrivacy disables mixing configuration and control.
		DisablePrivacy bool `json:"disablePrivacy"`
	} `json:"restrictedWallets"`
}

ExtensionModeConfig is configuration for running core in extension mode, primarily for restricting certain wallet reconfiguration options.

type FeeBreakdown

type FeeBreakdown struct {
	Swap       uint64 `json:"swap"`
	Redemption uint64 `json:"redemption"`
	Funding    uint64 `json:"funding"` // split fees
	// TODO: Refund is not yet being populated.
	Refund uint64 `json:"refund"`
}

FeeBreakdown is categorized fee information.

type FeePaymentNote

type FeePaymentNote struct {
	db.Notification
	Asset         *uint32 `json:"asset,omitempty"`
	Confirmations *uint32 `json:"confirmations,omitempty"`
	Dex           string  `json:"dex,omitempty"`
}

FeePaymentNote is a notification regarding registration fee payment.

type FeeState added in v1.0.0

type FeeState struct {
	Rate    uint64 `json:"rate"`
	Send    uint64 `json:"send"`
	Swap    uint64 `json:"swap"`
	Redeem  uint64 `json:"redeem"`
	Refund  uint64 `json:"refund"`
	StampMS int64  `json:"stampMS"`
}

FeeState is information about the current network transaction fees and estimates of standard operations.

type FiatRatesNote added in v0.5.0

type FiatRatesNote struct {
	db.Notification
	FiatRates map[uint32]float64 `json:"fiatRates"`
}

FiatRatesNote is an update of fiat rate data for assets.

type InFlightOrder added in v0.6.0

type InFlightOrder struct {
	*Order
	TemporaryID uint64 `json:"tempID"`
}

InFlightOrder is an Order that is not stamped yet, but has a temporary ID to match once order submission is complete.

type LoginNote added in v0.6.0

type LoginNote struct {
	db.Notification
}

LoginNote is a notification with the recent login status.

type Market

type Market struct {
	Name            string        `json:"name"`
	BaseID          uint32        `json:"baseid"`
	BaseSymbol      string        `json:"basesymbol"`
	QuoteID         uint32        `json:"quoteid"`
	QuoteSymbol     string        `json:"quotesymbol"`
	LotSize         uint64        `json:"lotsize"`
	ParcelSize      uint32        `json:"parcelsize"`
	RateStep        uint64        `json:"ratestep"`
	EpochLen        uint64        `json:"epochlen"`
	StartEpoch      uint64        `json:"startepoch"`
	MarketBuyBuffer float64       `json:"buybuffer"`
	Orders          []*Order      `json:"orders"`
	SpotPrice       *msgjson.Spot `json:"spot"`
	// AtomToConv is a rate conversion factor. Multiply by AtomToConv to convert
	// an atomic rate (e.g. gwei/sat) to a conventional rate (ETH/BTC). Divide
	// by AtomToConv to convert a conventional rate to an atomic rate.
	AtomToConv float64 `json:"atomToConv"`
	// InFlightOrders are Orders with zeroed IDs for the embedded Order, but
	// with a TemporaryID to match with a notification once asynchronous order
	// submission is complete.
	InFlightOrders []*InFlightOrder `json:"inflight"`
	// MinimumRate is the minimum rate allowed for the market, which is the
	// minimum rate at which 1 lot converts to something greater than dust.
	MinimumRate uint64 `json:"minimumRate"`
}

Market is market info.

func (*Market) BaseContractLocked

func (m *Market) BaseContractLocked() uint64

BaseContractLocked is the amount of base asset locked in un-redeemed contracts.

func (*Market) BaseOrderLocked

func (m *Market) BaseOrderLocked() uint64

BaseOrderLocked is the amount of base asset locked in epoch or booked orders.

func (*Market) ConventionalRateToMsg added in v0.6.0

func (m *Market) ConventionalRateToMsg(p float64) uint64

ConventionalRateToMsg converts a conventional rate to a message-rate.

func (*Market) Display

func (m *Market) Display() string

Display returns an ID string suitable for displaying in a UI.

func (*Market) MsgRateToConventional added in v0.6.0

func (m *Market) MsgRateToConventional(r uint64) float64

MsgRateToConventional converts a message-rate to a conventional rate.

func (*Market) QuoteContractLocked

func (m *Market) QuoteContractLocked() uint64

QuoteContractLocked is the amount of quote asset locked in un-redeemed contracts.

func (*Market) QuoteOrderLocked

func (m *Market) QuoteOrderLocked() uint64

QuoteOrderLocked is the amount of quote asset locked in epoch or booked orders.

type MarketOrderBook

type MarketOrderBook struct {
	Base  uint32     `json:"base"`
	Quote uint32     `json:"quote"`
	Book  *OrderBook `json:"book"`
}

MarketOrderBook is used as the BookUpdate's Payload with the FreshBookAction. The subscriber will likely need to translate into a JSON tagged type.

type Match

type Match struct {
	MatchID       dex.Bytes         `json:"matchID"`
	Status        order.MatchStatus `json:"status"`
	Active        bool              `json:"active"`
	Revoked       bool              `json:"revoked"`
	Rate          uint64            `json:"rate"`
	Qty           uint64            `json:"qty"`
	Side          order.MatchSide   `json:"side"`
	FeeRate       uint64            `json:"feeRate"`
	Swap          *Coin             `json:"swap,omitempty"`
	CounterSwap   *Coin             `json:"counterSwap,omitempty"`
	Redeem        *Coin             `json:"redeem,omitempty"`
	CounterRedeem *Coin             `json:"counterRedeem,omitempty"`
	Refund        *Coin             `json:"refund,omitempty"`
	Stamp         uint64            `json:"stamp"` // Server's time stamp - we have no local time recorded
	IsCancel      bool              `json:"isCancel"`
}

Match represents a match on an order. An order may have many matches.

type MatchNote added in v0.2.0

type MatchNote struct {
	db.Notification
	OrderID  dex.Bytes `json:"orderID"`
	Match    *Match    `json:"match"`
	Host     string    `json:"host"`
	MarketID string    `json:"marketID"`
}

MatchNote is a notification about a match.

type MaxOrderEstimate added in v0.2.0

type MaxOrderEstimate struct {
	Swap   *asset.SwapEstimate   `json:"swap"`
	Redeem *asset.RedeemEstimate `json:"redeem"`
}

MaxOrderEstimate is an estimate of the fees and locked amounts associated with an order.

type MiniOrder

type MiniOrder struct {
	Qty       float64 `json:"qty"`
	QtyAtomic uint64  `json:"qtyAtomic"`
	Rate      float64 `json:"rate"`
	MsgRate   uint64  `json:"msgRate"`
	Epoch     uint64  `json:"epoch,omitempty"`
	Sell      bool    `json:"sell"`
	Token     string  `json:"token"`
}

MiniOrder is minimal information about an order in a market's order book. Replaced MiniOrder, which had a float Qty in conventional units.

type MultiTradeForm added in v1.0.0

type MultiTradeForm struct {
	Host       string            `json:"host"`
	Sell       bool              `json:"sell"`
	Base       uint32            `json:"base"`
	Quote      uint32            `json:"quote"`
	Placements []*QtyRate        `json:"placement"`
	Options    map[string]string `json:"options"`
	// MaxLock is the maximum amount of the "from" asset that the wallet
	// should lock for the trade.
	MaxLock uint64 `json:"maxLock"`
}

MultiTradeForm is used to place multiple orders in one go. All orders must be on the same side of the same market, and only standing limit orders are supported.

type MultiTradeResult added in v1.0.1

type MultiTradeResult struct {
	Order *Order
	Error error
}

MultiTradeResult is returned from MultiTrade. Some orders may be placed successfully, while others may fail.

type NoteFeed added in v1.0.0

type NoteFeed struct {
	C <-chan Notification
	// contains filtered or unexported fields
}

NoteFeed contains a receiving channel for notifications.

func (*NoteFeed) ReturnFeed added in v1.0.0

func (c *NoteFeed) ReturnFeed()

ReturnFeed should be called when the channel is no longer needed.

type Notification

type Notification interface {
	// Type is a string ID unique to the concrete type.
	Type() string
	// Topic is a string ID unique to the message subject. Since subjects must
	// be translated, we cannot rely on the subject to programmatically identify
	// the message.
	Topic() Topic
	// Subject is a short description of the notification contents. When displayed
	// to the user, the Subject will typically be given visual prominence. For
	// notifications with Severity < Poke (not meant for display), the Subject
	// field may be repurposed as a second-level category ID.
	Subject() string
	// Details should contain more detailed information.
	Details() string
	// Severity is the notification severity.
	Severity() db.Severity
	// Time is the notification timestamp. The timestamp is set in
	// db.NewNotification. Time is a UNIX timestamp, in milliseconds.
	Time() uint64
	// Acked is true if the user has seen the notification. Acknowledgement is
	// recorded with (*Core).AckNotes.
	Acked() bool
	// ID should be unique, except in the case of identical copies of
	// db.Notification where the IDs should be the same.
	ID() dex.Bytes
	// Stamp sets the notification timestamp. If db.NewNotification is used to
	// construct the db.Notification, the timestamp will already be set.
	Stamp()
	// DBNote returns the underlying *db.Notification.
	DBNote() *db.Notification
	// String generates a compact human-readable representation of the
	// Notification that is suitable for logging.
	String() string
}

Notification is an interface for a user notification. Notification is satisfied by db.Notification, so concrete types can embed the db type.

type Order

type Order struct {
	Host             string            `json:"host"`
	BaseID           uint32            `json:"baseID"`
	BaseSymbol       string            `json:"baseSymbol"`
	QuoteID          uint32            `json:"quoteID"`
	QuoteSymbol      string            `json:"quoteSymbol"`
	MarketID         string            `json:"market"`
	Type             order.OrderType   `json:"type"`
	ID               dex.Bytes         `json:"id"`    // Can be empty if part of an InFlightOrder
	Stamp            uint64            `json:"stamp"` // Server's time stamp
	SubmitTime       uint64            `json:"submitTime"`
	Sig              dex.Bytes         `json:"sig"`
	Status           order.OrderStatus `json:"status"`
	Epoch            uint64            `json:"epoch"`
	Qty              uint64            `json:"qty"`
	Sell             bool              `json:"sell"`
	Filled           uint64            `json:"filled"`
	Matches          []*Match          `json:"matches"`
	Cancelling       bool              `json:"cancelling"`
	Canceled         bool              `json:"canceled"`
	FeesPaid         *FeeBreakdown     `json:"feesPaid"`
	AllFeesConfirmed bool              `json:"allFeesConfirmed"`
	FundingCoins     []*Coin           `json:"fundingCoins"`
	LockedAmt        uint64            `json:"lockedamt"`
	// ParentAssetLockedAmt is the swap fees locked when the "from asset" of a
	// trade is a token. This wil be 0 if the "from asset" is not a token.
	ParentAssetLockedAmt uint64 `json:"parentAssetLockedAmt"`
	// RedeemLockedAmt is the amount locked for redemption fees. If the
	// "to asset" is a token, it will be in units of the parent asset.
	RedeemLockedAmt uint64 `json:"redeemLockedAmt"`
	// RefundLockedAmt is the amount locked for refund fees. If the
	// "from asset" is a token, it will be in units of the parent asset.
	RefundLockedAmt   uint64            `json:"refundLockedAmt"`
	AccelerationCoins []*Coin           `json:"accelerationCoins"`
	Rate              uint64            `json:"rate"`          // limit only
	TimeInForce       order.TimeInForce `json:"tif"`           // limit only
	TargetOrderID     dex.Bytes         `json:"targetOrderID"` // cancel only
	ReadyToTick       bool              `json:"readyToTick"`
}

Order is core's general type for an order. An order may be a market, limit, or cancel order. Some fields are only relevant to particular order types.

type OrderBook

type OrderBook struct {
	Sells []*MiniOrder `json:"sells"`
	Buys  []*MiniOrder `json:"buys"`
	Epoch []*MiniOrder `json:"epoch"`
	// RecentMatches is a cache of up to 100 recent matches for a market.
	RecentMatches []*orderbook.MatchSummary `json:"recentMatches"`
}

OrderBook represents an order book, which are sorted buys and sells, and unsorted epoch orders.

type OrderEstimate added in v0.2.0

type OrderEstimate struct {
	Swap   *asset.PreSwap   `json:"swap"`
	Redeem *asset.PreRedeem `json:"redeem"`
}

OrderEstimate is a Core.PreOrder estimate.

type OrderFilter

type OrderFilter struct {
	N        int                 `json:"n"`
	Offset   dex.Bytes           `json:"offset"`
	Hosts    []string            `json:"hosts"`
	Assets   []uint32            `json:"assets"`
	Statuses []order.OrderStatus `json:"statuses"`
	Market   *struct {
		Base  uint32 `json:"baseID"`
		Quote uint32 `json:"quoteID"`
	} `json:"market"`
}

OrderFilter is almost the same as db.OrderFilter, except the Offset order ID is a dex.Bytes instead of a order.OrderID.

type OrderNote

type OrderNote struct {
	db.Notification
	Order       *Order `json:"order"`
	TemporaryID uint64 `json:"tempID,omitempty"`
}

OrderNote is a notification about an order or a match.

func (*OrderNote) String

func (on *OrderNote) String() string

String supplements db.Notification's Stringer with the Order's ID, if the Order is not nil.

type OrderReader added in v0.5.0

type OrderReader struct {
	*Order
	BaseUnitInfo        dex.UnitInfo
	BaseFeeUnitInfo     dex.UnitInfo
	BaseFeeAssetSymbol  string
	QuoteUnitInfo       dex.UnitInfo
	QuoteFeeUnitInfo    dex.UnitInfo
	QuoteFeeAssetSymbol string
}

OrderReader wraps a Order and provides methods for info display. Whenever possible, add an OrderReader methods rather than a template func.

func (*OrderReader) AskString added in v0.5.0

func (ord *OrderReader) AskString() string

AskString will print the minimum received amount for the filled limit order. The actual settled amount may be more.

func (*OrderReader) AverageRateString added in v0.5.0

func (ord *OrderReader) AverageRateString() string

AverageRateString returns a formatting string containing the average rate of the matches that have been filled in an order.

func (*OrderReader) BaseAssetFees added in v0.5.0

func (ord *OrderReader) BaseAssetFees() string

BaseAssetFees is a formatted string of the fees paid in the base asset.

func (*OrderReader) BaseFeeSymbol added in v0.6.0

func (ord *OrderReader) BaseFeeSymbol() string

BaseFeeSymbol is the symbol of the asset used to pay the base asset's network fees.

func (*OrderReader) BaseQtyString added in v0.5.0

func (ord *OrderReader) BaseQtyString() string

BaseQtyString formats the order quantity in units of the base asset.

func (*OrderReader) Cancelable added in v0.5.0

func (ord *OrderReader) Cancelable() bool

Cancelable will be true for standing limit orders in status epoch or booked.

func (*OrderReader) FilledFrom added in v0.5.0

func (ord *OrderReader) FilledFrom() string

FilledFrom is the sum filled in units of the outgoing asset. Excludes cancel matches.

func (*OrderReader) FilledPercent added in v0.5.0

func (ord *OrderReader) FilledPercent() string

FilledPercent is the percent of the order that has filled, without percent sign. Excludes cancel matches.

func (*OrderReader) FilledTo added in v0.5.0

func (ord *OrderReader) FilledTo() string

FilledTo is the sum filled in units of the incoming asset. Excludes cancel matches.

func (*OrderReader) FromFeeSymbol added in v0.6.0

func (ord *OrderReader) FromFeeSymbol() string

FromFeeSymbol is the symbol of the asset used to pay swap fees.

func (*OrderReader) FromID added in v0.5.0

func (ord *OrderReader) FromID() uint32

FromID is the asset ID of the asset which will be sent.

func (*OrderReader) FromSymbol added in v0.5.0

func (ord *OrderReader) FromSymbol() string

FromSymbol is the symbol of the asset which will be sent.

func (*OrderReader) FromTicker added in v1.0.0

func (ord *OrderReader) FromTicker() string

FromTicker if the conventional unit for the from asset.

func (*OrderReader) FundingCoinIDs added in v0.5.0

func (ord *OrderReader) FundingCoinIDs() []string

func (*OrderReader) IsMarketBuy added in v0.5.0

func (ord *OrderReader) IsMarketBuy() bool

IsMarketBuy is true if this is a market buy order.

func (*OrderReader) IsMarketOrder added in v0.5.0

func (ord *OrderReader) IsMarketOrder() bool

IsMarketOrder is true if this is a market order.

func (*OrderReader) OfferString added in v0.5.0

func (ord *OrderReader) OfferString() string

OfferString formats the order quantity in units of the outgoing asset, performing a conversion if necessary.

func (*OrderReader) QuoteAssetFees added in v0.5.0

func (ord *OrderReader) QuoteAssetFees() string

QuoteAssetFees is a formatted string of the fees paid in the quote asset.

func (*OrderReader) QuoteFeeSymbol added in v0.6.0

func (ord *OrderReader) QuoteFeeSymbol() string

QuoteFeeSymbol is the symbol of the asset used to pay the quote asset's network fees.

func (*OrderReader) RateString added in v0.5.0

func (ord *OrderReader) RateString() string

RateString is a formatted rate with units.

func (*OrderReader) RedemptionFeesString added in v0.5.0

func (ord *OrderReader) RedemptionFeesString() string

RedemptionFeesString is a formatted string of the paid redemption fees.

func (*OrderReader) SettledFrom added in v0.5.0

func (ord *OrderReader) SettledFrom() string

SettledFrom is the sum settled outgoing asset.

func (*OrderReader) SettledPercent added in v0.5.0

func (ord *OrderReader) SettledPercent() string

SettledPercent is the percent of the order which has completed settlement.

func (*OrderReader) SettledTo added in v0.5.0

func (ord *OrderReader) SettledTo() string

SettledTo is the sum settled of incoming asset.

func (*OrderReader) SideString added in v0.5.0

func (ord *OrderReader) SideString() string

SideString is "sell" for sell orders, "buy" for buy orders, and "" for cancels.

func (*OrderReader) SimpleRateString added in v0.5.0

func (ord *OrderReader) SimpleRateString() string

SimpleRateString is the formatted match rate.

func (*OrderReader) StatusString added in v0.5.0

func (ord *OrderReader) StatusString() string

StatusString is the order status.

IMPORTANT: we have similar function in JS for UI, it must match this one exactly, when updating make sure to update both!

func (*OrderReader) SwapFeesString added in v0.5.0

func (ord *OrderReader) SwapFeesString() string

SwapFeesString is a formatted string of the paid swap fees.

func (*OrderReader) ToFeeSymbol added in v0.6.0

func (ord *OrderReader) ToFeeSymbol() string

ToFeeSymbol is the symbol of the asset used to pay redeem fees.

func (*OrderReader) ToID added in v0.5.0

func (ord *OrderReader) ToID() uint32

FromID is the asset ID of the asset which will be received.

func (*OrderReader) ToSymbol added in v0.5.0

func (ord *OrderReader) ToSymbol() string

FromSymbol is the symbol of the asset which will be received.

func (*OrderReader) ToTicker added in v1.0.0

func (ord *OrderReader) ToTicker() string

ToTicker if the conventional unit for the to asset.

func (*OrderReader) TypeString added in v0.5.0

func (ord *OrderReader) TypeString() string

TypeString combines the order type and side into a single string.

type PendingBondState added in v0.6.0

type PendingBondState struct {
	CoinID  string `json:"coinID"`
	Symbol  string `json:"symbol"`
	AssetID uint32 `json:"assetID"`
	Confs   uint32 `json:"confs"`
}

PendingBondState conveys a pending bond's asset and current confirmation count.

type PostBondForm added in v0.6.0

type PostBondForm struct {
	Addr     string           `json:"host"`
	AppPass  encode.PassBytes `json:"appPass"`
	Asset    *uint32          `json:"assetID,omitempty"` // do not default to 0
	Bond     uint64           `json:"bond"`
	LockTime uint64           `json:"lockTime"` // 0 means go with server-derived value

	// FeeBuffer is optional, to use same value from BondsFeeBuffer during
	// wallet funding. If zero, the wallet will use an internal estimate.
	FeeBuffer uint64 `json:"feeBuffer,omitempty"`

	// These options may be set when creating an account.
	MaintainTier *bool   `json:"maintainTier,omitempty"` // tier implied from Bond amount
	MaxBondedAmt *uint64 `json:"maxBondedAmt,omitempty"`

	// Cert is needed if posting bond to a new DEX. Cert can be a string, which
	// is interpreted as a filepath, or a []byte, which is interpreted as the
	// file contents of the certificate.
	Cert any `json:"cert"`
}

PostBondForm is information necessary to post a new bond for a new or existing DEX account at the specified DEX address.

type PostBondResult added in v0.6.0

type PostBondResult struct {
	BondID      string `json:"bondID"`
	ReqConfirms uint16 `json:"reqConfirms"`
}

PostBondResult holds the data returned from PostBond.

type PreAccelerate added in v0.5.0

type PreAccelerate struct {
	SwapRate          uint64                   `json:"swapRate"`
	SuggestedRate     uint64                   `json:"suggestedRate"`
	SuggestedRange    asset.XYRange            `json:"suggestedRange"`
	EarlyAcceleration *asset.EarlyAcceleration `json:"earlyAcceleration,omitempty"`
}

PreAccelerate gives information that the user can use to decide on how much to accelerate stuck swap transactions in an order.

type QtyRate added in v1.0.0

type QtyRate struct {
	Qty  uint64 `json:"qty"`
	Rate uint64 `json:"rate"`
}

QtyRate specifies the quantity and rate of an order placement.

type RejectedRedemptionData added in v1.0.0

type RejectedRedemptionData struct {
	OrderID dex.Bytes `json:"orderID"`
	CoinID  dex.Bytes `json:"coinID"`
	AssetID uint32    `json:"assetID"`
	CoinFmt string    `json:"coinFmt"`
}

type RemainderUpdate added in v0.4.0

type RemainderUpdate struct {
	Token     string  `json:"token"`
	Qty       float64 `json:"qty"`
	QtyAtomic uint64  `json:"qtyAtomic"`
}

RemainderUpdate is an update to the quantity for an order on the order book. Replaced RemainingUpdate, which had a float Qty in conventional units.

type ReputationNote added in v1.0.0

type ReputationNote struct {
	db.Notification
	Host       string             `json:"host"`
	Reputation account.Reputation `json:"rep"`
}

type ResolvedEpoch added in v1.0.0

type ResolvedEpoch struct {
	Current  uint64 `json:"current"`
	Resolved uint64 `json:"resolved"`
}

type SecurityNote added in v0.4.0

type SecurityNote struct {
	db.Notification
}

SecurityNote is a note regarding application security, credentials, or authentication.

type SendNote added in v0.5.0

type SendNote struct {
	db.Notification
}

SendNote is a notification regarding a requested send or withdraw.

type ServerNotifyNote

type ServerNotifyNote struct {
	db.Notification
}

ServerNotifyNote is a notification containing a server-originating message.

type SingleLotFeesForm added in v1.0.0

type SingleLotFeesForm struct {
	Host          string `json:"host"`
	Base          uint32 `json:"base"`
	Quote         uint32 `json:"quote"`
	Sell          bool   `json:"sell"`
	UseMaxFeeRate bool   `json:"useMaxFeeRate"`
	UseSafeTxSize bool   `json:"useSafeTxSize"`
}

SingleLotFeesForm is used to determine the fees for a single lot trade.

type SpotPriceNote added in v0.4.0

type SpotPriceNote struct {
	db.Notification
	Host  string                   `json:"host"`
	Spots map[string]*msgjson.Spot `json:"spots"`
}

SpotPriceNote is a notification of an update to the market's spot price.

type SupportedAsset

type SupportedAsset struct {
	ID     uint32       `json:"id"`
	Symbol string       `json:"symbol"`
	Name   string       `json:"name"`
	Wallet *WalletState `json:"wallet"`
	// Info is only populated for base chain assets. One of either Info or
	// Token will be populated.
	Info *asset.WalletInfo `json:"info"`
	// Token is only populated for token assets.
	Token    *asset.Token `json:"token"`
	UnitInfo dex.UnitInfo `json:"unitInfo"`
	// WalletCreationPending will be true if this wallet's parent wallet is
	// being synced before this wallet is created.
	WalletCreationPending bool `json:"walletCreationPending"`
}

SupportedAsset is data about an asset and possibly the wallet associated with it.

type Topic added in v0.4.0

type Topic = db.Topic

Topic is a language-independent unique ID for a Notification.

const (
	TopicSeedNeedsSaving Topic = "SeedNeedsSaving"
	TopicUpgradedToSeed  Topic = "UpgradedToSeed"
)
const (
	TopicFeePaymentInProgress    Topic = "FeePaymentInProgress"
	TopicFeePaymentError         Topic = "FeePaymentError"
	TopicFeeCoinError            Topic = "FeeCoinError"
	TopicRegUpdate               Topic = "RegUpdate"
	TopicBondConfirming          Topic = "BondConfirming"
	TopicBondRefunded            Topic = "BondRefunded"
	TopicBondPostError           Topic = "BondPostError"
	TopicBondPostErrorConfirm    Topic = "BondPostErrorConfirm"
	TopicBondCoinError           Topic = "BondCoinError"
	TopicAccountRegistered       Topic = "AccountRegistered"
	TopicAccountUnlockError      Topic = "AccountUnlockError"
	TopicWalletConnectionWarning Topic = "WalletConnectionWarning"
	TopicWalletUnlockError       Topic = "WalletUnlockError"
	TopicWalletCommsWarning      Topic = "WalletCommsWarning"
	TopicWalletPeersRestored     Topic = "WalletPeersRestored"
)
const (
	TopicSendError   Topic = "SendError"
	TopicSendSuccess Topic = "SendSuccess"
)
const (
	TopicOrderLoadFailure     Topic = "OrderLoadFailure"
	TopicOrderResumeFailure   Topic = "OrderResumeFailure"
	TopicBuyOrderPlaced       Topic = "BuyOrderPlaced"
	TopicSellOrderPlaced      Topic = "SellOrderPlaced"
	TopicYoloPlaced           Topic = "YoloPlaced"
	TopicMissingMatches       Topic = "MissingMatches"
	TopicWalletMissing        Topic = "WalletMissing"
	TopicMatchErrorCoin       Topic = "MatchErrorCoin"
	TopicMatchErrorContract   Topic = "MatchErrorContract"
	TopicMatchRecoveryError   Topic = "MatchRecoveryError"
	TopicOrderCoinError       Topic = "OrderCoinError"
	TopicOrderCoinFetchError  Topic = "OrderCoinFetchError"
	TopicPreimageSent         Topic = "PreimageSent"
	TopicCancelPreimageSent   Topic = "CancelPreimageSent"
	TopicMissedCancel         Topic = "MissedCancel"
	TopicOrderBooked          Topic = "OrderBooked"
	TopicNoMatch              Topic = "NoMatch"
	TopicBuyOrderCanceled     Topic = "BuyOrderCanceled"
	TopicSellOrderCanceled    Topic = "SellOrderCanceled"
	TopicCancel               Topic = "Cancel"
	TopicBuyMatchesMade       Topic = "BuyMatchesMade"
	TopicSellMatchesMade      Topic = "SellMatchesMade"
	TopicSwapSendError        Topic = "SwapSendError"
	TopicInitError            Topic = "InitError"
	TopicReportRedeemError    Topic = "ReportRedeemError"
	TopicSwapsInitiated       Topic = "SwapsInitiated"
	TopicRedemptionError      Topic = "RedemptionError"
	TopicMatchComplete        Topic = "MatchComplete"
	TopicRefundFailure        Topic = "RefundFailure"
	TopicMatchesRefunded      Topic = "MatchesRefunded"
	TopicMatchRevoked         Topic = "MatchRevoked"
	TopicOrderRevoked         Topic = "OrderRevoked"
	TopicOrderAutoRevoked     Topic = "OrderAutoRevoked"
	TopicMatchRecovered       Topic = "MatchRecovered"
	TopicCancellingOrder      Topic = "CancellingOrder"
	TopicOrderStatusUpdate    Topic = "OrderStatusUpdate"
	TopicMatchResolutionError Topic = "MatchResolutionError"
	TopicFailedCancel         Topic = "FailedCancel"
	TopicOrderLoaded          Topic = "OrderLoaded"
	TopicOrderRetired         Topic = "OrderRetired"
	TopicAsyncOrderFailure    Topic = "AsyncOrderFailure"
	TopicAsyncOrderSubmitted  Topic = "AsyncOrderSubmitted"
	TopicOrderQuantityTooHigh Topic = "OrderQuantityTooHigh"
)
const (
	TopicAudit                 Topic = "Audit"
	TopicAuditTrouble          Topic = "AuditTrouble"
	TopicNewMatch              Topic = "NewMatch"
	TopicCounterConfirms       Topic = "CounterConfirms"
	TopicConfirms              Topic = "Confirms"
	TopicRedemptionResubmitted Topic = "RedemptionResubmitted"
	TopicSwapRefunded          Topic = "SwapRefunded"
	TopicRedemptionConfirmed   Topic = "RedemptionConfirmed"
)
const (
	TopicDEXConnected    Topic = "DEXConnected"
	TopicDEXDisconnected Topic = "DEXDisconnected"
	TopicDexConnectivity Topic = "DEXConnectivity"
)
const (
	TopicDexAuthError     Topic = "DexAuthError"
	TopicDexAuthErrorBond Topic = "DexAuthErrorBond"
	TopicUnknownOrders    Topic = "UnknownOrders"
	TopicOrdersReconciled Topic = "OrdersReconciled"
	TopicBondConfirmed    Topic = "BondConfirmed"
	TopicBondExpired      Topic = "BondExpired"
	TopicAccountRegTier   Topic = "AccountRegTier"
)
const (
	TopicWalletConfigurationUpdated Topic = "WalletConfigurationUpdated"
	TopicWalletPasswordUpdated      Topic = "WalletPasswordUpdated"
	TopicWalletPeersWarning         Topic = "WalletPeersWarning"
	TopicWalletTypeDeprecated       Topic = "WalletTypeDeprecated"
	TopicWalletPeersUpdate          Topic = "WalletPeersUpdate"
	TopicBondWalletNotConnected     Topic = "BondWalletNotConnected"
)
const (
	TopicMarketSuspendScheduled   Topic = "MarketSuspendScheduled"
	TopicMarketSuspended          Topic = "MarketSuspended"
	TopicMarketSuspendedWithPurge Topic = "MarketSuspendedWithPurge"
	TopicMarketResumeScheduled    Topic = "MarketResumeScheduled"
	TopicMarketResumed            Topic = "MarketResumed"
	TopicPenalized                Topic = "Penalized"
	TopicDEXNotification          Topic = "DEXNotification"
)
const (
	TopicQueuedCreationFailed  Topic = "QueuedCreationFailed"
	TopicQueuedCreationSuccess Topic = "QueuedCreationSuccess"
	TopicCreationQueued        Topic = "CreationQueued"
)
const TopicBalanceUpdated Topic = "BalanceUpdated"
const (
	TopicBondAuthUpdate Topic = "BondAuthUpdate"
)
const TopicEpoch Topic = "Epoch"
const TopicFiatRatesUpdate Topic = "fiatrateupdate"
const TopicLoginStatus Topic = "LoginStatus"
const TopicSpotsUpdate Topic = "SpotsUpdate"
const TopicTokenApproval Topic = "TokenApproval"
const (
	TopicUpgradeNeeded Topic = "UpgradeNeeded"
)
const TopicWalletNotification Topic = "WalletNotification"
const TopicWalletState Topic = "WalletState"

type TradeForm

type TradeForm struct {
	Host    string            `json:"host"`
	IsLimit bool              `json:"isLimit"`
	Sell    bool              `json:"sell"`
	Base    uint32            `json:"base"`
	Quote   uint32            `json:"quote"`
	Qty     uint64            `json:"qty"`
	Rate    uint64            `json:"rate"`
	TifNow  bool              `json:"tifnow"`
	Options map[string]string `json:"options"`
}

TradeForm is used to place a market or limit order

type UpgradeNote added in v0.4.0

type UpgradeNote struct {
	db.Notification
}

UpgradeNote is a notification regarding an outdated client.

type User

type User struct {
	Exchanges          map[string]*Exchange        `json:"exchanges"`
	Initialized        bool                        `json:"inited"`
	SeedGenerationTime uint64                      `json:"seedgentime"`
	Assets             map[uint32]*SupportedAsset  `json:"assets"`
	FiatRates          map[uint32]float64          `json:"fiatRates"`
	Net                dex.Network                 `json:"net"`
	ExtensionConfig    *ExtensionModeConfig        `json:"extensionModeConfig,omitempty"`
	Actions            []*asset.ActionRequiredNote `json:"actions,omitempty"`
}

User is information about the user's wallets and DEX accounts.

type WalletBalance

type WalletBalance struct {
	*db.Balance
	// OrderLocked is the total amount of funds that is currently locked
	// for swap, but not actually swapped yet. This amount is also included
	// in the `Locked` balance value.
	OrderLocked uint64 `json:"orderlocked"`
	// ContractLocked is the total amount of funds locked in unspent (i.e.
	// unredeemed / unrefunded) swap contracts. This amount is NOT included in
	// the db.Balance.
	ContractLocked uint64 `json:"contractlocked"`
	// BondLocked is the total amount of funds locked in unspent fidelity bonds.
	// This amount is NOT included in the db.Balance.
	BondLocked uint64 `json:"bondlocked"`
}

WalletBalance is an exchange wallet's balance which includes various locked amounts in addition to other balance details stored in db. Both the ContractLocked and BondLocked amounts are not included in the Locked field of the embedded asset.Balance since they correspond to outputs that are foreign to the wallet i.e. only spendable by externally-crafted transactions. On the other hand, OrderLocked is part of Locked since these are regular UTXOs that have been locked by the wallet to fund an order's swap transaction.

type WalletConfigNote

type WalletConfigNote struct {
	db.Notification
	Wallet *WalletState `json:"wallet"`
}

WalletConfigNote is a notification regarding a change in wallet configuration.

type WalletCreationNote added in v0.6.0

type WalletCreationNote struct {
	db.Notification
	AssetID uint32 `json:"assetID"`
}

WalletCreationNote is a notification regarding asynchronous wallet creation.

type WalletForm

type WalletForm struct {
	AssetID uint32
	Config  map[string]string
	Type    string
	// ParentForm is the configuration settings for a parent asset. If this is a
	// token whose parent asset needs configuration, a non-nil ParentForm can be
	// supplied. This will cause CreateWallet to run in a special mode which
	// will create the parent asset's wallet synchronously, but schedule the
	// creation of the token wallet to occur asynchronously after the parent
	// wallet is fully synced, sending NoteTypeCreateWallet notifications to
	// update with progress.
	ParentForm *WalletForm
}

WalletForm is information necessary to create a new exchange wallet. The ConfigText, if provided, will be parsed for wallet connection settings.

type WalletNoPeersError added in v1.0.1

type WalletNoPeersError struct {
	AssetID uint32
}

WalletNoPeersError should be returned when a wallet has no network peers.

func (*WalletNoPeersError) Error added in v1.0.1

func (e *WalletNoPeersError) Error() string

type WalletNote added in v1.0.0

type WalletNote struct {
	db.Notification
	Payload asset.WalletNotification `json:"payload"`
}

WalletNote is a notification originating from a wallet.

type WalletState

type WalletState struct {
	Symbol       string                          `json:"symbol"`
	AssetID      uint32                          `json:"assetID"`
	Version      uint32                          `json:"version"`
	WalletType   string                          `json:"type"`
	Traits       asset.WalletTrait               `json:"traits"`
	Open         bool                            `json:"open"`
	Running      bool                            `json:"running"`
	Balance      *WalletBalance                  `json:"balance"`
	Address      string                          `json:"address"`
	Units        string                          `json:"units"`
	Encrypted    bool                            `json:"encrypted"`
	PeerCount    uint32                          `json:"peerCount"`
	Synced       bool                            `json:"synced"`
	SyncProgress float32                         `json:"syncProgress"`
	SyncStatus   *asset.SyncStatus               `json:"syncStatus"`
	Disabled     bool                            `json:"disabled"`
	Approved     map[uint32]asset.ApprovalStatus `json:"approved"`
	FeeState     *FeeState                       `json:"feeState"`
}

WalletState is the current status of an exchange wallet.

type WalletStateNote

type WalletStateNote WalletConfigNote

WalletStateNote is a notification regarding a change in wallet state, including: creation, locking, unlocking, connect, disabling and enabling. This is intended to be a Data Severity notification.

type WalletSyncError added in v1.0.1

type WalletSyncError struct {
	AssetID  uint32
	Progress float32
}

WalletSyncError should be returned when a wallet is still syncing.

func (*WalletSyncError) Error added in v1.0.1

func (e *WalletSyncError) Error() string

type WalletSyncNote added in v1.0.0

type WalletSyncNote struct {
	db.Notification
	AssetID      uint32            `json:"assetID"`
	SyncStatus   *asset.SyncStatus `json:"syncStatus"`
	SyncProgress float32           `json:"syncProgress"`
}

WalletSyncNote is a notification of the wallet sync status.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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