Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Restrict orders to enabled networks #424

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 12 additions & 5 deletions controllers/sender/sender.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,16 +74,23 @@ func (ctrl *SenderController) InitiatePaymentOrder(ctx *gin.Context) {
Query().
Where(
tokenEnt.SymbolEQ(payload.Token),
tokenEnt.HasNetworkWith(network.IdentifierEQ(payload.Network)),
tokenEnt.HasNetworkWith(
network.IdentifierEQ(payload.Network),
network.IsEnabledEQ(true),
),
tokenEnt.IsEnabledEQ(true),
).
WithNetwork().
Only(ctx)
if err != nil {
u.APIResponse(ctx, http.StatusBadRequest, "error", "Failed to validate payload", types.ErrorData{
Field: "Token",
Message: "Provided token is not supported",
})
if ent.IsNotFound(err) {
u.APIResponse(ctx, http.StatusBadRequest, "error", "Failed to validate payload", types.ErrorData{
Field: "Token",
Message: "Provided token is not supported",
})
} else {
u.APIResponse(ctx, http.StatusInternalServerError, "error", "Internal server error", nil)
}
return
}

Expand Down
153 changes: 100 additions & 53 deletions controllers/sender/sender_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ func setup() error {
if err != nil {
return err
}

testCtx.apiKey = apiKey

testCtx.token = token
Expand All @@ -109,17 +110,19 @@ func setup() error {

func TestSender(t *testing.T) {

ctx := context.Background()

// Set up test database client
client := enttest.Open(t, "sqlite3", "file:ent?mode=memory&_fk=1")
defer client.Close()
defer client.Close()

db.Client = client

// Setup test data
err := setup()
assert.NoError(t, err)

senderTokens, err := client.SenderOrderToken.Query().All(context.Background())
senderTokens, err := client.SenderOrderToken.Query().All(ctx)
assert.NoError(t, err)
assert.Greater(t, len(senderTokens), 0)

Expand All @@ -136,14 +139,12 @@ func TestSender(t *testing.T) {
router.GET("/sender/stats", ctrl.Stats)

var paymentOrderUUID uuid.UUID

t.Run("InitiatePaymentOrder", func(t *testing.T) {

// Fetch network from db
network, err := db.Client.Network.
Query().
Where(network.IdentifierEQ(testCtx.networkIdentifier)).
Only(context.Background())
Only(ctx)
assert.NoError(t, err)

payload := map[string]interface{}{
Expand All @@ -164,69 +165,115 @@ func TestSender(t *testing.T) {
"API-Key": testCtx.apiKey.ID.String(),
}

res, err := test.PerformRequest(t, "POST", "/sender/orders", payload, headers, router)
assert.NoError(t, err)
t.Run("Should fail when network is disabled", func(t *testing.T) {
// Temporarily disable the network
_, err = db.Client.Network.UpdateOne(network).
SetIsEnabled(false).
Save(ctx)
assert.NoError(t, err)

// Assert the response body
assert.Equal(t, http.StatusCreated, res.Code)
res, err := test.PerformRequest(t, "POST", "/sender/orders", payload, headers, router)
assert.NoError(t, err)

var response types.Response
err = json.Unmarshal(res.Body.Bytes(), &response)
assert.NoError(t, err)
assert.Equal(t, "Payment order initiated successfully", response.Message)
data, ok := response.Data.(map[string]interface{})
assert.True(t, ok, "response.Data is not of type map[string]interface{}")
assert.NotNil(t, data, "response.Data is nil")
// Assert the response body
assert.Equal(t, http.StatusBadRequest, res.Code)

assert.Equal(t, data["amount"], payload["amount"])
assert.Equal(t, data["network"], payload["network"])
assert.Equal(t, data["reference"], payload["reference"])
assert.NotEmpty(t, data["validUntil"])
var response types.Response
err = json.Unmarshal(res.Body.Bytes(), &response)
assert.NoError(t, err)
assert.Equal(t, "Failed to validate payload", response.Message)

// Parse the payment order ID string to uuid.UUID
paymentOrderUUID, err = uuid.Parse(data["id"].(string))
assert.NoError(t, err)
errorData, ok := response.Data.(map[string]interface{})
assert.True(t, ok, "response.Data is not of type map[string]interface{}")
assert.Equal(t, "Token", errorData["field"])
assert.Equal(t, "Provided token is not supported", errorData["message"])

// Query the database for the payment order
paymentOrder, err := db.Client.PaymentOrder.
Query().
Where(paymentorder.IDEQ(paymentOrderUUID)).
WithRecipient().
Only(context.Background())
assert.NoError(t, err)
// Re-enable the network for subsequent tests
_, err = db.Client.Network.UpdateOne(network).
SetIsEnabled(true).
Save(ctx)
assert.NoError(t, err)
})

assert.NotNil(t, paymentOrder.Edges.Recipient)
assert.Equal(t, paymentOrder.Edges.Recipient.AccountIdentifier, payload["recipient"].(map[string]interface{})["accountIdentifier"])
assert.Equal(t, paymentOrder.Edges.Recipient.Memo, payload["recipient"].(map[string]interface{})["memo"])
assert.Equal(t, paymentOrder.Edges.Recipient.AccountName, payload["recipient"].(map[string]interface{})["accountName"])
assert.Equal(t, paymentOrder.Edges.Recipient.Institution, payload["recipient"].(map[string]interface{})["institution"])
assert.Equal(t, data["senderFee"], "5")
assert.Equal(t, data["transactionFee"], network.Fee.String())
t.Run("Should succeed when network is enabled", func(t *testing.T) {
res, err := test.PerformRequest(t, "POST", "/sender/orders", payload, headers, router)
assert.NoError(t, err)

t.Run("Check Transaction Logs", func(t *testing.T) {
headers := map[string]string{
"API-Key": testCtx.apiKey.ID.String(),
}
// Assert the response body
assert.Equal(t, http.StatusCreated, res.Code)

res, err = test.PerformRequest(t, "GET", fmt.Sprintf("/sender/orders/%s?timestamp=%v", paymentOrderUUID.String(), payload["timestamp"]), nil, headers, router)
var response types.Response
err = json.Unmarshal(res.Body.Bytes(), &response)
assert.NoError(t, err)
assert.Equal(t, "Payment order initiated successfully", response.Message)
data, ok := response.Data.(map[string]interface{})
assert.True(t, ok, "response.Data is not of type map[string]interface{}")
assert.NotNil(t, data, "response.Data is nil")

type Response struct {
Status string `json:"status"`
Message string `json:"message"`
Data types.PaymentOrderResponse `json:"data"`
}
assert.Equal(t, data["amount"], payload["amount"])
assert.Equal(t, data["network"], payload["network"])
assert.Equal(t, data["reference"], payload["reference"])
assert.NotEmpty(t, data["validUntil"])

var response2 Response
// Assert the response body
assert.Equal(t, http.StatusOK, res.Code)
// Parse the payment order ID string to uuid.UUID
paymentOrderUUID, err = uuid.Parse(data["id"].(string))
assert.NoError(t, err)

err = json.Unmarshal(res.Body.Bytes(), &response2)
// Query the database for the payment order
paymentOrder, err := db.Client.PaymentOrder.
Query().
Where(paymentorder.IDEQ(paymentOrderUUID)).
WithRecipient().
Only(ctx)
assert.NoError(t, err)
assert.Equal(t, "The order has been successfully retrieved", response2.Message)
assert.Equal(t, 1, len(response2.Data.Transactions), "response.Data is nil")

assert.NotNil(t, paymentOrder.Edges.Recipient)
assert.Equal(t, paymentOrder.Edges.Recipient.AccountIdentifier, payload["recipient"].(map[string]interface{})["accountIdentifier"])
assert.Equal(t, paymentOrder.Edges.Recipient.Memo, payload["recipient"].(map[string]interface{})["memo"])
assert.Equal(t, paymentOrder.Edges.Recipient.AccountName, payload["recipient"].(map[string]interface{})["accountName"])
assert.Equal(t, paymentOrder.Edges.Recipient.Institution, payload["recipient"].(map[string]interface{})["institution"])
assert.Equal(t, data["senderFee"], "5")
assert.Equal(t, data["transactionFee"], network.Fee.String())

t.Run("Check Transaction Logs", func(t *testing.T) {
headers := map[string]string{
"API-Key": testCtx.apiKey.ID.String(),
}

res, err = test.PerformRequest(t, "GET", fmt.Sprintf("/sender/orders/%s?timestamp=%v", paymentOrderUUID.String(), payload["timestamp"]), nil, headers, router)
assert.NoError(t, err)

type Response struct {
Status string `json:"status"`
Message string `json:"message"`
Data types.PaymentOrderResponse `json:"data"`
}

var response2 Response
// Assert the response body
assert.Equal(t, http.StatusOK, res.Code)

err = json.Unmarshal(res.Body.Bytes(), &response2)
assert.NoError(t, err)
assert.Equal(t, "The order has been successfully retrieved", response2.Message)
assert.Equal(t, 1, len(response2.Data.Transactions), "response.Data is nil")
})
})

t.Run("New networks should have is_enabled default to false", func(t *testing.T) {
newNetwork, err := db.Client.Network.
Create().
SetChainID(1).
SetIdentifier("bnb-smart-chain").
SetRPCEndpoint("https://testnet.rpc.url").
SetIdentifier("bnb-smart-chain").
SetIsTestnet(true).
SetFee(decimal.NewFromFloat(0.01)).
Save(ctx)
assert.NoError(t, err)

assert.False(t, newNetwork.IsEnabled, "is_enabled should default to false")
})
})

t.Run("GetPaymentOrderByID", func(t *testing.T) {
Expand Down
1 change: 1 addition & 0 deletions ent/migrate/schema.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

56 changes: 55 additions & 1 deletion ent/mutation.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

13 changes: 12 additions & 1 deletion ent/network.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading