diff --git a/api/api.go b/api/api.go index 1aecf1d7..64ad419b 100644 --- a/api/api.go +++ b/api/api.go @@ -69,7 +69,7 @@ func StartInternal(config APIConfig) { func baseMiddleware(logger *zerolog.Logger, e *echo.Echo) { e.Use(middleware.Tracer()) e.Use(middleware.CORS()) - e.Use(middleware.RequestID()) + e.Use(middleware.RequestId()) e.Use(middleware.Recover()) e.Use(middleware.Logger(logger)) e.Use(middleware.LogRequest()) diff --git a/api/handler/auth_key.go b/api/handler/auth_key.go index ef0aa904..eae3d826 100644 --- a/api/handler/auth_key.go +++ b/api/handler/auth_key.go @@ -61,7 +61,7 @@ func (o authAPIKey) Approve(c echo.Context) error { return NotAllowedError(c) } params := struct { - ID string `param:"id"` + Id string `param:"id"` }{} err := c.Bind(¶ms) @@ -69,7 +69,7 @@ func (o authAPIKey) Approve(c echo.Context) error { LogStringError(c, err, "authKey approve: bind") return echo.NewHTTPError(http.StatusInternalServerError, "Unable to process request") } - err = o.service.Approve(params.ID) + err = o.service.Approve(params.Id) if err != nil { LogStringError(c, err, "authKey approve: approve") return echo.NewHTTPError(http.StatusInternalServerError, "Unable to process request") diff --git a/api/handler/login_test.go b/api/handler/login_test.go index 4a05e618..6df70eb7 100644 --- a/api/handler/login_test.go +++ b/api/handler/login_test.go @@ -30,7 +30,7 @@ func TestStatus200LoginNoncePayload(t *testing.T) { request := httptest.NewRequest(http.MethodGet, "/?"+q.Encode(), nil) request.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON) - handler := NewLogin(nil, stubs.Auth{}) + handler := NewLogin(nil, stubs.Auth{}, stubs.Device{}) handler.RegisterRoutes(e.Group("/login")) rec := httptest.NewRecorder() c := e.NewContext(request, rec) @@ -53,7 +53,7 @@ func TestStatus200LoginVerifySignature(t *testing.T) { request := httptest.NewRequest(http.MethodPost, "/sign", strings.NewReader(string(jsonBody))) request.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON) - handler := NewLogin(nil, stubs.Auth{}) + handler := NewLogin(nil, stubs.Auth{}, stubs.Device{}) handler.RegisterRoutes(e.Group("/login")) rec := httptest.NewRecorder() c := e.NewContext(request, rec) @@ -68,7 +68,7 @@ func TestStatus400MissingWalletLoginNoncePayload(t *testing.T) { request := httptest.NewRequest(http.MethodGet, "/", nil) request.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON) - handler := NewLogin(nil, stubs.Auth{}) + handler := NewLogin(nil, stubs.Auth{}, stubs.Device{}) handler.RegisterRoutes(e.Group("/login")) rec := httptest.NewRecorder() c := e.NewContext(request, rec) diff --git a/api/handler/user.go b/api/handler/user.go index aa7f25ab..a9084f71 100644 --- a/api/handler/user.go +++ b/api/handler/user.go @@ -72,7 +72,7 @@ func (u user) Create(c echo.Context) error { } func (u user) Status(c echo.Context) error { - valid, userId := validUserID(IDParam(c), c) + valid, userId := validUserId(IdParam(c), c) if !valid { return Unauthorized(c) } @@ -92,7 +92,7 @@ func (u user) Update(c echo.Context) error { LogStringError(c, err, "user: update bind") return BadRequestError(c) } - _, userId := validUserID(IDParam(c), c) + _, userId := validUserId(IdParam(c), c) user, err := u.userService.Update(userId, body) if err != nil { LogStringError(c, err, "user: update") @@ -105,7 +105,7 @@ func (u user) Update(c echo.Context) error { // VerifyEmail send an email with a link, the user must click on the link for the email to be verified // the link sent is handled by (verification.VerifyEmail) handler func (u user) VerifyEmail(c echo.Context) error { - _, userId := validUserID(IDParam(c), c) + _, userId := validUserId(IdParam(c), c) email := c.QueryParam("email") if email == "" { return BadRequestError(c, "Missing or invalid email") @@ -145,12 +145,12 @@ func (u user) RegisterRoutes(g *echo.Group, ms ...echo.MiddlewareFunc) { } // get userId from context and also compare if both are valid -// this is useful for path params validation and userID from JWT -func validUserID(userID string, c echo.Context) (bool, string) { - userId := c.Get("userId").(string) - return userId == userID, userId +// this is useful for path params validation and userId from JWT +func validUserId(userId string, c echo.Context) (bool, string) { + _userId := c.Get("userId").(string) + return _userId == userId, _userId } -func IDParam(c echo.Context) string { +func IdParam(c echo.Context) string { return c.Param("id") } diff --git a/api/middleware/middleware.go b/api/middleware/middleware.go index 1726555e..6fe1c7e3 100644 --- a/api/middleware/middleware.go +++ b/api/middleware/middleware.go @@ -65,7 +65,7 @@ func LogRequest() echo.MiddlewareFunc { } // RequestID generates a unique request ID -func RequestID() echo.MiddlewareFunc { +func RequestId() echo.MiddlewareFunc { return echoMiddleware.RequestID() } diff --git a/pkg/internal/common/cost.go b/pkg/internal/common/cost.go index b9b34f62..fca08835 100644 --- a/pkg/internal/common/cost.go +++ b/pkg/internal/common/cost.go @@ -1,10 +1,10 @@ package common -func NativeTokenBuffer(chainID uint64) float64 { +func NativeTokenBuffer(chainId uint64) float64 { return 0.05 } -func GasBuffer(chainID uint64) float64 { +func GasBuffer(chainId uint64) float64 { return 0.05 } diff --git a/pkg/internal/common/fingerprint.go b/pkg/internal/common/fingerprint.go index afc345e7..e5b24b25 100644 --- a/pkg/internal/common/fingerprint.go +++ b/pkg/internal/common/fingerprint.go @@ -54,7 +54,7 @@ type FPVisitIpLocation struct { } type FPVisitorVisit struct { - RequestID string `json:"requestId"` + RequestId string `json:"requestId"` Incognito bool `json:"incognito"` LinkedId string `json:"linkedId"` Time string `json:"time"` @@ -66,7 +66,7 @@ type FPVisitorVisit struct { } type FPVisitor struct { - ID string `json:"visitorId"` + Id string `json:"visitorId"` Visits []FPVisitorVisit `json:"visits"` } @@ -80,8 +80,8 @@ type HTTPConfig struct { type FPVisitorOpts struct { Limit int - RequestID string - LinkedID string + RequestId string + LinkedId string } func NewHTTPClient(config HTTPConfig) HTTPClient { @@ -89,10 +89,10 @@ func NewHTTPClient(config HTTPConfig) HTTPClient { } type FingerprintClient interface { - // GetVisitorByID get the fingerprint visitor by its id + // GetVisitorById get the fingerprint visitor by its id // it returns the most up to date information for the visitor // The limit should always be 1 so we can get the latest information - GetVisitorByID(VisitorID string, opts FPVisitorOpts) (FPVisitor, error) + GetVisitorById(VisitorId string, opts FPVisitorOpts) (FPVisitor, error) Request(method, url string, body io.Reader) (*http.Request, error) } @@ -108,9 +108,9 @@ func NewFingerprint(client HTTPClient) FingerprintClient { return &fingerprint{client: client, apiKey: apiKey, baseURL: baseURL} } -func (f fingerprint) GetVisitorByID(visitorID string, opts FPVisitorOpts) (FPVisitor, error) { +func (f fingerprint) GetVisitorById(visitorId string, opts FPVisitorOpts) (FPVisitor, error) { m := FPVisitor{} - r, err := f.Request(http.MethodGet, f.baseURL+"visitors/"+visitorID, nil) + r, err := f.Request(http.MethodGet, f.baseURL+"visitors/"+visitorId, nil) if err != nil { return m, err } @@ -152,11 +152,11 @@ func (f fingerprint) optionsToQuery(opts FPVisitorOpts) url.Values { if opts.Limit != 0 { q.Add("limit", strconv.Itoa(opts.Limit)) } - if opts.RequestID != "" { - q.Add("request_id", opts.RequestID) + if opts.RequestId != "" { + q.Add("request_id", opts.RequestId) } - if opts.LinkedID != "" { - q.Add("linked_id", opts.LinkedID) + if opts.LinkedId != "" { + q.Add("linked_id", opts.LinkedId) } return q } diff --git a/pkg/internal/unit21/action.go b/pkg/internal/unit21/action.go index b816bec2..2916c201 100644 --- a/pkg/internal/unit21/action.go +++ b/pkg/internal/unit21/action.go @@ -32,9 +32,9 @@ func (a action) Create( actionData := actionData{ ActionType: instrument.Type, ActionDetails: actionDetails, - EntityId: instrument.UserID, + EntityId: instrument.UserId, EntityType: "user", - InstrumentId: instrument.ID, + InstrumentId: instrument.Id, } url := "https://" + os.Getenv("UNIT21_ENV") + ".unit21.com/v1/events/create" diff --git a/pkg/internal/unit21/entity.go b/pkg/internal/unit21/entity.go index 55210b0f..95f329d3 100644 --- a/pkg/internal/unit21/entity.go +++ b/pkg/internal/unit21/entity.go @@ -35,19 +35,19 @@ func (e entity) Create(user model.User) (unit21Id string, err error) { // ultimately may want a join here. - communications, err := e.getCommunications(user.ID) + communications, err := e.getCommunications(user.Id) if err != nil { log.Err(err).Msg("Failed to gather Unit21 entity communications") return "", common.StringError(err) } - digitalData, err := e.getEntityDigitalData(user.ID) + digitalData, err := e.getEntityDigitalData(user.Id) if err != nil { log.Err(err).Msg("Failed to gather Unit21 entity digitalData") return "", common.StringError(err) } - customData, err := e.getCustomData(user.ID) + customData, err := e.getCustomData(user.Id) if err != nil { log.Err(err).Msg("Failed to gather Unit21 entity customData") return "", common.StringError(err) @@ -77,21 +77,21 @@ func (e entity) Update(user model.User) (unit21Id string, err error) { // ultimately may want a join here. - communications, err := e.getCommunications(user.ID) + communications, err := e.getCommunications(user.Id) if err != nil { log.Err(err).Msg("Failed to gather Unit21 entity communications") err = common.StringError(err) return } - digitalData, err := e.getEntityDigitalData(user.ID) + digitalData, err := e.getEntityDigitalData(user.Id) if err != nil { log.Err(err).Msg("Failed to gather Unit21 entity digitalData") err = common.StringError(err) return } - customData, err := e.getCustomData(user.ID) + customData, err := e.getCustomData(user.Id) if err != nil { log.Err(err).Msg("Failed to gather Unit21 entity customData") err = common.StringError(err) @@ -99,7 +99,7 @@ func (e entity) Update(user model.User) (unit21Id string, err error) { } orgName := os.Getenv("UNIT21_ORG_NAME") - url := "https://" + os.Getenv("UNIT21_ENV") + ".unit21.com/v1/" + orgName + "/entities/" + user.ID + "/update" + url := "https://" + os.Getenv("UNIT21_ENV") + ".unit21.com/v1/" + orgName + "/entities/" + user.Id + "/update" body, err := u21Put(url, mapUserToEntity(user, communications, digitalData, customData)) if err != nil { @@ -182,7 +182,7 @@ func (e entity) getCustomData(userId string) (customData entityCustomData, err e } for _, platform := range devices { - customData.Platforms = append(customData.Platforms, platform.PlatformID) + customData.Platforms = append(customData.Platforms, platform.PlatformId) } return } @@ -197,7 +197,7 @@ func mapUserToEntity(user model.User, communication entityCommunication, digital jsonBody := &u21Entity{ GeneralData: &entityGeneral{ - EntityId: user.ID, + EntityId: user.Id, EntityType: "user", Status: user.Status, RegisteredAt: int(user.CreatedAt.Unix()), diff --git a/pkg/internal/unit21/entity_test.go b/pkg/internal/unit21/entity_test.go index 7e387e9b..e30fd38e 100644 --- a/pkg/internal/unit21/entity_test.go +++ b/pkg/internal/unit21/entity_test.go @@ -41,7 +41,7 @@ func TestUpdateEntity(t *testing.T) { assert.Greater(t, len([]rune(u21EntityId)), 0) user := model.User{ - ID: entityId, + Id: entityId, CreatedAt: time.Now(), UpdatedAt: time.Now(), DeactivatedAt: nil, @@ -119,7 +119,7 @@ func TestAddInstruments(t *testing.T) { func createMockUser(mock sqlmock.Sqlmock, sqlxDB *sqlx.DB) (entityId string, unit21Id string, err error) { entityId = uuid.NewString() user := model.User{ - ID: entityId, + Id: entityId, CreatedAt: time.Now(), UpdatedAt: time.Now(), DeactivatedAt: nil, @@ -161,7 +161,7 @@ func createMockInstrumentForUser(userId string, mock sqlmock.Sqlmock, sqlxDB *sq locationId := uuid.NewString() instrument = model.Instrument{ - ID: instrumentId, + Id: instrumentId, CreatedAt: time.Now(), UpdatedAt: time.Now(), DeactivatedAt: nil, @@ -171,8 +171,8 @@ func createMockInstrumentForUser(userId string, mock sqlmock.Sqlmock, sqlxDB *sq Network: "Visa", PublicKey: "", Last4: "1234", - UserID: userId, - LocationID: sql.NullString{String: locationId}, + UserId: userId, + LocationId: sql.NullString{String: locationId}, } mockedUserRow1 := sqlmock.NewRows([]string{"id", "type", "status", "tags", "first_name", "middle_name", "last_name"}). @@ -191,13 +191,15 @@ func createMockInstrumentForUser(userId string, mock sqlmock.Sqlmock, sqlxDB *sq AddRow(locationId, "Home", "Verified", "20181", "411", "Lark Avenue", "Somerville", "MA", "01443", "USA") mock.ExpectQuery("SELECT * FROM location WHERE id = $1 AND deactivated_at IS NULL").WithArgs(locationId).WillReturnRows(mockedLocationRow) - repo := InstrumentRepo{ + repos := InstrumentRepos{ User: repository.NewUser(sqlxDB), Device: repository.NewDevice(sqlxDB), Location: repository.NewLocation(sqlxDB), } - u21Instrument := NewInstrument(repo) + action := NewAction() + + u21Instrument := NewInstrument(repos, action) u21InstrumentId, err := u21Instrument.Create(instrument) diff --git a/pkg/internal/unit21/evaluate_test.go b/pkg/internal/unit21/evaluate_test.go index fd108ff5..df1bf051 100644 --- a/pkg/internal/unit21/evaluate_test.go +++ b/pkg/internal/unit21/evaluate_test.go @@ -66,17 +66,10 @@ func TestEvaluateTransactionManyLinkedCards(t *testing.T) { assert.NoError(t, err) assert.Greater(t, len([]rune(u21InstrumentId)), 0) - // Log create instrument action w/ Unit21 - u21ActionRepo := ActionRepo{ - User: repository.NewUser(sqlxDB), - Device: repository.NewDevice(sqlxDB), - Location: repository.NewLocation(sqlxDB), - } - - u21Action := NewAction(u21ActionRepo) + u21Action := NewAction() _, err = u21Action.Create(instrument, "Creation", u21InstrumentId, "Creation") if err != nil { - fmt.Printf("Error creating a new instrument action in Unit21") + t.Log("Error creating a new instrument action in Unit21") return } } @@ -174,13 +167,13 @@ func TestEvaluateTransactionNewUserHighSpend(t *testing.T) { } func evaluateMockTransaction(transaction model.Transaction, sqlxDB *sqlx.DB) (pass bool, err error) { - repo := TransactionRepo{ + repos := TransactionRepos{ TxLeg: repository.NewTxLeg((sqlxDB)), User: repository.NewUser(sqlxDB), Asset: repository.NewAsset(sqlxDB), } - u21Transaction := NewTransaction(repo) + u21Transaction := NewTransaction(repos) pass, err = u21Transaction.Evaluate(transaction) diff --git a/pkg/internal/unit21/instrument.go b/pkg/internal/unit21/instrument.go index 91c93f2a..17810cac 100644 --- a/pkg/internal/unit21/instrument.go +++ b/pkg/internal/unit21/instrument.go @@ -32,25 +32,25 @@ func NewInstrument(r InstrumentRepos, a Action) Instrument { func (i instrument) Create(instrument model.Instrument) (unit21Id string, err error) { - source, err := i.getSource(instrument.UserID) + source, err := i.getSource(instrument.UserId) if err != nil { log.Err(err).Msg("Failed to gather Unit21 instrument source") return "", common.StringError(err) } - entities, err := i.getEntities(instrument.UserID) + entities, err := i.getEntities(instrument.UserId) if err != nil { log.Err(err).Msg("Failed to gather Unit21 instrument entity") return "", common.StringError(err) } - digitalData, err := i.getInstrumentDigitalData(instrument.UserID) + digitalData, err := i.getInstrumentDigitalData(instrument.UserId) if err != nil { log.Err(err).Msg("Failed to gather Unit21 entity digitalData") return "", common.StringError(err) } - locationData, err := i.getLocationData(instrument.LocationID.String) + locationData, err := i.getLocationData(instrument.LocationId.String) if err != nil { log.Err(err).Msg("Failed to gather Unit21 instrument location") return "", common.StringError(err) @@ -84,32 +84,32 @@ func (i instrument) Create(instrument model.Instrument) (unit21Id string, err er func (i instrument) Update(instrument model.Instrument) (unit21Id string, err error) { - source, err := i.getSource(instrument.UserID) + source, err := i.getSource(instrument.UserId) if err != nil { log.Err(err).Msg("Failed to gather Unit21 instrument source") return "", common.StringError(err) } - entities, err := i.getEntities(instrument.UserID) + entities, err := i.getEntities(instrument.UserId) if err != nil { log.Err(err).Msg("Failed to gather Unit21 instrument entity") return "", common.StringError(err) } - digitalData, err := i.getInstrumentDigitalData(instrument.UserID) + digitalData, err := i.getInstrumentDigitalData(instrument.UserId) if err != nil { log.Err(err).Msg("Failed to gather Unit21 entity digitalData") return "", common.StringError(err) } - locationData, err := i.getLocationData(instrument.LocationID.String) + locationData, err := i.getLocationData(instrument.LocationId.String) if err != nil { log.Err(err).Msg("Failed to gather Unit21 instrument location") return "", common.StringError(err) } orgName := os.Getenv("UNIT21_ORG_NAME") - url := "https://" + os.Getenv("UNIT21_ENV") + ".unit21.com/v1/" + orgName + "/instruments/" + instrument.ID + "/update" + url := "https://" + os.Getenv("UNIT21_ENV") + ".unit21.com/v1/" + orgName + "/instruments/" + instrument.Id + "/update" body, err := u21Put(url, mapToUnit21Instrument(instrument, source, entities, digitalData, locationData)) if err != nil { @@ -227,7 +227,7 @@ func mapToUnit21Instrument(instrument model.Instrument, source string, entityDat entityArray = append(entityArray, entityData) jsonBody := &u21Instrument{ - InstrumentId: instrument.ID, + InstrumentId: instrument.Id, InstrumentType: instrument.Type, // InstrumentSubtype: "", // Source: "internal", diff --git a/pkg/internal/unit21/instrument_test.go b/pkg/internal/unit21/instrument_test.go index 73f72062..3afbec8d 100644 --- a/pkg/internal/unit21/instrument_test.go +++ b/pkg/internal/unit21/instrument_test.go @@ -40,7 +40,7 @@ func TestUpdateInstrument(t *testing.T) { locationId := uuid.NewString() instrument = model.Instrument{ - ID: instrument.ID, + Id: instrument.Id, CreatedAt: time.Now(), UpdatedAt: time.Now(), DeactivatedAt: nil, @@ -50,8 +50,8 @@ func TestUpdateInstrument(t *testing.T) { Network: "Visa", PublicKey: "", Last4: "1235", - UserID: userId, - LocationID: sql.NullString{String: locationId}, + UserId: userId, + LocationId: sql.NullString{String: locationId}, } mockedUserRow1 := sqlmock.NewRows([]string{"id", "type", "status", "tags", "first_name", "middle_name", "last_name"}). @@ -69,13 +69,16 @@ func TestUpdateInstrument(t *testing.T) { mockedLocationRow := sqlmock.NewRows([]string{"id", "type", "status", "building_number", "unit_number", "street_name", "city", "state", "postal_code", "country"}). AddRow(locationId, "Home", "Verified", "20181", "411", "Lark Avenue", "Somerville", "MA", "01443", "USA") mock.ExpectQuery("SELECT * FROM location WHERE id = $1 AND deactivated_at IS NULL").WithArgs(locationId).WillReturnRows(mockedLocationRow) - repo := InstrumentRepo{ + + repos := InstrumentRepos{ User: repository.NewUser(sqlxDB), Device: repository.NewDevice(sqlxDB), Location: repository.NewLocation(sqlxDB), } - u21Instrument := NewInstrument(repo) + action := NewAction() + + u21Instrument := NewInstrument(repos, action) u21InstrumentId, err = u21Instrument.Update(instrument) assert.NoError(t, err) diff --git a/pkg/internal/unit21/transaction.go b/pkg/internal/unit21/transaction.go index 75d268eb..3b73a2a3 100644 --- a/pkg/internal/unit21/transaction.go +++ b/pkg/internal/unit21/transaction.go @@ -117,7 +117,7 @@ func (t transaction) Update(transaction model.Transaction) (unit21Id string, err } orgName := os.Getenv("UNIT21_ORG_NAME") - url := "https://" + os.Getenv("UNIT21_ENV") + ".unit21.com/v1/" + orgName + "/events/" + transaction.ID + "/update" + url := "https://" + os.Getenv("UNIT21_ENV") + ".unit21.com/v1/" + orgName + "/events/" + transaction.Id + "/update" body, err := u21Put(url, mapToUnit21TransactionEvent(transaction, transactionData, digitalData)) if err != nil { @@ -136,28 +136,28 @@ func (t transaction) Update(transaction model.Transaction) (unit21Id string, err } func (t transaction) getTransactionData(transaction model.Transaction) (txData transactionData, err error) { - senderData, err := t.repos.TxLeg.GetById(transaction.OriginTxLegID) + senderData, err := t.repos.TxLeg.GetById(transaction.OriginTxLegId) if err != nil { log.Err(err).Msg("Failed go get origin transaction leg") err = common.StringError(err) return } - receiverData, err := t.repos.TxLeg.GetById(transaction.DestinationTxLegID) + receiverData, err := t.repos.TxLeg.GetById(transaction.DestinationTxLegId) if err != nil { log.Err(err).Msg("Failed go get origin transaction leg") err = common.StringError(err) return } - senderAsset, err := t.repos.Asset.GetById(senderData.AssetID) + senderAsset, err := t.repos.Asset.GetById(senderData.AssetId) if err != nil { log.Err(err).Msg("Failed go get transaction sender asset") err = common.StringError(err) return } - receiverAsset, err := t.repos.Asset.GetById(receiverData.AssetID) + receiverAsset, err := t.repos.Asset.GetById(receiverData.AssetId) if err != nil { log.Err(err).Msg("Failed go get transaction receiver asset") err = common.StringError(err) @@ -213,14 +213,14 @@ func (t transaction) getTransactionData(transaction model.Transaction) (txData t Amount: amount, SentAmount: senderAmount, SentCurrency: senderAsset.Name, - SenderEntityId: senderData.UserID, + SenderEntityId: senderData.UserId, SenderEntityType: "user", - SenderInstrumentId: senderData.InstrumentID, + SenderInstrumentId: senderData.InstrumentId, ReceivedAmount: receiverAmount, ReceivedCurrency: receiverAsset.Name, - ReceiverEntityId: receiverData.UserID, + ReceiverEntityId: receiverData.UserId, ReceiverEntityType: "user", - ReceiverInstrumentId: receiverData.InstrumentID, + ReceiverInstrumentId: receiverData.InstrumentId, ExchangeRate: exchangeRate, TransactionHash: transaction.TransactionHash, USDConversionNotes: "", @@ -232,11 +232,11 @@ func (t transaction) getTransactionData(transaction model.Transaction) (txData t } func (t transaction) getEventDigitalData(transaction model.Transaction) (digitalData eventDigitalData, err error) { - if transaction.DeviceID == "" { + if transaction.DeviceId == "" { return } - device, err := t.repos.Device.GetById(transaction.DeviceID) + device, err := t.repos.Device.GetById(transaction.DeviceId) if err != nil { log.Err(err).Msg("Failed to get transaction device") err = common.StringError(err) @@ -260,7 +260,7 @@ func mapToUnit21TransactionEvent(transaction model.Transaction, transactionData jsonBody := &u21Event{ GeneralData: &eventGeneral{ - EventId: transaction.ID, //required + EventId: transaction.Id, //required EventType: "transaction", //required EventTime: int(transaction.CreatedAt.Unix()), //required EventSubtype: "Fiat to Crypto", //required for RTR diff --git a/pkg/internal/unit21/transaction_test.go b/pkg/internal/unit21/transaction_test.go index ed4845d9..fe90507b 100644 --- a/pkg/internal/unit21/transaction_test.go +++ b/pkg/internal/unit21/transaction_test.go @@ -50,8 +50,8 @@ func TestUpdateTransaction(t *testing.T) { u21TransactionId, err := executeMockTransactionForUser(transaction, sqlxDB) assert.NoError(t, err) - OriginTxLegID := uuid.NewString() - DestinationTxLegID := uuid.NewString() + OriginTxLegId := uuid.NewString() + DestinationTxLegId := uuid.NewString() assetId1 = uuid.NewString() assetId2 = uuid.NewString() networkId := uuid.NewString() @@ -59,38 +59,38 @@ func TestUpdateTransaction(t *testing.T) { instrumentId2 = uuid.NewString() transaction = model.Transaction{ - ID: transaction.ID, + Id: transaction.Id, CreatedAt: time.Now(), UpdatedAt: time.Now(), Type: "fiat-to-crypto", Status: "Completed", Tags: map[string]string{}, - DeviceID: uuid.NewString(), + DeviceId: uuid.NewString(), IPAddress: "187.25.24.128", - PlatformID: uuid.NewString(), + PlatformId: uuid.NewString(), TransactionHash: "", - NetworkID: networkId, + NetworkId: networkId, NetworkFee: "100000000", ContractParams: pq.StringArray{}, ContractFunc: "mintTo()", TransactionAmount: "1000000000", - OriginTxLegID: OriginTxLegID, - ReceiptTxLegID: sql.NullString{String: uuid.NewString()}, - ResponseTxLegID: sql.NullString{String: uuid.NewString()}, - DestinationTxLegID: DestinationTxLegID, + OriginTxLegId: OriginTxLegId, + ReceiptTxLegId: sql.NullString{String: uuid.NewString()}, + ResponseTxLegId: sql.NullString{String: uuid.NewString()}, + DestinationTxLegId: DestinationTxLegId, ProcessingFee: "1000000", ProcessingFeeAsset: uuid.NewString(), StringFee: "2000000", } mockTransactionRows(mock, transaction, userId, assetId1, assetId2, instrumentId1, instrumentId2) - repo := TransactionRepo{ + repos := TransactionRepos{ TxLeg: repository.NewTxLeg((sqlxDB)), User: repository.NewUser(sqlxDB), Asset: repository.NewAsset(sqlxDB), } - u21Transaction := NewTransaction(repo) + u21Transaction := NewTransaction(repos) u21TransactionId, err = u21Transaction.Update(transaction) assert.NoError(t, err) @@ -102,13 +102,13 @@ func TestUpdateTransaction(t *testing.T) { } func executeMockTransactionForUser(transaction model.Transaction, sqlxDB *sqlx.DB) (unit21Id string, err error) { - repo := TransactionRepo{ + repos := TransactionRepos{ TxLeg: repository.NewTxLeg(sqlxDB), User: repository.NewUser(sqlxDB), Asset: repository.NewAsset(sqlxDB), } - u21Transaction := NewTransaction(repo) + u21Transaction := NewTransaction(repos) unit21Id, err = u21Transaction.Create(transaction) @@ -117,30 +117,30 @@ func executeMockTransactionForUser(transaction model.Transaction, sqlxDB *sqlx.D func createMockTransactionForUser(userId string, amount string, sqlxDB *sqlx.DB) (transaction model.Transaction) { transactionId := uuid.NewString() - OriginTxLegID := uuid.NewString() - DestinationTxLegID := uuid.NewString() + OriginTxLegId := uuid.NewString() + DestinationTxLegId := uuid.NewString() networkId := uuid.NewString() transaction = model.Transaction{ - ID: transactionId, + Id: transactionId, CreatedAt: time.Now(), UpdatedAt: time.Now(), Type: "fiat-to-crypto", Status: "Completed", Tags: map[string]string{}, - DeviceID: uuid.NewString(), + DeviceId: uuid.NewString(), IPAddress: "187.25.24.128", - PlatformID: uuid.NewString(), + PlatformId: uuid.NewString(), TransactionHash: "", - NetworkID: networkId, + NetworkId: networkId, NetworkFee: "100000000", ContractParams: pq.StringArray{}, ContractFunc: "mintTo()", TransactionAmount: amount, - OriginTxLegID: OriginTxLegID, - ReceiptTxLegID: sql.NullString{String: uuid.NewString()}, - ResponseTxLegID: sql.NullString{String: uuid.NewString()}, - DestinationTxLegID: DestinationTxLegID, + OriginTxLegId: OriginTxLegId, + ReceiptTxLegId: sql.NullString{String: uuid.NewString()}, + ResponseTxLegId: sql.NullString{String: uuid.NewString()}, + DestinationTxLegId: DestinationTxLegId, ProcessingFee: "1000000", ProcessingFeeAsset: uuid.NewString(), StringFee: "1000000", @@ -151,18 +151,18 @@ func createMockTransactionForUser(userId string, amount string, sqlxDB *sqlx.DB) func mockTransactionRows(mock sqlmock.Sqlmock, transaction model.Transaction, userId string, assetId1 string, assetId2 string, instrumentId1 string, instrumentId2 string) { mockedTxLegRow1 := sqlmock.NewRows([]string{"id", "timestamp", "amount", "value", "asset_id", "user_id", "instrument_id"}). - AddRow(transaction.OriginTxLegID, time.Now(), transaction.TransactionAmount, transaction.TransactionAmount, assetId1, userId, instrumentId1) - mock.ExpectQuery("SELECT * FROM tx_leg WHERE id = $1 AND deactivated_at IS NULL").WithArgs(transaction.OriginTxLegID).WillReturnRows(mockedTxLegRow1) + AddRow(transaction.OriginTxLegId, time.Now(), transaction.TransactionAmount, transaction.TransactionAmount, assetId1, userId, instrumentId1) + mock.ExpectQuery("SELECT * FROM tx_leg WHERE id = $1 AND deactivated_at IS NULL").WithArgs(transaction.OriginTxLegId).WillReturnRows(mockedTxLegRow1) mockedTxLegRow2 := sqlmock.NewRows([]string{"id", "timestamp", "amount", "value", "asset_id", "user_id", "instrument_id"}). - AddRow(transaction.DestinationTxLegID, time.Now(), "1", transaction.TransactionAmount, assetId2, userId, instrumentId2) - mock.ExpectQuery("SELECT * FROM tx_leg WHERE id = $1 AND deactivated_at IS NULL").WithArgs(transaction.DestinationTxLegID).WillReturnRows(mockedTxLegRow2) + AddRow(transaction.DestinationTxLegId, time.Now(), "1", transaction.TransactionAmount, assetId2, userId, instrumentId2) + mock.ExpectQuery("SELECT * FROM tx_leg WHERE id = $1 AND deactivated_at IS NULL").WithArgs(transaction.DestinationTxLegId).WillReturnRows(mockedTxLegRow2) mockedAssetRow1 := sqlmock.NewRows([]string{"id", "name", "description", "decimals", "is_crypto", "network_id", "value_oracle"}). - AddRow(assetId1, "USD", "fiat USD", 6, false, transaction.NetworkID, "self") + AddRow(assetId1, "USD", "fiat USD", 6, false, transaction.NetworkId, "self") mock.ExpectQuery("SELECT * FROM asset WHERE id = $1 AND deactivated_at IS NULL").WithArgs(assetId1).WillReturnRows(mockedAssetRow1) mockedAssetRow2 := sqlmock.NewRows([]string{"id", "name", "description", "decimals", "is_crypto", "network_id", "value_oracle"}). - AddRow(assetId2, "Noose The Goose", "Noose the Goose NFT", 0, true, transaction.NetworkID, "joepegs.com") + AddRow(assetId2, "Noose The Goose", "Noose the Goose NFT", 0, true, transaction.NetworkId, "joepegs.com") mock.ExpectQuery("SELECT * FROM asset WHERE id = $1 AND deactivated_at IS NULL").WithArgs(assetId2).WillReturnRows(mockedAssetRow2) } diff --git a/pkg/model/entity.go b/pkg/model/entity.go index 0c8f0229..ec69dfb9 100644 --- a/pkg/model/entity.go +++ b/pkg/model/entity.go @@ -10,7 +10,7 @@ import ( // See STRING_USER in Migrations 0001 type User struct { - ID string `json:"id" db:"id"` + Id string `json:"id" db:"id"` CreatedAt time.Time `json:"createdAt" db:"created_at"` UpdatedAt time.Time `json:"updatedAt" db:"updated_at"` DeactivatedAt *time.Time `json:"deactivatedAt,omitempty" db:"deactivated_at"` @@ -25,7 +25,7 @@ type User struct { // See PLATFORM in Migrations 0005 type Platform struct { - ID string `json:"id,omitempty" db:"id"` + Id string `json:"id,omitempty" db:"id"` CreatedAt time.Time `json:"createdAt,omitempty" db:"created_at"` UpdatedAt time.Time `json:"updatedAt,omitempty" db:"updated_at"` DeactivatedAt *time.Time `json:"deactivatedAt,omitempty" db:"deactivated_at"` @@ -38,14 +38,14 @@ type Platform struct { // See NETWORK in Migrations 0001 type Network struct { - ID string `json:"id" db:"id"` + Id string `json:"id" db:"id"` CreatedAt time.Time `json:"createdAt" db:"created_at"` UpdatedAt time.Time `json:"updatedAt" db:"updated_at"` DeactivatedAt *time.Time `json:"deactivatedAt,omitempty" db:"deactivated_at"` Name string `json:"name" db:"name"` - NetworkID uint64 `json:"networkId" db:"network_id"` - ChainID uint64 `json:"chainId" db:"chain_id"` - GasTokenID string `json:"gasTokenId" db:"gas_token_id"` + NetworkId uint64 `json:"networkId" db:"network_id"` + ChainId uint64 `json:"chainId" db:"chain_id"` + GasTokenId string `json:"gasTokenId" db:"gas_token_id"` GasOracle string `json:"gasOracle" db:"gas_oracle"` RPCUrl string `json:"rpcUrl" db:"rpc_url"` ExplorerUrl string `json:"explorerUrl" db:"explorer_url"` @@ -53,7 +53,7 @@ type Network struct { // See ASSET in Migrations 0001 type Asset struct { - ID string `json:"id" db:"id"` + Id string `json:"id" db:"id"` CreatedAt time.Time `json:"createdAt" db:"created_at"` UpdatedAt time.Time `json:"updatedAt" db:"updated_at"` DeactivatedAt *time.Time `json:"deactivatedAt,omitempty" db:"deactivated_at"` @@ -61,19 +61,19 @@ type Asset struct { Description string `json:"description" db:"description"` Decimals uint64 `json:"decimals" db:"decimals"` IsCrypto bool `json:"isCrypto" db:"is_crypto"` - NetworkID sql.NullString `json:"networkId" db:"network_id"` + NetworkId sql.NullString `json:"networkId" db:"network_id"` ValueOracle sql.NullString `json:"valueOracle" db:"value_oracle"` } // See USER_PLATFORM in Migrations 0002 type UserToPlatform struct { - UserID string `json:"userId" db:"user_id"` - PlatformID string `json:"platformId" db:"platform_id"` + UserId string `json:"userId" db:"user_id"` + PlatformId string `json:"platformId" db:"platform_id"` } // See DEVICE in Migrations 0002 type Device struct { - ID string `json:"id" db:"id"` + Id string `json:"id" db:"id"` CreatedAt time.Time `json:"createdAt" db:"created_at"` UpdatedAt time.Time `json:"updatedAt" db:"updated_at"` LastUsedAt time.Time `json:"lastUsedAt" db:"last_used_at"` @@ -83,13 +83,13 @@ type Device struct { Description string `json:"description" db:"description"` Fingerprint string `json:"fingerprint" db:"fingerprint"` IpAddresses pq.StringArray `json:"ipAddresses,omitempty" db:"ip_addresses"` - UserID string `json:"userId" db:"user_id"` + UserId string `json:"userId" db:"user_id"` } // See CONTACT in Migrations 0002 type Contact struct { - ID string `json:"id" db:"id"` - UserID string `json:"userId" db:"user_id"` + Id string `json:"id" db:"id"` + UserId string `json:"userId" db:"user_id"` CreatedAt time.Time `json:"createdAt" db:"created_at"` UpdatedAt time.Time `json:"updatedAt" db:"updated_at"` LastAuthenticatedAt *time.Time `json:"lastAuthenticatedAt" db:"last_authenticated_at"` @@ -102,8 +102,8 @@ type Contact struct { // See LOCATION in Migrations 0002 type Location struct { - ID string `json:"id" db:"id"` - UserID string `json:"userId" db:"user_id"` + Id string `json:"id" db:"id"` + UserId string `json:"userId" db:"user_id"` CreatedAt time.Time `json:"createdAt" db:"created_at"` UpdatedAt time.Time `json:"updatedAt" db:"updated_at"` DeactivatedAt *time.Time `json:"deactivatedAt,omitempty" db:"deactivated_at"` @@ -121,7 +121,7 @@ type Location struct { // See INSTRUMENT in Migrations 0002 type Instrument struct { - ID string `json:"id" db:"id"` + Id string `json:"id" db:"id"` CreatedAt time.Time `json:"createdAt" db:"created_at"` UpdatedAt time.Time `json:"updatedAt" db:"updated_at"` DeactivatedAt *time.Time `json:"deactivatedAt,omitempty" db:"deactivated_at"` @@ -131,58 +131,58 @@ type Instrument struct { Network string `json:"network" db:"network"` PublicKey string `json:"publicKey" db:"public_key"` Last4 string `json:"last4" db:"last_4"` - UserID string `json:"userId" db:"user_id"` - LocationID sql.NullString `json:"locationId" db:"location_id"` + UserId string `json:"userId" db:"user_id"` + LocationId sql.NullString `json:"locationId" db:"location_id"` } // See CONTACT_PLATFORM in Migrations 0003 type ContactToPlatform struct { - ContactID string `json:"contactId" db:"contact_id"` - PlatformID string `json:"platformId" db:"platform_id"` + ContactId string `json:"contactId" db:"contact_id"` + PlatformId string `json:"platformId" db:"platform_id"` } // See DEVICE_INSTRUMENT in Migrations 0003 type DeviceToInstrument struct { - DeviceID string `json:"deviceId" db:"device_id"` - InstrumentID string `json:"instrumentId" db:"instrument_id"` + DeviceId string `json:"deviceId" db:"device_id"` + InstrumentId string `json:"instrumentId" db:"instrument_id"` } // See Tx_LEG in Migrations 0003 type TxLeg struct { - ID string `json:"id" db:"id"` + Id string `json:"id" db:"id"` CreatedAt time.Time `json:"createdAt" db:"created_at"` UpdatedAt time.Time `json:"updatedAt" db:"updated_at"` DeactivatedAt *time.Time `json:"deactivatedAt,omitempty" db:"deactivated_at"` Timestamp time.Time `json:"timestamp" db:"timestamp"` Amount string `json:"amount" db:"amount"` Value string `json:"value" db:"value"` - AssetID string `json:"assetId" db:"asset_id"` - UserID string `json:"userId" db:"user_id"` - InstrumentID string `json:"instrumentId" db:"instrument_id"` + AssetId string `json:"assetId" db:"asset_id"` + UserId string `json:"userId" db:"user_id"` + InstrumentId string `json:"instrumentId" db:"instrument_id"` } // See TRANSACTION in Migrations 0003 type Transaction struct { - ID string `json:"id" db:"id"` + Id string `json:"id" db:"id"` CreatedAt time.Time `json:"createdAt" db:"created_at"` UpdatedAt time.Time `json:"updatedAt" db:"updated_at"` DeactivatedAt *time.Time `json:"deactivatedAt,omitempty" db:"deactivated_at"` Type string `json:"type,omitempty" db:"type"` Status string `json:"status,omitempty" db:"status"` Tags StringMap `json:"tags,omitempty" db:"tags"` - DeviceID string `json:"deviceId,omitempty" db:"device_id"` + DeviceId string `json:"deviceId,omitempty" db:"device_id"` IPAddress string `json:"ipAddress,omitempty" db:"ip_address"` - PlatformID string `json:"platformId,omitempty" db:"platform_id"` + PlatformId string `json:"platformId,omitempty" db:"platform_id"` TransactionHash string `json:"transactionHash,omitempty" db:"transaction_hash"` - NetworkID string `json:"networkId,omitempty" db:"network_id"` + NetworkId string `json:"networkId,omitempty" db:"network_id"` NetworkFee string `json:"networkFee,omitempty" db:"network_fee"` ContractParams pq.StringArray `json:"contractParameters,omitempty" db:"contract_params"` ContractFunc string `json:"contractFunc,omitempty" db:"contract_func"` TransactionAmount string `json:"transactionAmount,omitempty" db:"transaction_amount"` - OriginTxLegID string `json:"originTxLegId,omitempty" db:"origin_tx_leg_id"` - ReceiptTxLegID sql.NullString `json:"receiptTxLegId,omitempty" db:"receipt_tx_leg_id"` - ResponseTxLegID sql.NullString `json:"responseTxLegId,omitempty" db:"response_tx_leg_id"` - DestinationTxLegID string `json:"destinationTxLegId,omitempty" db:"destination_tx_leg_id"` + OriginTxLegId string `json:"originTxLegId,omitempty" db:"origin_tx_leg_id"` + ReceiptTxLegId sql.NullString `json:"receiptTxLegId,omitempty" db:"receipt_tx_leg_id"` + ResponseTxLegId sql.NullString `json:"responseTxLegId,omitempty" db:"response_tx_leg_id"` + DestinationTxLegId string `json:"destinationTxLegId,omitempty" db:"destination_tx_leg_id"` ProcessingFee string `json:"processingFee,omitempty" db:"processing_fee"` ProcessingFeeAsset string `json:"processingFeeAsset,omitempty" db:"processing_fee_asset"` StringFee string `json:"stringFee,omitempty" db:"string_fee"` @@ -190,13 +190,13 @@ type Transaction struct { } type AuthStrategy struct { - ID string `json:"id,omitempty" db:"id"` + Id string `json:"id,omitempty" db:"id"` Status string `json:"status" db:"status"` - EntityID string `json:"entityId,omitempty"` // for redis use only + EntityId string `json:"entityId,omitempty"` // for redis use only Type string `json:"authType" db:"type"` EntityType string `json:"entityType,omitempty"` // for redis use only ContactData string `json:"contactData,omitempty"` // for redis use only - ContactID NullableString `json:"contactId,omitempty" db:"contact_id"` + ContactId NullableString `json:"contactId,omitempty" db:"contact_id"` Data string `json:"data" data:"data"` CreatedAt time.Time `json:"createdAt,omitempty" db:"created_at"` UpdatedAt time.Time `json:"updatedAt,omitempty" db:"updated_at"` diff --git a/pkg/model/request.go b/pkg/model/request.go index 4fe3cec4..839df014 100644 --- a/pkg/model/request.go +++ b/pkg/model/request.go @@ -15,19 +15,19 @@ type TransactionUpdates struct { Type *string `json:"type" db:"type"` Status *string `json:"status" db:"status"` Tags *types.JSONText `json:"tags" db:"tags"` - DeviceID *string `json:"deviceId" db:"device_id"` + DeviceId *string `json:"deviceId" db:"device_id"` IPAddress *string `json:"ipAddress" db:"ip_address"` - PlatformID *string `json:"platformId" db:"platform_id"` + PlatformId *string `json:"platformId" db:"platform_id"` TransactionHash *string `json:"transactionHash" db:"transaction_hash"` - NetworkID *string `json:"networkId" db:"network_id"` + NetworkId *string `json:"networkId" db:"network_id"` NetworkFee *string `json:"networkFee" db:"network_fee"` ContractParams *pq.StringArray `json:"contractParameters" db:"contract_params"` ContractFunc *string `json:"contractFunc" db:"contract_func"` TransactionAmount *string `json:"transactionAmount" db:"transaction_amount"` - OriginTxLegID *string `json:"originTxLegId" db:"origin_tx_leg_id"` - ReceiptTxLegID *string `json:"receiptTxLegId" db:"receipt_tx_leg_id"` - ResponseTxLegID *string `json:"responseTxLegId" db:"response_tx_leg_id"` - DestinationTxLegID *string `json:"destinationTxLegId" db:"destination_tx_leg_id"` + OriginTxLegId *string `json:"originTxLegId" db:"origin_tx_leg_id"` + ReceiptTxLegId *string `json:"receiptTxLegId" db:"receipt_tx_leg_id"` + ResponseTxLegId *string `json:"responseTxLegId" db:"response_tx_leg_id"` + DestinationTxLegId *string `json:"destinationTxLegId" db:"destination_tx_leg_id"` ProcessingFee *string `json:"processingFee" db:"processing_fee"` ProcessingFeeAsset *string `json:"processingFeeAsset" db:"processing_fee_asset"` StringFee *string `json:"stringFee" db:"string_fee"` @@ -41,17 +41,17 @@ type InstrumentUpdates struct { Network *string `json:"network" db:"network"` PublicKey *string `json:"publicKey" db:"public_key"` Last4 *string `json:"last4" db:"last_4"` - UserID *string `json:"userId" db:"user_id"` - LocationID *sql.NullString `json:"locationId" db:"location_id"` + UserId *string `json:"userId" db:"user_id"` + LocationId *sql.NullString `json:"locationId" db:"location_id"` } type TxLegUpdates struct { Timestamp *time.Time `json:"timestamp" db:"timestamp"` Amount *string `json:"amount" db:"amount"` Value *string `json:"value" db:"value"` - AssetID *string `json:"assetId" db:"asset_id"` - UserID *string `json:"userId" db:"user_id"` - InstrumentID *string `json:"instrumentId" db:"instrument_id"` + AssetId *string `json:"assetId" db:"asset_id"` + UserId *string `json:"userId" db:"user_id"` + InstrumentId *string `json:"instrumentId" db:"instrument_id"` } type UserRegister struct { @@ -124,7 +124,7 @@ type UpdateStatus struct { } type NetworkUpdates struct { - GasTokenID *string `json:"gasTokenId" db:"gas_token_id"` + GasTokenId *string `json:"gasTokenId" db:"gas_token_id"` } type DeviceUpdates struct { diff --git a/pkg/model/transaction.go b/pkg/model/transaction.go index d34b97d8..1427ee41 100644 --- a/pkg/model/transaction.go +++ b/pkg/model/transaction.go @@ -27,7 +27,7 @@ type ExecutionRequest struct { // User will pass this in for a quote and receive Execution Parameters type TransactionRequest struct { UserAddress string `json:"userAddress"` // Used to keep track of user ie "0x44A4b9E2A69d86BA382a511f845CbF2E31286770" - ChainID int `json:"chainID"` // Chain ID to execute on ie 80000 + ChainId int `json:"chainId"` // Chain ID to execute on e.g. 80000 CxAddr string `json:"contractAddress"` // Address of contract ie "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2" CxFunc string `json:"contractFunction"` // Function declaration ie "mintTo(address) payable" CxReturn string `json:"contractReturn"` // Function return type ie "uint256" @@ -37,6 +37,6 @@ type TransactionRequest struct { } type TransactionReceipt struct { - TxID string `json:"txID"` + TxId string `json:"txId"` TxURL string `json:"txUrl"` } diff --git a/pkg/model/user.go b/pkg/model/user.go index ae622e16..25178bab 100644 --- a/pkg/model/user.go +++ b/pkg/model/user.go @@ -10,8 +10,8 @@ type WalletSignaturePayload struct { } type FingerprintPayload struct { - VisitorID string `json:"visitorId"` - RequestID string `json:"requestId"` + VisitorId string `json:"visitorId"` + RequestId string `json:"requestId"` } type WalletSignaturePayloadSigned struct { diff --git a/pkg/repository/asset.go b/pkg/repository/asset.go index d0f984e1..ff80e38c 100644 --- a/pkg/repository/asset.go +++ b/pkg/repository/asset.go @@ -14,7 +14,7 @@ type Asset interface { Create(model.Asset) (model.Asset, error) GetById(id string) (model.Asset, error) GetByName(name string) (model.Asset, error) - Update(ID string, updates any) error + Update(Id string, updates any) error } type asset[T any] struct { diff --git a/pkg/repository/auth.go b/pkg/repository/auth.go index ee671d2b..9acd3ed9 100644 --- a/pkg/repository/auth.go +++ b/pkg/repository/auth.go @@ -29,14 +29,14 @@ const ( type AuthStrategy interface { Create(authType AuthType, m model.AuthStrategy) error CreateAny(key string, val any, expire time.Duration) error - CreateAPIKey(entityID string, authType AuthType, apiKey string, persistOnly bool) (model.AuthStrategy, error) + CreateAPIKey(entityId string, authType AuthType, apiKey string, persistOnly bool) (model.AuthStrategy, error) CreateJWTRefresh(key string, val string) (model.AuthStrategy, error) GetUserIdFromRefreshToken(key string) (string, error) Get(string) (model.AuthStrategy, error) GetKeyString(key string) (string, error) List(limit, offset int) ([]model.AuthStrategy, error) ListByStatus(limit, offset int, status string) ([]model.AuthStrategy, error) - UpdateStatus(ID, status string) (model.AuthStrategy, error) + UpdateStatus(Id, status string) (model.AuthStrategy, error) Delete(key string) error } @@ -66,7 +66,7 @@ func (a auth) CreateAny(key string, val any, expire time.Duration) error { } // CreateAPIKey creates and persists an API Key for a platform -func (a auth) CreateAPIKey(entityID string, authType AuthType, key string, persistOnly bool) (model.AuthStrategy, error) { +func (a auth) CreateAPIKey(entityId string, authType AuthType, key string, persistOnly bool) (model.AuthStrategy, error) { // only insert to postgres and skip redis cache if persistOnly { rows, err := a.store.Queryx("INSERT INTO auth_strategy(type,data) VALUES($1, $2) RETURNING *", authType, key) @@ -82,7 +82,7 @@ func (a auth) CreateAPIKey(entityID string, authType AuthType, key string, persi } m := model.AuthStrategy{ - EntityID: entityID, + EntityId: entityId, CreatedAt: time.Now(), Type: string(authType), EntityType: string(EntityTypePlatform), @@ -96,7 +96,7 @@ func (a auth) CreateAPIKey(entityID string, authType AuthType, key string, persi func (a auth) CreateJWTRefresh(key string, userId string) (model.AuthStrategy, error) { expireAt := time.Hour * 24 * 7 // 7 days expiration m := model.AuthStrategy{ - ID: key, + Id: key, CreatedAt: time.Now(), Type: string(AuthTypeJWT), EntityType: string(EntityTypeUser), @@ -169,9 +169,8 @@ func (a auth) ListByStatus(limit, offset int, status string) ([]model.AuthStrate } // UpdateStatus updates the status on postgres db and returns the updated row -func (a auth) UpdateStatus(ID, status string) (model.AuthStrategy, error) { - fmt.Println("Status and ID", status, ID) - row := a.store.QueryRowx("UPDATE auth_strategy SET status = $2 WHERE id = $1 RETURNING *", ID, status) +func (a auth) UpdateStatus(Id, status string) (model.AuthStrategy, error) { + row := a.store.QueryRowx("UPDATE auth_strategy SET status = $2 WHERE id = $1 RETURNING *", Id, status) m := model.AuthStrategy{} err := row.StructScan(&m) return m, err diff --git a/pkg/repository/base.go b/pkg/repository/base.go index 8f78d12a..1668fd2d 100644 --- a/pkg/repository/base.go +++ b/pkg/repository/base.go @@ -127,8 +127,8 @@ func (b base[T]) List(limit int, offset int) (list []T, err error) { return list, err } -func (b base[T]) GetById(ID string) (m T, err error) { - err = b.store.Get(&m, fmt.Sprintf("SELECT * FROM %s WHERE id = $1 AND deactivated_at IS NULL", b.table), ID) +func (b base[T]) GetById(id string) (m T, err error) { + err = b.store.Get(&m, fmt.Sprintf("SELECT * FROM %s WHERE id = $1 AND deactivated_at IS NULL", b.table), id) if err != nil && err == sql.ErrNoRows { return m, common.StringError(ErrNotFound) } @@ -136,20 +136,20 @@ func (b base[T]) GetById(ID string) (m T, err error) { } // Returns the first match of the user's ID -func (b base[T]) GetByUserId(userID string) (m T, err error) { - err = b.store.Get(&m, fmt.Sprintf("SELECT * FROM %s WHERE user_id = $1 AND deactivated_at IS NULL LIMIT 1", b.table), userID) +func (b base[T]) GetByUserId(userId string) (m T, err error) { + err = b.store.Get(&m, fmt.Sprintf("SELECT * FROM %s WHERE user_id = $1 AND deactivated_at IS NULL LIMIT 1", b.table), userId) if err != nil && err == sql.ErrNoRows { return m, common.StringError(ErrNotFound) } return m, err } -func (b base[T]) ListByUserId(userID string, limit int, offset int) ([]T, error) { +func (b base[T]) ListByUserId(userId string, limit int, offset int) ([]T, error) { list := []T{} if limit == 0 { limit = 20 } - err := b.store.Select(&list, fmt.Sprintf("SELECT * FROM %s WHERE user_id = $1 LIMIT $2 OFFSET $3", b.table), userID, limit, offset) + err := b.store.Select(&list, fmt.Sprintf("SELECT * FROM %s WHERE user_id = $1 LIMIT $2 OFFSET $3", b.table), userId, limit, offset) if err == sql.ErrNoRows { return list, common.StringError(err) } @@ -160,12 +160,12 @@ func (b base[T]) ListByUserId(userID string, limit int, offset int) ([]T, error) return list, nil } -func (b base[T]) Update(ID string, updates any) error { +func (b base[T]) Update(id string, updates any) error { names, keyToUpdate := common.KeysAndValues(updates) if len(names) == 0 { return common.StringError(errors.New("no fields to update")) } - query := fmt.Sprintf("UPDATE %s SET %s WHERE id = '%s'", b.table, strings.Join(names, ", "), ID) + query := fmt.Sprintf("UPDATE %s SET %s WHERE id = '%s'", b.table, strings.Join(names, ", "), id) _, err := b.store.NamedExec(query, keyToUpdate) if err != nil { return common.StringError(err) diff --git a/pkg/repository/base_test.go b/pkg/repository/base_test.go index e099d8c9..9edfc201 100644 --- a/pkg/repository/base_test.go +++ b/pkg/repository/base_test.go @@ -19,7 +19,7 @@ func TestBaseUpdate(t *testing.T) { mType := "type" m := model.ContactUpdates{Type: &mType} - NewContact(sqlxDB).Update("ID", m) + NewContact(sqlxDB).Update("Id", m) if err := mock.ExpectationsWereMet(); err != nil { t.Errorf("error '%s' was not expected, while updating a contact", err) } diff --git a/pkg/repository/contact.go b/pkg/repository/contact.go index 621ff979..6a918bba 100644 --- a/pkg/repository/contact.go +++ b/pkg/repository/contact.go @@ -13,14 +13,15 @@ type Contact interface { Transactable Readable Create(model.Contact) (model.Contact, error) - GetById(ID string) (model.Contact, error) - GetByUserId(userID string) (model.Contact, error) - ListByUserId(userID string, imit int, offset int) ([]model.Contact, error) + GetById(id string) (model.Contact, error) + GetByUserId(userId string) (model.Contact, error) + ListByUserId(userId string, imit int, offset int) ([]model.Contact, error) List(limit int, offset int) ([]model.Contact, error) - Update(ID string, updates any) error + Update(id string, updates any) error GetByData(data string) (model.Contact, error) - //GetByUserIdAndStatus gets a contact with the user id and status - GetByUserIdAndStatus(userID string, status string) (model.Contact, error) + GetByUserIdAndPlatformId(userId string, platformId string) (model.Contact, error) + GetByUserIdAndType(userId string, _type string) (model.Contact, error) + GetByUserIdAndStatus(userId string, status string) (model.Contact, error) } type contact[T any] struct { @@ -59,9 +60,37 @@ func (u contact[T]) GetByData(data string) (model.Contact, error) { return m, nil } -func (u contact[T]) GetByUserIdAndStatus(userID, status string) (model.Contact, error) { +// TODO: replace references to GetByUserIdAndStatus with the following: +func (u contact[T]) GetByUserIdAndPlatformId(userId string, platformId string) (model.Contact, error) { m := model.Contact{} - err := u.store.Get(&m, fmt.Sprintf("SELECT * FROM %s WHERE user_id = $1 AND status = $2 LIMIT 1", u.table), userID, status) + err := u.store.Get(&m, fmt.Sprintf(` + SELECT contact.* + FROM %s + LEFT JOIN contact_platform + ON contact.id = contact_to_platform.contact_id + LEFT JOIN platform + ON contact_to_platform.platform_id = platform.id + WHERE contact.user_id = $1 + AND platform.id = $2 + `, u.table), userId, platformId) + if err != nil && err == sql.ErrNoRows { + return m, ErrNotFound + } + return m, common.StringError(err) +} + +func (u contact[T]) GetByUserIdAndType(userId string, _type string) (model.Contact, error) { + m := model.Contact{} + err := u.store.Get(&m, fmt.Sprintf("SELECT * FROM %s WHERE user_id = $1 AND type = $2 LIMIT 1", u.table), userId, _type) + if err != nil && err == sql.ErrNoRows { + return m, ErrNotFound + } + return m, common.StringError(err) +} + +func (u contact[T]) GetByUserIdAndStatus(userId, status string) (model.Contact, error) { + m := model.Contact{} + err := u.store.Get(&m, fmt.Sprintf("SELECT * FROM %s WHERE user_id = $1 AND status = $2 LIMIT 1", u.table), userId, status) if err != nil && err == sql.ErrNoRows { return m, ErrNotFound } diff --git a/pkg/repository/contact_to_platform.go b/pkg/repository/contact_to_platform.go index ca0d1543..f4be9e74 100644 --- a/pkg/repository/contact_to_platform.go +++ b/pkg/repository/contact_to_platform.go @@ -10,9 +10,9 @@ type ContactToPlatform interface { Transactable Readable Create(model.ContactToPlatform) (model.ContactToPlatform, error) - GetById(ID string) (model.ContactToPlatform, error) + GetById(id string) (model.ContactToPlatform, error) List(limit int, offset int) ([]model.ContactToPlatform, error) - Update(ID string, updates any) error + Update(id string, updates any) error } type contactToPlatform[T any] struct { diff --git a/pkg/repository/device.go b/pkg/repository/device.go index c7195432..08410694 100644 --- a/pkg/repository/device.go +++ b/pkg/repository/device.go @@ -13,12 +13,12 @@ type Device interface { Create(model.Device) (model.Device, error) GetById(id string) (model.Device, error) - // GetByUserIdAndFingerprint gets a device by fingerprint ID and userID, using a compound index + // GetByUserIdAndFingerprint gets a device by fingerprint ID and userId, using a compound index // the visitor might exisit for two users but the uniqueness comes from (userId, fingerprint) - GetByUserIdAndFingerprint(userID string, fingerprint string) (model.Device, error) - GetByUserId(userID string) (model.Device, error) - ListByUserId(userID string, imit int, offset int) ([]model.Device, error) - Update(ID string, updates any) error + GetByUserIdAndFingerprint(userId string, fingerprint string) (model.Device, error) + GetByUserId(userId string) (model.Device, error) + ListByUserId(userId string, imit int, offset int) ([]model.Device, error) + Update(id string, updates any) error } type device[T any] struct { @@ -49,9 +49,9 @@ func (d device[T]) Create(insert model.Device) (model.Device, error) { return m, nil } -func (d device[T]) GetByUserIdAndFingerprint(userID, fingerprint string) (model.Device, error) { +func (d device[T]) GetByUserIdAndFingerprint(userId, fingerprint string) (model.Device, error) { m := model.Device{} - err := d.store.Get(&m, "SELECT * FROM device WHERE user_id = $1 AND fingerprint = $2 LIMIT 1", userID, fingerprint) + err := d.store.Get(&m, "SELECT * FROM device WHERE user_id = $1 AND fingerprint = $2 LIMIT 1", userId, fingerprint) if err != nil && err == sql.ErrNoRows { return m, ErrNotFound } diff --git a/pkg/repository/instrument.go b/pkg/repository/instrument.go index c6e17c30..35f6e86f 100644 --- a/pkg/repository/instrument.go +++ b/pkg/repository/instrument.go @@ -13,7 +13,7 @@ import ( type Instrument interface { Transactable Create(model.Instrument) (model.Instrument, error) - Update(ID string, updates any) error + Update(id string, updates any) error GetById(id string) (model.Instrument, error) GetWalletByAddr(addr string) (model.Instrument, error) GetCardByFingerprint(fingerprint string) (m model.Instrument, err error) @@ -91,7 +91,7 @@ func (i instrument[T]) WalletAlreadyExists(addr string) (bool, error) { if err != nil && errors.Cause(err).Error() != "not found" { // because we are wrapping error and care about its value return true, common.StringError(err) - } else if err == nil && wallet.UserID != "" { + } else if err == nil && wallet.UserId != "" { return true, common.StringError(errors.New("wallet already associated with user")) } else if err == nil && wallet.PublicKey == addr { return true, common.StringError(errors.New("wallet already exists")) diff --git a/pkg/repository/location.go b/pkg/repository/location.go index 737b908e..1b6976ff 100644 --- a/pkg/repository/location.go +++ b/pkg/repository/location.go @@ -10,7 +10,7 @@ type Location interface { Transactable Create(model.Location) (model.Location, error) GetById(id string) (model.Location, error) - Update(ID string, updates any) error + Update(id string, updates any) error } type location[T any] struct { diff --git a/pkg/repository/location_test.go b/pkg/repository/location_test.go index b7c4291a..5d06c4b5 100644 --- a/pkg/repository/location_test.go +++ b/pkg/repository/location_test.go @@ -26,7 +26,7 @@ func TestGetLocation(t *testing.T) { location, err := NewLocation(sqlxDB).GetById(id) assert.NoError(t, err) - assert.NotEmpty(t, location.ID) + assert.NotEmpty(t, location.Id) if err := mock.ExpectationsWereMet(); err != nil { t.Errorf("error '%s' was not expected, getting location by id", err) } diff --git a/pkg/repository/network.go b/pkg/repository/network.go index c387c19c..f4a29e32 100644 --- a/pkg/repository/network.go +++ b/pkg/repository/network.go @@ -14,7 +14,7 @@ type Network interface { Create(model.Network) (model.Network, error) GetById(id string) (model.Network, error) GetByChainId(chainId uint64) (model.Network, error) - Update(ID string, updates any) error + Update(id string, updates any) error } type network[T any] struct { diff --git a/pkg/repository/platform.go b/pkg/repository/platform.go index 8d21f93d..45627b6b 100644 --- a/pkg/repository/platform.go +++ b/pkg/repository/platform.go @@ -19,9 +19,9 @@ type PlaformUpdates struct { type Platform interface { Transactable Create(model.Platform) (model.Platform, error) - GetById(ID string) (model.Platform, error) + GetById(id string) (model.Platform, error) List(limit int, offset int) ([]model.Platform, error) - Update(ID string, updates any) error + Update(id string, updates any) error } type platform[T any] struct { @@ -51,4 +51,3 @@ func (p platform[T]) Create(m model.Platform) (model.Platform, error) { defer rows.Close() return plat, nil } - diff --git a/pkg/repository/transaction.go b/pkg/repository/transaction.go index 71e89e48..daf59b99 100644 --- a/pkg/repository/transaction.go +++ b/pkg/repository/transaction.go @@ -10,7 +10,7 @@ type Transaction interface { Transactable Create(model.Transaction) (model.Transaction, error) GetById(id string) (model.Transaction, error) - Update(ID string, updates any) error + Update(id string, updates any) error } type transaction[T any] struct { @@ -31,7 +31,7 @@ func (t transaction[T]) Create(insert model.Transaction) (model.Transaction, err return m, common.StringError(err) } for rows.Next() { - err = rows.Scan(&m.ID) + err = rows.Scan(&m.Id) if err != nil { return m, common.StringError(err) } diff --git a/pkg/repository/tx_leg.go b/pkg/repository/tx_leg.go index f3657e53..1e1ac14b 100644 --- a/pkg/repository/tx_leg.go +++ b/pkg/repository/tx_leg.go @@ -10,7 +10,7 @@ type TxLeg interface { Transactable Create(model.TxLeg) (model.TxLeg, error) GetById(id string) (model.TxLeg, error) - Update(ID string, updates any) error + Update(id string, updates any) error } type txLeg[T any] struct { diff --git a/pkg/repository/user.go b/pkg/repository/user.go index 4ae2d4ac..a839a4b7 100644 --- a/pkg/repository/user.go +++ b/pkg/repository/user.go @@ -15,11 +15,11 @@ type User interface { Transactable Readable Create(model.User) (model.User, error) - GetById(ID string) (model.User, error) + GetById(id string) (model.User, error) List(limit int, offset int) ([]model.User, error) - Update(ID string, updates any) (model.User, error) + Update(id string, updates any) (model.User, error) GetByType(label string) (model.User, error) - UpdateStatus(ID string, status string) (model.User, error) + UpdateStatus(id string, status string) (model.User, error) } type user[T any] struct { @@ -49,13 +49,13 @@ func (u user[T]) Create(insert model.User) (model.User, error) { return m, nil } -func (u user[T]) Update(ID string, updates any) (model.User, error) { +func (u user[T]) Update(id string, updates any) (model.User, error) { names, keyToUpdate := common.KeysAndValues(updates) var user model.User if len(names) == 0 { return user, common.StringError(errors.New("no fields to update")) } - query := fmt.Sprintf("UPDATE %s SET %s WHERE id = '%s' RETURNING *", u.table, strings.Join(names, ", "), ID) + query := fmt.Sprintf("UPDATE %s SET %s WHERE id = '%s' RETURNING *", u.table, strings.Join(names, ", "), id) rows, err := u.store.NamedQuery(query, keyToUpdate) if err != nil { @@ -74,9 +74,9 @@ func (u user[T]) Update(ID string, updates any) (model.User, error) { } // update user status -func (u user[T]) UpdateStatus(ID string, status string) (model.User, error) { +func (u user[T]) UpdateStatus(id string, status string) (model.User, error) { m := model.User{} - err := u.store.Get(&m, fmt.Sprintf("UPDATE %s SET status = $1 WHERE id = $2 RETURNING *", u.table), status, ID) + err := u.store.Get(&m, fmt.Sprintf("UPDATE %s SET status = $1 WHERE id = $2 RETURNING *", u.table), status, id) if err != nil { return m, common.StringError(err) } diff --git a/pkg/repository/user_test.go b/pkg/repository/user_test.go index 4625c194..b4e4ebf2 100644 --- a/pkg/repository/user_test.go +++ b/pkg/repository/user_test.go @@ -48,7 +48,7 @@ func TestGetUser(t *testing.T) { user, err := NewUser(sqlxDB).GetById(id) assert.NoError(t, err) - assert.Equal(t, id, user.ID) + assert.Equal(t, id, user.Id) if err := mock.ExpectationsWereMet(); err != nil { t.Errorf("error '%s' was not expected, getting user by id", err) } diff --git a/pkg/repository/user_to_platform.go b/pkg/repository/user_to_platform.go index c3fc066b..f5d7f534 100644 --- a/pkg/repository/user_to_platform.go +++ b/pkg/repository/user_to_platform.go @@ -10,10 +10,10 @@ type UserToPlatform interface { Transactable Readable Create(model.UserToPlatform) (model.UserToPlatform, error) - GetById(ID string) (model.UserToPlatform, error) + GetById(id string) (model.UserToPlatform, error) List(limit int, offset int) ([]model.UserToPlatform, error) - ListByUserId(userID string, imit int, offset int) ([]model.UserToPlatform, error) - Update(ID string, updates any) error + ListByUserId(userId string, imit int, offset int) ([]model.UserToPlatform, error) + Update(id string, updates any) error } type userToPlatform[T any] struct { diff --git a/pkg/service/auth.go b/pkg/service/auth.go index 1eed666a..1c1c0b2c 100644 --- a/pkg/service/auth.go +++ b/pkg/service/auth.go @@ -101,26 +101,26 @@ func (a auth) VerifySignedPayload(request model.WalletSignaturePayloadSigned) (U if err != nil { return resp, common.StringError(err) } - user, err := a.repos.User.GetById(instrument.UserID) + user, err := a.repos.User.GetById(instrument.UserId) if err != nil { return resp, common.StringError(err) } + // TODO: remove user.Email and replace with association with contact via user and platform + user.Email = getValidatedEmailOrEmpty(a.repos.Contact, user.Id) - user.Email = getValidatedEmailOrEmpty(a.repos.Contact, user.ID) - - device, err := a.device.CreateDeviceIfNeeded(user.ID, request.Fingerprint.VisitorID, request.Fingerprint.RequestID) + device, err := a.device.CreateDeviceIfNeeded(user.Id, request.Fingerprint.VisitorId, request.Fingerprint.RequestId) if err != nil && !strings.Contains(err.Error(), "not found") { return resp, common.StringError(err) } // Send verification email if device is unknown and user has a validated email if user.Email != "" && !isDeviceValidated(device) { - go a.verification.SendDeviceVerification(user.ID, user.Email, device.ID, device.Description) + go a.verification.SendDeviceVerification(user.Id, user.Email, device.Id, device.Description) return resp, common.StringError(errors.New("unknown device")) } // Create the JWT - jwt, err := a.GenerateJWT(user.ID, device) + jwt, err := a.GenerateJWT(user.Id, device) if err != nil { return resp, common.StringError(err) } @@ -145,7 +145,7 @@ func (a auth) GenerateJWT(userId string, m ...model.Device) (JWT, error) { // set device id if available if len(m) > 0 { - claims.DeviceId = m[0].ID + claims.DeviceId = m[0].Id } claims.UserId = userId @@ -212,7 +212,7 @@ func (a auth) RefreshToken(refreshToken string, walletAddress string) (UserCreat return resp, common.StringError(err) } - if instrument.UserID != userId { + if instrument.UserId != userId { return resp, common.StringError(errors.New("wallet address not associated with this user: " + walletAddress)) } @@ -235,13 +235,13 @@ func (a auth) RefreshToken(refreshToken string, walletAddress string) (UserCreat return resp, common.StringError(err) } - user, err := a.repos.User.GetById(instrument.UserID) + user, err := a.repos.User.GetById(instrument.UserId) if err != nil { return resp, common.StringError(err) } // get email - user.Email = getValidatedEmailOrEmpty(a.repos.Contact, user.ID) + user.Email = getValidatedEmailOrEmpty(a.repos.Contact, user.Id) resp.User = user return resp, nil diff --git a/pkg/service/auth_key.go b/pkg/service/auth_key.go index 87dfff86..ec24ef18 100644 --- a/pkg/service/auth_key.go +++ b/pkg/service/auth_key.go @@ -9,7 +9,7 @@ import ( type APIKeyStrategy interface { Create() (model.AuthStrategy, error) List(limit, offset int, status string) ([]model.AuthStrategy, error) - Approve(ID string) error + Approve(id string) error } type aPIKeyStrategy struct { @@ -44,12 +44,12 @@ func (g aPIKeyStrategy) ListByStatus(limit, offset int, status string) ([]model. } // Approve updates the APIKey status and creates an entry on redis -func (g aPIKeyStrategy) Approve(ID string) error { - m, err := g.repo.UpdateStatus(ID, "active") +func (g aPIKeyStrategy) Approve(id string) error { + m, err := g.repo.UpdateStatus(id, "active") if err != nil { return err } - _, err = g.repo.CreateAPIKey(m.ID, repository.AuthTypeAPIKey, m.Data, false) + _, err = g.repo.CreateAPIKey(m.Id, repository.AuthTypeAPIKey, m.Data, false) return err } diff --git a/pkg/service/chain.go b/pkg/service/chain.go index fd252a6a..493c0855 100644 --- a/pkg/service/chain.go +++ b/pkg/service/chain.go @@ -8,14 +8,14 @@ import ( ) type Chain struct { - ChainID uint64 + ChainId uint64 RPC string Explorer string CoingeckoName string OwlracleName string StringFee float64 UUID string - GasTokenID string + GasTokenId string } // TODO: should we store this in a DB or determine it dynamically??? Previously this was defined in the preprocessor in the Chain array @@ -28,7 +28,7 @@ func ChainInfo(chainId uint64, networkRepo repository.Network, assetRepo reposit if err != nil { return Chain{}, common.StringError(err) } - asset, err := assetRepo.GetById(network.GasTokenID) + asset, err := assetRepo.GetById(network.GasTokenId) if err != nil { return Chain{}, common.StringError(err) } @@ -36,5 +36,5 @@ func ChainInfo(chainId uint64, networkRepo repository.Network, assetRepo reposit if err != nil { return Chain{}, common.StringError(err) } - return Chain{ChainID: chainId, RPC: network.RPCUrl, Explorer: network.ExplorerUrl, CoingeckoName: asset.ValueOracle.String, OwlracleName: network.GasOracle, StringFee: fee, UUID: network.ID, GasTokenID: network.GasTokenID}, nil + return Chain{ChainId: chainId, RPC: network.RPCUrl, Explorer: network.ExplorerUrl, CoingeckoName: asset.ValueOracle.String, OwlracleName: network.GasOracle, StringFee: fee, UUID: network.Id, GasTokenId: network.GasTokenId}, nil } diff --git a/pkg/service/checkout.go b/pkg/service/checkout.go index da5fd7de..21920f76 100644 --- a/pkg/service/checkout.go +++ b/pkg/service/checkout.go @@ -5,6 +5,7 @@ package service import ( "math" "os" + "strings" "github.com/String-xyz/string-api/pkg/internal/common" "github.com/checkout/checkout-sdk-go" @@ -49,7 +50,7 @@ func CreateToken(card *tokens.Card) (token *tokens.Response, err error) { } type AuthorizedCharge struct { - AuthID string + AuthId string CheckoutFingerprint string Last4 string Issuer string @@ -67,7 +68,7 @@ func AuthorizeCharge(p transactionProcessingData) (transactionProcessingData, er } client := payments.NewClient(*config) - var paymentTokenID string + var paymentTokenId string if common.IsLocalEnv() { // Generate a payment token ID in case we don't yet have one in the front end // For testing purposes only @@ -86,28 +87,32 @@ func AuthorizeCharge(p transactionProcessingData) (transactionProcessingData, er if err != nil { return p, common.StringError(err) } - paymentTokenID = paymentToken.Created.Token + paymentTokenId = paymentToken.Created.Token if p.executionRequest.CardToken != "" { - paymentTokenID = p.executionRequest.CardToken + paymentTokenId = p.executionRequest.CardToken } } else { - paymentTokenID = p.executionRequest.CardToken + paymentTokenId = p.executionRequest.CardToken } - usd := convertAmount(p.executionRequest.TotalUSD) + fullName := p.user.FirstName + " " + p.user.MiddleName + " " + p.user.LastName + fullName = strings.Replace(fullName, " ", " ", 1) // If no middle name, ensure there is only one space between first name and last name + usd := convertAmount(p.executionRequest.TotalUSD) capture := false request := &payments.Request{ Source: payments.TokenSource{ Type: checkoutCommon.Token.String(), - Token: paymentTokenID, + Token: paymentTokenId, }, Amount: usd, Currency: "USD", Customer: &payments.Customer{ - Name: p.executionRequest.UserAddress, + Name: fullName, + Email: p.user.Email, // Replace with more robust email from platform and user }, - Capture: &capture, + Capture: &capture, + PaymentIP: p.transactionModel.IPAddress, } idempotencyKey := checkout.NewIdempotencyKey() @@ -121,7 +126,7 @@ func AuthorizeCharge(p transactionProcessingData) (transactionProcessingData, er // Collect authorization ID and Instrument ID if response.Processed != nil { - auth.AuthID = response.Processed.ID + auth.AuthId = response.Processed.ID auth.Approved = *response.Processed.Approved auth.Status = string(response.Processed.Status) auth.Summary = response.Processed.ResponseSummary @@ -155,14 +160,14 @@ func CaptureCharge(p transactionProcessingData) (transactionProcessingData, erro Amount: usd, } - capture, err := client.Captures(p.cardAuthorization.AuthID, &request, ¶ms) + capture, err := client.Captures(p.cardAuthorization.AuthId, &request, ¶ms) if err != nil { return p, common.StringError(err) } p.cardCapture = capture - // TODO: call action, err = client.Actions(capture.Accepted.ActionID) in another service to check on + // TODO: call action, err = client.Actions(capture.Accepted.ActionId) in another service to check on // TODO: Create entry for capture in our DB associated with userWallet return p, nil diff --git a/pkg/service/cost.go b/pkg/service/cost.go index be967b6a..524c6104 100644 --- a/pkg/service/cost.go +++ b/pkg/service/cost.go @@ -12,7 +12,7 @@ import ( ) type EstimationParams struct { - ChainID uint64 `json:"chainID"` + ChainId uint64 `json:"chainId"` CostETH big.Int `json:"costETH"` UseBuffer bool `json:"useBuffer"` GasUsedWei uint64 `json:"gasUsedWei"` @@ -67,7 +67,7 @@ func (c cost) EstimateTransaction(p EstimationParams, chain Chain) (model.Quote, // Use it to convert transactioncost and apply buffer if p.UseBuffer { - nativeCost *= 1.0 + common.NativeTokenBuffer(chain.ChainID) + nativeCost *= 1.0 + common.NativeTokenBuffer(chain.ChainId) } costEth := common.WeiToEther(&p.CostETH) // transactionCost is for native token transaction cost (tx_value) @@ -82,7 +82,7 @@ func (c cost) EstimateTransaction(p EstimationParams, chain Chain) (model.Quote, // Convert it from gwei to eth to USD and apply buffer gasInUSD := ethGasFee * float64(p.GasUsedWei) * nativeCost / float64(1e9) if p.UseBuffer { - gasInUSD *= 1.0 + common.GasBuffer(chain.ChainID) + gasInUSD *= 1.0 + common.GasBuffer(chain.ChainId) } // Query cost of token in USD if used and apply buffer diff --git a/pkg/service/device.go b/pkg/service/device.go index ad92126f..68552c50 100644 --- a/pkg/service/device.go +++ b/pkg/service/device.go @@ -14,8 +14,8 @@ import ( type Device interface { VerifyDevice(encrypted string) error UpsertDeviceIP(deviceId string, Ip string) (err error) - CreateDeviceIfNeeded(userID, visitorID, requestID string) (model.Device, error) - CreateUnknownDevice(userID string) (model.Device, error) + CreateDeviceIfNeeded(userId, visitorId, requestId string) (model.Device, error) + CreateUnknownDevice(userId string) (model.Device, error) InvalidateUnknownDevice(device model.Device) error } @@ -39,7 +39,7 @@ func (d device) VerifyDevice(encrypted string) error { if now.Unix()-received.Timestamp > (60 * 15) { return common.StringError(errors.New("link expired")) } - err = d.repos.Device.Update(received.DeviceID, model.DeviceUpdates{ValidatedAt: &now}) + err = d.repos.Device.Update(received.DeviceId, model.DeviceUpdates{ValidatedAt: &now}) return err } @@ -60,10 +60,10 @@ func (d device) UpsertDeviceIP(deviceId string, ip string) (err error) { return } -func (d device) CreateDeviceIfNeeded(userID, visitorID, requestID string) (model.Device, error) { - if visitorID == "" || requestID == "" { +func (d device) CreateDeviceIfNeeded(userId, visitorId, requestId string) (model.Device, error) { + if visitorId == "" || requestId == "" { /* fingerprint is not available, create an unknown device. It should be invalidated on every login */ - device, err := d.getOrCreateUnknownDevice(userID, "unknown") + device, err := d.getOrCreateUnknownDevice(userId, "unknown") if err != nil { return device, common.StringError(err) } @@ -76,18 +76,18 @@ func (d device) CreateDeviceIfNeeded(userID, visitorID, requestID string) (model return device, common.StringError(err) } else { /* device recognized, create or get the device */ - device, err := d.repos.Device.GetByUserIdAndFingerprint(userID, visitorID) + device, err := d.repos.Device.GetByUserIdAndFingerprint(userId, visitorId) if err == nil { return device, err } /* create device only if the error is not found */ if err == repository.ErrNotFound { - visitor, fpErr := d.fingerprint.GetVisitor(visitorID, requestID) + visitor, fpErr := d.fingerprint.GetVisitor(visitorId, requestId) if fpErr != nil { return model.Device{}, common.StringError(fpErr) } - device, dErr := d.createDevice(userID, visitor, "a new device "+visitor.UserAgent+" ") + device, dErr := d.createDevice(userId, visitor, "a new device "+visitor.UserAgent+" ") return device, dErr } @@ -95,13 +95,13 @@ func (d device) CreateDeviceIfNeeded(userID, visitorID, requestID string) (model } } -func (d device) CreateUnknownDevice(userID string) (model.Device, error) { +func (d device) CreateUnknownDevice(userId string) (model.Device, error) { visitor := FPVisitor{ - VisitorID: "unknown", + VisitorId: "unknown", Type: "unknown", UserAgent: "unknown", } - device, err := d.createDevice(userID, visitor, "an unknown device") + device, err := d.createDevice(userId, visitor, "an unknown device") return device, common.StringError(err) } @@ -111,18 +111,18 @@ func (d device) InvalidateUnknownDevice(device model.Device) error { } device.ValidatedAt = &time.Time{} // Zero time to set it to nil - return d.repos.Device.Update(device.ID, device) + return d.repos.Device.Update(device.Id, device) } -func (d device) createDevice(userID string, visitor FPVisitor, description string) (model.Device, error) { +func (d device) createDevice(userId string, visitor FPVisitor, description string) (model.Device, error) { addresses := pq.StringArray{} if visitor.IPAddress.String != "" { addresses = pq.StringArray{visitor.IPAddress.String} } return d.repos.Device.Create(model.Device{ - UserID: userID, - Fingerprint: visitor.VisitorID, + UserId: userId, + Fingerprint: visitor.VisitorId, Type: visitor.Type, IpAddresses: addresses, Description: description, @@ -138,7 +138,7 @@ func (d device) getOrCreateUnknownDevice(userId, visitorId string) (model.Device return device, common.StringError(err) } - if device.ID != "" { + if device.Id != "" { return device, nil } diff --git a/pkg/service/executor.go b/pkg/service/executor.go index cbc5ea6d..8881eaad 100644 --- a/pkg/service/executor.go +++ b/pkg/service/executor.go @@ -37,7 +37,7 @@ type Executor interface { Initialize(RPC string) error Initiate(call ContractCall) (string, *big.Int, error) Estimate(call ContractCall) (CallEstimate, error) - TxWait(txID string) (uint64, error) + TxWait(txId string) (uint64, error) Close() error GetByChainId() (uint64, error) GetBalance() (float64, error) @@ -95,7 +95,7 @@ func (e executor) Estimate(call ContractCall) (CallEstimate, error) { } sender := crypto.PubkeyToAddress(*publicKeyECDSA) - // Get ChainID from state + // Get ChainId from state var chainId64 uint64 err = e.client.Call(eth.ChainID().Returns(&chainId64)) if err != nil { @@ -168,7 +168,7 @@ func (e executor) Initiate(call ContractCall) (string, *big.Int, error) { // Use provided gas limit gasLimit := w3.I(call.TxGasLimit) - // Get chainID from state + // Get chainId from state var chainId64 uint64 err = e.client.Call(eth.ChainID().Returns(&chainId64)) if err != nil { @@ -198,7 +198,7 @@ func (e executor) Initiate(call ContractCall) (string, *big.Int, error) { return "", nil, stringCommon.StringError(err) } - // Type conversion for chainID + // Type conversion for chainId chainIdBig := new(big.Int).SetUint64(chainId64) // Get signer type, this is used to encode the tx @@ -228,8 +228,8 @@ func (e executor) Initiate(call ContractCall) (string, *big.Int, error) { return hash.String(), value, nil } -func (e executor) TxWait(txID string) (uint64, error) { - txHash := common.HexToHash(txID) +func (e executor) TxWait(txId string) (uint64, error) { + txHash := common.HexToHash(txId) receipt := types.Receipt{} for receipt.Status == 0 { pendingReceipt, err := e.geth.TransactionReceipt(context.Background(), txHash) @@ -246,7 +246,7 @@ func (e executor) TxWait(txID string) (uint64, error) { } func (e executor) GetByChainId() (uint64, error) { - // Get ChainID from state + // Get ChainId from state var chainId64 uint64 err := e.client.Call(eth.ChainID().Returns(&chainId64)) if err != nil { diff --git a/pkg/service/fingerprint.go b/pkg/service/fingerprint.go index bbcecdcd..4171cb5a 100644 --- a/pkg/service/fingerprint.go +++ b/pkg/service/fingerprint.go @@ -11,7 +11,7 @@ type FPClient common.FingerprintClient type HTTPConfig common.HTTPConfig type HTTPClient common.HTTPClient type FPVisitor struct { - VisitorID string + VisitorId string Country string State string IPAddress sql.NullString @@ -31,7 +31,7 @@ func NewFingerprintClient(client HTTPClient) FPClient { type Fingerprint interface { //GetVisitor fetches the visitor data by id, it does not validate if the device is the database - GetVisitor(ID string, request string) (FPVisitor, error) + GetVisitor(id string, request string) (FPVisitor, error) } type fingerprint struct { @@ -42,8 +42,8 @@ func NewFingerprint(client FPClient) Fingerprint { return &fingerprint{client} } -func (f fingerprint) GetVisitor(ID, requestID string) (FPVisitor, error) { - visitor, err := f.client.GetVisitorByID(ID, common.FPVisitorOpts{Limit: 1, RequestID: requestID}) +func (f fingerprint) GetVisitor(id, requestId string) (FPVisitor, error) { + visitor, err := f.client.GetVisitorById(id, common.FPVisitorOpts{Limit: 1, RequestId: requestId}) if err != nil { return FPVisitor{}, common.StringError(err) } @@ -65,7 +65,7 @@ func (f fingerprint) hydrateVisitor(visitor common.FPVisitor) (FPVisitor, error) } return FPVisitor{ - VisitorID: visitor.ID, + VisitorId: visitor.Id, Country: visit.IPLocation.Coutry.Code, State: state, IPAddress: sql.NullString{String: visit.IP}, diff --git a/pkg/service/platform.go b/pkg/service/platform.go index aae5753f..4d1c2408 100644 --- a/pkg/service/platform.go +++ b/pkg/service/platform.go @@ -30,7 +30,7 @@ func (a platform) Create(c CreatePlatform) (model.Platform, error) { return model.Platform{}, common.StringError(err) } - _, err = a.repos.Auth.CreateAPIKey(plat.ID, c.Authentication, hashed, false) + _, err = a.repos.Auth.CreateAPIKey(plat.Id, c.Authentication, hashed, false) pt := &plat if err != nil { return *pt, common.StringError(err) diff --git a/pkg/service/transaction.go b/pkg/service/transaction.go index 48dc3bb2..d6ee8c42 100644 --- a/pkg/service/transaction.go +++ b/pkg/service/transaction.go @@ -56,6 +56,7 @@ func NewTransaction(repos repository.Repositories, redis store.RedisStore, unit2 type transactionProcessingData struct { userId *string + user *model.User deviceId *string ip *string executor *Executor @@ -75,8 +76,8 @@ type transactionProcessingData struct { func (t transaction) Quote(d model.TransactionRequest) (model.ExecutionRequest, error) { // TODO: use prefab service to parse d and fill out known params res := model.ExecutionRequest{TransactionRequest: d} - // chain, err := model.ChainInfo(uint64(d.ChainID)) - chain, err := ChainInfo(uint64(d.ChainID), t.repos.Network, t.repos.Asset) + // chain, err := model.ChainInfo(uint64(d.ChainId)) + chain, err := ChainInfo(uint64(d.ChainId), t.repos.Network, t.repos.Asset) if err != nil { return res, common.StringError(err) } @@ -135,7 +136,188 @@ func (t transaction) Execute(e model.ExecutionRequest, userId string, deviceId s // Send required information to new thread and return txId to the endpoint go t.postProcess(p) - return model.TransactionReceipt{TxID: *p.txId, TxURL: p.chain.Explorer + "/tx/" + *p.txId}, nil + return model.TransactionReceipt{TxId: *p.txId, TxURL: p.chain.Explorer + "/tx/" + *p.txId}, nil +} + +func (t transaction) transactionSetup(p transactionProcessingData) (transactionProcessingData, error) { + // get user object + user, err := t.repos.User.GetById(*p.userId) + if err != nil { + return p, common.StringError(err) + } + email, err := t.repos.Contact.GetByUserIdAndType(user.Id, "email") + if err != nil { + return p, common.StringError(err) + } + user.Email = email.Data + p.user = &user + + // Pull chain info needed for execution from repository + chain, err := ChainInfo(uint64(p.executionRequest.ChainId), t.repos.Network, t.repos.Asset) + if err != nil { + return p, common.StringError(err) + } + p.chain = &chain + + // Create new Tx in repository, populate it with known info + transactionModel, err := t.repos.Transaction.Create(model.Transaction{Status: "Created", NetworkId: chain.UUID, DeviceId: *p.deviceId, IPAddress: *p.ip, PlatformId: t.ids.StringPlatformId}) + if err != nil { + return p, common.StringError(err) + } + p.transactionModel = &transactionModel + + updateDB := &model.TransactionUpdates{} + processingFeeAsset, err := t.populateInitialTxModelData(*p.executionRequest, updateDB) + p.processingFeeAsset = &processingFeeAsset + if err != nil { + return p, common.StringError(err) + } + err = t.repos.Transaction.Update(transactionModel.Id, updateDB) + if err != nil { + log.Err(err).Send() + return p, common.StringError(err) + } + + // Dial the RPC and update model status + executor := NewExecutor() + p.executor = &executor + err = executor.Initialize(chain.RPC) + if err != nil { + return p, common.StringError(err) + } + + err = t.updateTransactionStatus("RPC Dialed", transactionModel.Id) + if err != nil { + return p, common.StringError(err) + } + + return p, err +} + +func (t transaction) safetyCheck(p transactionProcessingData) (transactionProcessingData, error) { + // Test the Tx and update model status + estimateUSD, estimateETH, err := t.testTransaction(*p.executor, p.executionRequest.TransactionRequest, *p.chain, false) + if err != nil { + return p, common.StringError(err) + } + err = t.updateTransactionStatus("Tested and Estimated", p.transactionModel.Id) + if err != nil { + return p, common.StringError(err) + } + + // Verify the Quote and update model status + _, err = verifyQuote(*p.executionRequest, estimateUSD) + if err != nil { + return p, common.StringError(err) + } + err = t.updateTransactionStatus("Quote Verified", p.transactionModel.Id) + if err != nil { + return p, common.StringError(err) + } + + // Get current balance of primary token + preBalance, err := (*p.executor).GetBalance() + p.preBalance = &preBalance + if err != nil { + return p, common.StringError(err) + } + if preBalance < estimateETH { + msg := fmt.Sprintf("STRING-API: %s balance is too low to execute %.2f transaction at %.2f", p.chain.OwlracleName, estimateETH, preBalance) + MessageStaff(msg) + return p, common.StringError(errors.New("hot wallet ETH balance too low")) + } + + // Authorize quoted cost on end-user CC and update model status + p, err = t.authCard(p) + if err != nil { + return p, common.StringError(err) + } + + // Validate Transaction through Real Time Rules engine + txModel, err := t.repos.Transaction.GetById(p.transactionModel.Id) + if err != nil { + log.Err(err).Msg("error getting tx model in unit21 Tx Evalute") + return p, common.StringError(err) + } + + evaluation, err := t.unit21.Transaction.Evaluate(txModel) + + if err != nil { + // If Unit21 Evaluate fails, just log, but otherwise continue with the transaction + log.Err(err).Msg("Error evaluating transaction in Unit21") + return p, nil // NOTE: intentionally returning nil here in order to continue the transaction + } + + if !evaluation { + err = t.updateTransactionStatus("Failed", p.transactionModel.Id) + if err != nil { + return p, common.StringError(err) + } + + err = t.unit21CreateTransaction(p.transactionModel.Id) + if err != nil { + return p, common.StringError(err) + } + + return p, common.StringError(errors.New("risk: Transaction Failed Unit21 Real Time Rules Evaluation")) + } + + err = t.updateTransactionStatus("Unit21 Authorized", p.transactionModel.Id) + if err != nil { + return p, common.StringError(err) + } + + return p, nil +} + +func (t transaction) initiateTransaction(p transactionProcessingData) (transactionProcessingData, error) { + call := ContractCall{ + CxAddr: p.executionRequest.CxAddr, + CxFunc: p.executionRequest.CxFunc, + CxReturn: p.executionRequest.CxReturn, + CxParams: p.executionRequest.CxParams, + TxValue: p.executionRequest.TxValue, + TxGasLimit: p.executionRequest.TxGasLimit, + } + + txId, value, err := (*p.executor).Initiate(call) + p.cumulativeValue = value + if err != nil { + return p, common.StringError(err) + } + p.txId = &txId + + // Create Response Tx leg + eth := common.WeiToEther(value) + wei := floatToFixedString(eth, 18) + usd := floatToFixedString(p.executionRequest.TotalUSD, int(p.processingFeeAsset.Decimals)) + responseLeg := model.TxLeg{ + Timestamp: time.Now(), + Amount: wei, + Value: usd, + AssetId: p.processingFeeAsset.Id, + UserId: *p.userId, + InstrumentId: t.ids.StringWalletId, + } + responseLeg, err = t.repos.TxLeg.Create(responseLeg) + if err != nil { + return p, common.StringError(err) + } + txLeg := model.TransactionUpdates{ResponseTxLegId: &responseLeg.Id} + err = t.repos.Transaction.Update(p.transactionModel.Id, txLeg) + if err != nil { + return p, common.StringError(err) + } + + status := "Transaction Initiated" + txAmount := p.cumulativeValue.String() + updateDB := &model.TransactionUpdates{Status: &status, TransactionHash: p.txId, TransactionAmount: &txAmount} + err = t.repos.Transaction.Update(p.transactionModel.Id, updateDB) + if err != nil { + return p, common.StringError(err) + } + + return p, nil } func (t transaction) postProcess(p transactionProcessingData) { @@ -152,7 +334,7 @@ func (t transaction) postProcess(p transactionProcessingData) { updateDB := model.TransactionUpdates{} status := "Post Process RPC Dialed" updateDB.Status = &status - err = t.repos.Transaction.Update(p.transactionModel.ID, updateDB) + err = t.repos.Transaction.Update(p.transactionModel.Id, updateDB) if err != nil { log.Err(err).Msg("Failed to update transaction repo with status 'Post Process RPC Dialed'") // TODO: Handle error instead of returning it @@ -171,7 +353,7 @@ func (t transaction) postProcess(p transactionProcessingData) { updateDB.Status = &status networkFee := strconv.FormatUint(trueGas, 10) updateDB.NetworkFee = &networkFee // geth uses uint64 for gas - err = t.repos.Transaction.Update(p.transactionModel.ID, updateDB) + err = t.repos.Transaction.Update(p.transactionModel.Id, updateDB) if err != nil { log.Err(err).Msg("Failed to update transaction repo with status 'Tx Confirmed'") // TODO: Handle error instead of returning it @@ -215,7 +397,7 @@ func (t transaction) postProcess(p transactionProcessingData) { updateDB.ProcessingFee = &processingFee status = "Profit Tendered" updateDB.Status = &status - err = t.repos.Transaction.Update(p.transactionModel.ID, updateDB) + err = t.repos.Transaction.Update(p.transactionModel.Id, updateDB) if err != nil { log.Err(err).Msg("Failed to update transaction repo with status 'Profit Tendered'") // TODO: Handle error instead of returning it @@ -233,7 +415,7 @@ func (t transaction) postProcess(p transactionProcessingData) { updateDB.Status = &status // TODO: Figure out how much we paid the CC payment processor and deduct it // and use it to populate processing_fee and processing_fee_asset in the table - err = t.repos.Transaction.Update(p.transactionModel.ID, updateDB) + err = t.repos.Transaction.Update(p.transactionModel.Id, updateDB) if err != nil { log.Err(err).Msg("Failed to update transaction repo with status 'Card Charged'") // TODO: Handle error instead of returning it @@ -242,13 +424,13 @@ func (t transaction) postProcess(p transactionProcessingData) { // Transaction complete! Update status status = "Completed" updateDB.Status = &status - err = t.repos.Transaction.Update(p.transactionModel.ID, updateDB) + err = t.repos.Transaction.Update(p.transactionModel.Id, updateDB) if err != nil { log.Err(err).Msg("Failed to update transaction repo with status 'Completed'") } // Create Transaction data in Unit21 - err = t.unit21CreateTransaction(p.transactionModel.ID) + err = t.unit21CreateTransaction(p.transactionModel.Id) if err != nil { log.Err(err).Msg("Error creating Unit21 transaction") } @@ -260,138 +442,13 @@ func (t transaction) postProcess(p transactionProcessingData) { } } -func (t transaction) transactionSetup(p transactionProcessingData) (transactionProcessingData, error) { - // get user object - _, err := t.repos.User.GetById(*p.userId) - if err != nil { - return p, common.StringError(err) - } - - // Pull chain info needed for execution from repository - chain, err := ChainInfo(uint64(p.executionRequest.ChainID), t.repos.Network, t.repos.Asset) - p.chain = &chain - if err != nil { - return p, common.StringError(err) - } - - // Create new Tx in repository, populate it with known info - transactionModel, err := t.repos.Transaction.Create(model.Transaction{Status: "Created", NetworkID: chain.UUID, DeviceID: *p.deviceId, IPAddress: *p.ip, PlatformID: t.ids.StringPlatformId}) - if err != nil { - return p, common.StringError(err) - } - p.transactionModel = &transactionModel - - updateDB := &model.TransactionUpdates{} - processingFeeAsset, err := t.populateInitialTxModelData(*p.executionRequest, updateDB) - p.processingFeeAsset = &processingFeeAsset - if err != nil { - return p, common.StringError(err) - } - err = t.repos.Transaction.Update(transactionModel.ID, updateDB) - if err != nil { - log.Err(err).Send() - return p, common.StringError(err) - } - - // Dial the RPC and update model status - executor := NewExecutor() - p.executor = &executor - err = executor.Initialize(chain.RPC) - if err != nil { - return p, common.StringError(err) - } - - err = t.updateTransactionStatus("RPC Dialed", transactionModel.ID) - if err != nil { - return p, common.StringError(err) - } - - return p, err -} - -func (t transaction) safetyCheck(p transactionProcessingData) (transactionProcessingData, error) { - // Test the Tx and update model status - estimateUSD, estimateETH, err := t.testTransaction(*p.executor, p.executionRequest.TransactionRequest, *p.chain, false) - if err != nil { - return p, common.StringError(err) - } - err = t.updateTransactionStatus("Tested and Estimated", p.transactionModel.ID) - if err != nil { - return p, common.StringError(err) - } - - // Verify the Quote and update model status - _, err = verifyQuote(*p.executionRequest, estimateUSD) - if err != nil { - return p, common.StringError(err) - } - err = t.updateTransactionStatus("Quote Verified", p.transactionModel.ID) - if err != nil { - return p, common.StringError(err) - } - - // Get current balance of primary token - preBalance, err := (*p.executor).GetBalance() - p.preBalance = &preBalance - if err != nil { - return p, common.StringError(err) - } - if preBalance < estimateETH { - msg := fmt.Sprintf("STRING-API: %s balance is too low to execute %.2f transaction at %.2f", p.chain.OwlracleName, estimateETH, preBalance) - MessageStaff(msg) - return p, common.StringError(errors.New("hot wallet ETH balance too low")) - } - - // Authorize quoted cost on end-user CC and update model status - p, err = t.authCard(p) - if err != nil { - return p, common.StringError(err) - } - - // Validate Transaction through Real Time Rules engine - txModel, err := t.repos.Transaction.GetById(p.transactionModel.ID) - if err != nil { - log.Err(err).Msg("error getting tx model in unit21 Tx Evalute") - return p, common.StringError(err) - } - - evaluation, err := t.unit21.Transaction.Evaluate(txModel) - - if err != nil { - // If Unit21 Evaluate fails, just log, but otherwise continue with the transaction - log.Err(err).Msg("Error evaluating transaction in Unit21") - return p, nil // NOTE: intentionally returning nil here in order to continue the transaction - } - - if !evaluation { - err = t.updateTransactionStatus("Failed", p.transactionModel.ID) - if err != nil { - return p, common.StringError(err) - } - - err = t.unit21CreateTransaction(p.transactionModel.ID) - if err != nil { - return p, common.StringError(err) - } - - return p, common.StringError(errors.New("risk: Transaction Failed Unit21 Real Time Rules Evaluation")) - } - - err = t.updateTransactionStatus("Unit21 Authorized", p.transactionModel.ID) - if err != nil { - return p, common.StringError(err) - } - - return p, nil -} - func (t transaction) populateInitialTxModelData(e model.ExecutionRequest, m *model.TransactionUpdates) (model.Asset, error) { txType := "fiat-to-crypto" m.Type = &txType // TODO populate transactionModel.Tags with key-val pairs for Unit21 - // TODO populate transactionModel.DeviceID with info from fingerprint + // TODO populate transactionModel.DeviceId with info from fingerprint // TODO populate transactionModel.IPAddress with info from fingerprint - // TODO populate transactionModel.PlatformID with UUID of customer + // TODO populate transactionModel.PlatformId with UUID of customer // bytes, err := json.Marshal() contractParams := pq.StringArray(e.CxParams) @@ -403,7 +460,7 @@ func (t transaction) populateInitialTxModelData(e model.ExecutionRequest, m *mod if err != nil { return model.Asset{}, common.StringError(err) } - m.ProcessingFeeAsset = &asset.ID // Checkout processing asset + m.ProcessingFeeAsset = &asset.Id // Checkout processing asset return asset, nil } @@ -430,13 +487,13 @@ func (t transaction) testTransaction(executor Executor, request model.Transactio wei := gas.Add(&estimateEVM.Value, gas) eth := common.WeiToEther(wei) - chainID, err := executor.GetByChainId() + chainId, err := executor.GetByChainId() if err != nil { return res, eth, common.StringError(err) } cost := NewCost(t.redis) estimationParams := EstimationParams{ - ChainID: chainID, + ChainId: chainId, CostETH: estimateEVM.Value, UseBuffer: useBuffer, GasUsedWei: estimateEVM.Gas, @@ -482,9 +539,9 @@ func (t transaction) addCardInstrumentIdIfNew(p transactionProcessingData) (stri instrument, err := t.repos.Instrument.GetCardByFingerprint(p.cardAuthorization.CheckoutFingerprint) if err != nil && !strings.Contains(err.Error(), "not found") { // because we are wrapping error and care about its value return "", common.StringError(err) - } else if err == nil && instrument.UserID != "" { + } else if err == nil && instrument.UserId != "" { go t.unit21.Instrument.Update(instrument) // if instrument already exists, update it anyways - return instrument.ID, nil // return if instrument already exists + return instrument.Id, nil // return if instrument already exists } // We should gather type from the payment processor @@ -493,11 +550,11 @@ func (t transaction) addCardInstrumentIdIfNew(p transactionProcessingData) (stri instrument_type = "Credit Card" } // Create a new instrument - instrument = model.Instrument{ // No locationID until fingerprint + instrument = model.Instrument{ // No locationId until fingerprint Type: instrument_type, Status: "created", Last4: p.cardAuthorization.Last4, - UserID: *p.userId, + UserId: *p.userId, PublicKey: p.cardAuthorization.CheckoutFingerprint, } instrument, err = t.repos.Instrument.Create(instrument) @@ -507,7 +564,7 @@ func (t transaction) addCardInstrumentIdIfNew(p transactionProcessingData) (stri go t.unit21.Instrument.Create(instrument) - return instrument.ID, nil + return instrument.Id, nil } func (t transaction) addWalletInstrumentIdIfNew(address string, id string) (string, error) { @@ -516,11 +573,11 @@ func (t transaction) addWalletInstrumentIdIfNew(address string, id string) (stri return "", common.StringError(err) } else if err == nil && instrument.PublicKey == address { go t.unit21.Instrument.Update(instrument) // if instrument already exists, update it anyways - return instrument.ID, nil // return if instrument already exists + return instrument.Id, nil // return if instrument already exists } // Create a new instrument - instrument = model.Instrument{Type: "Crypto Wallet", Status: "external", Network: "ethereum", PublicKey: address, UserID: id} // No locationID or userID because this wallet was not registered with the user and is some other recipient + instrument = model.Instrument{Type: "Crypto Wallet", Status: "external", Network: "ethereum", PublicKey: address, UserId: id} // No locationId or userId because this wallet was not registered with the user and is some other recipient instrument, err = t.repos.Instrument.Create(instrument) if err != nil { return "", common.StringError(err) @@ -528,7 +585,7 @@ func (t transaction) addWalletInstrumentIdIfNew(address string, id string) (stri go t.unit21.Instrument.Create(instrument) - return instrument.ID, nil + return instrument.Id, nil } func (t transaction) authCard(p transactionProcessingData) (transactionProcessingData, error) { @@ -550,21 +607,21 @@ func (t transaction) authCard(p transactionProcessingData) (transactionProcessin Timestamp: time.Now(), Amount: usdWei, Value: usdWei, - AssetID: p.processingFeeAsset.ID, - UserID: *p.userId, - InstrumentID: instrumentId, + AssetId: p.processingFeeAsset.Id, + UserId: *p.userId, + InstrumentId: instrumentId, } origin, err = t.repos.TxLeg.Create(origin) if err != nil { return p, common.StringError(err) } - txLegUpdates := model.TransactionUpdates{OriginTxLegID: &origin.ID} - err = t.repos.Transaction.Update(p.transactionModel.ID, txLegUpdates) + txLegUpdates := model.TransactionUpdates{OriginTxLegId: &origin.Id} + err = t.repos.Transaction.Update(p.transactionModel.Id, txLegUpdates) if err != nil { return p, common.StringError(err) } - err = t.updateTransactionStatus("Card "+p.cardAuthorization.Status, p.transactionModel.ID) + err = t.updateTransactionStatus("Card "+p.cardAuthorization.Status, p.transactionModel.Id) if err != nil { return p, common.StringError(err) } @@ -580,9 +637,9 @@ func (t transaction) authCard(p transactionProcessingData) (transactionProcessin Timestamp: time.Now(), // Required by the db. Should be updated when the tx occurs Amount: "0", // Required by Unit21. The amount of the asset received by the user Value: "0", // Default to '0'. The value of the asset received by the user - AssetID: p.chain.GasTokenID, // Required by the db. the asset received by the user - UserID: *p.userId, // the user who received the asset - InstrumentID: recipientWalletId, // Required by the db. the instrument which received the asset (wallet usually) + AssetId: p.chain.GasTokenId, // Required by the db. the asset received by the user + UserId: *p.userId, // the user who received the asset + InstrumentId: recipientWalletId, // Required by the db. the instrument which received the asset (wallet usually) } destinationLeg, err = t.repos.TxLeg.Create(destinationLeg) @@ -590,15 +647,15 @@ func (t transaction) authCard(p transactionProcessingData) (transactionProcessin return p, common.StringError(err) } - txLegUpdates = model.TransactionUpdates{DestinationTxLegID: &destinationLeg.ID} + txLegUpdates = model.TransactionUpdates{DestinationTxLegId: &destinationLeg.Id} - err = t.repos.Transaction.Update(p.transactionModel.ID, txLegUpdates) + err = t.repos.Transaction.Update(p.transactionModel.Id, txLegUpdates) if err != nil { return p, common.StringError(err) } if !p.cardAuthorization.Approved { - err := t.unit21CreateTransaction(p.transactionModel.ID) + err := t.unit21CreateTransaction(p.transactionModel.Id) if err != nil { return p, common.StringError(err) } @@ -609,58 +666,8 @@ func (t transaction) authCard(p transactionProcessingData) (transactionProcessin return p, nil } -func (t transaction) initiateTransaction(p transactionProcessingData) (transactionProcessingData, error) { - call := ContractCall{ - CxAddr: p.executionRequest.CxAddr, - CxFunc: p.executionRequest.CxFunc, - CxReturn: p.executionRequest.CxReturn, - CxParams: p.executionRequest.CxParams, - TxValue: p.executionRequest.TxValue, - TxGasLimit: p.executionRequest.TxGasLimit, - } - - txID, value, err := (*p.executor).Initiate(call) - p.cumulativeValue = value - if err != nil { - return p, common.StringError(err) - } - p.txId = &txID - - // Create Response Tx leg - eth := common.WeiToEther(value) - wei := floatToFixedString(eth, 18) - usd := floatToFixedString(p.executionRequest.TotalUSD, int(p.processingFeeAsset.Decimals)) - responseLeg := model.TxLeg{ - Timestamp: time.Now(), - Amount: wei, - Value: usd, - AssetID: p.processingFeeAsset.ID, - UserID: *p.userId, - InstrumentID: t.ids.StringWalletId, - } - responseLeg, err = t.repos.TxLeg.Create(responseLeg) - if err != nil { - return p, common.StringError(err) - } - txLeg := model.TransactionUpdates{ResponseTxLegID: &responseLeg.ID} - err = t.repos.Transaction.Update(p.transactionModel.ID, txLeg) - if err != nil { - return p, common.StringError(err) - } - - status := "Transaction Initiated" - txAmount := p.cumulativeValue.String() - updateDB := &model.TransactionUpdates{Status: &status, TransactionHash: p.txId, TransactionAmount: &txAmount} - err = t.repos.Transaction.Update(p.transactionModel.ID, updateDB) - if err != nil { - return p, common.StringError(err) - } - - return p, nil -} - -func confirmTx(executor Executor, txID string) (uint64, error) { - trueGas, err := executor.TxWait(txID) +func confirmTx(executor Executor, txId string) (uint64, error) { + trueGas, err := executor.TxWait(txId) if err != nil { return 0, common.StringError(err) } @@ -679,14 +686,14 @@ func (t transaction) tenderTransaction(p transactionProcessingData) (float64, er profit := p.executionRequest.Quote.TotalUSD - trueUSD // Create Receive Tx leg - asset, err := t.repos.Asset.GetById(p.chain.GasTokenID) + asset, err := t.repos.Asset.GetById(p.chain.GasTokenId) if err != nil { return profit, common.StringError(err) } wei := floatToFixedString(trueEth, int(asset.Decimals)) usd := floatToFixedString(p.executionRequest.Quote.TotalUSD, 6) - txModel, err := t.repos.Transaction.GetById(p.transactionModel.ID) + txModel, err := t.repos.Transaction.GetById(p.transactionModel.Id) if err != nil { return profit, common.StringError(err) } @@ -696,13 +703,13 @@ func (t transaction) tenderTransaction(p transactionProcessingData) (float64, er Timestamp: &now, // updated based on *when the transaction occured* not time.Now() Amount: &wei, // Should be the amount of the asset received by the user Value: &usd, // The value of the asset received by the user - AssetID: &asset.ID, // the asset received by the user - UserID: p.userId, // the user who received the asset - InstrumentID: p.recipientWalletId, // the instrument which received the asset (wallet usually) + AssetId: &asset.Id, // the asset received by the user + UserId: p.userId, // the user who received the asset + InstrumentId: p.recipientWalletId, // the instrument which received the asset (wallet usually) } // We now update the destination leg instead of creating it - err = t.repos.TxLeg.Update(txModel.DestinationTxLegID, destinationLeg) + err = t.repos.TxLeg.Update(txModel.DestinationTxLegId, destinationLeg) if err != nil { return profit, common.StringError(err) } @@ -722,16 +729,16 @@ func (t transaction) chargeCard(p transactionProcessingData) error { Timestamp: time.Now(), Amount: usdWei, Value: usdWei, - AssetID: p.processingFeeAsset.ID, - UserID: t.ids.StringUserId, - InstrumentID: t.ids.StringBankId, + AssetId: p.processingFeeAsset.Id, + UserId: t.ids.StringUserId, + InstrumentId: t.ids.StringBankId, } receiptLeg, err = t.repos.TxLeg.Create(receiptLeg) if err != nil { return common.StringError(err) } - txLeg := model.TransactionUpdates{ReceiptTxLegID: &receiptLeg.ID, PaymentCode: &p.cardCapture.Accepted.ActionID} - err = t.repos.Transaction.Update(p.transactionModel.ID, txLeg) + txLeg := model.TransactionUpdates{ReceiptTxLegId: &receiptLeg.Id, PaymentCode: &p.cardCapture.Accepted.ActionID} + err = t.repos.Transaction.Update(p.transactionModel.Id, txLeg) if err != nil { return common.StringError(err) } @@ -745,7 +752,7 @@ func (t transaction) sendEmailReceipt(p transactionProcessingData) error { log.Err(err).Msg("Error getting user from repo") return common.StringError(err) } - contact, err := t.repos.Contact.GetByUserId(user.ID) + contact, err := t.repos.Contact.GetByUserId(user.Id) if err != nil { log.Err(err).Msg("Error getting user contact from repo") return common.StringError(err) @@ -757,7 +764,7 @@ func (t transaction) sendEmailReceipt(p transactionProcessingData) error { receiptParams := common.ReceiptGenerationParams{ ReceiptType: "NFT Purchase", // TODO: retrieve dynamically CustomerName: name, - StringPaymentId: p.transactionModel.ID, + StringPaymentId: p.transactionModel.Id, PaymentDescriptor: "String Digital Asset", // TODO: retrieve dynamically TransactionDate: time.Now().Format(time.RFC1123), } diff --git a/pkg/service/user.go b/pkg/service/user.go index 94408d0f..b59eec87 100644 --- a/pkg/service/user.go +++ b/pkg/service/user.go @@ -19,7 +19,7 @@ type UserCreateResponse struct { type User interface { //GetStatus returns the onboarding status of an user - GetStatus(userID string) (model.UserOnboardingStatus, error) + GetStatus(userId string) (model.UserOnboardingStatus, error) // Create creates an user from a wallet signed payload // It associates the wallet to the user and also sets its status as verified @@ -28,7 +28,7 @@ type User interface { //Update updates the user firstname lastname middlename. // It fetches the user using the walletAddress provided - Update(userID string, request UserUpdates) (model.User, error) + Update(userId string, request UserUpdates) (model.User, error) } type user struct { @@ -43,10 +43,10 @@ func NewUser(repos repository.Repositories, auth Auth, fprint Fingerprint, devic return &user{repos, auth, fprint, device, unit21} } -func (u user) GetStatus(userID string) (model.UserOnboardingStatus, error) { +func (u user) GetStatus(userId string) (model.UserOnboardingStatus, error) { res := model.UserOnboardingStatus{Status: "not found"} - user, err := u.repos.User.GetById(userID) + user, err := u.repos.User.GetById(userId) if err != nil { return res, common.StringError(err) } @@ -97,13 +97,13 @@ func (u user) Create(request model.WalletSignaturePayloadSigned) (UserCreateResp } // create device only if there is a visitor - device, err := u.device.CreateDeviceIfNeeded(user.ID, request.Fingerprint.VisitorID, request.Fingerprint.RequestID) + device, err := u.device.CreateDeviceIfNeeded(user.Id, request.Fingerprint.VisitorId, request.Fingerprint.RequestId) if err != nil && errors.Cause(err).Error() != "not found" { return resp, common.StringError(err) } - jwt, err := u.auth.GenerateJWT(user.ID, device) + jwt, err := u.auth.GenerateJWT(user.Id, device) if err != nil { return resp, common.StringError(err) } @@ -129,7 +129,7 @@ func (u user) createUserData(addr string) (model.User, error) { return user, common.StringError(err) } // Create a new wallet instrument and associate it with the new user - instrument := model.Instrument{Type: "Crypto Wallet", Status: "verified", Network: "EVM", PublicKey: addr, UserID: user.ID} + instrument := model.Instrument{Type: "Crypto Wallet", Status: "verified", Network: "EVM", PublicKey: addr, UserId: user.Id} instrument, err = u.repos.Instrument.Create(instrument) if err != nil { u.repos.Instrument.Rollback() @@ -144,9 +144,9 @@ func (u user) createUserData(addr string) (model.User, error) { return user, nil } -func (u user) Update(userID string, request UserUpdates) (model.User, error) { +func (u user) Update(userId string, request UserUpdates) (model.User, error) { updates := model.UpdateUserName{FirstName: request.FirstName, MiddleName: request.MiddleName, LastName: request.LastName} - user, err := u.repos.User.Update(userID, updates) + user, err := u.repos.User.Update(userId, updates) if err != nil { return user, common.StringError(err) } diff --git a/pkg/service/verification.go b/pkg/service/verification.go index 3e4032b1..65be5f73 100644 --- a/pkg/service/verification.go +++ b/pkg/service/verification.go @@ -18,23 +18,23 @@ import ( type EmailVerification struct { Timestamp int64 Email string - UserID string + UserId string } type DeviceVerification struct { Timestamp int64 - DeviceID string - UserID string + DeviceId string + UserId string } type Verification interface { // SendEmailVerification sends a link to the provided email for verification purpose, link expires in 15 minutes - SendEmailVerification(userID string, email string) error + SendEmailVerification(userId string, email string) error // VerifyEmail verifies the provided email and creates a contact VerifyEmail(encrypted string) error - SendDeviceVerification(userID, email string, deviceID string, deviceDescription string) error + SendDeviceVerification(userId, email string, deviceId string, deviceDescription string) error } type verification struct { @@ -46,13 +46,13 @@ func NewVerification(repos repository.Repositories, unit21 Unit21) Verification return &verification{repos, unit21} } -func (v verification) SendEmailVerification(userID, email string) error { +func (v verification) SendEmailVerification(userId, email string) error { if !validEmail(email) { return common.StringError(errors.New("missing or invalid email")) } - user, err := v.repos.User.GetById(userID) - if err != nil || user.ID != userID { + user, err := v.repos.User.GetById(userId) + if err != nil || user.Id != userId { return common.StringError(errors.New("invalid user")) // JWT expiration will not be hit here } @@ -63,7 +63,7 @@ func (v verification) SendEmailVerification(userID, email string) error { // Encrypt required data to Base64 string and insert it in an email hyperlink key := os.Getenv("STRING_ENCRYPTION_KEY") - code, err := common.Encrypt(EmailVerification{Timestamp: time.Now().Unix(), Email: email, UserID: userID}, key) + code, err := common.Encrypt(EmailVerification{Timestamp: time.Now().Unix(), Email: email, UserId: userId}, key) if err != nil { return common.StringError(err) } @@ -97,9 +97,9 @@ func (v verification) SendEmailVerification(userID, email string) error { } else if err == nil && contact.Data == email { // success // update user status - user, err := v.repos.User.UpdateStatus(userID, "email_verified") + user, err := v.repos.User.UpdateStatus(userId, "email_verified") if err != nil { - return common.StringError(errors.New("User email verify error - userID: " + user.ID)) + return common.StringError(errors.New("User email verify error - userId: " + user.Id)) } return nil @@ -109,10 +109,10 @@ func (v verification) SendEmailVerification(userID, email string) error { return common.StringError(errors.New("link expired")) } -func (v verification) SendDeviceVerification(userID, email, deviceID, deviceDescription string) error { +func (v verification) SendDeviceVerification(userId, email, deviceId, deviceDescription string) error { log.Info().Str("email", email) key := os.Getenv("STRING_ENCRYPTION_KEY") - code, err := common.Encrypt(DeviceVerification{Timestamp: time.Now().Unix(), DeviceID: deviceID, UserID: userID}, key) + code, err := common.Encrypt(DeviceVerification{Timestamp: time.Now().Unix(), DeviceId: deviceId, UserId: userId}, key) if err != nil { return common.StringError(err) } @@ -151,16 +151,16 @@ func (v verification) VerifyEmail(encrypted string) error { if now.Unix()-received.Timestamp > (60 * 15) { return common.StringError(errors.New("link expired")) } - contact := model.Contact{UserID: received.UserID, Type: "email", Status: "validated", Data: received.Email, ValidatedAt: &now} + contact := model.Contact{UserId: received.UserId, Type: "email", Status: "validated", Data: received.Email, ValidatedAt: &now} contact, err = v.repos.Contact.Create(contact) if err != nil { return common.StringError(err) } // update user status - user, err := v.repos.User.UpdateStatus(received.UserID, "email_verified") + user, err := v.repos.User.UpdateStatus(received.UserId, "email_verified") if err != nil { - return common.StringError(errors.New("User email verify error - userID: " + user.ID)) + return common.StringError(errors.New("User email verify error - userId: " + user.Id)) } go v.unit21.Entity.Update(user) diff --git a/pkg/test/stubs/repository.go b/pkg/test/stubs/repository.go index 2dad2992..bdf06ae2 100644 --- a/pkg/test/stubs/repository.go +++ b/pkg/test/stubs/repository.go @@ -12,26 +12,26 @@ import ( // } // var avax = model.Asset{ -// ID: "1", +// Id: "1", // CreatedAt: time.Now(), // UpdatedAt: time.Now(), // Name: "AVAX", // Description: "Avalanche", // Decimals: 18, // IsCrypto: true, -// NetworkID: sql.NullString{}, +// NetworkId: sql.NullString{}, // ValueOracle: sql.NullString{String: "avalanche-2", Valid: true}, // } // var usd = model.Asset{ -// ID: "2", +// Id: "2", // CreatedAt: time.Now(), // UpdatedAt: time.Now(), // Name: "USD", // Description: "United States Dollar", // Decimals: 6, // IsCrypto: false, -// NetworkID: sql.NullString{}, +// NetworkId: sql.NullString{}, // ValueOracle: sql.NullString{}, // } @@ -59,7 +59,7 @@ import ( // return model.Asset{}, nil // } -// func (Asset) Update(ID string, updates any) error { +// func (Asset) Update(Id string, updates any) error { // return nil // } @@ -70,11 +70,11 @@ func (AuthStrategyRepo) Create(authType repository.AuthType, m model.AuthStrateg return nil } -func (AuthStrategyRepo) CreateAPIKey(entityID string, authType model.AuthType, apiKey string, persistOnly bool) error { +func (AuthStrategyRepo) CreateAPIKey(entityId string, authType model.AuthType, apiKey string, persistOnly bool) error { return nil } -func (AuthStrategyRepo) CreateJWTRefresh(ID string, token string) error { +func (AuthStrategyRepo) CreateJWTRefresh(id string, token string) error { return nil } func (AuthStrategyRepo) Get(string) (model.AuthStrategy, error) { @@ -95,6 +95,6 @@ func (AuthStrategyRepo) List(limit, offset int) ([]model.AuthStrategy, error) { func (AuthStrategyRepo) ListByStatus(limit, offset int, status string) ([]model.AuthStrategy, error) { return []model.AuthStrategy{}, nil } -func (AuthStrategyRepo) UpdateStatus(ID, status string) (model.AuthStrategy, error) { +func (AuthStrategyRepo) UpdateStatus(id, status string) (model.AuthStrategy, error) { return model.AuthStrategy{}, nil } diff --git a/pkg/test/stubs/service.go b/pkg/test/stubs/service.go index 215f1c22..0aa50694 100644 --- a/pkg/test/stubs/service.go +++ b/pkg/test/stubs/service.go @@ -14,7 +14,7 @@ func (v *Verification) SetError(e error) { v.Error = e } -func (v Verification) SendEmailVerification(userID string, email string) error { +func (v Verification) SendEmailVerification(userId string, email string) error { return v.Error } @@ -22,7 +22,7 @@ func (v Verification) VerifyEmail(encrypted string) error { return v.Error } -func (v Verification) SendDeviceVerification(userID string, deviceID string, deviceDescription string) error { +func (v Verification) SendDeviceVerification(userId string, deviceId string, deviceDescription string) error { return v.Error } @@ -50,7 +50,7 @@ func (u *User) SetUser(user model.User) { u.User = user } -func (u User) GetStatus(ID string) (model.UserOnboardingStatus, error) { +func (u User) GetStatus(id string) (model.UserOnboardingStatus, error) { return u.UserOnboardingStatus, u.Error } @@ -58,7 +58,7 @@ func (u User) Create(request model.WalletSignaturePayloadSigned) (service.UserCr return u.UserCreateResponse, u.Error } -func (u User) Update(userID string, request service.UserUpdates) (model.User, error) { +func (u User) Update(userId string, request service.UserUpdates) (model.User, error) { return u.User, u.Error } diff --git a/scripts/data_seeding.go b/scripts/data_seeding.go index 2dd9a52d..ae9c757b 100644 --- a/scripts/data_seeding.go +++ b/scripts/data_seeding.go @@ -37,54 +37,54 @@ func DataSeeding() { // Write to repos - // Networks without GasTokenID - networkPolygon, err := repos.Network.Create(model.Network{Name: "Polygon Mainnet", NetworkID: 137, ChainID: 137, GasOracle: "poly", RPCUrl: "https://rpc-mainnet.matic.quiknode.pro", ExplorerUrl: "https://polygonscan.com"}) + // Networks without GasTokenId + networkPolygon, err := repos.Network.Create(model.Network{Name: "Polygon Mainnet", NetworkId: 137, ChainId: 137, GasOracle: "poly", RPCUrl: "https://rpc-mainnet.matic.quiknode.pro", ExplorerUrl: "https://polygonscan.com"}) if err != nil { fmt.Printf("%+v", err) return } - networkMumbai, err := repos.Network.Create(model.Network{Name: "Mumbai Testnet", NetworkID: 80001, ChainID: 80001, GasOracle: "poly", RPCUrl: "https://matic-mumbai.chainstacklabs.com", ExplorerUrl: "https://mumbai.polygonscan.com"}) + networkMumbai, err := repos.Network.Create(model.Network{Name: "Mumbai Testnet", NetworkId: 80001, ChainId: 80001, GasOracle: "poly", RPCUrl: "https://matic-mumbai.chainstacklabs.com", ExplorerUrl: "https://mumbai.polygonscan.com"}) if err != nil { panic(err) } - networkGoerli, err := repos.Network.Create(model.Network{Name: "Goerli Testnet", NetworkID: 5, ChainID: 5, GasOracle: "eth", RPCUrl: "https://goerli.infura.io/v3/9aa3d95b3bc440fa88ea12eaa4456161", ExplorerUrl: "https://goerli.etherscan.io"}) + networkGoerli, err := repos.Network.Create(model.Network{Name: "Goerli Testnet", NetworkId: 5, ChainId: 5, GasOracle: "eth", RPCUrl: "https://goerli.infura.io/v3/9aa3d95b3bc440fa88ea12eaa4456161", ExplorerUrl: "https://goerli.etherscan.io"}) if err != nil { panic(err) } - networkEthereum, err := repos.Network.Create(model.Network{Name: "Ethereum Mainnet", NetworkID: 1, ChainID: 1, GasOracle: "eth", RPCUrl: "https://rpc.ankr.com/eth", ExplorerUrl: "https://etherscan.io"}) + networkEthereum, err := repos.Network.Create(model.Network{Name: "Ethereum Mainnet", NetworkId: 1, ChainId: 1, GasOracle: "eth", RPCUrl: "https://rpc.ankr.com/eth", ExplorerUrl: "https://etherscan.io"}) if err != nil { panic(err) } - networkFuji, err := repos.Network.Create(model.Network{Name: "Fuji Testnet", NetworkID: 1, ChainID: 43113, GasOracle: "avax", RPCUrl: "https://api.avax-test.network/ext/bc/C/rpc", ExplorerUrl: "https://testnet.snowtrace.io"}) + networkFuji, err := repos.Network.Create(model.Network{Name: "Fuji Testnet", NetworkId: 1, ChainId: 43113, GasOracle: "avax", RPCUrl: "https://api.avax-test.network/ext/bc/C/rpc", ExplorerUrl: "https://testnet.snowtrace.io"}) if err != nil { panic(err) } - networkAvalanche, err := repos.Network.Create(model.Network{Name: "Avalanche Mainnet", NetworkID: 1, ChainID: 43114, GasOracle: "avax", RPCUrl: "https://api.avax.network/ext/bc/C/rpc", ExplorerUrl: "https://snowtrace.io"}) + networkAvalanche, err := repos.Network.Create(model.Network{Name: "Avalanche Mainnet", NetworkId: 1, ChainId: 43114, GasOracle: "avax", RPCUrl: "https://api.avax.network/ext/bc/C/rpc", ExplorerUrl: "https://snowtrace.io"}) if err != nil { panic(err) } - networkNitroGoerli, err := repos.Network.Create(model.Network{Name: "Nitro Goerli Rollup Testnet", NetworkID: 421613, ChainID: 421613, GasOracle: "arb", RPCUrl: "https://goerli-rollup.arbitrum.io/rpc", ExplorerUrl: "https://goerli.arbiscan.io"}) + networkNitroGoerli, err := repos.Network.Create(model.Network{Name: "Nitro Goerli Rollup Testnet", NetworkId: 421613, ChainId: 421613, GasOracle: "arb", RPCUrl: "https://goerli-rollup.arbitrum.io/rpc", ExplorerUrl: "https://goerli.arbiscan.io"}) if err != nil { panic(err) } - networkArbitrumNova, err := repos.Network.Create(model.Network{Name: "Arbitrum Nova Mainnet", NetworkID: 42170, ChainID: 42170, GasOracle: "arb", RPCUrl: "https://nova.arbitrum.io/rpc", ExplorerUrl: "https://nova-explorer.arbitrum.io"}) + networkArbitrumNova, err := repos.Network.Create(model.Network{Name: "Arbitrum Nova Mainnet", NetworkId: 42170, ChainId: 42170, GasOracle: "arb", RPCUrl: "https://nova.arbitrum.io/rpc", ExplorerUrl: "https://nova-explorer.arbitrum.io"}) if err != nil { panic(err) } // Assets - assetAvalanche, err := repos.Asset.Create(model.Asset{Name: "AVAX", Description: "Avalanche", Decimals: 18, IsCrypto: true, NetworkID: nullString(networkAvalanche.ID), ValueOracle: nullString("avalanche-2")}) + assetAvalanche, err := repos.Asset.Create(model.Asset{Name: "AVAX", Description: "Avalanche", Decimals: 18, IsCrypto: true, NetworkId: nullString(networkAvalanche.Id), ValueOracle: nullString("avalanche-2")}) if err != nil { panic(err) } - assetEthereum, err := repos.Asset.Create(model.Asset{Name: "ETH", Description: "Ethereum", Decimals: 18, IsCrypto: true, NetworkID: nullString(networkEthereum.ID), ValueOracle: nullString("ethereum")}) + assetEthereum, err := repos.Asset.Create(model.Asset{Name: "ETH", Description: "Ethereum", Decimals: 18, IsCrypto: true, NetworkId: nullString(networkEthereum.Id), ValueOracle: nullString("ethereum")}) if err != nil { panic(err) } - assetMatic, err := repos.Asset.Create(model.Asset{Name: "MATIC", Description: "Matic", Decimals: 18, IsCrypto: true, NetworkID: nullString(networkPolygon.ID), ValueOracle: nullString("matic-network")}) + assetMatic, err := repos.Asset.Create(model.Asset{Name: "MATIC", Description: "Matic", Decimals: 18, IsCrypto: true, NetworkId: nullString(networkPolygon.Id), ValueOracle: nullString("matic-network")}) if err != nil { panic(err) } - assetGoerliEth, err := repos.Asset.Create(model.Asset{Name: "GOERLIETH", Description: "Goerli Ethereum", Decimals: 18, IsCrypto: true, NetworkID: nullString(networkNitroGoerli.ID), ValueOracle: nullString("ethereum")}) + assetGoerliEth, err := repos.Asset.Create(model.Asset{Name: "GOERLIETH", Description: "Goerli Ethereum", Decimals: 18, IsCrypto: true, NetworkId: nullString(networkNitroGoerli.Id), ValueOracle: nullString("ethereum")}) if err != nil { panic(err) } @@ -94,36 +94,36 @@ func DataSeeding() { panic(err) } - // Update Networks with GasTokenIDs - err = repos.Network.Update(networkPolygon.ID, model.NetworkUpdates{GasTokenID: &assetMatic.ID}) + // Update Networks with GasTokenIds + err = repos.Network.Update(networkPolygon.Id, model.NetworkUpdates{GasTokenId: &assetMatic.Id}) if err != nil { panic(err) } - err = repos.Network.Update(networkMumbai.ID, model.NetworkUpdates{GasTokenID: &assetMatic.ID}) + err = repos.Network.Update(networkMumbai.Id, model.NetworkUpdates{GasTokenId: &assetMatic.Id}) if err != nil { panic(err) } - err = repos.Network.Update(networkGoerli.ID, model.NetworkUpdates{GasTokenID: &assetEthereum.ID}) + err = repos.Network.Update(networkGoerli.Id, model.NetworkUpdates{GasTokenId: &assetEthereum.Id}) if err != nil { panic(err) } - err = repos.Network.Update(networkEthereum.ID, model.NetworkUpdates{GasTokenID: &assetEthereum.ID}) + err = repos.Network.Update(networkEthereum.Id, model.NetworkUpdates{GasTokenId: &assetEthereum.Id}) if err != nil { panic(err) } - err = repos.Network.Update(networkFuji.ID, model.NetworkUpdates{GasTokenID: &assetAvalanche.ID}) + err = repos.Network.Update(networkFuji.Id, model.NetworkUpdates{GasTokenId: &assetAvalanche.Id}) if err != nil { panic(err) } - err = repos.Network.Update(networkAvalanche.ID, model.NetworkUpdates{GasTokenID: &assetAvalanche.ID}) + err = repos.Network.Update(networkAvalanche.Id, model.NetworkUpdates{GasTokenId: &assetAvalanche.Id}) if err != nil { panic(err) } - err = repos.Network.Update(networkNitroGoerli.ID, model.NetworkUpdates{GasTokenID: &assetGoerliEth.ID}) + err = repos.Network.Update(networkNitroGoerli.Id, model.NetworkUpdates{GasTokenId: &assetGoerliEth.Id}) if err != nil { panic(err) } - err = repos.Network.Update(networkArbitrumNova.ID, model.NetworkUpdates{GasTokenID: &assetEthereum.ID}) + err = repos.Network.Update(networkArbitrumNova.Id, model.NetworkUpdates{GasTokenId: &assetEthereum.Id}) if err != nil { panic(err) } @@ -140,18 +140,18 @@ func DataSeeding() { panic("STRING_INTERNAL_ID is not set in ENV!") } - type UpdateID struct { - ID string `json:"id" db:"id"` + type UpdateId struct { + Id string `json:"id" db:"id"` } - updateId := UpdateID{ID: internalId} - userString, err = repos.User.Update(userString.ID, updateId) + updateId := UpdateId{Id: internalId} + userString, err = repos.User.Update(userString.Id, updateId) if err != nil { panic(err) } // Instruments, used in TX Legs /*instrumentDeveloperCard*/ - bankString, err := repos.Instrument.Create(model.Instrument{Type: "Bank Account", Status: "Live", Network: "bankprov", PublicKey: "420481286", UserID: userString.ID}) + bankString, err := repos.Instrument.Create(model.Instrument{Type: "Bank Account", Status: "Live", Network: "bankprov", PublicKey: "420481286", UserId: userString.Id}) if err != nil { panic(err) } @@ -161,14 +161,14 @@ func DataSeeding() { panic("STRING_BANK_ID is not set in ENV!") } - updateId = UpdateID{ID: bankId} - err = repos.Instrument.Update(bankString.ID, updateId) + updateId = UpdateId{Id: bankId} + err = repos.Instrument.Update(bankString.Id, updateId) if err != nil { panic(err) } /*instrumentDeveloperWallet*/ - walletString, err := repos.Instrument.Create(model.Instrument{Type: "Crypto Wallet", Status: "Internal", Network: "EVM", PublicKey: stringPublicAddress, UserID: userString.ID}) + walletString, err := repos.Instrument.Create(model.Instrument{Type: "Crypto Wallet", Status: "Internal", Network: "EVM", PublicKey: stringPublicAddress, UserId: userString.Id}) if err != nil { panic(err) } @@ -178,8 +178,8 @@ func DataSeeding() { panic("STRING_WALLET_ID is not set in ENV!") } - updateId = UpdateID{ID: walletId} - err = repos.Instrument.Update(walletString.ID, updateId) + updateId = UpdateId{Id: walletId} + err = repos.Instrument.Update(walletString.Id, updateId) if err != nil { panic(err) } @@ -197,8 +197,8 @@ func DataSeeding() { panic("STRING_PLACEHOLDER_PLATFORM_ID is not set in ENV!") } - updateId = UpdateID{ID: platformId} - err = repos.Platform.Update(placeholderPlatform.ID, updateId) + updateId = UpdateId{Id: platformId} + err = repos.Platform.Update(placeholderPlatform.Id, updateId) if err != nil { panic(err) } @@ -225,54 +225,54 @@ func MockSeeding() { // Write to repos - // Networks without GasTokenID - networkPolygon, err := repos.Network.Create(model.Network{Name: "Polygon Mainnet", NetworkID: 137, ChainID: 137, GasOracle: "poly", RPCUrl: "https://rpc-mainnet.matic.quiknode.pro", ExplorerUrl: "https://polygonscan.com"}) + // Networks without GasTokenId + networkPolygon, err := repos.Network.Create(model.Network{Name: "Polygon Mainnet", NetworkId: 137, ChainId: 137, GasOracle: "poly", RPCUrl: "https://rpc-mainnet.matic.quiknode.pro", ExplorerUrl: "https://polygonscan.com"}) if err != nil { fmt.Printf("%+v", err) return } - networkMumbai, err := repos.Network.Create(model.Network{Name: "Mumbai Testnet", NetworkID: 80001, ChainID: 80001, GasOracle: "poly", RPCUrl: "https://matic-mumbai.chainstacklabs.com", ExplorerUrl: "https://mumbai.polygonscan.com"}) + networkMumbai, err := repos.Network.Create(model.Network{Name: "Mumbai Testnet", NetworkId: 80001, ChainId: 80001, GasOracle: "poly", RPCUrl: "https://matic-mumbai.chainstacklabs.com", ExplorerUrl: "https://mumbai.polygonscan.com"}) if err != nil { panic(err) } - networkGoerli, err := repos.Network.Create(model.Network{Name: "Goerli Testnet", NetworkID: 5, ChainID: 5, GasOracle: "eth", RPCUrl: "https://goerli.infura.io/v3/9aa3d95b3bc440fa88ea12eaa4456161", ExplorerUrl: "https://goerli.etherscan.io"}) + networkGoerli, err := repos.Network.Create(model.Network{Name: "Goerli Testnet", NetworkId: 5, ChainId: 5, GasOracle: "eth", RPCUrl: "https://goerli.infura.io/v3/9aa3d95b3bc440fa88ea12eaa4456161", ExplorerUrl: "https://goerli.etherscan.io"}) if err != nil { panic(err) } - networkEthereum, err := repos.Network.Create(model.Network{Name: "Ethereum Mainnet", NetworkID: 1, ChainID: 1, GasOracle: "eth", RPCUrl: "https://rpc.ankr.com/eth", ExplorerUrl: "https://etherscan.io"}) + networkEthereum, err := repos.Network.Create(model.Network{Name: "Ethereum Mainnet", NetworkId: 1, ChainId: 1, GasOracle: "eth", RPCUrl: "https://rpc.ankr.com/eth", ExplorerUrl: "https://etherscan.io"}) if err != nil { panic(err) } - networkFuji, err := repos.Network.Create(model.Network{Name: "Fuji Testnet", NetworkID: 1, ChainID: 43113, GasOracle: "avax", RPCUrl: "https://api.avax-test.network/ext/bc/C/rpc", ExplorerUrl: "https://testnet.snowtrace.io"}) + networkFuji, err := repos.Network.Create(model.Network{Name: "Fuji Testnet", NetworkId: 1, ChainId: 43113, GasOracle: "avax", RPCUrl: "https://api.avax-test.network/ext/bc/C/rpc", ExplorerUrl: "https://testnet.snowtrace.io"}) if err != nil { panic(err) } - networkAvalanche, err := repos.Network.Create(model.Network{Name: "Avalanche Mainnet", NetworkID: 1, ChainID: 43114, GasOracle: "avax", RPCUrl: "https://api.avax.network/ext/bc/C/rpc", ExplorerUrl: "https://snowtrace.io"}) + networkAvalanche, err := repos.Network.Create(model.Network{Name: "Avalanche Mainnet", NetworkId: 1, ChainId: 43114, GasOracle: "avax", RPCUrl: "https://api.avax.network/ext/bc/C/rpc", ExplorerUrl: "https://snowtrace.io"}) if err != nil { panic(err) } - networkNitroGoerli, err := repos.Network.Create(model.Network{Name: "Nitro Goerli Rollup Testnet", NetworkID: 421613, ChainID: 421613, GasOracle: "arb", RPCUrl: "https://goerli-rollup.arbitrum.io/rpc", ExplorerUrl: "https://goerli.arbiscan.io"}) + networkNitroGoerli, err := repos.Network.Create(model.Network{Name: "Nitro Goerli Rollup Testnet", NetworkId: 421613, ChainId: 421613, GasOracle: "arb", RPCUrl: "https://goerli-rollup.arbitrum.io/rpc", ExplorerUrl: "https://goerli.arbiscan.io"}) if err != nil { panic(err) } - networkArbitrumNova, err := repos.Network.Create(model.Network{Name: "Arbitrum Nova Mainnet", NetworkID: 42170, ChainID: 42170, GasOracle: "arb", RPCUrl: "https://nova.arbitrum.io/rpc", ExplorerUrl: "https://nova-explorer.arbitrum.io"}) + networkArbitrumNova, err := repos.Network.Create(model.Network{Name: "Arbitrum Nova Mainnet", NetworkId: 42170, ChainId: 42170, GasOracle: "arb", RPCUrl: "https://nova.arbitrum.io/rpc", ExplorerUrl: "https://nova-explorer.arbitrum.io"}) if err != nil { panic(err) } // Assets - assetAvalanche, err := repos.Asset.Create(model.Asset{Name: "AVAX", Description: "Avalanche", Decimals: 18, IsCrypto: true, NetworkID: nullString(networkAvalanche.ID), ValueOracle: nullString("avalanche-2")}) + assetAvalanche, err := repos.Asset.Create(model.Asset{Name: "AVAX", Description: "Avalanche", Decimals: 18, IsCrypto: true, NetworkId: nullString(networkAvalanche.Id), ValueOracle: nullString("avalanche-2")}) if err != nil { panic(err) } - assetEthereum, err := repos.Asset.Create(model.Asset{Name: "ETH", Description: "Ethereum", Decimals: 18, IsCrypto: true, NetworkID: nullString(networkEthereum.ID), ValueOracle: nullString("ethereum")}) + assetEthereum, err := repos.Asset.Create(model.Asset{Name: "ETH", Description: "Ethereum", Decimals: 18, IsCrypto: true, NetworkId: nullString(networkEthereum.Id), ValueOracle: nullString("ethereum")}) if err != nil { panic(err) } - assetMatic, err := repos.Asset.Create(model.Asset{Name: "MATIC", Description: "Matic", Decimals: 18, IsCrypto: true, NetworkID: nullString(networkPolygon.ID), ValueOracle: nullString("matic-network")}) + assetMatic, err := repos.Asset.Create(model.Asset{Name: "MATIC", Description: "Matic", Decimals: 18, IsCrypto: true, NetworkId: nullString(networkPolygon.Id), ValueOracle: nullString("matic-network")}) if err != nil { panic(err) } - assetGoerliEth, err := repos.Asset.Create(model.Asset{Name: "GOERLIETH", Description: "Goerli Ethereum", Decimals: 18, IsCrypto: true, NetworkID: nullString(networkNitroGoerli.ID), ValueOracle: nullString("ethereum")}) + assetGoerliEth, err := repos.Asset.Create(model.Asset{Name: "GOERLIETH", Description: "Goerli Ethereum", Decimals: 18, IsCrypto: true, NetworkId: nullString(networkNitroGoerli.Id), ValueOracle: nullString("ethereum")}) if err != nil { panic(err) } @@ -282,36 +282,36 @@ func MockSeeding() { panic(err) } - // Update Networks with GasTokenIDs - err = repos.Network.Update(networkPolygon.ID, model.NetworkUpdates{GasTokenID: &assetMatic.ID}) + // Update Networks with GasTokenIds + err = repos.Network.Update(networkPolygon.Id, model.NetworkUpdates{GasTokenId: &assetMatic.Id}) if err != nil { panic(err) } - err = repos.Network.Update(networkMumbai.ID, model.NetworkUpdates{GasTokenID: &assetMatic.ID}) + err = repos.Network.Update(networkMumbai.Id, model.NetworkUpdates{GasTokenId: &assetMatic.Id}) if err != nil { panic(err) } - err = repos.Network.Update(networkGoerli.ID, model.NetworkUpdates{GasTokenID: &assetEthereum.ID}) + err = repos.Network.Update(networkGoerli.Id, model.NetworkUpdates{GasTokenId: &assetEthereum.Id}) if err != nil { panic(err) } - err = repos.Network.Update(networkEthereum.ID, model.NetworkUpdates{GasTokenID: &assetEthereum.ID}) + err = repos.Network.Update(networkEthereum.Id, model.NetworkUpdates{GasTokenId: &assetEthereum.Id}) if err != nil { panic(err) } - err = repos.Network.Update(networkFuji.ID, model.NetworkUpdates{GasTokenID: &assetAvalanche.ID}) + err = repos.Network.Update(networkFuji.Id, model.NetworkUpdates{GasTokenId: &assetAvalanche.Id}) if err != nil { panic(err) } - err = repos.Network.Update(networkAvalanche.ID, model.NetworkUpdates{GasTokenID: &assetAvalanche.ID}) + err = repos.Network.Update(networkAvalanche.Id, model.NetworkUpdates{GasTokenId: &assetAvalanche.Id}) if err != nil { panic(err) } - err = repos.Network.Update(networkNitroGoerli.ID, model.NetworkUpdates{GasTokenID: &assetGoerliEth.ID}) + err = repos.Network.Update(networkNitroGoerli.Id, model.NetworkUpdates{GasTokenId: &assetGoerliEth.Id}) if err != nil { panic(err) } - err = repos.Network.Update(networkArbitrumNova.ID, model.NetworkUpdates{GasTokenID: &assetEthereum.ID}) + err = repos.Network.Update(networkArbitrumNova.Id, model.NetworkUpdates{GasTokenId: &assetEthereum.Id}) if err != nil { panic(err) } @@ -328,12 +328,12 @@ func MockSeeding() { panic("STRING_INTERNAL_ID is not set in ENV!") } - type UpdateID struct { - ID string `json:"id" db:"id"` + type UpdateId struct { + Id string `json:"id" db:"id"` } - updateId := UpdateID{ID: internalId} - userString, err = repos.User.Update(userString.ID, updateId) + updateId := UpdateId{Id: internalId} + userString, err = repos.User.Update(userString.Id, updateId) if err != nil { panic(err) } @@ -343,7 +343,7 @@ func MockSeeding() { // Instruments, used in TX Legs /*instrumentDeveloperCard*/ - bankString, err := repos.Instrument.Create(model.Instrument{Type: "Bank Account", Status: "Live", Network: "bankprov", PublicKey: "420481286", UserID: userString.ID}) + bankString, err := repos.Instrument.Create(model.Instrument{Type: "Bank Account", Status: "Live", Network: "bankprov", PublicKey: "420481286", UserId: userString.Id}) if err != nil { panic(err) } @@ -353,14 +353,14 @@ func MockSeeding() { panic("STRING_BANK_ID is not set in ENV!") } - updateId = UpdateID{ID: bankId} - err = repos.Instrument.Update(bankString.ID, updateId) + updateId = UpdateId{Id: bankId} + err = repos.Instrument.Update(bankString.Id, updateId) if err != nil { panic(err) } /*instrumentDeveloperWallet*/ - walletString, err := repos.Instrument.Create(model.Instrument{Type: "Crypto Wallet", Status: "Internal", Network: "EVM", PublicKey: stringPublicAddress, UserID: userString.ID}) + walletString, err := repos.Instrument.Create(model.Instrument{Type: "Crypto Wallet", Status: "Internal", Network: "EVM", PublicKey: stringPublicAddress, UserId: userString.Id}) if err != nil { panic(err) } @@ -370,8 +370,8 @@ func MockSeeding() { panic("STRING_WALLET_ID is not set in ENV!") } - updateId = UpdateID{ID: walletId} - err = repos.Instrument.Update(walletString.ID, updateId) + updateId = UpdateId{Id: walletId} + err = repos.Instrument.Update(walletString.Id, updateId) if err != nil { panic(err) } @@ -388,8 +388,8 @@ func MockSeeding() { panic("STRING_PLACEHOLDER_PLATFORM_ID is not set in ENV!") } - updateId = UpdateID{ID: platformId} - err = repos.Platform.Update(placeholderPlatform.ID, updateId) + updateId = UpdateId{Id: platformId} + err = repos.Platform.Update(placeholderPlatform.Id, updateId) if err != nil { panic(err) }