code.vegaprotocol.io/vega@v0.79.0/datanode/api/errors.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 api
    17  
    18  import (
    19  	"code.vegaprotocol.io/vega/datanode/entities"
    20  	types "code.vegaprotocol.io/vega/protos/vega"
    21  
    22  	"github.com/pkg/errors"
    23  	"google.golang.org/grpc/codes"
    24  	"google.golang.org/grpc/status"
    25  )
    26  
    27  // API Errors and descriptions.
    28  var (
    29  	// ErrNoTrustedProxy indactes a forwarded request that did not pass through a trusted proxy.
    30  	ErrNoTrustedProxy = errors.New("forwarded requests need to pass through a trusted proxy")
    31  	// ErrChannelClosed signals that the channel streaming data is closed.
    32  	ErrChannelClosed = errors.New("channel closed")
    33  	// ErrNotAValidVegaID signals an invalid id.
    34  	ErrNotAValidVegaID = newInvalidArgumentError("not a valid vega id")
    35  	// ErrMissingResourceID signals to the caller that the request expected a
    36  	// resource id but the field is missing or empty.
    37  	ErrMissingResourceID = newInvalidArgumentError("missing resource ID")
    38  	// ErrEmptyMissingMarketID signals to the caller that the request expected a
    39  	// market id but the field is missing or empty.
    40  	ErrEmptyMissingMarketID = newInvalidArgumentError("empty or missing market ID")
    41  	// ErrInvalidMarketID signals to the caller that the request expected a
    42  	// market id but the field is not in the right format.
    43  	ErrInvalidMarketID = newInvalidArgumentError("invalid market ID")
    44  	// ErrMissingPrice signals to the caller that the request expected a price.
    45  	ErrMissingPrice = newInvalidArgumentError("missing price")
    46  	// ErrInvalidOrderPrice signals to the caller that the request expected a valid price.
    47  	ErrInvalidOrderPrice = newInvalidArgumentError("invalid order price")
    48  	// ErrInvalidOrderSize signals to the caller that the request expected a valid size.
    49  	ErrInvalidOrderSize = newInvalidArgumentError("invalid order size")
    50  	// ErrServerShutdown signals to the client that the server  is shutting down.
    51  	ErrServerShutdown = errors.New("server shutdown")
    52  	// ErrStreamClosed signals to the users that the grpc stream is closing.
    53  	ErrStreamClosed = errors.New("stream closed")
    54  	// ErrStreamInternal signals to the users that the grpc stream has an internal problem.
    55  	ErrStreamInternal = errors.New("internal stream failure")
    56  	// ErrNotMapped is when an error cannot be found in the current error map/lookup table.
    57  	ErrNotMapped = errors.New("error not found in error lookup table")
    58  	// ErrMissingPartyID signals that the payload is expected to contain a party id.
    59  	ErrMissingPartyID = newInvalidArgumentError("missing party id")
    60  	// ErrInvalidPartyID signals that the given party id is not a valid ID.
    61  	ErrInvalidPartyID = newInvalidArgumentError("invalid party id")
    62  	// ErrInvalidPagination signals that the pagination is invalid.
    63  	ErrInvalidPagination = newInvalidArgumentError("invalid pagination")
    64  	// ErrInvalidCandleID signals an invalid candle ID submitted.
    65  	ErrInvalidCandleID = newInvalidArgumentError("invalid candle id")
    66  	// ErrInvalidCandleTimestampsRange signals an impossible range with the candle timestamps.
    67  	ErrInvalidCandleTimestampsRange = newInvalidArgumentError("invalid candle timestamps range")
    68  	// ErrInvalidFilter signals that the filter is invalid.
    69  	ErrInvalidFilter = newInvalidArgumentError("invalid filter")
    70  	// ErrMalformedRequest signals that the request was malformed.
    71  	ErrMalformedRequest = newInvalidArgumentError("malformed request")
    72  	// ErrMissingOrderID signals that an order ID was required but not specified.
    73  	ErrMissingOrderID = newInvalidArgumentError("missing orderID parameter")
    74  	// ErrInvalidOrderID signals that an order ID provided was not a valid ID.
    75  	ErrInvalidOrderID = newInvalidArgumentError("invalid orderID parameter")
    76  	// ErrMissingCandleID returned if candle with this id is missing.
    77  	ErrMissingCandleID = newInvalidArgumentError("candle id is a required parameter")
    78  	// ErrMissingProposalID returned if proposal with this id is missing.
    79  	ErrMissingProposalID = newInvalidArgumentError("proposal id is a required parameter")
    80  	// ErrMissingProposalIDAndPartyID returned if proposal id and party id is missing.
    81  	ErrMissingProposalIDAndPartyID = newInvalidArgumentError("missing proposal id and party id")
    82  	// ErrMissingProposalIDOrPartyID returned if proposal id and party id is missing.
    83  	ErrMissingProposalIDOrPartyID = newInvalidArgumentError("missing proposal id or party id")
    84  	// ErrMissingProposalIDOrReference returned if proposal id or reference is missing.
    85  	ErrMissingProposalIDOrReference = newInvalidArgumentError("missing proposal ID or reference")
    86  	// ErrInvalidProposalID returned if proposal id is invalid.
    87  	ErrInvalidProposalID = newInvalidArgumentError("invalid proposal id")
    88  	// ErrMissingWithdrawalID is returned when the withdrawal ID is missing from the request.
    89  	ErrMissingWithdrawalID = newInvalidArgumentError("missing withdrawal ID")
    90  	// ErrInvalidWithdrawalID is returned when the withdrawal ID is not a valid vega ID.
    91  	ErrInvalidWithdrawalID = newInvalidArgumentError("invalid withdrawal ID")
    92  	// ErrMissingOracleSpecID is returned when the ID is missing from the request.
    93  	ErrMissingOracleSpecID = newInvalidArgumentError("missing oracle spec ID")
    94  	// ErrInvalidOracleSpecID is returned when the ID is not a valid ID.
    95  	ErrInvalidOracleSpecID = newInvalidArgumentError("invalid oracle spec ID")
    96  	// ErrMissingDepositID is returned when the deposit ID is missing from the request.
    97  	ErrMissingDepositID = newInvalidArgumentError("missing deposit ID")
    98  	// ErrMissingAssetID is returned when the Asset ID is missing from the request.
    99  	ErrMissingAssetID = newInvalidArgumentError("missing asset ID")
   100  	// ErrInvalidAssetID is returned when the Asset ID is not a valid ID.
   101  	ErrInvalidAssetID = newInvalidArgumentError("invalid asset ID")
   102  	// ErrMissingNodeID is returned when the node ID is missing from the request.
   103  	ErrMissingNodeID = newInvalidArgumentError("missing node id")
   104  	// ErrNegativeOrderVersion is returned when a request is made for an
   105  	// order with a negative version.
   106  	ErrNegativeOrderVersion = newInvalidArgumentError("negative order version")
   107  	// ErrLastPaginationNotSupported is returned when last pagination is not supported.
   108  	ErrLastPaginationNotSupported = newInvalidArgumentError("'last' pagination is not supported")
   109  	// ErrMissingMarginFactor is returned when isolated margin mode is specified, but margin factor is not supplied.
   110  	ErrMissingMarginFactor = newInvalidArgumentError("missing margin factor")
   111  	// ErrInvalidGameID is returned when the game ID is not a valid ID.
   112  	ErrInvalidGameID = newInvalidArgumentError("invalid game ID")
   113  
   114  	// ErrOracleServiceSpecID is returned when there was no data found for the given ID.
   115  	ErrOracleServiceGetSpec = errors.New("failed to retrieve data for oracle spec")
   116  	// ErrERC20InvalidTokenContractAddress is returned when the ERC20 token contract address is invalid.
   117  	ErrERC20InvalidTokenContractAddress = errors.New("invalid erc20 token contract address")
   118  	ErrSendingGRPCHeader                = errors.New("failed to send header")
   119  	ErrEstimateFee                      = errors.New("failed to estimate fee")
   120  	ErrEstimateMargin                   = errors.New("failed to estimate margin")
   121  	// OrderService...
   122  	ErrOrderServiceGetOrders        = errors.New("failed to get orders")
   123  	ErrOrderServiceGetVersions      = errors.New("failed to get order versions")
   124  	ErrOrderNotFound                = errors.New("order not found")
   125  	ErrOrderServiceGetByMarket      = errors.New("failed to get orders for market")
   126  	ErrOrderServiceGetByMarketAndID = errors.New("failed to get orders for market and ID")
   127  	ErrOrderServiceGetByParty       = errors.New("failed to get orders for party")
   128  	ErrOrderServiceGetByReference   = errors.New("failed to get orders for reference")
   129  	ErrOrderServiceGetByTxHash      = errors.New("failed to get orders for tx hash")
   130  	ErrMissingOrderIDParameter      = errors.New("missing orderID parameter")
   131  	// NodeService...
   132  	ErrNodeServiceGetNodes    = errors.New("failed to get nodes")
   133  	ErrNodeServiceGetNodeData = errors.New("failed to get node data")
   134  	ErrNodeServiceGetByTxHash = errors.New("failed to get nodes for tx hash")
   135  	// TradeService...
   136  	ErrTradeServiceGetByParty          = errors.New("failed to get trades for party")
   137  	ErrTradeServiceGetByMarket         = errors.New("failed to get trades for market")
   138  	ErrTradeServiceList                = errors.New("failed to list trades")
   139  	ErrTradeServiceGetPositionsByParty = errors.New("failed to get positions for party")
   140  	ErrTradeServiceGetByOrderID        = errors.New("failed to get trades for order ID")
   141  	ErrTradeServiceGetByTxHash         = errors.New("failed to get trades for tx hash")
   142  	// MarketService...
   143  	ErrMarketServiceGetByID              = errors.New("failed to get market for ID")
   144  	ErrMarketServiceGetAllPaged          = errors.New("failed to get all markets paged")
   145  	ErrMarketServiceGetMarketData        = errors.New("failed to get market data")
   146  	ErrMarketServiceGetMarketDataHistory = errors.New("failed to get market data history")
   147  	ErrMarketServiceGetMarkets           = errors.New("failed to get markets")
   148  	ErrMarketServiceGetByTxHash          = errors.New("failed to get orders for tx hash")
   149  	ErrMarketServiceGetDepth             = errors.New("failed to get market depth")
   150  	// AccountService...
   151  	ErrAccountServiceListAccounts        = errors.New("failed to get accounts")
   152  	ErrFailedToSendSnapshot              = errors.New("failed to send accounts snapshot")
   153  	ErrAccountServiceGetBalances         = errors.New("failed to get balances")
   154  	ErrAccountServiceGetByTxHash         = errors.New("failed to get accounts for tx hash")
   155  	ErrAccountServiceGetBalancesByTxHash = errors.New("failed to get balances for tx hash")
   156  	// DelegationService...
   157  	ErrDelegationServiceGet = errors.New("failed to get delegation")
   158  	// SummaryService...
   159  	ErrSummaryServiceGet = errors.New("failed to get summary")
   160  	// WithdrawalService...
   161  	ErrWithdrawalServiceGet = errors.New("failed to get withdrawal")
   162  	// PositionService...
   163  	ErrPositionServiceGetByParty   = errors.New("failed to get positions for party")
   164  	ErrPositionServiceSendSnapshot = errors.New("failed to send positions snapshot")
   165  	// RiskService...
   166  	ErrRiskServiceGetMarginLevelsByID = errors.New("failed to get margin levels")
   167  	ErrInvalidOrderSide               = newInvalidArgumentError("invalid order side")
   168  	// RiskFactorService...
   169  	ErrRiskFactorServiceGet = errors.New("failed to get risk factor")
   170  	// GovernanceService...
   171  	ErrGovernanceServiceGet          = errors.New("failed to get proposal")
   172  	ErrGovernanceServiceGetProposals = errors.New("failed to get proposals")
   173  	ErrGovernanceServiceGetVotes     = errors.New("failed to get votes")
   174  	// CandleService...
   175  	ErrCandleServiceGetCandleData       = errors.New("failed to get candle data")
   176  	ErrCandleServiceSubscribeToCandles  = errors.New("failed to subscribe to candle data")
   177  	ErrCandleServiceGetCandlesForMarket = errors.New("failed to get candles for market")
   178  	// PartyService...
   179  	ErrPartyServiceGetAll       = errors.New("failed to get parties")
   180  	ErrPartyServiceListProfiles = errors.New("failed to get parties' profiles")
   181  	ErrPartyServiceGetByID      = errors.New("failed to get party for ID")
   182  	ErrPartyServiceGetByTxHash  = errors.New("failed to get parties for tx hash")
   183  	// NotaryService...
   184  	ErrNotaryServiceGetByResourceID = errors.New("failed to get notary for resource ID")
   185  	// OracleSpecService...
   186  	// ErrOracleSpecServiceGet is returned when there was no data found for the given ID.
   187  	ErrOracleSpecServiceGet = errors.New("failed retrieve data for oracle spec")
   188  	// ErrOracleSpecServiceGetAll is returned when there was no data found for the given ID.
   189  	ErrOracleSpecServiceGetAll = errors.New("failed retrieve data for oracle specs")
   190  	// OracleDataService...
   191  	// ErrOracleDataServiceGet is returned when there was no data found for the given ID.
   192  	ErrOracleDataServiceGet = errors.New("failed retrieve data for oracle data")
   193  	// AssetService...
   194  	ErrAssetServiceGetAll            = errors.New("failed to get assets")
   195  	ErrAssetServiceGetByID           = errors.New("failed to get asset for ID")
   196  	ErrScalingPriceFromMarketToAsset = errors.New("failed to scale price from market to asset")
   197  	// DepositService...
   198  	ErrDepositServiceGet = errors.New("failed to get deposit")
   199  	// TransferService...
   200  	ErrTransferServiceGet            = errors.New("failed to get transfer")
   201  	ErrTransferServiceGetFeeDiscount = errors.New("failed to get current transfer fee discount")
   202  	ErrMissingTransferID             = errors.New("missing transfer id")
   203  	// NetworkLimits...
   204  	ErrGetNetworkLimits = errors.New("failed to get network limits")
   205  	// ErrGetNetworkParameters is returned when the network parameters cannot be retrieved.
   206  	ErrGetNetworkParameters = errors.New("failed to get network parameters")
   207  	// Network History...
   208  	ErrGetConnectedPeerAddresses = errors.New("failed to get connected peer addresses")
   209  	// TimeService...
   210  	ErrTimeServiceGetTimeNow = errors.New("failed to get time now")
   211  	// Blockchain...
   212  	ErrBlockchainBacklogLength = errors.New("failed to get backlog length from blockchain")
   213  	ErrBlockchainNetworkInfo   = errors.New("failed to get network info from blockchain")
   214  	ErrBlockchainGenesisTime   = errors.New("failed to get genesis time from blockchain")
   215  	ErrBlockchainChainID       = errors.New("failed to get chain ID from blockchain")
   216  	// Rewards.
   217  	ErrGetRewards         = errors.New("failed to get rewards")
   218  	ErrRewardsGetByTxHash = errors.New("failed to get rewards for tx hash")
   219  	// Network History.
   220  	ErrGetActivePeerAddresses              = errors.New("failed to get active peer addresses")
   221  	ErrGetMostRecentHistorySegment         = errors.New("failed to get most recent history segment")
   222  	ErrListAllNetworkHistorySegment        = errors.New("failed to list all history segments")
   223  	ErrFetchNetworkHistorySegment          = errors.New("failed to fetch segment")
   224  	ErrNetworkHistoryNotEnabled            = errors.New("network history not enabled")
   225  	ErrCopyHistorySegmentToFile            = errors.New("failed to copy history segment to file")
   226  	ErrGetIpfsAddress                      = errors.New("failed to get node's ipfs address")
   227  	ErrNetworkHistoryNoTableName           = errors.New("no table name for network history supplied")
   228  	ErrNetworkHistoryGetContiguousSegments = newInvalidArgumentError("could not to get contiguous history segments")
   229  	ErrNetworkHistoryOpeningSegment        = errors.New("failed to open network history segment file")
   230  	ErrNetworkHistoryExtractingSegment     = errors.New("failed to extract data from network history segment file")
   231  	ErrNetworkHistoryCreatingZipFile       = errors.New("failed to create zip file writer for network history segment")
   232  	ErrNetworkHistoryServiceNotInitialised = errors.New("network history service not initialised")
   233  
   234  	// ErrGetEpoch is returned when the epoch cannot be retrieved.
   235  	ErrGetEpoch     = errors.New("failed to get epoch")
   236  	ErrEpochIDParse = newInvalidArgumentError("failed to parse epoch id")
   237  	// LedgerService...
   238  	ErrLedgerServiceGet    = errors.New("failed to query ledger entries")
   239  	ErrLedgerServiceExport = errors.New("failed to export ledger entries")
   240  	// MultiSigService...
   241  	ErrMultiSigServiceGetAdded   = errors.New("failed to get added multisig events")
   242  	ErrMultiSigServiceGetRemoved = errors.New("failed to get removed multisig events")
   243  	// LiquidityProvisionService...
   244  	ErrLiquidityProvisionServiceGet          = errors.New("failed to get liquidity provision")
   245  	ErrLiquidityProvisionServiceGetProviders = errors.New("failed to get liquidity providers")
   246  	// CheckpointService...
   247  	ErrCheckpointServiceGet = errors.New("failed to get checkpoint")
   248  	// StakeLinkingService...
   249  	ErrStakeLinkingServiceGet = errors.New("failed to get stake linking")
   250  	// CoreSnapshotService...
   251  	ErrCoreSnapshotServiceListSnapshots = errors.New("failed to list core snapshots")
   252  	// ProtocolUpgradeService...
   253  	ErrProtocolUpgradeServiceListProposals = errors.New("failed to list protocol upgrade proposals")
   254  	// KeyRotationService...
   255  	ErrKeyRotationServiceGetPerNode = errors.New("failed to get key rotations for node")
   256  	ErrKeyRotationServiceGetAll     = errors.New("failed to get all key rotations")
   257  	// EthereumKeyRotationService...
   258  	ErrEthereumKeyRotationServiceGetPerNode = errors.New("failed to get ethereum key rotations for node")
   259  	ErrEthereumKeyRotationServiceGetAll     = errors.New("failed to get all ethereum key rotations")
   260  	// BlockService...
   261  	ErrBlockServiceGetLast = errors.New("failed to get last block")
   262  	// Positions...
   263  	ErrPositionsGetByTxHash           = errors.New("failed to get positions for tx hash")
   264  	ErrPositionsInvalidAccountBalance = newInvalidArgumentError("invalid account balance")
   265  	// Ledger entries...
   266  	ErrLedgerEntriesGetByTxHash = errors.New("failed to get ledger entries for tx hash")
   267  	// Transfers...
   268  	ErrTransfersGetByTxHash = errors.New("failed to get transfers for tx hash")
   269  	// Votes...
   270  	ErrVotesGetByTxHash = errors.New("failed to get votes for tx hash")
   271  	// ERC20MultiSigSignerEvents...
   272  	ErrERC20MultiSigSignerAddedEventGetByTxHash   = errors.New("failed to get ERC20 multisig signer add events for tx hash")
   273  	ErrERC20MultiSigSignerRemovedEventGetByTxHash = errors.New("failed to get ERC20 multisig signer removed events for tx hash")
   274  	// Oracles...
   275  	ErrOracleSpecGetByTxHash = errors.New("failed to get oracle spec for tx hash")
   276  	ErrOracleDataGetByTxHash = errors.New("failed to get oracle data for tx hash")
   277  	// Deposits...
   278  	ErrDepositsGetByTxHash = errors.New("failed to get deposits for tx hash")
   279  	// Withdrawals...
   280  	ErrWithdrawalsGetByTxHash = errors.New("failed to get withdrawals for tx hash")
   281  	// Assets...
   282  	ErrAssetsGetByTxHash = errors.New("failed to get assets for tx hash")
   283  	// Liquidity provision...
   284  	ErrLiquidityProvisionGetByTxHash = errors.New("failed to get liquidity provision for tx hash")
   285  	// Proposals...
   286  	ErrProposalsGetByTxHash = errors.New("failed to get proposals for tx hash")
   287  	// Delegations...
   288  	ErrDelegationsGetByTxHash = errors.New("failed to get delegations for tx hash")
   289  	// Signatures...
   290  	ErrSignaturesGetByTxHash = errors.New("failed to get signatures for tx hash")
   291  	// NetworkParamaters...
   292  	ErrNetworkParametersGetByTxHash = errors.New("failed to get network parameters for tx hash")
   293  	ErrNetworkParameterNotFound     = errors.New("network parameter not found")
   294  
   295  	// KeyRotations...
   296  	ErrKeyRotationsGetByTxHash = errors.New("failed to get key rotations for tx hash")
   297  	// EthereumKeyRotations...
   298  	ErrEthereumKeyRotationsGetByTxHash = errors.New("failed to get ethereum key rotations for tx hash")
   299  	// ProtocolUpgradeProposals...
   300  	ErrProtocolUpgradeProposalsGetByTxHash = errors.New("failed to get protocol upgrade proposals for tx hash")
   301  	// MarginLevels...
   302  	ErrMarginLevelsGetByTxHash = errors.New("failed to get margin levels for tx hash")
   303  
   304  	// TxHashes...
   305  	ErrMissingEmptyTxHash = newInvalidArgumentError("missing or empty transaction hash")
   306  	ErrInvalidTxHash      = newInvalidArgumentError("not a valid transaction hash")
   307  
   308  	// Funding Periods.
   309  	ErrListFundingPeriod           = errors.New("failed to get funding periods")
   310  	ErrListFundingPeriodDataPoints = errors.New("failed to get funding period data points")
   311  
   312  	// Referral Programs.
   313  	ErrGetCurrentReferralProgram = errors.New("failed to get current referral program")
   314  	ErrGetReferralSetStats       = errors.New("failed to get referral set stats")
   315  
   316  	// Fees stats.
   317  	ErrGetFeesStats         = errors.New("failed to get current fees stats")
   318  	ErrFeesStatsRequest     = errors.New("marketID or assetID must be provided")
   319  	ErrGetFeesStatsForParty = errors.New("failed to get current fees stats for party")
   320  
   321  	// Teams.
   322  	ErrListTeams              = errors.New("failed to list teams")
   323  	ErrListTeamReferees       = errors.New("failed to list team referees")
   324  	ErrListTeamStatistics     = errors.New("failed to list team statistics")
   325  	ErrListTeamRefereeHistory = errors.New("failed to list team referee history")
   326  
   327  	// Volume discount Programs.
   328  	ErrGetCurrentVolumeDiscountProgram = errors.New("failed to get current volume discount program")
   329  	ErrGetVolumeDiscountStats          = errors.New("failed to get volume discount stats")
   330  	ErrGetVolumeRebateStats            = errors.New("failed to get volume rebate stats")
   331  
   332  	// Paid liquidity fees.
   333  	ErrListPaidLiquidityFees = errors.New("failed to list paid liquidity fees")
   334  	// List Games.
   335  	ErrListGames = errors.New("failed to list games")
   336  
   337  	// Transfer fee estimates.
   338  	ErrInvalidTransferAmount = newInvalidArgumentError("invalid transfer amount")
   339  
   340  	ErrListPartyMarginModes = errors.New("failed to list parties margin modes")
   341  	// ErrGetTimeWeightedNotionalPosition is returned when the time weighted notional position cannot be retrieved.
   342  	ErrGetTimeWeightedNotionalPosition = errors.New("failed to get time weighted notional position")
   343  
   344  	ErrDateRangeValidationFailed = newInvalidArgumentError("invalid date range")
   345  
   346  	ErrListAMMPools                     = errors.New("failed to list AMM pools")
   347  	ErrCannotFilterByStatusWhenLiveOnly = newInvalidArgumentError("status filter and live-only cannot both be set")
   348  
   349  	// Amm bounds estimates.
   350  	ErrInvalidBasePrice            = newInvalidArgumentError("invalid base price")
   351  	ErrInvalidUpperPrice           = newInvalidArgumentError("invalid upper price")
   352  	ErrInvalidLowerPrice           = newInvalidArgumentError("invalid lower price")
   353  	ErrInvalidLeverageAtLowerPrice = newInvalidArgumentError("invalid leverage at lower price")
   354  	ErrInvalidLeverageAtUpperPrice = newInvalidArgumentError("invalid leverage at upper price")
   355  	ErrInvalidCommitmentAmount     = newInvalidArgumentError("invalid commitment amount")
   356  	ErrEstimateAMMBounds           = errors.New("failed to estimate AMM bounds")
   357  )
   358  
   359  // errorMap contains a mapping between errors and Vega numeric error codes.
   360  var errorMap = map[string]int32{
   361  	// General
   362  	ErrNotMapped.Error(): 10000,
   363  	//   ErrChainNotConnected.Error():          10001,
   364  	ErrChannelClosed.Error():        10002,
   365  	ErrEmptyMissingMarketID.Error(): 10003,
   366  	//   ErrEmptyMissingOrderID.Error():        10004,
   367  	//   ErrEmptyMissingOrderReference.Error(): 10005,
   368  	//   ErrEmptyMissingPartyID.Error():        10006,
   369  	//   ErrEmptyMissingSinceTimestamp.Error(): 10007,
   370  	ErrStreamClosed.Error():   10008,
   371  	ErrServerShutdown.Error(): 10009,
   372  	ErrStreamInternal.Error(): 10010,
   373  	//   ErrInvalidMarketID.Error():            10011,
   374  	ErrMissingOrderID.Error():   10012,
   375  	ErrMissingPartyID.Error():   10014,
   376  	ErrMalformedRequest.Error(): 10015,
   377  	//   ErrMissingAsset.Error():             10017,
   378  	ErrMissingAssetID.Error(): 10017,
   379  	//   ErrSubmitOrder.Error():              10018,
   380  	//   ErrAmendOrder.Error():               10019,
   381  	//   ErrCancelOrder.Error():              10020,
   382  	ErrMissingProposalID.Error():            10021,
   383  	ErrMissingProposalIDOrReference.Error(): 10022,
   384  	ErrMissingProposalIDAndPartyID.Error():  10023,
   385  	ErrMissingProposalIDOrPartyID.Error():   10024,
   386  	ErrMissingResourceID.Error():            10025,
   387  	ErrMissingPrice.Error():                 10026,
   388  	ErrInvalidOrderPrice.Error():            10027,
   389  	ErrInvalidPagination.Error():            10028,
   390  	ErrInvalidFilter.Error():                10029,
   391  	ErrMissingCandleID.Error():              10030,
   392  	ErrMissingOracleSpecID.Error():          10031,
   393  	ErrMissingNodeID.Error():                10034,
   394  	ErrInvalidOrderSide.Error():             10035,
   395  	ErrEpochIDParse.Error():                 10036,
   396  	ErrSendingGRPCHeader.Error():            10037,
   397  	ErrInvalidAssetID.Error():               10038,
   398  	ErrEstimateFee.Error():                  10039,
   399  	ErrEstimateMargin.Error():               10040,
   400  	// Orders
   401  	//   ErrOrderServiceGetByMarket.Error():      20001,
   402  	//   ErrOrderServiceGetByMarketAndID.Error(): 20002,
   403  	//   ErrOrderServiceGetByParty.Error():       20003,
   404  	//   ErrOrderServiceGetByReference.Error():   20004,
   405  	ErrOrderServiceGetVersions.Error(): 20005,
   406  	ErrOrderNotFound.Error():           20006,
   407  	ErrOrderServiceGetOrders.Error():   20007,
   408  	// Markets
   409  	//   ErrMarketServiceGetMarkets.Error():    30001,
   410  	ErrMarketServiceGetByID.Error(): 30002,
   411  	//   ErrMarketServiceGetDepth.Error():      30003,
   412  	ErrMarketServiceGetMarketData.Error():        30004,
   413  	ErrMarketServiceGetAllPaged.Error():          30005,
   414  	ErrMarketServiceGetMarketDataHistory.Error(): 30006,
   415  	// Trades
   416  	ErrTradeServiceGetByMarket.Error(): 40001,
   417  	//   ErrTradeServiceGetByParty.Error():          40002,
   418  	//   ErrTradeServiceGetPositionsByParty.Error(): 40003,
   419  	//   ErrTradeServiceGetByOrderID.Error():        40004,
   420  	ErrTradeServiceList.Error(): 40005,
   421  	// Parties
   422  	ErrPartyServiceGetAll.Error():  50001,
   423  	ErrPartyServiceGetByID.Error(): 50002,
   424  	// Candles
   425  	ErrCandleServiceGetCandleData.Error():       60001,
   426  	ErrCandleServiceSubscribeToCandles.Error():  60002,
   427  	ErrCandleServiceGetCandlesForMarket.Error(): 60003,
   428  	// Risk
   429  	ErrRiskServiceGetMarginLevelsByID.Error(): 70001,
   430  	// Accounts
   431  	//   ErrAccountServiceGetMarketAccounts.Error(): 80001,
   432  	//   ErrAccountServiceGetPartyAccounts.Error():  80002,
   433  	ErrMissingWithdrawalID.Error(): 80003,
   434  	ErrMissingDepositID.Error():    80004,
   435  	// ErrMissingAssetID.Error():             80005,
   436  	ErrAccountServiceListAccounts.Error(): 80006,
   437  	// ErrAccountServiceSQLStoreNotAvailable.Error(): 80007,
   438  	ErrFailedToSendSnapshot.Error(): 80008,
   439  	// Blockchain client
   440  	//   ErrBlockchainBacklogLength.Error(): 90001,
   441  	//   ErrBlockchainNetworkInfo.Error():   90002,
   442  	//   ErrBlockchainGenesisTime.Error():   90003,
   443  	ErrAccountServiceGetBalances.Error(): 90004,
   444  	// Network limits
   445  	ErrGetNetworkLimits.Error():         100001,
   446  	ErrGetNetworkParameters.Error():     100002,
   447  	ErrNetworkParameterNotFound.Error(): 100003,
   448  	// Node
   449  	ErrNodeServiceGetNodes.Error():    110001,
   450  	ErrNodeServiceGetNodeData.Error(): 110002,
   451  	// ERC20
   452  	ErrERC20InvalidTokenContractAddress.Error(): 120001,
   453  	// Delegation
   454  	ErrDelegationServiceGet.Error(): 130001,
   455  	// Summary
   456  	ErrSummaryServiceGet.Error(): 140001,
   457  	// Withdrawal
   458  	ErrWithdrawalServiceGet.Error(): 150001,
   459  	// Position
   460  	ErrPositionServiceGetByParty.Error():   160001,
   461  	ErrPositionServiceSendSnapshot.Error(): 160002,
   462  	// Governance
   463  	ErrGovernanceServiceGet.Error():          170001,
   464  	ErrGovernanceServiceGetProposals.Error(): 170002,
   465  	ErrGovernanceServiceGetVotes.Error():     170003,
   466  	// Notary
   467  	ErrNotaryServiceGetByResourceID.Error(): 180001,
   468  	// Oracle
   469  	ErrOracleSpecServiceGet.Error():    190001,
   470  	ErrOracleSpecServiceGetAll.Error(): 190002,
   471  	ErrOracleDataServiceGet.Error():    190003,
   472  	// Asset
   473  	ErrAssetServiceGetAll.Error():            200001,
   474  	ErrAssetServiceGetByID.Error():           200002,
   475  	ErrScalingPriceFromMarketToAsset.Error(): 200003,
   476  	// Deposit
   477  	ErrDepositServiceGet.Error(): 210001,
   478  	// Transfer
   479  	ErrTransferServiceGet.Error(): 220001,
   480  	// Reward
   481  	ErrGetRewards.Error(): 230001,
   482  	// Network History
   483  	ErrGetConnectedPeerAddresses.Error():    240001,
   484  	ErrGetMostRecentHistorySegment.Error():  240002,
   485  	ErrListAllNetworkHistorySegment.Error(): 240003,
   486  	ErrGetIpfsAddress.Error():               240004,
   487  	// Epoch
   488  	ErrGetEpoch.Error(): 250001,
   489  	// Ledger
   490  	ErrLedgerServiceGet.Error():    260001,
   491  	ErrLedgerServiceExport.Error(): 260002,
   492  	// MultiSig
   493  	ErrMultiSigServiceGetAdded.Error():   270001,
   494  	ErrMultiSigServiceGetRemoved.Error(): 270002,
   495  	// Liquidity Provision
   496  	ErrLiquidityProvisionServiceGet.Error(): 280001,
   497  	// Checkpoint
   498  	ErrCheckpointServiceGet.Error(): 290001,
   499  	// Stake Linking
   500  	ErrStakeLinkingServiceGet.Error(): 300001,
   501  	// Risk Factor
   502  	ErrRiskFactorServiceGet.Error(): 310001,
   503  	// Core Snapshot
   504  	ErrCoreSnapshotServiceListSnapshots.Error(): 320001,
   505  	// Protocol Upgrade
   506  	ErrProtocolUpgradeServiceListProposals.Error(): 330001,
   507  	// Key Rotation
   508  	ErrKeyRotationServiceGetPerNode.Error(): 340001,
   509  	ErrKeyRotationServiceGetAll.Error():     340002,
   510  	// Ethereum Key Rotation
   511  	ErrEthereumKeyRotationServiceGetPerNode.Error(): 350001,
   512  	ErrEthereumKeyRotationServiceGetAll.Error():     350002,
   513  	// Block
   514  	ErrBlockServiceGetLast.Error(): 360001,
   515  	// End of mapping
   516  }
   517  
   518  // ErrorMap returns a map of error to code, which is a mapping between
   519  // API errors and Vega API specific numeric codes.
   520  func ErrorMap() map[string]int32 {
   521  	return errorMap
   522  }
   523  
   524  // apiError is a helper function to build the Vega specific Error Details that
   525  // can be returned by gRPC API and therefore also REST, GraphQL will be mapped too.
   526  // It takes a standardised grpcCode, a Vega specific apiError, and optionally one
   527  // or more internal errors (error from the core, rather than API).
   528  func apiError(grpcCode codes.Code, apiError error, innerErrors ...error) error {
   529  	s := status.Newf(grpcCode, "%v error", grpcCode)
   530  	// Create the API specific error detail for error e.g. missing party ID
   531  	detail := types.ErrorDetail{
   532  		Message: apiError.Error(),
   533  	}
   534  	// Lookup the API specific error in the table, return not found/not mapped
   535  	// if a code has not yet been added to the map, can happen if developer misses
   536  	// a step, periodic checking/ownership of API package can keep this up to date.
   537  	vegaCode, found := errorMap[apiError.Error()]
   538  	if found {
   539  		detail.Code = vegaCode
   540  	} else {
   541  		detail.Code = errorMap[ErrNotMapped.Error()]
   542  	}
   543  	// If there is an inner error (and possibly in the future, a config to turn this
   544  	// level of detail on/off) then process and append to inner.
   545  	first := true
   546  	for _, err := range innerErrors {
   547  		if !first {
   548  			detail.Inner += ", "
   549  		}
   550  		detail.Inner += err.Error()
   551  		first = false
   552  	}
   553  	// Pack the Vega domain specific errorDetails into the status returned by gRPC domain.
   554  	s, _ = s.WithDetails(&detail)
   555  	return s.Err()
   556  }
   557  
   558  type invalidArgumentError struct {
   559  	err error
   560  }
   561  
   562  func newInvalidArgumentError(msg string) *invalidArgumentError {
   563  	return &invalidArgumentError{err: errors.New(msg)}
   564  }
   565  
   566  func (e *invalidArgumentError) Error() string {
   567  	if e.err == nil {
   568  		return ""
   569  	}
   570  	return e.err.Error()
   571  }
   572  
   573  func hasInvalidArgumentError(errs ...error) bool {
   574  	for _, err := range errs {
   575  		if _, ok := err.(*invalidArgumentError); ok || errors.Is(err, entities.ErrInvalidID) {
   576  			return true
   577  		}
   578  	}
   579  	return false
   580  }
   581  
   582  func hasNotFoundError(errs ...error) bool {
   583  	for _, err := range errs {
   584  		if errors.Is(err, entities.ErrNotFound) {
   585  			return true
   586  		}
   587  	}
   588  	return false
   589  }
   590  
   591  func hasError(errs ...error) bool {
   592  	for _, err := range errs {
   593  		if err != nil {
   594  			return true
   595  		}
   596  	}
   597  	return false
   598  }
   599  
   600  func formatE(err error, errs ...error) error {
   601  	allErrs := append(errs, err)
   602  
   603  	if !hasError(allErrs...) {
   604  		return nil
   605  	}
   606  
   607  	switch {
   608  	// only for "GetOne"-like store methods
   609  	case hasNotFoundError(allErrs...):
   610  		return apiError(codes.NotFound, err, errs...)
   611  	case hasInvalidArgumentError(allErrs...):
   612  		return apiError(codes.InvalidArgument, err, errs...)
   613  	default:
   614  		// could handle more errors like context cancelled,
   615  		// deadline exceeded, but let's see later
   616  		return apiError(codes.Internal, err, errs...)
   617  	}
   618  }
   619  
   620  // FormatE exports the formatE function (primarily for testing).
   621  var FormatE = formatE