diff --git a/cmd/staking-api-service/main.go b/cmd/staking-api-service/main.go index e10d2c84..d0e66d3b 100644 --- a/cmd/staking-api-service/main.go +++ b/cmd/staking-api-service/main.go @@ -89,7 +89,7 @@ func main() { if cli.GetReplayFlag() { log.Info().Msg("Replay flag is set. Starting replay of unprocessable messages.") - err := scripts.ReplayUnprocessableMessages(ctx, cfg, queueClients, dbClients.DBClient) + err := scripts.ReplayUnprocessableMessages(ctx, cfg, queueClients, dbClients.SharedDBClient) if err != nil { log.Fatal().Err(err).Msg("error while replaying unprocessable messages") } diff --git a/cmd/staking-api-service/scripts/replay_unprocessed_messages.go b/cmd/staking-api-service/scripts/replay_unprocessed_messages.go index 42cec480..4f3c2e98 100644 --- a/cmd/staking-api-service/scripts/replay_unprocessed_messages.go +++ b/cmd/staking-api-service/scripts/replay_unprocessed_messages.go @@ -17,7 +17,7 @@ type GenericEvent struct { EventType queueClient.EventType `json:"event_type"` } -func ReplayUnprocessableMessages(ctx context.Context, cfg *config.Config, queues *queueclients.QueueClients, db dbclient.DBClient) (err error) { +func ReplayUnprocessableMessages(ctx context.Context, cfg *config.Config, queues *queueclients.QueueClients, db dbclient.DBClientInterface) (err error) { // Fetch unprocessable messages unprocessableMessages, err := db.FindUnprocessableMessages(ctx) if err != nil { diff --git a/internal/shared/api/handlers/handlers.go b/internal/shared/api/handlers/handlers.go index 9981447f..63dd20f0 100644 --- a/internal/shared/api/handlers/handlers.go +++ b/internal/shared/api/handlers/handlers.go @@ -11,9 +11,9 @@ import ( ) type Handlers struct { - Shared *handler.Handler - V1 *v1handler.V1Handler - V2 *v2handler.V2Handler + SharedHandler *handler.Handler + V1Handler *v1handler.V1Handler + V2Handler *v2handler.V2Handler } func New(ctx context.Context, config *config.Config, services *services.Services) (*Handlers, error) { @@ -31,8 +31,8 @@ func New(ctx context.Context, config *config.Config, services *services.Services } return &Handlers{ - Shared: sharedHandler, - V1: v1Handler, - V2: v2Handler, + SharedHandler: sharedHandler, + V1Handler: v1Handler, + V2Handler: v2Handler, }, nil } diff --git a/internal/shared/api/routes.go b/internal/shared/api/routes.go index 8e324428..3dcb541a 100644 --- a/internal/shared/api/routes.go +++ b/internal/shared/api/routes.go @@ -9,35 +9,35 @@ import ( func (a *Server) SetupRoutes(r *chi.Mux) { handlers := a.handlers // Extend on the healthcheck endpoint here - r.Get("/healthcheck", registerHandler(handlers.Shared.HealthCheck)) + r.Get("/healthcheck", registerHandler(handlers.SharedHandler.HealthCheck)) - r.Get("/v1/staker/delegations", registerHandler(handlers.V1.GetStakerDelegations)) - r.Post("/v1/unbonding", registerHandler(handlers.V1.UnbondDelegation)) - r.Get("/v1/unbonding/eligibility", registerHandler(handlers.V1.GetUnbondingEligibility)) - r.Get("/v1/global-params", registerHandler(handlers.V1.GetBabylonGlobalParams)) - r.Get("/v1/finality-providers", registerHandler(handlers.V1.GetFinalityProviders)) - r.Get("/v1/stats", registerHandler(handlers.V1.GetOverallStats)) - r.Get("/v1/stats/staker", registerHandler(handlers.V1.GetStakersStats)) - r.Get("/v1/staker/delegation/check", registerHandler(handlers.V1.CheckStakerDelegationExist)) - r.Get("/v1/delegation", registerHandler(handlers.V1.GetDelegationByTxHash)) + r.Get("/v1/staker/delegations", registerHandler(handlers.V1Handler.GetStakerDelegations)) + r.Post("/v1/unbonding", registerHandler(handlers.V1Handler.UnbondDelegation)) + r.Get("/v1/unbonding/eligibility", registerHandler(handlers.V1Handler.GetUnbondingEligibility)) + r.Get("/v1/global-params", registerHandler(handlers.V1Handler.GetBabylonGlobalParams)) + r.Get("/v1/finality-providers", registerHandler(handlers.V1Handler.GetFinalityProviders)) + r.Get("/v1/stats", registerHandler(handlers.V1Handler.GetOverallStats)) + r.Get("/v1/stats/staker", registerHandler(handlers.V1Handler.GetStakersStats)) + r.Get("/v1/staker/delegation/check", registerHandler(handlers.V1Handler.CheckStakerDelegationExist)) + r.Get("/v1/delegation", registerHandler(handlers.V1Handler.GetDelegationByTxHash)) // Only register these routes if the asset has been configured // The endpoints are used to check ordinals within the UTXOs // Don't deprecate this endpoint if a.cfg.Assets != nil { - r.Post("/v1/ordinals/verify-utxos", registerHandler(handlers.Shared.VerifyUTXOs)) + r.Post("/v1/ordinals/verify-utxos", registerHandler(handlers.SharedHandler.VerifyUTXOs)) } // Don't deprecate this endpoint - r.Get("/v1/staker/pubkey-lookup", registerHandler(handlers.V1.GetPubKeys)) + r.Get("/v1/staker/pubkey-lookup", registerHandler(handlers.V1Handler.GetPubKeys)) r.Get("/swagger/*", httpSwagger.WrapHandler) // V2 API // TODO: Implement the handlers for the V2 API - r.Get("/v2/stats", registerHandler(handlers.V2.GetStats)) - r.Get("/v2/finality-providers", registerHandler(handlers.V2.GetFinalityProviders)) - r.Get("/v2/global-params", registerHandler(handlers.V2.GetGlobalParams)) - r.Get("/v2/staker/delegations", registerHandler(handlers.V2.GetStakerDelegations)) - r.Get("/v2/staker/stats", registerHandler(handlers.V2.GetStakerStats)) + r.Get("/v2/stats", registerHandler(handlers.V2Handler.GetStats)) + r.Get("/v2/finality-providers", registerHandler(handlers.V2Handler.GetFinalityProviders)) + r.Get("/v2/global-params", registerHandler(handlers.V2Handler.GetGlobalParams)) + r.Get("/v2/staker/delegations", registerHandler(handlers.V2Handler.GetStakerDelegations)) + r.Get("/v2/staker/stats", registerHandler(handlers.V2Handler.GetStakerStats)) } diff --git a/internal/shared/db/client/interface.go b/internal/shared/db/client/interface.go index e1605714..497cbbfb 100644 --- a/internal/shared/db/client/interface.go +++ b/internal/shared/db/client/interface.go @@ -6,7 +6,7 @@ import ( dbmodel "github.com/babylonlabs-io/staking-api-service/internal/shared/db/model" ) -type DBClient interface { +type DBClientInterface interface { Ping(ctx context.Context) error // InsertPkAddressMappings inserts the btc public key and // its corresponding btc addresses into the database. diff --git a/internal/shared/db/clients/db_clients.go b/internal/shared/db/clients/db_clients.go index a67c5587..0df67e8d 100644 --- a/internal/shared/db/clients/db_clients.go +++ b/internal/shared/db/clients/db_clients.go @@ -12,10 +12,10 @@ import ( ) type DbClients struct { - MongoClient *mongo.Client - DBClient dbclient.DBClient - V1DBClient v1dbclient.V1DBClient - V2DBClient v2dbclient.V2DBClient + MongoClient *mongo.Client + SharedDBClient dbclient.DBClientInterface + V1DBClient v1dbclient.V1DBClientInterface + V2DBClient v2dbclient.V2DBClientInterface } func New(ctx context.Context, cfg *config.Config) (*DbClients, error) { @@ -41,10 +41,10 @@ func New(ctx context.Context, cfg *config.Config) (*DbClients, error) { } dbClients := DbClients{ - MongoClient: mongoClient, - DBClient: dbClient, - V1DBClient: v1dbClient, - V2DBClient: v2dbClient, + MongoClient: mongoClient, + SharedDBClient: dbClient, + V1DBClient: v1dbClient, + V2DBClient: v2dbClient, } return &dbClients, nil diff --git a/internal/shared/http/client/http_client.go b/internal/shared/http/client/http_client.go index f533b02d..e017404b 100644 --- a/internal/shared/http/client/http_client.go +++ b/internal/shared/http/client/http_client.go @@ -15,13 +15,13 @@ import ( var ALLOWED_METHODS = []string{"GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"} -type Client interface { +type HttpClientInterface interface { GetBaseURL() string GetDefaultRequestTimeout() int GetHttpClient() *http.Client } -type ClientOptions struct { +type HttpClientOptions struct { Timeout int Path string TemplatePath string // Metrics purpose @@ -38,7 +38,7 @@ func isAllowedMethod(method string) bool { } func sendRequest[I any, R any]( - ctx context.Context, client Client, method string, opts *ClientOptions, input *I, + ctx context.Context, client HttpClientInterface, method string, opts *HttpClientOptions, input *I, ) (*R, *types.Error) { if !isAllowedMethod(method) { return nil, types.NewInternalServiceError(fmt.Errorf("method %s is not allowed", method)) @@ -122,7 +122,7 @@ func sendRequest[I any, R any]( } func SendRequest[I any, R any]( - ctx context.Context, client Client, method string, opts *ClientOptions, input *I, + ctx context.Context, client HttpClientInterface, method string, opts *HttpClientOptions, input *I, ) (*R, *types.Error) { timer := metrics.StartClientRequestDurationTimer( client.GetBaseURL(), method, opts.TemplatePath, diff --git a/internal/shared/http/clients/ordinals/ordinals.go b/internal/shared/http/clients/ordinals/ordinals.go index 5357266e..95f64049 100644 --- a/internal/shared/http/clients/ordinals/ordinals.go +++ b/internal/shared/http/clients/ordinals/ordinals.go @@ -57,7 +57,7 @@ func (c *OrdinalsClient) FetchUTXOInfos( ctx context.Context, utxos []types.UTXOIdentifier, ) ([]OrdinalsOutputResponse, *types.Error) { path := "/outputs" - opts := &client.ClientOptions{ + opts := &client.HttpClientOptions{ Path: path, TemplatePath: path, Headers: c.defaultHeaders, diff --git a/internal/shared/utils/datagen/datagen.go b/internal/shared/utils/datagen/datagen.go new file mode 100644 index 00000000..5b04488b --- /dev/null +++ b/internal/shared/utils/datagen/datagen.go @@ -0,0 +1,215 @@ +package datagen + +import ( + "bytes" + "encoding/hex" + "fmt" + "log" + "math/rand" + "time" + + "github.com/babylonlabs-io/staking-api-service/internal/shared/types" + "github.com/btcsuite/btcd/btcec/v2" + "github.com/btcsuite/btcd/btcec/v2/schnorr" + "github.com/btcsuite/btcd/chaincfg/chainhash" + "github.com/btcsuite/btcd/wire" +) + +const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" + +func GenRandomByteArray(r *rand.Rand, length uint64) []byte { + newHeaderBytes := make([]byte, length) + r.Read(newHeaderBytes) + return newHeaderBytes +} + +func RandomPk() (string, error) { + fpPirvKey, err := btcec.NewPrivateKey() + if err != nil { + return "", err + } + fpPk := fpPirvKey.PubKey() + return hex.EncodeToString(schnorr.SerializePubKey(fpPk)), nil +} + +func GeneratePks(numOfKeys int) []string { + var pks []string + for i := 0; i < numOfKeys; i++ { + k, err := RandomPk() + if err != nil { + log.Fatalf("Failed to generate random pk: %v", err) + } + pks = append(pks, k) + } + return pks +} + +// RandomPostiveFloat64 generates a random float64 value greater than 0. +func RandomPostiveFloat64(r *rand.Rand) float64 { + for { + f := r.Float64() // Generate a random float64 + if f > 0 { + return f + } + // If f is 0 (extremely rare), regenerate + } +} + +// RandomPositiveInt generates a random positive integer from 1 to max. +func RandomPositiveInt(r *rand.Rand, max int) int { + // Generate a random number from 1 to max (inclusive) + return r.Intn(max) + 1 +} + +// RandomString generates a random alphanumeric string of length n. +func RandomString(r *rand.Rand, n int) string { + result := make([]byte, n) + letterLen := len(letters) + for i := range result { + num := r.Int() % letterLen + result[i] = letters[num] + } + return string(result) +} + +// RandomAmount generates a random BTC amount from 0.1 to 10000 +// the returned value is in satoshis +func RandomAmount(r *rand.Rand) int64 { + // Generate a random value range from 0.1 to 10000 BTC + randomBTC := r.Float64()*(9999.9-0.1) + 0.1 + // convert to satoshi + return int64(randomBTC*1e8) + 1 +} + +// GenerateRandomTx generates a random transaction with random values for each field. +func GenerateRandomTx( + r *rand.Rand, + options *struct{ DisableRbf bool }, +) (*wire.MsgTx, string, error) { + sequence := r.Uint32() + if options != nil && options.DisableRbf { + sequence = wire.MaxTxInSequenceNum + } + tx := &wire.MsgTx{ + Version: 1, + TxIn: []*wire.TxIn{ + { + PreviousOutPoint: wire.OutPoint{ + Hash: chainhash.HashH(GenRandomByteArray(r, 10)), + Index: r.Uint32(), + }, + SignatureScript: []byte{}, + Sequence: sequence, + }, + }, + TxOut: []*wire.TxOut{ + { + Value: int64(r.Int31()), + PkScript: GenRandomByteArray(r, 80), + }, + }, + LockTime: 0, + } + var buf bytes.Buffer + if err := tx.Serialize(&buf); err != nil { + return nil, "", err + } + txHex := hex.EncodeToString(buf.Bytes()) + + return tx, txHex, nil +} + +// GenerateRandomTxWithOutput generates a random transaction with random values +// for each field. +func RandomBytes(r *rand.Rand, n uint64) ([]byte, string) { + randomBytes := GenRandomByteArray(r, n) + return randomBytes, hex.EncodeToString(randomBytes) +} + +// GenerateRandomTimestamp generates a random timestamp before the specified timestamp. +// If beforeTimestamp is 0, then the current time is used. +func GenerateRandomTimestamp(afterTimestamp, beforeTimestamp int64) int64 { + timeNow := time.Now().Unix() + if beforeTimestamp == 0 && afterTimestamp == 0 { + return timeNow + } + if beforeTimestamp == 0 { + return afterTimestamp + rand.Int63n(timeNow-afterTimestamp) + } else if afterTimestamp == 0 { + // Generate a reasonable timestamp between 1 second to 6 months in the past + sixMonthsInSeconds := int64(6 * 30 * 24 * 60 * 60) + return beforeTimestamp - rand.Int63n(sixMonthsInSeconds) + } + return afterTimestamp + rand.Int63n(beforeTimestamp-afterTimestamp) +} + +// GenerateRandomFinalityProviderDetail generates a random number of finality providers +func GenerateRandomFinalityProviderDetail(r *rand.Rand, numOfFps uint64) []types.FinalityProviderDetails { + var finalityProviders []types.FinalityProviderDetails + + for i := uint64(0); i < numOfFps; i++ { + fpPkInHex, err := RandomPk() + if err != nil { + log.Fatalf("failed to generate random public key: %v", err) + } + + randomStr := RandomString(r, 10) + finalityProviders = append(finalityProviders, types.FinalityProviderDetails{ + Description: types.FinalityProviderDescription{ + Moniker: "Moniker" + randomStr, + Identity: "Identity" + randomStr, + Website: "Website" + randomStr, + SecurityContact: "SecurityContact" + randomStr, + Details: "Details" + randomStr, + }, + Commission: fmt.Sprintf("%f", RandomPostiveFloat64(r)), + BtcPk: fpPkInHex, + }) + } + return finalityProviders +} + +func RandomFinalityProviderState(r *rand.Rand) types.FinalityProviderState { + states := []types.FinalityProviderState{types.FinalityProviderStateActive, types.FinalityProviderStateStandby} + return states[r.Intn(len(states))] +} + +func GenerateRandomBabylonParams(r *rand.Rand) types.BabylonParams { + return types.BabylonParams{ + Version: r.Intn(10), + CovenantPKs: GeneratePks(r.Intn(10)), + CovenantQuorum: r.Intn(10), + MaxStakingAmount: int64(r.Intn(1000000000000000000)), + MinStakingAmount: int64(r.Intn(1000000000000000000)), + MaxStakingTime: int64(r.Intn(1000000000000000000)), + MinStakingTime: int64(r.Intn(1000000000000000000)), + SlashingPKScript: RandomString(r, 10), + MinSlashingTxFee: int64(r.Intn(1000000000000000000)), + SlashingRate: RandomPostiveFloat64(r), + MinUnbondingTime: int64(r.Intn(1000000000000000000)), + UnbondingFee: int64(r.Intn(1000000000000000000)), + MinCommissionRate: RandomPostiveFloat64(r), + MaxActiveFinalityProviders: r.Intn(10), + DelegationCreationBaseGasFee: int64(r.Intn(1000000000000000000)), + } +} + +func GenerateRandomBTCParams(r *rand.Rand) types.BTCParams { + return types.BTCParams{ + Version: r.Intn(10), + BTCConfirmationDepth: r.Intn(10), + } +} + +func RandomDelegationState(r *rand.Rand) types.DelegationState { + states := []types.DelegationState{types.Active, types.UnbondingRequested, types.Unbonding, types.Unbonded, types.Withdrawn} + return states[r.Intn(len(states))] +} + +func RandomTransactionInfo(r *rand.Rand) types.TransactionInfo { + _, txHex, _ := GenerateRandomTx(r, nil) + return types.TransactionInfo{ + TxHex: txHex, + OutputIndex: r.Intn(100), + } +} diff --git a/internal/v1/db/client/interface.go b/internal/v1/db/client/interface.go index 163dff1f..16593e58 100644 --- a/internal/v1/db/client/interface.go +++ b/internal/v1/db/client/interface.go @@ -9,8 +9,8 @@ import ( v1dbmodel "github.com/babylonlabs-io/staking-api-service/internal/v1/db/model" ) -type V1DBClient interface { - dbclient.DBClient +type V1DBClientInterface interface { + dbclient.DBClientInterface SaveActiveStakingDelegation( ctx context.Context, stakingTxHashHex, stakerPkHex, fpPkHex string, stakingTxHex string, amount, startHeight, timelock, outputIndex uint64, diff --git a/internal/v2/db/client/interface.go b/internal/v2/db/client/interface.go index 02bd61c4..0ae29c0e 100644 --- a/internal/v2/db/client/interface.go +++ b/internal/v2/db/client/interface.go @@ -4,6 +4,6 @@ import ( dbclient "github.com/babylonlabs-io/staking-api-service/internal/shared/db/client" ) -type V2DBClient interface { - dbclient.DBClient +type V2DBClientInterface interface { + dbclient.DBClientInterface } diff --git a/internal/v2/service/finality_provider.go b/internal/v2/service/finality_provider.go index 365ecca6..729593cd 100644 --- a/internal/v2/service/finality_provider.go +++ b/internal/v2/service/finality_provider.go @@ -2,11 +2,8 @@ package v2service import ( "context" - "math/rand" - "time" "github.com/babylonlabs-io/staking-api-service/internal/shared/types" - "github.com/babylonlabs-io/staking-api-service/tests/testutils" ) type FinalityProviderPublic struct { @@ -26,23 +23,24 @@ type FinalityProvidersPublic struct { } func (s *V2Service) GetFinalityProviders(ctx context.Context, paginationKey string) ([]FinalityProviderPublic, string, *types.Error) { - r := rand.New(rand.NewSource(time.Now().UnixNano())) - // random number of providers between 1 and 10 - numProviders := testutils.RandomPositiveInt(r, 10) - providers := testutils.GenerateRandomFinalityProviderDetail(r, uint64(numProviders)) - publicProviders := make([]FinalityProviderPublic, len(providers)) - for i, provider := range providers { - publicProviders[i] = FinalityProviderPublic{ - BtcPK: testutils.GeneratePks(1)[0], - State: testutils.RandomFinalityProviderState(r), - Description: provider.Description, - Commission: provider.Commission, - ActiveTVL: int64(testutils.RandomPositiveInt(r, 1000000000000000000)), - TotalTVL: int64(testutils.RandomPositiveInt(r, 1000000000000000000)), - ActiveDelegations: int64(testutils.RandomPositiveInt(r, 100)), - TotalDelegations: int64(testutils.RandomPositiveInt(r, 100)), - } - } + // r := rand.New(rand.NewSource(time.Now().UnixNano())) + // // random number of providers between 1 and 10 + // numProviders := datagen.RandomPositiveInt(r, 10) + // providers := datagen.GenerateRandomFinalityProviderDetail(r, uint64(numProviders)) + // publicProviders := make([]FinalityProviderPublic, len(providers)) + // for i, provider := range providers { + // publicProviders[i] = FinalityProviderPublic{ + // BtcPK: datagen.GeneratePks(1)[0], + // State: datagen.RandomFinalityProviderState(r), + // Description: provider.Description, + // Commission: provider.Commission, + // ActiveTVL: int64(datagen.RandomPositiveInt(r, 1000000000000000000)), + // TotalTVL: int64(datagen.RandomPositiveInt(r, 1000000000000000000)), + // ActiveDelegations: int64(datagen.RandomPositiveInt(r, 100)), + // TotalDelegations: int64(datagen.RandomPositiveInt(r, 100)), + // } + // } - return publicProviders, "", nil + // return publicProviders, "", nil + return nil, "", nil } diff --git a/internal/v2/service/global_params.go b/internal/v2/service/global_params.go index 2231cb3e..96954f3a 100644 --- a/internal/v2/service/global_params.go +++ b/internal/v2/service/global_params.go @@ -6,7 +6,7 @@ import ( "time" "github.com/babylonlabs-io/staking-api-service/internal/shared/types" - "github.com/babylonlabs-io/staking-api-service/tests/testutils" + "github.com/babylonlabs-io/staking-api-service/internal/shared/utils/datagen" ) type GlobalParamsPublic struct { @@ -16,8 +16,8 @@ type GlobalParamsPublic struct { func (s *V2Service) GetGlobalParams(ctx context.Context) (GlobalParamsPublic, *types.Error) { r := rand.New(rand.NewSource(time.Now().UnixNano())) - babylonParams := testutils.GenerateRandomBabylonParams(r) - btcParams := testutils.GenerateRandomBTCParams(r) + babylonParams := datagen.GenerateRandomBabylonParams(r) + btcParams := datagen.GenerateRandomBTCParams(r) return GlobalParamsPublic{ Babylon: []types.BabylonParams{babylonParams}, BTC: []types.BTCParams{btcParams}, diff --git a/internal/v2/service/staker.go b/internal/v2/service/staker.go index 11151e7f..1700a76b 100644 --- a/internal/v2/service/staker.go +++ b/internal/v2/service/staker.go @@ -6,7 +6,7 @@ import ( "time" "github.com/babylonlabs-io/staking-api-service/internal/shared/types" - "github.com/babylonlabs-io/staking-api-service/tests/testutils" + "github.com/babylonlabs-io/staking-api-service/internal/shared/utils/datagen" ) type StakerDelegationPublic struct { @@ -33,23 +33,23 @@ type StakerStatsPublic struct { func (s *V2Service) GetStakerDelegations(ctx context.Context, paginationKey string) ([]StakerDelegationPublic, string, *types.Error) { r := rand.New(rand.NewSource(time.Now().UnixNano())) // random positive int - numStakerDelegations := testutils.RandomPositiveInt(r, 10) + numStakerDelegations := datagen.RandomPositiveInt(r, 10) stakerDelegationPublics := []StakerDelegationPublic{} for i := 0; i < numStakerDelegations; i++ { - _, stakingTxHash, _ := testutils.GenerateRandomTx(r, nil) - stakerPkHex, _ := testutils.RandomPk() - fpPkHex, _ := testutils.RandomPk() + _, stakingTxHash, _ := datagen.GenerateRandomTx(r, nil) + stakerPkHex, _ := datagen.RandomPk() + fpPkHex, _ := datagen.RandomPk() stakerDelegation := &StakerDelegationPublic{ StakingTxHashHex: stakingTxHash, StakerPKHex: stakerPkHex, FinalityProviderPKHex: fpPkHex, - StakingStartHeight: int64(testutils.RandomPositiveInt(r, 1000000)), - UnbondingStartHeight: int64(testutils.RandomPositiveInt(r, 1000000)), - Timelock: int64(testutils.RandomPositiveInt(r, 1000000)), - StakingValue: testutils.RandomAmount(r), + StakingStartHeight: int64(datagen.RandomPositiveInt(r, 1000000)), + UnbondingStartHeight: int64(datagen.RandomPositiveInt(r, 1000000)), + Timelock: int64(datagen.RandomPositiveInt(r, 1000000)), + StakingValue: datagen.RandomAmount(r), State: types.Active.ToString(), - StakingTx: testutils.RandomTransactionInfo(r), - UnbondingTx: testutils.RandomTransactionInfo(r), + StakingTx: datagen.RandomTransactionInfo(r), + UnbondingTx: datagen.RandomTransactionInfo(r), } stakerDelegationPublics = append(stakerDelegationPublics, *stakerDelegation) } @@ -60,10 +60,10 @@ func (s *V2Service) GetStakerStats(ctx context.Context, stakerPKHex string) (Sta r := rand.New(rand.NewSource(time.Now().UnixNano())) stakerStats := StakerStatsPublic{ StakerPKHex: stakerPKHex, - ActiveTVL: int64(testutils.RandomPositiveInt(r, 1000000)), - TotalTVL: int64(testutils.RandomPositiveInt(r, 1000000)), - ActiveDelegations: int64(testutils.RandomPositiveInt(r, 100)), - TotalDelegations: int64(testutils.RandomPositiveInt(r, 100)), + ActiveTVL: int64(datagen.RandomPositiveInt(r, 1000000)), + TotalTVL: int64(datagen.RandomPositiveInt(r, 1000000)), + ActiveDelegations: int64(datagen.RandomPositiveInt(r, 100)), + TotalDelegations: int64(datagen.RandomPositiveInt(r, 100)), } return stakerStats, nil } diff --git a/internal/v2/service/stats.go b/internal/v2/service/stats.go index f14d4d80..62175b5e 100644 --- a/internal/v2/service/stats.go +++ b/internal/v2/service/stats.go @@ -6,7 +6,7 @@ import ( "time" "github.com/babylonlabs-io/staking-api-service/internal/shared/types" - "github.com/babylonlabs-io/staking-api-service/tests/testutils" + "github.com/babylonlabs-io/staking-api-service/internal/shared/utils/datagen" ) type OverallStatsPublic struct { @@ -23,14 +23,14 @@ type OverallStatsPublic struct { func (s *V2Service) GetOverallStats(ctx context.Context) (OverallStatsPublic, *types.Error) { r := rand.New(rand.NewSource(time.Now().UnixNano())) overallStats := OverallStatsPublic{ - ActiveTVL: int64(testutils.RandomPositiveInt(r, 1000000)), - TotalTVL: int64(testutils.RandomPositiveInt(r, 1000000)), - ActiveDelegations: int64(testutils.RandomPositiveInt(r, 100)), - TotalDelegations: int64(testutils.RandomPositiveInt(r, 100)), - ActiveStakers: int64(testutils.RandomPositiveInt(r, 100)), - TotalStakers: int64(testutils.RandomPositiveInt(r, 100)), - ActiveFinalityProviders: int64(testutils.RandomPositiveInt(r, 100)), - TotalFinalityProviders: int64(testutils.RandomPositiveInt(r, 100)), + ActiveTVL: int64(datagen.RandomPositiveInt(r, 1000000)), + TotalTVL: int64(datagen.RandomPositiveInt(r, 1000000)), + ActiveDelegations: int64(datagen.RandomPositiveInt(r, 100)), + TotalDelegations: int64(datagen.RandomPositiveInt(r, 100)), + ActiveStakers: int64(datagen.RandomPositiveInt(r, 100)), + TotalStakers: int64(datagen.RandomPositiveInt(r, 100)), + ActiveFinalityProviders: int64(datagen.RandomPositiveInt(r, 100)), + TotalFinalityProviders: int64(datagen.RandomPositiveInt(r, 100)), } return overallStats, nil } diff --git a/tests/testutils/database.go b/tests/testutils/database.go index 2500125d..a9e5f5cf 100644 --- a/tests/testutils/database.go +++ b/tests/testutils/database.go @@ -37,10 +37,10 @@ func DirectDbConnection(cfg *config.Config) (*dbclients.DbClients, string) { log.Fatal(err) } return &dbclients.DbClients{ - MongoClient: mongoClient, - DBClient: dbClient, - V1DBClient: v1dbClient, - V2DBClient: v2dbClient, + MongoClient: mongoClient, + SharedDBClient: dbClient, + V1DBClient: v1dbClient, + V2DBClient: v2dbClient, }, cfg.Db.DbName }