code.vegaprotocol.io/vega@v0.79.0/core/types/collateral.go (about)

     1  // Copyright (C) 2023 Gobalsky Labs Limited
     2  //
     3  // This program is free software: you can redistribute it and/or modify
     4  // it under the terms of the GNU Affero General Public License as
     5  // published by the Free Software Foundation, either version 3 of the
     6  // License, or (at your option) any later version.
     7  //
     8  // This program is distributed in the hope that it will be useful,
     9  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    10  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    11  // GNU Affero General Public License for more details.
    12  //
    13  // You should have received a copy of the GNU Affero General Public License
    14  // along with this program.  If not, see <http://www.gnu.org/licenses/>.
    15  
    16  package types
    17  
    18  import (
    19  	"fmt"
    20  
    21  	"code.vegaprotocol.io/vega/libs/num"
    22  	"code.vegaprotocol.io/vega/libs/ptr"
    23  	"code.vegaprotocol.io/vega/libs/stringer"
    24  	proto "code.vegaprotocol.io/vega/protos/vega"
    25  )
    26  
    27  const (
    28  	systemOwner = "*"
    29  	noMarket    = "!"
    30  )
    31  
    32  type AccountDetails struct {
    33  	Owner    string
    34  	AssetID  string
    35  	MarketID string
    36  	Type     AccountType
    37  }
    38  
    39  func (ad *AccountDetails) ID() string {
    40  	idbuf := make([]byte, 256)
    41  	marketID, partyID := ad.MarketID, ad.Owner
    42  	if len(marketID) <= 0 {
    43  		marketID = noMarket
    44  	}
    45  
    46  	// market account
    47  	if len(partyID) <= 0 {
    48  		partyID = systemOwner
    49  	}
    50  
    51  	copy(idbuf, marketID)
    52  	ln := len(marketID)
    53  	copy(idbuf[ln:], partyID)
    54  	ln += len(partyID)
    55  	copy(idbuf[ln:], []byte(ad.AssetID))
    56  	ln += len(ad.AssetID)
    57  	idbuf[ln] = byte(ad.Type + 48)
    58  	return string(idbuf[:ln+1])
    59  }
    60  
    61  func (ad *AccountDetails) IntoProto() *proto.AccountDetails {
    62  	var marketID, owner *string
    63  	if ad.Owner != systemOwner {
    64  		owner = ptr.From(ad.Owner)
    65  	}
    66  	if ad.MarketID != noMarket {
    67  		marketID = ptr.From(ad.MarketID)
    68  	}
    69  
    70  	return &proto.AccountDetails{
    71  		Owner:    owner,
    72  		MarketId: marketID,
    73  		AssetId:  ad.AssetID,
    74  		Type:     ad.Type,
    75  	}
    76  }
    77  
    78  type Account struct {
    79  	ID       string
    80  	Owner    string
    81  	Balance  *num.Uint
    82  	Asset    string
    83  	MarketID string // NB: this market may not always refer to a valid market id. instead in the case of transfers it just represents a hash corresponding to a dispatch metric.
    84  	Type     AccountType
    85  }
    86  
    87  func (a Account) ToDetails() *AccountDetails {
    88  	return &AccountDetails{
    89  		Owner:    a.Owner,
    90  		MarketID: a.MarketID,
    91  		AssetID:  a.Asset,
    92  		Type:     a.Type,
    93  	}
    94  }
    95  
    96  func (a Account) String() string {
    97  	return fmt.Sprintf(
    98  		"ID(%s) owner(%s) balance(%s) asset(%s) marketID(%s) type(%s)",
    99  		a.ID,
   100  		a.Owner,
   101  		stringer.PtrToString(a.Balance),
   102  		a.Asset,
   103  		a.MarketID,
   104  		a.Type.String(),
   105  	)
   106  }
   107  
   108  func (a *Account) Clone() *Account {
   109  	acccpy := *a
   110  	acccpy.Balance = acccpy.Balance.Clone()
   111  	return &acccpy
   112  }
   113  
   114  func AccountFromProto(a *proto.Account) *Account {
   115  	bal, _ := num.UintFromString(a.Balance, 10)
   116  	return &Account{
   117  		ID:       a.Id,
   118  		Owner:    a.Owner,
   119  		Balance:  bal,
   120  		Asset:    a.Asset,
   121  		MarketID: a.MarketId,
   122  		Type:     a.Type,
   123  	}
   124  }
   125  
   126  func (a *Account) IntoProto() *proto.Account {
   127  	return &proto.Account{
   128  		Id:       a.ID,
   129  		Owner:    a.Owner,
   130  		Balance:  num.UintToString(a.Balance),
   131  		Asset:    a.Asset,
   132  		MarketId: a.MarketID,
   133  		Type:     a.Type,
   134  	}
   135  }
   136  
   137  type Accounts []*Account
   138  
   139  func (a Accounts) IntoProto() []*proto.Account {
   140  	out := make([]*proto.Account, 0, len(a))
   141  	for _, v := range a {
   142  		out = append(out, v.IntoProto())
   143  	}
   144  	return out
   145  }
   146  
   147  type TransferRequest struct {
   148  	FromAccount []*Account
   149  	ToAccount   []*Account
   150  	Amount      *num.Uint
   151  	MinAmount   *num.Uint
   152  	Asset       string
   153  	// Reference   string
   154  	Type       TransferType
   155  	TransferID *string
   156  }
   157  
   158  func (t *TransferRequest) IntoProto() *proto.TransferRequest {
   159  	return &proto.TransferRequest{
   160  		FromAccount: Accounts(t.FromAccount).IntoProto(),
   161  		ToAccount:   Accounts(t.ToAccount).IntoProto(),
   162  		Amount:      num.UintToString(t.Amount),
   163  		MinAmount:   num.UintToString(t.MinAmount),
   164  		Asset:       t.Asset,
   165  		// Reference:   t.Reference,
   166  	}
   167  }
   168  
   169  type LedgerMovement struct {
   170  	Entries  []*LedgerEntry
   171  	Balances []*PostTransferBalance
   172  }
   173  
   174  func (t *LedgerMovement) IntoProto() *proto.LedgerMovement {
   175  	return &proto.LedgerMovement{
   176  		Entries:  LedgerEntries(t.Entries).IntoProto(),
   177  		Balances: PostTransferBalances(t.Balances).IntoProto(),
   178  	}
   179  }
   180  
   181  type LedgerMovements []*LedgerMovement
   182  
   183  func (a LedgerMovements) IntoProto() []*proto.LedgerMovement {
   184  	out := make([]*proto.LedgerMovement, 0, len(a))
   185  	for _, v := range a {
   186  		out = append(out, v.IntoProto())
   187  	}
   188  	return out
   189  }
   190  
   191  type PostTransferBalance struct {
   192  	Account *Account
   193  	Balance *num.Uint
   194  }
   195  
   196  func (t *PostTransferBalance) IntoProto() *proto.PostTransferBalance {
   197  	var acc *proto.AccountDetails
   198  	if t.Account != nil {
   199  		acc = t.Account.ToDetails().IntoProto()
   200  	}
   201  	return &proto.PostTransferBalance{
   202  		Account: acc,
   203  		Balance: t.Balance.String(),
   204  	}
   205  }
   206  
   207  type PostTransferBalances []*PostTransferBalance
   208  
   209  func (a PostTransferBalances) IntoProto() []*proto.PostTransferBalance {
   210  	out := make([]*proto.PostTransferBalance, 0, len(a))
   211  	for _, v := range a {
   212  		out = append(out, v.IntoProto())
   213  	}
   214  	return out
   215  }
   216  
   217  type LedgerEntry struct {
   218  	FromAccount        *AccountDetails
   219  	ToAccount          *AccountDetails
   220  	Amount             *num.Uint
   221  	Type               TransferType
   222  	Timestamp          int64
   223  	FromAccountBalance *num.Uint
   224  	ToAccountBalance   *num.Uint
   225  	TransferID         *string
   226  }
   227  
   228  func (l *LedgerEntry) IntoProto() *proto.LedgerEntry {
   229  	return &proto.LedgerEntry{
   230  		FromAccount:        l.FromAccount.IntoProto(),
   231  		ToAccount:          l.ToAccount.IntoProto(),
   232  		Amount:             num.UintToString(l.Amount),
   233  		Type:               l.Type,
   234  		Timestamp:          l.Timestamp,
   235  		FromAccountBalance: num.UintToString(l.FromAccountBalance),
   236  		ToAccountBalance:   num.UintToString(l.ToAccountBalance),
   237  		TransferId:         l.TransferID,
   238  	}
   239  }
   240  
   241  type LedgerEntries []*LedgerEntry
   242  
   243  func (a LedgerEntries) IntoProto() []*proto.LedgerEntry {
   244  	out := make([]*proto.LedgerEntry, 0, len(a))
   245  	for _, v := range a {
   246  		out = append(out, v.IntoProto())
   247  	}
   248  	return out
   249  }
   250  
   251  type AccountType = proto.AccountType
   252  
   253  const (
   254  	// Default value.
   255  	AccountTypeUnspecified AccountType = proto.AccountType_ACCOUNT_TYPE_UNSPECIFIED
   256  	// Per asset network treasury.
   257  	AccountTypeNetworkTreasury AccountType = proto.AccountType_ACCOUNT_TYPE_NETWORK_TREASURY
   258  	// Insurance pool accounts contain insurance pool funds for a market.
   259  	AccountTypeInsurance AccountType = proto.AccountType_ACCOUNT_TYPE_INSURANCE
   260  	// Settlement accounts exist only during settlement or mark-to-market.
   261  	AccountTypeSettlement AccountType = proto.AccountType_ACCOUNT_TYPE_SETTLEMENT
   262  	// Global insurance account for the asset.
   263  	AccountTypeGlobalInsurance AccountType = proto.AccountType_ACCOUNT_TYPE_GLOBAL_INSURANCE
   264  
   265  	// Margin accounts contain margin funds for a party and each party will
   266  	// have multiple margin accounts, one for each market they have traded in
   267  	//
   268  	// Margin account funds will alter as margin requirements on positions change.
   269  	AccountTypeMargin AccountType = proto.AccountType_ACCOUNT_TYPE_MARGIN
   270  
   271  	// Margin account for isolated margin mode.
   272  	AccountTypeOrderMargin AccountType = proto.AccountType_ACCOUNT_TYPE_ORDER_MARGIN
   273  
   274  	// General accounts contains general funds for a party. A party will
   275  	// have multiple general accounts, one for each asset they want
   276  	// to trade with
   277  	//
   278  	// General accounts are where funds are initially deposited or withdrawn from,
   279  	// it is also the account where funds are taken to fulfil fees and initial margin requirements.
   280  	AccountTypeGeneral AccountType = proto.AccountType_ACCOUNT_TYPE_GENERAL
   281  	// Infrastructure accounts contain fees earned by providing infrastructure on Vega.
   282  	AccountTypeFeesInfrastructure AccountType = proto.AccountType_ACCOUNT_TYPE_FEES_INFRASTRUCTURE
   283  	// Liquidity accounts contain fees earned by providing liquidity on Vega markets.
   284  	AccountTypeFeesLiquidity AccountType = proto.AccountType_ACCOUNT_TYPE_FEES_LIQUIDITY
   285  	// This account is created to hold fees earned by placing orders that sit on the book
   286  	// and are then matched with an incoming order to create a trade - These fees reward parties
   287  	// who provide the best priced liquidity that actually allows trading to take place.
   288  	AccountTypeFeesMaker AccountType = proto.AccountType_ACCOUNT_TYPE_FEES_MAKER
   289  	// This account is created to maintain liquidity providers funds commitments.
   290  	AccountTypeBond AccountType = proto.AccountType_ACCOUNT_TYPE_BOND
   291  	// External account represents an external source (deposit/withdrawal).
   292  	AccountTypeExternal AccountType = proto.AccountType_ACCOUNT_TYPE_EXTERNAL
   293  	// Global reward accounts contain rewards per asset.
   294  	AccountTypeGlobalReward AccountType = proto.AccountType_ACCOUNT_TYPE_GLOBAL_REWARD
   295  	// Global account to hold pending transfers.
   296  	AccountTypePendingTransfers AccountType = proto.AccountType_ACCOUNT_TYPE_PENDING_TRANSFERS
   297  	// Asset account for paid taker fees.
   298  	AccountTypeMakerPaidFeeReward AccountType = proto.AccountType_ACCOUNT_TYPE_REWARD_MAKER_PAID_FEES
   299  	// Asset account for received maker fees.
   300  	AccountTypeMakerReceivedFeeReward AccountType = proto.AccountType_ACCOUNT_TYPE_REWARD_MAKER_RECEIVED_FEES
   301  	// Asset account for received LP fees.
   302  	AccountTypeLPFeeReward AccountType = proto.AccountType_ACCOUNT_TYPE_REWARD_LP_RECEIVED_FEES
   303  	// Asset account for market proposers.
   304  	AccountTypeMarketProposerReward AccountType = proto.AccountType_ACCOUNT_TYPE_REWARD_MARKET_PROPOSERS
   305  	// Market account for holding in-flight spot passive orders funds.
   306  	AccountTypeHolding AccountType = proto.AccountType_ACCOUNT_TYPE_HOLDING
   307  	// Market account per LP to receive liquidity fees.
   308  	AccountTypeLPLiquidityFees                AccountType = proto.AccountType_ACCOUNT_TYPE_LP_LIQUIDITY_FEES
   309  	AccountTypeLiquidityFeesBonusDistribution AccountType = proto.AccountType_ACCOUNT_TYPE_LIQUIDITY_FEES_BONUS_DISTRIBUTION
   310  	AccountTypeVestingRewards                 AccountType = proto.AccountType_ACCOUNT_TYPE_VESTING_REWARDS
   311  	AccountTypeVestedRewards                  AccountType = proto.AccountType_ACCOUNT_TYPE_VESTED_REWARDS
   312  	// Reward account for average notional metric.
   313  	AccountTypeAverageNotionalReward AccountType = proto.AccountType_ACCOUNT_TYPE_REWARD_AVERAGE_NOTIONAL
   314  	// Reward account for relative return metric.
   315  	AccountTypeRelativeReturnReward AccountType = proto.AccountType_ACCOUNT_TYPE_REWARD_RELATIVE_RETURN
   316  	// Reward account for return volatility metric.
   317  	AccountTypeReturnVolatilityReward AccountType = proto.AccountType_ACCOUNT_TYPE_REWARD_RETURN_VOLATILITY
   318  	// Reward account for validator ranking metric.
   319  	AccountTypeValidatorRankingReward AccountType = proto.AccountType_ACCOUNT_TYPE_REWARD_VALIDATOR_RANKING
   320  	// Account for pending fee referral rewards.
   321  	AccountTypePendingFeeReferralReward AccountType = proto.AccountType_ACCOUNT_TYPE_PENDING_FEE_REFERRAL_REWARD
   322  	// Account for realised return rewards.
   323  	AccountTypeRealisedReturnReward = proto.AccountType_ACCOUNT_TYPE_REWARD_REALISED_RETURN
   324  	// Account for buy back fees.
   325  	AccountTypeBuyBackFees AccountType = proto.AccountType_ACCOUNT_TYPE_BUY_BACK_FEES
   326  	// Account for eligible entities rewards.
   327  	AccountTypeEligibleEntitiesReward = proto.AccountType_ACCOUNT_TYPE_REWARD_ELIGIBLE_ENTITIES
   328  	AccountTypeLockedForStaking       = proto.AccountType_ACCOUNT_TYPE_LOCKED_FOR_STAKING
   329  )