Documentation ¶
Index ¶
- Constants
- Variables
- type Account
- type AccountAndKey
- type AddressInfo
- type BalanceInfo
- type CompleteResult
- type Market
- func (m *Market) BaseAssetPrice() decimal.Decimal
- func (m *Market) ChangeBasePrice(price decimal.Decimal) error
- func (m *Market) ChangeFee(fee int64) error
- func (m *Market) ChangeQuotePrice(price decimal.Decimal) error
- func (m *Market) FundMarket(fundingTxs []OutpointWithAsset) error
- func (m *Market) IsFunded() bool
- func (m *Market) IsStrategyPluggable() bool
- func (m *Market) IsStrategyPluggableInitialized() bool
- func (m *Market) IsTradable() bool
- func (m *Market) MakeNotTradable() error
- func (m *Market) MakeStrategyBalanced() error
- func (m *Market) MakeStrategyPluggable() error
- func (m *Market) MakeTradable() error
- func (m *Market) QuoteAssetPrice() decimal.Decimal
- type MarketRepository
- type OutpointWithAsset
- type Prices
- type Status
- type StrategyType
- type Swap
- type Timestamp
- type Trade
- func (t *Trade) Accept(psetBase64 string, inputBlindingKeys, outputBlindingKeys map[string][]byte) (bool, error)
- func (t *Trade) AddBlocktime(blocktime uint64) error
- func (t *Trade) Complete(psetBase64 string) (*CompleteResult, error)
- func (t *Trade) ContainsSwap(swapID string) bool
- func (t *Trade) Fail(swapID string, tradeStatus Status, errCode pkgswap.ErrCode, errMsg string)
- func (t *Trade) IsAccepted() bool
- func (t *Trade) IsCompleted() bool
- func (t *Trade) IsEmpty() bool
- func (t *Trade) IsExpired() bool
- func (t *Trade) IsProposal() bool
- func (t *Trade) IsRejected() bool
- func (t *Trade) Propose(swapRequest *pb.SwapRequest, marketQuoteAsset string, ...) (bool, error)
- func (t *Trade) Settle(settlementTime uint64) error
- func (t *Trade) SwapAcceptMessage() *pb.SwapAccept
- func (t *Trade) SwapAcceptTime() uint64
- func (t *Trade) SwapCompleteMessage() *pb.SwapComplete
- func (t *Trade) SwapCompleteTime() uint64
- func (t *Trade) SwapExpiryTime() uint64
- func (t *Trade) SwapFailMessage() *pb.SwapFail
- func (t *Trade) SwapRequestMessage() *pb.SwapRequest
- func (t *Trade) SwapRequestTime() uint64
- type TradeRepository
- type Unspent
- func (u *Unspent) Confirm()
- func (u *Unspent) IsConfirmed() bool
- func (u *Unspent) IsKeyEqual(key UnspentKey) bool
- func (u *Unspent) IsLocked() bool
- func (u *Unspent) IsSpent() bool
- func (u *Unspent) Key() UnspentKey
- func (u *Unspent) Lock(tradeID *uuid.UUID)
- func (u *Unspent) Spend()
- func (u *Unspent) ToUtxo() explorer.Utxo
- func (u *Unspent) UnLock()
- type UnspentKey
- type UnspentRepository
- type Vault
- func (v *Vault) AccountByAddress(addr string) (*Account, int, error)
- func (v *Vault) AccountByIndex(accountIndex int) (*Account, error)
- func (v *Vault) AllDerivedAddressesAndBlindingKeysForAccount(accountIndex int) ([]string, [][]byte, error)
- func (v *Vault) AllDerivedAddressesInfo() []AddressInfo
- func (v *Vault) AllDerivedExternalAddressesForAccount(accountIndex int) ([]string, error)
- func (v *Vault) ChangePassphrase(currentPassphrase, newPassphrase string) error
- func (v *Vault) DeriveNextExternalAddressForAccount(accountIndex int) (address string, script string, blindingPrivateKey []byte, err error)
- func (v *Vault) DeriveNextInternalAddressForAccount(accountIndex int) (address string, script string, blindingPrivateKey []byte, err error)
- func (v *Vault) GetMnemonicSafe() ([]string, error)
- func (v *Vault) InitAccount(accountIndex int)
- func (v *Vault) IsZero() bool
- func (v *Vault) Lock() error
- func (v *Vault) Unlock(passphrase string) error
- type VaultRepository
Constants ¶
const ( FeeAccount = iota WalletAccount UnusedAccount1 UnusedAccount2 UnusedAccount3 MarketAccountStart ExternalChain = 0 InternalChain = 1 MinMilliSatPerByte = 100 StrategyTypePluggable StrategyType = 0 StrategyTypeBalanced StrategyType = 1 StrategyTypeUnbalanced StrategyType = 2 )
Variables ¶
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") )
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 ¶
NewAccount returns an empty Account instance
type AccountAndKey ¶
type AddressInfo ¶
type BalanceInfo ¶
type CompleteResult ¶
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 (*Market) BaseAssetPrice ¶
BaseAssetPrice returns the latest price for the base asset
func (*Market) ChangeBasePrice ¶
ChangeBasePrice ...
func (*Market) ChangeQuotePrice ¶
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 ¶
IsFunded method returns true if the market contains a non empty funding tx outpoint for each asset
func (*Market) IsStrategyPluggable ¶
IsStrategyPluggable returns true if the the startegy isn't automated.
func (*Market) IsStrategyPluggableInitialized ¶
IsStrategyPluggableInitialized returns true if the prices have been set.
func (*Market) IsTradable ¶
IsTradable returns true if the market is available for trading
func (*Market) MakeStrategyBalanced ¶
MakeStrategyBalanced makes the current market using a balanced AMM formula 50/50
func (*Market) MakeStrategyPluggable ¶
MakeStrategyPluggable makes the current market using a given price (ie. set via UpdateMarketPrice rpc either manually or a price feed plugin)
func (*Market) QuoteAssetPrice ¶
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 ¶
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 ...
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 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 (*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 ¶
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 ¶
ContainsSwap returns whether some swap identified by an id belongs to the current trade
func (*Trade) Fail ¶
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 ¶
IsAccepted returns whether the trade is in Accepted status
func (*Trade) IsCompleted ¶
IsCompleted returns whether the trade is in Completed status
func (*Trade) IsExpired ¶
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 ¶
IsProposal returns whether the trade is in Proposal status
func (*Trade) IsRejected ¶
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) SwapAcceptMessage ¶
func (t *Trade) SwapAcceptMessage() *pb.SwapAccept
SwapAcceptMessage returns the swap accept made for the trade
func (*Trade) SwapAcceptTime ¶
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 ¶
SwapCompleteTime returns the timestamp of when the accepted trade has been completed
func (*Trade) SwapExpiryTime ¶
SwapExpiryTime returns the timestamp of when the current trade will expire
func (*Trade) SwapFailMessage ¶
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 ¶
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) IsConfirmed ¶
func (*Unspent) IsKeyEqual ¶
func (u *Unspent) IsKeyEqual(key UnspentKey) bool
func (*Unspent) Key ¶
func (u *Unspent) Key() UnspentKey
type UnspentKey ¶
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 ¶
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 ¶
AccountByAddress returns the account to which the provided address belongs
func (*Vault) AccountByIndex ¶
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 ¶
AllDerivedExternalAddressesForAccount returns all the external derived for the provided account
func (*Vault) ChangePassphrase ¶
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 ¶
GetMnemonicSafe is getter for Vault's mnemonic in plain text
func (*Vault) InitAccount ¶
InitAccount creates a new account in the current Vault if not existing
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) }