Compare commits
11 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7c36f3c214 | ||
|
|
37ff644aa7 | ||
|
|
c80ed89c0a | ||
|
|
6590cbf4be | ||
|
|
61a8c5fe8b | ||
|
|
c79136a06e | ||
|
|
a5590a438f | ||
|
|
1c196cae9f | ||
|
|
c494bf5f53 | ||
|
|
d07dc971fe | ||
|
|
b1e63a24c7 |
1
.gitignore
vendored
1
.gitignore
vendored
@@ -42,3 +42,4 @@ Prompts/
|
||||
|
||||
# Logs
|
||||
*.log
|
||||
.claude
|
||||
|
||||
21
README.md
21
README.md
@@ -1,9 +1,8 @@
|
||||
# Koin Ping
|
||||
A lightweight on-chain monitoring and alerting system designed to give users situational awareness over blockchain addresses they care about.
|
||||
|
||||
Koin Ping is an MIT-licensed blockchain monitoring system by Steven Jannette
|
||||
that polls Ethereum addresses for on-chain activity and delivers real-time
|
||||
alerts to users via a Go REST API backend and a React single-page application
|
||||
frontend.
|
||||
# Overview
|
||||
Koin Ping observes on-chain activity and notifies users when predefined conditions are met. It does not execute transactions, manage wallets, or speculate on prices.
|
||||
|
||||
## Getting Started
|
||||
|
||||
@@ -99,20 +98,6 @@ to the database, and dispatches Discord notifications.
|
||||
Firebase, communicates with the API via fetch, and renders the address/alert
|
||||
management UI.
|
||||
|
||||
## TODO
|
||||
|
||||
- [ ] Switch frontend package manager from npm to yarn (per repo policy)
|
||||
- [ ] Rename `go.mod` module path from `github.com/kjannette/koin-ping` to
|
||||
`sneak.berlin/go/koin-ping` (per repo policy)
|
||||
- [ ] Move database migrations to `internal/db/migrations/` and embed them in
|
||||
the binary
|
||||
- [ ] Pin all Docker base images by `@sha256` in Dockerfile
|
||||
- [ ] Install `golangci-lint` locally and pass `make lint`
|
||||
- [ ] Add vitest unit tests for the React frontend
|
||||
- [ ] Add a `make db-reset` / `make migrate` target for schema management
|
||||
- [ ] Set HTTP server read/write timeouts (currently unbounded)
|
||||
- [ ] Replace `log.Printf` calls with structured `log/slog`
|
||||
|
||||
## License
|
||||
|
||||
MIT. See [LICENSE](LICENSE).
|
||||
|
||||
@@ -14,3 +14,7 @@ POLL_INTERVAL_MS=60000
|
||||
|
||||
# Firebase
|
||||
FIREBASE_PROJECT_ID=koin-ping
|
||||
|
||||
# Email notifications (Resend — https://resend.com)
|
||||
# RESEND_API_KEY=re_xxxxxxxxxxxx
|
||||
# EMAIL_FROM=Koin Ping <alerts@yourdomain.com>
|
||||
|
||||
@@ -14,12 +14,13 @@ import (
|
||||
"github.com/kjannette/koin-ping/backend-go/internal/handlers"
|
||||
"github.com/kjannette/koin-ping/backend-go/internal/middleware"
|
||||
"github.com/kjannette/koin-ping/backend-go/internal/models"
|
||||
"github.com/kjannette/koin-ping/backend-go/internal/services"
|
||||
)
|
||||
|
||||
const (
|
||||
// serverReadTimeoutSeconds is the maximum duration to read a request.
|
||||
// max duration to read a request.
|
||||
serverReadTimeoutSeconds = 5
|
||||
// serverWriteTimeoutSeconds is the maximum duration to write a response.
|
||||
// maxiduration to write a response.
|
||||
serverWriteTimeoutSeconds = 10
|
||||
)
|
||||
|
||||
@@ -46,19 +47,26 @@ func main() {
|
||||
addressModel := models.NewAddressModel(pool)
|
||||
alertRuleModel := models.NewAlertRuleModel(pool)
|
||||
alertEventModel := models.NewAlertEventModel(pool)
|
||||
checkpointModel := models.NewCheckpointModel(pool)
|
||||
notifConfigModel := models.NewNotificationConfigModel(pool)
|
||||
|
||||
emailDigestSvc := services.NewEmailDigestService(
|
||||
cfg.ResendAPIKey, cfg.EmailFrom, alertEventModel, notifConfigModel,
|
||||
)
|
||||
|
||||
addressHandler := handlers.NewAddressHandler(addressModel)
|
||||
alertRuleHandler := handlers.NewAlertRuleHandler(alertRuleModel, addressModel)
|
||||
alertEventHandler := handlers.NewAlertEventHandler(alertEventModel)
|
||||
notifConfigHandler := handlers.NewNotificationConfigHandler(notifConfigModel)
|
||||
notifConfigHandler := handlers.NewNotificationConfigHandler(notifConfigModel, cfg)
|
||||
emailDigestHandler := handlers.NewEmailDigestHandler(emailDigestSvc, notifConfigModel)
|
||||
statusHandler := handlers.NewStatusHandler(checkpointModel)
|
||||
|
||||
mux := http.NewServeMux()
|
||||
b := cfg.APIBasePath // e.g. "/v1"
|
||||
|
||||
// Public routes
|
||||
mux.HandleFunc("GET "+b+"/health", handlers.HealthCheck)
|
||||
mux.HandleFunc("GET "+b+"/status", handlers.SystemStatus)
|
||||
mux.HandleFunc("GET "+b+"/status", statusHandler.GetStatus)
|
||||
|
||||
// Authenticated routes — addresses
|
||||
mux.Handle("POST "+b+"/addresses",
|
||||
@@ -67,8 +75,10 @@ func main() {
|
||||
middleware.Authenticate(http.HandlerFunc(addressHandler.List)))
|
||||
mux.Handle("DELETE "+b+"/addresses/{addressId}",
|
||||
middleware.Authenticate(http.HandlerFunc(addressHandler.Remove)))
|
||||
mux.Handle("PATCH "+b+"/addresses/{addressId}",
|
||||
middleware.Authenticate(http.HandlerFunc(addressHandler.UpdateLabel)))
|
||||
|
||||
// Authenticated routes — alert rules
|
||||
// Authenticated routes for alert rules
|
||||
mux.Handle("POST "+b+"/addresses/{addressId}/alerts",
|
||||
middleware.Authenticate(http.HandlerFunc(alertRuleHandler.Create)))
|
||||
mux.Handle("GET "+b+"/addresses/{addressId}/alerts",
|
||||
@@ -89,6 +99,14 @@ func main() {
|
||||
middleware.Authenticate(http.HandlerFunc(notifConfigHandler.UpdateConfig)))
|
||||
mux.Handle("DELETE "+b+"/notification-config",
|
||||
middleware.Authenticate(http.HandlerFunc(notifConfigHandler.DeleteConfig)))
|
||||
mux.Handle("POST "+b+"/notification-config/test",
|
||||
middleware.Authenticate(http.HandlerFunc(notifConfigHandler.TestChannels)))
|
||||
|
||||
// Authenticated routes — email digest
|
||||
mux.Handle("POST "+b+"/email/setup",
|
||||
middleware.Authenticate(http.HandlerFunc(emailDigestHandler.SetupEmail)))
|
||||
mux.Handle("POST "+b+"/email/digest",
|
||||
middleware.Authenticate(http.HandlerFunc(emailDigestHandler.SendDigest)))
|
||||
|
||||
handler := corsMiddleware(mux)
|
||||
|
||||
|
||||
@@ -58,7 +58,11 @@ func main() {
|
||||
notifConfigModel := models.NewNotificationConfigModel(pool)
|
||||
|
||||
observer := services.NewObserverService(eth, addressModel, checkpointModel)
|
||||
evaluator := services.NewEvaluatorService(eth, alertRuleModel, alertEventModel, addressModel, notifConfigModel)
|
||||
evaluator := services.NewEvaluatorService(
|
||||
eth, alertRuleModel, alertEventModel, addressModel, notifConfigModel,
|
||||
cfg.ResendAPIKey, cfg.EmailFrom,
|
||||
)
|
||||
digestSvc := services.NewEmailDigestService(cfg.ResendAPIKey, cfg.EmailFrom, alertEventModel, notifConfigModel)
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
@@ -75,12 +79,14 @@ func main() {
|
||||
}()
|
||||
|
||||
interval := time.Duration(cfg.PollIntervalMS) * time.Millisecond
|
||||
digestInterval := time.Duration(cfg.DigestIntervalHours) * time.Hour
|
||||
|
||||
log.Println(strings.Repeat("=", separatorWidth))
|
||||
log.Println("Koin Ping Observer Poller Starting")
|
||||
log.Println(strings.Repeat("=", separatorWidth))
|
||||
log.Printf("RPC URL: %s", cfg.EthRPCURL)
|
||||
log.Printf("Poll Interval: %dms (%ds)", cfg.PollIntervalMS, cfg.PollIntervalMS/msPerSecond)
|
||||
log.Printf("Digest Interval: %dh", cfg.DigestIntervalHours)
|
||||
log.Println(strings.Repeat("=", separatorWidth))
|
||||
|
||||
runCycle(ctx, observer, evaluator)
|
||||
@@ -88,6 +94,9 @@ func main() {
|
||||
ticker := time.NewTicker(interval)
|
||||
defer ticker.Stop()
|
||||
|
||||
digestTicker := time.NewTicker(digestInterval)
|
||||
defer digestTicker.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
@@ -96,6 +105,13 @@ func main() {
|
||||
return
|
||||
case <-ticker.C:
|
||||
runCycle(ctx, observer, evaluator)
|
||||
case <-digestTicker.C:
|
||||
sent, digestErr := digestSvc.SendDigestsForAllUsers(ctx)
|
||||
if digestErr != nil {
|
||||
log.Printf("Email digest failed: %v", digestErr)
|
||||
} else {
|
||||
log.Printf("Sent %d email digests", sent)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,6 +42,7 @@ require (
|
||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||
github.com/joho/godotenv v1.5.1 // indirect
|
||||
github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10 // indirect
|
||||
github.com/resend/resend-go/v3 v3.1.1 // indirect
|
||||
github.com/spiffe/go-spiffe/v2 v2.6.0 // indirect
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
|
||||
go.opentelemetry.io/contrib/detectors/gcp v1.39.0 // indirect
|
||||
|
||||
@@ -92,6 +92,8 @@ github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10/go.mod h1
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/resend/resend-go/v3 v3.1.1 h1:Uwpf/tZU+O/r/3nMWE6zUAMIG9dX/vTBS3wlQzYJKSw=
|
||||
github.com/resend/resend-go/v3 v3.1.1/go.mod h1:iI7VA0NoGjWvsNii5iNC5Dy0llsI3HncXPejhniYzwE=
|
||||
github.com/spiffe/go-spiffe/v2 v2.6.0 h1:l+DolpxNWYgruGQVV0xsfeya3CsC7m8iBzDnMpsbLuo=
|
||||
github.com/spiffe/go-spiffe/v2 v2.6.0/go.mod h1:gm2SeUoMZEtpnzPNs2Csc0D/gX33k1xIx7lEzqblHEs=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
|
||||
2
backend-go/infra/migrations/003_add_slack_webhook.sql
Normal file
2
backend-go/infra/migrations/003_add_slack_webhook.sql
Normal file
@@ -0,0 +1,2 @@
|
||||
ALTER TABLE user_notification_configs
|
||||
ADD COLUMN IF NOT EXISTS slack_webhook_url TEXT;
|
||||
3
backend-go/infra/migrations/004_alert_event_dedup.sql
Normal file
3
backend-go/infra/migrations/004_alert_event_dedup.sql
Normal file
@@ -0,0 +1,3 @@
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_alert_events_dedup
|
||||
ON alert_events (alert_rule_id, tx_hash)
|
||||
WHERE tx_hash IS NOT NULL;
|
||||
@@ -54,8 +54,9 @@ CREATE TABLE user_notification_configs (
|
||||
user_id VARCHAR(128) PRIMARY KEY,
|
||||
discord_webhook_url TEXT, -- Discord webhook URL (nullable)
|
||||
telegram_chat_id VARCHAR(128), -- Telegram chat ID (nullable)
|
||||
telegram_bot_token VARCHAR(255), -- Telegram bot token (nullable, future use)
|
||||
telegram_bot_token VARCHAR(255), -- Telegram bot token (nullable)
|
||||
email VARCHAR(255), -- Email for notifications (nullable)
|
||||
slack_webhook_url TEXT, -- Slack incoming webhook URL (nullable)
|
||||
notification_enabled BOOLEAN DEFAULT TRUE, -- Master on/off switch
|
||||
created_at TIMESTAMP DEFAULT NOW(),
|
||||
updated_at TIMESTAMP DEFAULT NOW()
|
||||
|
||||
@@ -13,6 +13,7 @@ const (
|
||||
defaultDBPort = 5432
|
||||
defaultPollIntervalMS = 60000
|
||||
minPollIntervalMS = 1000
|
||||
defaultDigestIntervalHours = 24
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
@@ -28,6 +29,9 @@ type Config struct {
|
||||
EthRPCURL string
|
||||
PollIntervalMS int
|
||||
NodeEnv string
|
||||
ResendAPIKey string
|
||||
EmailFrom string
|
||||
DigestIntervalHours int
|
||||
}
|
||||
|
||||
// Load reads configuration from environment variables and returns a Config.
|
||||
@@ -45,6 +49,9 @@ func Load() (*Config, error) {
|
||||
EthRPCURL: os.Getenv("ETH_RPC_URL"),
|
||||
PollIntervalMS: getEnvInt("POLL_INTERVAL_MS", defaultPollIntervalMS),
|
||||
NodeEnv: getEnv("NODE_ENV", "development"),
|
||||
ResendAPIKey: os.Getenv("RESEND_API_KEY"),
|
||||
EmailFrom: getEnv("EMAIL_FROM", "Koin Ping <alerts@koinping.com>"),
|
||||
DigestIntervalHours: getEnvInt("DIGEST_INTERVAL_HOURS", defaultDigestIntervalHours),
|
||||
}
|
||||
|
||||
if cfg.PollIntervalMS < minPollIntervalMS {
|
||||
|
||||
@@ -103,8 +103,9 @@ type NotificationConfig struct {
|
||||
UserID string `json:"user_id"` //nolint:tagliatelle
|
||||
DiscordWebhookURL *string `json:"discord_webhook_url"` //nolint:tagliatelle
|
||||
TelegramChatID *string `json:"telegram_chat_id"` //nolint:tagliatelle
|
||||
TelegramBotToken *string `json:"telegram_bot_token,omitempty"` //nolint:tagliatelle
|
||||
TelegramBotToken *string `json:"telegram_bot_token"` //nolint:tagliatelle
|
||||
Email *string `json:"email"`
|
||||
SlackWebhookURL *string `json:"slack_webhook_url"` //nolint:tagliatelle
|
||||
NotificationEnabled bool `json:"notification_enabled"` //nolint:tagliatelle
|
||||
CreatedAt *time.Time `json:"created_at,omitempty"` //nolint:tagliatelle
|
||||
UpdatedAt *time.Time `json:"updated_at,omitempty"` //nolint:tagliatelle
|
||||
|
||||
@@ -92,6 +92,44 @@ func (h *AddressHandler) List(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, addresses)
|
||||
}
|
||||
|
||||
// UpdateLabel handles PATCH requests to update an address label.
|
||||
func (h *AddressHandler) UpdateLabel(w http.ResponseWriter, r *http.Request) {
|
||||
userID := middleware.GetUserID(r.Context())
|
||||
addressID, ok := parseIntParam(r.PathValue("addressId"))
|
||||
if !ok {
|
||||
writeError(w, http.StatusBadRequest, "VALIDATION_ERROR", "Invalid address ID")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
var body struct {
|
||||
Label *string `json:"label"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "VALIDATION_ERROR", "Invalid request body")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
log.Printf("User %s updating label for address ID: %d", userID, addressID)
|
||||
|
||||
addr, err := h.addresses.UpdateLabel(r.Context(), addressID, userID, body.Label)
|
||||
if err != nil {
|
||||
log.Printf("Error updating address label: %v", err)
|
||||
writeError(w, http.StatusInternalServerError, "INTERNAL_ERROR", "Failed to update address")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if addr == nil {
|
||||
writeError(w, http.StatusNotFound, "NOT_FOUND", "Address not found")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, addr)
|
||||
}
|
||||
|
||||
// Remove handles DELETE requests to remove a tracked address.
|
||||
func (h *AddressHandler) Remove(w http.ResponseWriter, r *http.Request) {
|
||||
userID := middleware.GetUserID(r.Context())
|
||||
|
||||
@@ -4,7 +4,6 @@ import (
|
||||
"log"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/kjannette/koin-ping/backend-go/internal/domain"
|
||||
"github.com/kjannette/koin-ping/backend-go/internal/middleware"
|
||||
@@ -51,45 +50,9 @@ func (h *AlertEventHandler) List(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
log.Printf("Found %d alert events for user", len(events))
|
||||
|
||||
// MVP scaffolding: return mock data if DB is empty
|
||||
if len(events) == 0 {
|
||||
events = mockEvents(limit)
|
||||
if events == nil {
|
||||
events = []domain.AlertEvent{}
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, events)
|
||||
}
|
||||
|
||||
func mockEvents(limit int) []domain.AlertEvent {
|
||||
label1 := "Treasury Wallet"
|
||||
label2 := "Cold Storage"
|
||||
|
||||
mocks := []domain.AlertEvent{
|
||||
{
|
||||
ID: 1,
|
||||
AlertRuleID: 1,
|
||||
Message: "Incoming transaction detected: 5.5 ETH received",
|
||||
AddressLabel: &label1,
|
||||
Timestamp: time.Now().Add(-2 * time.Hour),
|
||||
},
|
||||
{
|
||||
ID: 2, //nolint:mnd
|
||||
AlertRuleID: 2, //nolint:mnd
|
||||
Message: "Balance dropped below threshold: Current balance 8.2 ETH",
|
||||
AddressLabel: &label1,
|
||||
Timestamp: time.Now().Add(-5 * time.Hour),
|
||||
},
|
||||
{
|
||||
ID: 3, //nolint:mnd
|
||||
AlertRuleID: 3, //nolint:mnd
|
||||
Message: "Outgoing transaction detected: 2.0 ETH sent",
|
||||
AddressLabel: &label2,
|
||||
Timestamp: time.Now().Add(-24 * time.Hour),
|
||||
},
|
||||
}
|
||||
|
||||
if limit < len(mocks) {
|
||||
return mocks[:limit]
|
||||
}
|
||||
|
||||
return mocks
|
||||
}
|
||||
|
||||
101
backend-go/internal/handlers/email_digest.go
Normal file
101
backend-go/internal/handlers/email_digest.go
Normal file
@@ -0,0 +1,101 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"github.com/kjannette/koin-ping/backend-go/internal/middleware"
|
||||
"github.com/kjannette/koin-ping/backend-go/internal/models"
|
||||
"github.com/kjannette/koin-ping/backend-go/internal/services"
|
||||
)
|
||||
|
||||
type EmailDigestHandler struct {
|
||||
digestSvc *services.EmailDigestService
|
||||
configs *models.NotificationConfigModel
|
||||
}
|
||||
|
||||
func NewEmailDigestHandler(
|
||||
digestSvc *services.EmailDigestService,
|
||||
configs *models.NotificationConfigModel,
|
||||
) *EmailDigestHandler {
|
||||
return &EmailDigestHandler{digestSvc: digestSvc, configs: configs}
|
||||
}
|
||||
|
||||
// SetupEmail reads the user's email from their notification config and sends
|
||||
// a confirmation message via Resend to verify the integration works.
|
||||
func (h *EmailDigestHandler) SetupEmail(w http.ResponseWriter, r *http.Request) {
|
||||
userID := middleware.GetUserID(r.Context())
|
||||
|
||||
if !h.digestSvc.Configured() {
|
||||
writeError(w, http.StatusServiceUnavailable, "EMAIL_NOT_CONFIGURED",
|
||||
"Email service is not configured on the server")
|
||||
return
|
||||
}
|
||||
|
||||
cfg, err := h.configs.GetConfig(r.Context(), userID)
|
||||
if err != nil {
|
||||
log.Printf("Error getting notification config for email setup: %v", err)
|
||||
writeError(w, http.StatusInternalServerError, "INTERNAL_ERROR",
|
||||
"Failed to load notification config")
|
||||
return
|
||||
}
|
||||
|
||||
if cfg == nil || cfg.Email == nil || *cfg.Email == "" {
|
||||
writeError(w, http.StatusBadRequest, "VALIDATION_ERROR",
|
||||
"Save an email address in notification settings first")
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.digestSvc.SetupEmail(*cfg.Email); err != nil {
|
||||
log.Printf("Email setup failed for user %s: %v", userID, err)
|
||||
writeError(w, http.StatusBadGateway, "EMAIL_SEND_FAILED",
|
||||
"Failed to send confirmation email — check server email config")
|
||||
return
|
||||
}
|
||||
|
||||
log.Printf("Email setup confirmation sent to user %s (%s)", userID, *cfg.Email)
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"success": true,
|
||||
"email": *cfg.Email,
|
||||
"message": "Confirmation email sent",
|
||||
})
|
||||
}
|
||||
|
||||
// SendDigest compiles and sends a digest of recent alerts to the user's email.
|
||||
func (h *EmailDigestHandler) SendDigest(w http.ResponseWriter, r *http.Request) {
|
||||
userID := middleware.GetUserID(r.Context())
|
||||
|
||||
if !h.digestSvc.Configured() {
|
||||
writeError(w, http.StatusServiceUnavailable, "EMAIL_NOT_CONFIGURED",
|
||||
"Email service is not configured on the server")
|
||||
return
|
||||
}
|
||||
|
||||
cfg, err := h.configs.GetConfig(r.Context(), userID)
|
||||
if err != nil {
|
||||
log.Printf("Error getting notification config for digest: %v", err)
|
||||
writeError(w, http.StatusInternalServerError, "INTERNAL_ERROR",
|
||||
"Failed to load notification config")
|
||||
return
|
||||
}
|
||||
|
||||
if cfg == nil || cfg.Email == nil || *cfg.Email == "" {
|
||||
writeError(w, http.StatusBadRequest, "VALIDATION_ERROR",
|
||||
"No email address configured")
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.digestSvc.SendDigest(r.Context(), userID, *cfg.Email); err != nil {
|
||||
log.Printf("Digest send failed for user %s: %v", userID, err)
|
||||
writeError(w, http.StatusBadGateway, "DIGEST_SEND_FAILED",
|
||||
"Failed to send digest email")
|
||||
return
|
||||
}
|
||||
|
||||
log.Printf("Digest sent to user %s (%s)", userID, *cfg.Email)
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"success": true,
|
||||
"email": *cfg.Email,
|
||||
"message": "Digest email sent",
|
||||
})
|
||||
}
|
||||
@@ -7,19 +7,22 @@ import (
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/kjannette/koin-ping/backend-go/internal/config"
|
||||
"github.com/kjannette/koin-ping/backend-go/internal/domain"
|
||||
"github.com/kjannette/koin-ping/backend-go/internal/middleware"
|
||||
"github.com/kjannette/koin-ping/backend-go/internal/models"
|
||||
"github.com/kjannette/koin-ping/backend-go/internal/notifications"
|
||||
)
|
||||
|
||||
var emailRe = regexp.MustCompile(`^[^\s@]+@[^\s@]+\.[^\s@]+$`)
|
||||
|
||||
type NotificationConfigHandler struct {
|
||||
configs *models.NotificationConfigModel
|
||||
cfg *config.Config
|
||||
}
|
||||
|
||||
func NewNotificationConfigHandler(configs *models.NotificationConfigModel) *NotificationConfigHandler {
|
||||
return &NotificationConfigHandler{configs: configs}
|
||||
func NewNotificationConfigHandler(configs *models.NotificationConfigModel, cfg *config.Config) *NotificationConfigHandler {
|
||||
return &NotificationConfigHandler{configs: configs, cfg: cfg}
|
||||
}
|
||||
|
||||
func (h *NotificationConfigHandler) GetConfig(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -51,7 +54,9 @@ func (h *NotificationConfigHandler) UpdateConfig(w http.ResponseWriter, r *http.
|
||||
var body struct {
|
||||
DiscordWebhookURL *string `json:"discord_webhook_url"`
|
||||
TelegramChatID *string `json:"telegram_chat_id"`
|
||||
TelegramBotToken *string `json:"telegram_bot_token"`
|
||||
Email *string `json:"email"`
|
||||
SlackWebhookURL *string `json:"slack_webhook_url"`
|
||||
NotificationEnabled *bool `json:"notification_enabled"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
@@ -63,7 +68,8 @@ func (h *NotificationConfigHandler) UpdateConfig(w http.ResponseWriter, r *http.
|
||||
log.Printf("User %s updating notification config", userID)
|
||||
|
||||
if body.DiscordWebhookURL == nil && body.TelegramChatID == nil &&
|
||||
body.Email == nil && body.NotificationEnabled == nil {
|
||||
body.TelegramBotToken == nil && body.Email == nil &&
|
||||
body.SlackWebhookURL == nil && body.NotificationEnabled == nil {
|
||||
writeError(w, http.StatusBadRequest, "VALIDATION_ERROR",
|
||||
"At least one configuration field must be provided")
|
||||
return
|
||||
@@ -76,6 +82,13 @@ func (h *NotificationConfigHandler) UpdateConfig(w http.ResponseWriter, r *http.
|
||||
return
|
||||
}
|
||||
|
||||
if body.SlackWebhookURL != nil && *body.SlackWebhookURL != "" &&
|
||||
!strings.HasPrefix(*body.SlackWebhookURL, "https://hooks.slack.com/") {
|
||||
writeError(w, http.StatusBadRequest, "VALIDATION_ERROR",
|
||||
"Invalid Slack webhook URL format")
|
||||
return
|
||||
}
|
||||
|
||||
if body.Email != nil && *body.Email != "" && !emailRe.MatchString(*body.Email) {
|
||||
writeError(w, http.StatusBadRequest, "VALIDATION_ERROR",
|
||||
"Invalid email address format")
|
||||
@@ -90,7 +103,9 @@ func (h *NotificationConfigHandler) UpdateConfig(w http.ResponseWriter, r *http.
|
||||
cfg := domain.NotificationConfig{
|
||||
DiscordWebhookURL: body.DiscordWebhookURL,
|
||||
TelegramChatID: body.TelegramChatID,
|
||||
TelegramBotToken: body.TelegramBotToken,
|
||||
Email: body.Email,
|
||||
SlackWebhookURL: body.SlackWebhookURL,
|
||||
NotificationEnabled: enabled,
|
||||
}
|
||||
|
||||
@@ -126,3 +141,76 @@ func (h *NotificationConfigHandler) DeleteConfig(w http.ResponseWriter, r *http.
|
||||
log.Println("Notification config deleted")
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// TestChannels sends a test message to all configured notification channels.
|
||||
func (h *NotificationConfigHandler) TestChannels(w http.ResponseWriter, r *http.Request) {
|
||||
userID := middleware.GetUserID(r.Context())
|
||||
log.Printf("User %s testing notification channels", userID)
|
||||
|
||||
cfg, err := h.configs.GetConfig(r.Context(), userID)
|
||||
if err != nil {
|
||||
log.Printf("Error getting notification config for test: %v", err)
|
||||
writeError(w, http.StatusInternalServerError, "INTERNAL_ERROR", "Failed to get notification config")
|
||||
return
|
||||
}
|
||||
|
||||
if cfg == nil {
|
||||
writeError(w, http.StatusNotFound, "NOT_FOUND", "No notification configuration found")
|
||||
return
|
||||
}
|
||||
|
||||
type channelResult struct {
|
||||
Channel string `json:"channel"`
|
||||
Success bool `json:"success"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
var results []channelResult
|
||||
|
||||
if cfg.DiscordWebhookURL != nil && *cfg.DiscordWebhookURL != "" {
|
||||
ok, testErr := notifications.TestDiscordWebhook(*cfg.DiscordWebhookURL)
|
||||
res := channelResult{Channel: "discord", Success: ok}
|
||||
if testErr != nil {
|
||||
res.Error = testErr.Error()
|
||||
}
|
||||
results = append(results, res)
|
||||
}
|
||||
|
||||
if cfg.TelegramBotToken != nil && *cfg.TelegramBotToken != "" &&
|
||||
cfg.TelegramChatID != nil && *cfg.TelegramChatID != "" {
|
||||
ok, testErr := notifications.TestTelegramWebhook(*cfg.TelegramBotToken, *cfg.TelegramChatID)
|
||||
res := channelResult{Channel: "telegram", Success: ok}
|
||||
if testErr != nil {
|
||||
res.Error = testErr.Error()
|
||||
}
|
||||
results = append(results, res)
|
||||
}
|
||||
|
||||
if cfg.SlackWebhookURL != nil && *cfg.SlackWebhookURL != "" {
|
||||
ok, testErr := notifications.TestSlackWebhook(*cfg.SlackWebhookURL)
|
||||
res := channelResult{Channel: "slack", Success: ok}
|
||||
if testErr != nil {
|
||||
res.Error = testErr.Error()
|
||||
}
|
||||
results = append(results, res)
|
||||
}
|
||||
|
||||
if cfg.Email != nil && *cfg.Email != "" {
|
||||
ok, testErr := notifications.TestEmailNotification(
|
||||
h.cfg.ResendAPIKey, h.cfg.EmailFrom, *cfg.Email,
|
||||
)
|
||||
res := channelResult{Channel: "email", Success: ok}
|
||||
if testErr != nil {
|
||||
res.Error = testErr.Error()
|
||||
}
|
||||
results = append(results, res)
|
||||
}
|
||||
|
||||
if len(results) == 0 {
|
||||
writeError(w, http.StatusBadRequest, "NO_CHANNELS",
|
||||
"No notification channels are configured")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, map[string]any{"results": results})
|
||||
}
|
||||
|
||||
@@ -1,10 +1,67 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/kjannette/koin-ping/backend-go/internal/models"
|
||||
)
|
||||
|
||||
// StatusHandler handles the system status endpoint.
|
||||
type StatusHandler struct {
|
||||
checkpoints *models.CheckpointModel
|
||||
}
|
||||
|
||||
// NewStatusHandler creates a new StatusHandler.
|
||||
func NewStatusHandler(checkpoints *models.CheckpointModel) *StatusHandler {
|
||||
return &StatusHandler{checkpoints: checkpoints}
|
||||
}
|
||||
|
||||
// GetStatus returns real-time system status derived from checkpoint data.
|
||||
func (h *StatusHandler) GetStatus(w http.ResponseWriter, r *http.Request) {
|
||||
block, checkedAt, err := h.checkpoints.GetLatestBlock(r.Context())
|
||||
if err != nil {
|
||||
log.Printf("Error querying latest block: %v", err)
|
||||
writeError(w, http.StatusInternalServerError, "INTERNAL_ERROR", "Failed to get system status")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
latestBlock := 0
|
||||
lag := 0
|
||||
status := "starting"
|
||||
|
||||
if checkedAt != nil {
|
||||
lag = int(time.Since(*checkedAt).Seconds())
|
||||
if lag > 600 { //nolint:mnd
|
||||
status = "idle"
|
||||
} else {
|
||||
status = "active"
|
||||
}
|
||||
}
|
||||
|
||||
if block != nil {
|
||||
latestBlock = *block
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, map[string]interface{}{
|
||||
"status": status,
|
||||
"latestBlock": latestBlock,
|
||||
"lag": lag,
|
||||
"lastCheckedAt": checkedAtStr(checkedAt),
|
||||
"timestamp": time.Now().UTC().Format(time.RFC3339),
|
||||
})
|
||||
}
|
||||
|
||||
func checkedAtStr(t *time.Time) string {
|
||||
if t == nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
return t.UTC().Format(time.RFC3339)
|
||||
}
|
||||
|
||||
func HealthCheck(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, map[string]interface{}{
|
||||
"status": "ok",
|
||||
@@ -12,12 +69,3 @@ func HealthCheck(w http.ResponseWriter, r *http.Request) {
|
||||
"service": "koin-ping-backend",
|
||||
})
|
||||
}
|
||||
|
||||
func SystemStatus(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, map[string]interface{}{
|
||||
"latestBlock": 0,
|
||||
"lag": 0,
|
||||
"status": "healthy",
|
||||
"timestamp": time.Now().UTC().Format(time.RFC3339),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -107,6 +107,24 @@ func (m *AddressModel) FindByID(ctx context.Context, id int, userID *string) (*d
|
||||
return &a, nil
|
||||
}
|
||||
|
||||
// UpdateLabel updates the label for an address owned by userID.
|
||||
// Returns nil, nil if no row matched (address not found or not owned by user).
|
||||
func (m *AddressModel) UpdateLabel(ctx context.Context, id int, userID string, label *string) (*domain.Address, error) {
|
||||
var a domain.Address
|
||||
err := m.pool.QueryRow(ctx,
|
||||
`UPDATE addresses SET label = $3 WHERE id = $1 AND user_id = $2
|
||||
RETURNING id, user_id, address, label, created_at`,
|
||||
id, userID, label,
|
||||
).Scan(&a.ID, &a.UserID, &a.Address, &a.Label, &a.CreatedAt)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &a, nil
|
||||
}
|
||||
|
||||
func (m *AddressModel) Remove(ctx context.Context, id int, userID string) (bool, error) {
|
||||
tag, err := m.pool.Exec(ctx,
|
||||
`DELETE FROM addresses WHERE id = $1 AND user_id = $2`,
|
||||
|
||||
@@ -2,7 +2,9 @@ package models
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/kjannette/koin-ping/backend-go/internal/domain"
|
||||
)
|
||||
@@ -71,10 +73,15 @@ func (m *AlertEventModel) Create(ctx context.Context, alertRuleID int, message s
|
||||
err := m.pool.QueryRow(ctx,
|
||||
`INSERT INTO alert_events (alert_rule_id, message, address_label, tx_hash)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
ON CONFLICT DO NOTHING
|
||||
RETURNING id, alert_rule_id, message, address_label, tx_hash, timestamp`,
|
||||
alertRuleID, message, addressLabel, txHash,
|
||||
).Scan(&e.ID, &e.AlertRuleID, &e.Message, &e.AddressLabel, &e.TxHash, &e.Timestamp)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
// Duplicate silently skipped by ON CONFLICT DO NOTHING
|
||||
return nil, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &e, nil
|
||||
|
||||
@@ -3,6 +3,7 @@ package models
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
@@ -17,6 +18,20 @@ func NewCheckpointModel(pool *pgxpool.Pool) *CheckpointModel {
|
||||
return &CheckpointModel{pool: pool}
|
||||
}
|
||||
|
||||
// GetLatestBlock returns the highest last_checked_block and its timestamp across all addresses.
|
||||
// Returns nil, nil, nil when no checkpoints exist yet.
|
||||
func (m *CheckpointModel) GetLatestBlock(ctx context.Context) (*int, *time.Time, error) {
|
||||
var block *int
|
||||
var checkedAt *time.Time
|
||||
err := m.pool.QueryRow(ctx,
|
||||
`SELECT MAX(last_checked_block), MAX(last_checked_at) FROM address_checkpoints`,
|
||||
).Scan(&block, &checkedAt)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return block, checkedAt, nil
|
||||
}
|
||||
|
||||
// GetLastCheckedBlock returns the last checked block for an address, or -1 if never checked.
|
||||
func (m *CheckpointModel) GetLastCheckedBlock(ctx context.Context, addressID int) (int, bool, error) {
|
||||
var block int
|
||||
|
||||
@@ -21,12 +21,12 @@ func (m *NotificationConfigModel) GetConfig(ctx context.Context, userID string)
|
||||
var c domain.NotificationConfig
|
||||
err := m.pool.QueryRow(ctx,
|
||||
`SELECT user_id, discord_webhook_url, telegram_chat_id, telegram_bot_token,
|
||||
email, notification_enabled, created_at, updated_at
|
||||
email, slack_webhook_url, notification_enabled, created_at, updated_at
|
||||
FROM user_notification_configs
|
||||
WHERE user_id = $1`,
|
||||
userID,
|
||||
).Scan(&c.UserID, &c.DiscordWebhookURL, &c.TelegramChatID, &c.TelegramBotToken,
|
||||
&c.Email, &c.NotificationEnabled, &c.CreatedAt, &c.UpdatedAt)
|
||||
&c.Email, &c.SlackWebhookURL, &c.NotificationEnabled, &c.CreatedAt, &c.UpdatedAt)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, nil
|
||||
@@ -40,22 +40,24 @@ func (m *NotificationConfigModel) UpsertConfig(ctx context.Context, userID strin
|
||||
var c domain.NotificationConfig
|
||||
err := m.pool.QueryRow(ctx,
|
||||
`INSERT INTO user_notification_configs
|
||||
(user_id, discord_webhook_url, telegram_chat_id, telegram_bot_token, email, notification_enabled, updated_at)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, NOW())
|
||||
(user_id, discord_webhook_url, telegram_chat_id, telegram_bot_token,
|
||||
email, slack_webhook_url, notification_enabled, updated_at)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, NOW())
|
||||
ON CONFLICT (user_id)
|
||||
DO UPDATE SET
|
||||
discord_webhook_url = COALESCE($2, user_notification_configs.discord_webhook_url),
|
||||
telegram_chat_id = COALESCE($3, user_notification_configs.telegram_chat_id),
|
||||
telegram_bot_token = COALESCE($4, user_notification_configs.telegram_bot_token),
|
||||
email = COALESCE($5, user_notification_configs.email),
|
||||
notification_enabled = $6,
|
||||
discord_webhook_url = $2,
|
||||
telegram_chat_id = $3,
|
||||
telegram_bot_token = $4,
|
||||
email = $5,
|
||||
slack_webhook_url = $6,
|
||||
notification_enabled = $7,
|
||||
updated_at = NOW()
|
||||
RETURNING user_id, discord_webhook_url, telegram_chat_id, telegram_bot_token,
|
||||
email, notification_enabled, created_at, updated_at`,
|
||||
email, slack_webhook_url, notification_enabled, created_at, updated_at`,
|
||||
userID, cfg.DiscordWebhookURL, cfg.TelegramChatID, cfg.TelegramBotToken,
|
||||
cfg.Email, cfg.NotificationEnabled,
|
||||
cfg.Email, cfg.SlackWebhookURL, cfg.NotificationEnabled,
|
||||
).Scan(&c.UserID, &c.DiscordWebhookURL, &c.TelegramChatID, &c.TelegramBotToken,
|
||||
&c.Email, &c.NotificationEnabled, &c.CreatedAt, &c.UpdatedAt)
|
||||
&c.Email, &c.SlackWebhookURL, &c.NotificationEnabled, &c.CreatedAt, &c.UpdatedAt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -75,7 +77,8 @@ func (m *NotificationConfigModel) Remove(ctx context.Context, userID string) (bo
|
||||
|
||||
func (m *NotificationConfigModel) ListEnabled(ctx context.Context) ([]domain.NotificationConfig, error) {
|
||||
rows, err := m.pool.Query(ctx,
|
||||
`SELECT user_id, discord_webhook_url, telegram_chat_id, email
|
||||
`SELECT user_id, discord_webhook_url, telegram_chat_id, telegram_bot_token,
|
||||
email, slack_webhook_url
|
||||
FROM user_notification_configs
|
||||
WHERE notification_enabled = TRUE`,
|
||||
)
|
||||
@@ -87,7 +90,8 @@ func (m *NotificationConfigModel) ListEnabled(ctx context.Context) ([]domain.Not
|
||||
var configs []domain.NotificationConfig
|
||||
for rows.Next() {
|
||||
var c domain.NotificationConfig
|
||||
if err := rows.Scan(&c.UserID, &c.DiscordWebhookURL, &c.TelegramChatID, &c.Email); err != nil {
|
||||
if err := rows.Scan(&c.UserID, &c.DiscordWebhookURL, &c.TelegramChatID,
|
||||
&c.TelegramBotToken, &c.Email, &c.SlackWebhookURL); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c.NotificationEnabled = true
|
||||
|
||||
@@ -2,6 +2,7 @@ package notifications
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
@@ -25,11 +26,15 @@ var discordHTTPClient = &http.Client{ //nolint:gochecknoglobals
|
||||
Timeout: discordHTTPTimeoutSeconds * time.Second,
|
||||
}
|
||||
|
||||
type AlertMetadata struct {
|
||||
TxHash string
|
||||
AddressLabel string
|
||||
AlertType string
|
||||
Address string
|
||||
// DiscordNotifier sends alert notifications via a Discord webhook.
|
||||
type DiscordNotifier struct {
|
||||
WebhookURL string
|
||||
}
|
||||
|
||||
// Send implements Notifier for Discord.
|
||||
func (d *DiscordNotifier) Send(_ context.Context, message string, meta AlertMetadata) error {
|
||||
_, err := SendDiscordNotification(d.WebhookURL, message, meta)
|
||||
return err
|
||||
}
|
||||
|
||||
type discordEmbed struct {
|
||||
|
||||
156
backend-go/internal/notifications/email.go
Normal file
156
backend-go/internal/notifications/email.go
Normal file
@@ -0,0 +1,156 @@
|
||||
package notifications
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
// EmailNotifier sends alert notifications via email (Resend).
|
||||
type EmailNotifier struct {
|
||||
APIKey string
|
||||
From string
|
||||
To string
|
||||
}
|
||||
|
||||
// Send implements Notifier for email.
|
||||
func (e *EmailNotifier) Send(_ context.Context, message string, meta AlertMetadata) error {
|
||||
_, err := SendEmailNotification(e.APIKey, e.From, e.To, message, meta)
|
||||
return err
|
||||
}
|
||||
|
||||
const emailHTTPTimeoutSeconds = 10
|
||||
|
||||
var emailHTTPClient = &http.Client{ //nolint:gochecknoglobals
|
||||
Timeout: emailHTTPTimeoutSeconds * time.Second,
|
||||
}
|
||||
|
||||
type resendPayload struct {
|
||||
From string `json:"from"`
|
||||
To string `json:"to"`
|
||||
Subject string `json:"subject"`
|
||||
HTML string `json:"html"`
|
||||
}
|
||||
|
||||
func SendEmailNotification(apiKey, fromAddress, toAddress, message string, meta AlertMetadata) (bool, error) {
|
||||
if apiKey == "" {
|
||||
log.Printf("Skipping email notification: RESEND_API_KEY not configured")
|
||||
return false, nil
|
||||
}
|
||||
|
||||
subject := fmt.Sprintf("Koin Ping Alert: %s", alertTypeLabel(meta.AlertType))
|
||||
|
||||
txLink := ""
|
||||
if meta.TxHash != "" {
|
||||
txLink = fmt.Sprintf(
|
||||
`<p><a href="https://etherscan.io/tx/%s">View on Etherscan</a></p>`,
|
||||
meta.TxHash,
|
||||
)
|
||||
}
|
||||
|
||||
html := fmt.Sprintf(`
|
||||
<div style="font-family: sans-serif; max-width: 600px; margin: 0 auto;">
|
||||
<h2 style="color: #333;">Koin Ping Alert</h2>
|
||||
<p style="font-size: 16px;">%s</p>
|
||||
<table style="margin: 16px 0; border-collapse: collapse;">
|
||||
<tr>
|
||||
<td style="padding: 4px 12px 4px 0; color: #666;">Address</td>
|
||||
<td style="padding: 4px 0;">%s</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td style="padding: 4px 12px 4px 0; color: #666;">Blockchain</td>
|
||||
<td style="padding: 4px 0; font-family: monospace; font-size: 13px;">%s</td>
|
||||
</tr>
|
||||
</table>
|
||||
%s
|
||||
<hr style="border: none; border-top: 1px solid #eee; margin: 24px 0;" />
|
||||
<p style="font-size: 12px; color: #999;">Sent by Koin Ping</p>
|
||||
</div>`,
|
||||
message, meta.AddressLabel, meta.Address, txLink)
|
||||
|
||||
payload := resendPayload{
|
||||
From: fromAddress,
|
||||
To: toAddress,
|
||||
Subject: subject,
|
||||
HTML: html,
|
||||
}
|
||||
|
||||
body, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("marshal email payload: %w", err)
|
||||
}
|
||||
|
||||
req, err := http.NewRequest(http.MethodPost, "https://api.resend.com/emails", bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("create email request: %w", err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+apiKey)
|
||||
|
||||
resp, err := emailHTTPClient.Do(req)
|
||||
if err != nil {
|
||||
log.Printf("Failed to send email notification: %v", err)
|
||||
return false, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
log.Printf("Resend API failed: HTTP %d", resp.StatusCode)
|
||||
return false, fmt.Errorf("resend API failed: HTTP %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func TestEmailNotification(apiKey, fromAddress, toAddress string) (bool, error) {
|
||||
if apiKey == "" {
|
||||
return false, fmt.Errorf("email not configured: RESEND_API_KEY not set") //nolint:err113
|
||||
}
|
||||
|
||||
payload := resendPayload{
|
||||
From: fromAddress,
|
||||
To: toAddress,
|
||||
Subject: "Koin Ping — Test Notification",
|
||||
HTML: `<p>Your email alerts are configured correctly!</p><p style="font-size:12px;color:#999;">Sent by Koin Ping</p>`,
|
||||
}
|
||||
|
||||
body, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
req, err := http.NewRequest(http.MethodPost, "https://api.resend.com/emails", bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+apiKey)
|
||||
|
||||
resp, err := emailHTTPClient.Do(req)
|
||||
if err != nil {
|
||||
log.Printf("Email test failed: %v", err)
|
||||
return false, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
return resp.StatusCode >= 200 && resp.StatusCode < 300, nil
|
||||
}
|
||||
|
||||
func alertTypeLabel(alertType string) string {
|
||||
switch alertType {
|
||||
case "incoming_tx":
|
||||
return "Incoming Transaction"
|
||||
case "outgoing_tx":
|
||||
return "Outgoing Transaction"
|
||||
case "large_transfer":
|
||||
return "Large Transfer"
|
||||
case "balance_below":
|
||||
return "Balance Below Threshold"
|
||||
default:
|
||||
return "Alert"
|
||||
}
|
||||
}
|
||||
16
backend-go/internal/notifications/notifier.go
Normal file
16
backend-go/internal/notifications/notifier.go
Normal file
@@ -0,0 +1,16 @@
|
||||
package notifications
|
||||
|
||||
import "context"
|
||||
|
||||
// AlertMetadata holds context about the alert being sent.
|
||||
type AlertMetadata struct {
|
||||
TxHash string
|
||||
AddressLabel string
|
||||
AlertType string
|
||||
Address string
|
||||
}
|
||||
|
||||
// Notifier is the interface implemented by all notification channels.
|
||||
type Notifier interface {
|
||||
Send(ctx context.Context, message string, meta AlertMetadata) error
|
||||
}
|
||||
128
backend-go/internal/notifications/slack.go
Normal file
128
backend-go/internal/notifications/slack.go
Normal file
@@ -0,0 +1,128 @@
|
||||
package notifications
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
// SlackNotifier sends alert notifications via a Slack webhook.
|
||||
type SlackNotifier struct {
|
||||
WebhookURL string
|
||||
}
|
||||
|
||||
// Send implements Notifier for Slack.
|
||||
func (s *SlackNotifier) Send(_ context.Context, message string, meta AlertMetadata) error {
|
||||
_, err := SendSlackNotification(s.WebhookURL, message, meta)
|
||||
return err
|
||||
}
|
||||
|
||||
const slackHTTPTimeoutSeconds = 10
|
||||
|
||||
var slackHTTPClient = &http.Client{ //nolint:gochecknoglobals
|
||||
Timeout: slackHTTPTimeoutSeconds * time.Second,
|
||||
}
|
||||
|
||||
type slackAttachment struct {
|
||||
Color string `json:"color"`
|
||||
Title string `json:"title"`
|
||||
Text string `json:"text"`
|
||||
Fields []slackField `json:"fields"`
|
||||
Footer string `json:"footer"`
|
||||
Ts int64 `json:"ts"`
|
||||
}
|
||||
|
||||
type slackField struct {
|
||||
Title string `json:"title"`
|
||||
Value string `json:"value"`
|
||||
Short bool `json:"short"`
|
||||
}
|
||||
|
||||
type slackPayload struct {
|
||||
Text string `json:"text,omitempty"`
|
||||
Attachments []slackAttachment `json:"attachments,omitempty"`
|
||||
}
|
||||
|
||||
func SendSlackNotification(webhookURL, message string, meta AlertMetadata) (bool, error) {
|
||||
fields := []slackField{
|
||||
{Title: "Address", Value: meta.AddressLabel, Short: true},
|
||||
{Title: "Blockchain Address", Value: fmt.Sprintf("`%s`", meta.Address), Short: false},
|
||||
}
|
||||
|
||||
if meta.TxHash != "" {
|
||||
fields = append(fields, slackField{
|
||||
Title: "Transaction",
|
||||
Value: fmt.Sprintf("<https://etherscan.io/tx/%s|View on Etherscan>", meta.TxHash),
|
||||
Short: false,
|
||||
})
|
||||
}
|
||||
|
||||
payload := slackPayload{
|
||||
Attachments: []slackAttachment{
|
||||
{
|
||||
Color: slackColorForAlertType(meta.AlertType),
|
||||
Title: "Koin Ping Alert",
|
||||
Text: message,
|
||||
Fields: fields,
|
||||
Footer: "Koin Ping",
|
||||
Ts: time.Now().Unix(),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
body, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("marshal slack payload: %w", err)
|
||||
}
|
||||
|
||||
resp, err := slackHTTPClient.Post(webhookURL, "application/json", bytes.NewReader(body))
|
||||
if err != nil {
|
||||
log.Printf("Failed to send Slack notification: %v", err)
|
||||
return false, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
log.Printf("Slack webhook failed: HTTP %d", resp.StatusCode)
|
||||
return false, fmt.Errorf("slack webhook failed: HTTP %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func TestSlackWebhook(webhookURL string) (bool, error) {
|
||||
payload := slackPayload{
|
||||
Text: "Koin Ping test notification — Your Slack alerts are configured correctly!",
|
||||
}
|
||||
|
||||
body, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
resp, err := slackHTTPClient.Post(webhookURL, "application/json", bytes.NewReader(body))
|
||||
if err != nil {
|
||||
log.Printf("Slack webhook test failed: %v", err)
|
||||
return false, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
return resp.StatusCode >= 200 && resp.StatusCode < 300, nil
|
||||
}
|
||||
|
||||
func slackColorForAlertType(alertType string) string {
|
||||
switch alertType {
|
||||
case "incoming_tx":
|
||||
return "#00ff00"
|
||||
case "outgoing_tx":
|
||||
return "#ff9900"
|
||||
case "large_transfer", "balance_below":
|
||||
return "#ff0000"
|
||||
default:
|
||||
return "#0099ff"
|
||||
}
|
||||
}
|
||||
122
backend-go/internal/notifications/telegram.go
Normal file
122
backend-go/internal/notifications/telegram.go
Normal file
@@ -0,0 +1,122 @@
|
||||
package notifications
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TelegramNotifier sends alert notifications via Telegram.
|
||||
type TelegramNotifier struct {
|
||||
BotToken string
|
||||
ChatID string
|
||||
}
|
||||
|
||||
// Send implements Notifier for Telegram.
|
||||
func (t *TelegramNotifier) Send(_ context.Context, message string, meta AlertMetadata) error {
|
||||
_, err := SendTelegramNotification(t.BotToken, t.ChatID, message, meta)
|
||||
return err
|
||||
}
|
||||
|
||||
const telegramHTTPTimeoutSeconds = 10
|
||||
|
||||
var telegramHTTPClient = &http.Client{ //nolint:gochecknoglobals
|
||||
Timeout: telegramHTTPTimeoutSeconds * time.Second,
|
||||
}
|
||||
|
||||
type telegramPayload struct {
|
||||
ChatID string `json:"chat_id"`
|
||||
Text string `json:"text"`
|
||||
ParseMode string `json:"parse_mode"`
|
||||
}
|
||||
|
||||
func SendTelegramNotification(botToken, chatID, message string, meta AlertMetadata) (bool, error) {
|
||||
text := fmt.Sprintf("*Koin Ping Alert*\n\n%s\n\n*Address:* %s\n`%s`",
|
||||
escapeMarkdown(message), escapeMarkdown(meta.AddressLabel), meta.Address)
|
||||
|
||||
if meta.TxHash != "" {
|
||||
text += fmt.Sprintf("\n\n[View on Etherscan](https://etherscan.io/tx/%s)", meta.TxHash)
|
||||
}
|
||||
|
||||
payload := telegramPayload{
|
||||
ChatID: chatID,
|
||||
Text: text,
|
||||
ParseMode: "Markdown",
|
||||
}
|
||||
|
||||
body, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("marshal telegram payload: %w", err)
|
||||
}
|
||||
|
||||
url := fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage", botToken)
|
||||
|
||||
resp, err := telegramHTTPClient.Post(url, "application/json", bytes.NewReader(body))
|
||||
if err != nil {
|
||||
log.Printf("Failed to send Telegram notification: %v", err)
|
||||
return false, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
log.Printf("Telegram API failed: HTTP %d", resp.StatusCode)
|
||||
return false, fmt.Errorf("telegram API failed: HTTP %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func TestTelegramWebhook(botToken, chatID string) (bool, error) {
|
||||
payload := telegramPayload{
|
||||
ChatID: chatID,
|
||||
Text: "Koin Ping test notification — Your Telegram alerts are configured correctly!",
|
||||
ParseMode: "Markdown",
|
||||
}
|
||||
|
||||
body, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
url := fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage", botToken)
|
||||
|
||||
resp, err := telegramHTTPClient.Post(url, "application/json", bytes.NewReader(body))
|
||||
if err != nil {
|
||||
log.Printf("Telegram test failed: %v", err)
|
||||
return false, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
return resp.StatusCode >= 200 && resp.StatusCode < 300, nil
|
||||
}
|
||||
|
||||
func escapeMarkdown(s string) string {
|
||||
replacer := []struct{ old, new string }{
|
||||
{"_", "\\_"}, {"*", "\\*"}, {"[", "\\["}, {"]", "\\]"},
|
||||
{"(", "\\("}, {")", "\\)"}, {"~", "\\~"}, {"`", "\\`"},
|
||||
{">", "\\>"}, {"#", "\\#"}, {"+", "\\+"}, {"-", "\\-"},
|
||||
{"=", "\\="}, {"|", "\\|"}, {"{", "\\{"}, {"}", "\\}"},
|
||||
{".", "\\."}, {"!", "\\!"},
|
||||
}
|
||||
result := s
|
||||
for _, r := range replacer {
|
||||
result = replaceAll(result, r.old, r.new)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func replaceAll(s, old, new string) string {
|
||||
out := ""
|
||||
for i := 0; i < len(s); i++ {
|
||||
if string(s[i]) == old {
|
||||
out += new
|
||||
} else {
|
||||
out += string(s[i])
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -4,7 +4,9 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"math/big"
|
||||
"net/http"
|
||||
"strings"
|
||||
@@ -13,7 +15,11 @@ import (
|
||||
"github.com/kjannette/koin-ping/backend-go/internal/domain"
|
||||
)
|
||||
|
||||
const rpcTimeoutMS = 30000
|
||||
const (
|
||||
rpcTimeoutMS = 30000
|
||||
rpcMaxRetries = 3
|
||||
rpcRetryBaseMS = 1000
|
||||
)
|
||||
|
||||
type JsonRpcEthereum struct {
|
||||
rpcURL string
|
||||
@@ -66,6 +72,44 @@ func (j *JsonRpcEthereum) callRPC(ctx context.Context, method string, params ...
|
||||
return nil, fmt.Errorf("marshal RPC request: %w", err)
|
||||
}
|
||||
|
||||
return j.callWithRetry(ctx, method, body)
|
||||
}
|
||||
|
||||
// callWithRetry executes a JSON-RPC POST with exponential backoff on transient errors.
|
||||
// It retries on network errors, HTTP 429, and HTTP 5xx. It does NOT retry on RPC-level
|
||||
// errors or other 4xx responses (those are permanent failures).
|
||||
func (j *JsonRpcEthereum) callWithRetry(ctx context.Context, method string, body []byte) (json.RawMessage, error) {
|
||||
var lastErr error
|
||||
for attempt := range rpcMaxRetries {
|
||||
if attempt > 0 {
|
||||
wait := time.Duration(rpcRetryBaseMS*(1<<(attempt-1))) * time.Millisecond
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
case <-time.After(wait):
|
||||
}
|
||||
log.Printf("Retrying RPC call [%s] (attempt %d/%d)", method, attempt+1, rpcMaxRetries)
|
||||
}
|
||||
|
||||
result, err := j.doRPCCall(ctx, method, body)
|
||||
if err == nil {
|
||||
return result, nil
|
||||
}
|
||||
|
||||
lastErr = err
|
||||
|
||||
// Permanent errors: do not retry
|
||||
if isPermanentRPCError(err) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
log.Printf("Transient RPC error [%s] (attempt %d/%d): %v", method, attempt+1, rpcMaxRetries, err)
|
||||
}
|
||||
|
||||
return nil, lastErr
|
||||
}
|
||||
|
||||
func (j *JsonRpcEthereum) doRPCCall(ctx context.Context, method string, body []byte) (json.RawMessage, error) {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, j.rpcURL, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create RPC request: %w", err)
|
||||
@@ -78,8 +122,13 @@ func (j *JsonRpcEthereum) callRPC(ctx context.Context, method string, params ...
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
// 429 and 5xx are transient; other non-200 are permanent.
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("HTTP %d: %s for %s", resp.StatusCode, resp.Status, method)
|
||||
err := fmt.Errorf("HTTP %d: %s for %s", resp.StatusCode, resp.Status, method)
|
||||
if resp.StatusCode == http.StatusTooManyRequests || resp.StatusCode >= 500 { //nolint:mnd
|
||||
return nil, err // transient — will be retried
|
||||
}
|
||||
return nil, &permanentRPCError{err}
|
||||
}
|
||||
|
||||
var rpcResp rpcResponse
|
||||
@@ -88,12 +137,25 @@ func (j *JsonRpcEthereum) callRPC(ctx context.Context, method string, params ...
|
||||
}
|
||||
|
||||
if rpcResp.Error != nil {
|
||||
return nil, fmt.Errorf("RPC Error [%s]: %s (code: %d)", method, rpcResp.Error.Message, rpcResp.Error.Code)
|
||||
// RPC-level errors are permanent (bad params, unsupported method, etc.)
|
||||
return nil, &permanentRPCError{
|
||||
fmt.Errorf("RPC Error [%s]: %s (code: %d)", method, rpcResp.Error.Message, rpcResp.Error.Code),
|
||||
}
|
||||
}
|
||||
|
||||
return rpcResp.Result, nil
|
||||
}
|
||||
|
||||
type permanentRPCError struct{ cause error }
|
||||
|
||||
func (e *permanentRPCError) Error() string { return e.cause.Error() }
|
||||
func (e *permanentRPCError) Unwrap() error { return e.cause }
|
||||
|
||||
func isPermanentRPCError(err error) bool {
|
||||
var p *permanentRPCError
|
||||
return errors.As(err, &p)
|
||||
}
|
||||
|
||||
func (j *JsonRpcEthereum) GetLatestBlockNumber(ctx context.Context) (int, error) {
|
||||
result, err := j.callRPC(ctx, "eth_blockNumber")
|
||||
if err != nil {
|
||||
|
||||
199
backend-go/internal/services/email_digest.go
Normal file
199
backend-go/internal/services/email_digest.go
Normal file
@@ -0,0 +1,199 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/kjannette/koin-ping/backend-go/internal/models"
|
||||
)
|
||||
|
||||
const (
|
||||
resendAPIURL = "https://api.resend.com/emails"
|
||||
emailHTTPTimeout = 10 * time.Second
|
||||
defaultDigestMaxItems = 50
|
||||
)
|
||||
|
||||
var digestHTTPClient = &http.Client{Timeout: emailHTTPTimeout} //nolint:gochecknoglobals
|
||||
|
||||
// EmailDigestService handles email setup and digest sending via Resend.
|
||||
type EmailDigestService struct {
|
||||
apiKey string
|
||||
fromAddress string
|
||||
alertEvents *models.AlertEventModel
|
||||
notifCfgs *models.NotificationConfigModel
|
||||
}
|
||||
|
||||
func NewEmailDigestService(
|
||||
apiKey, fromAddress string,
|
||||
alertEvents *models.AlertEventModel,
|
||||
notifCfgs *models.NotificationConfigModel,
|
||||
) *EmailDigestService {
|
||||
return &EmailDigestService{
|
||||
apiKey: apiKey,
|
||||
fromAddress: fromAddress,
|
||||
alertEvents: alertEvents,
|
||||
notifCfgs: notifCfgs,
|
||||
}
|
||||
}
|
||||
|
||||
// Configured returns true when the Resend API key is present.
|
||||
func (s *EmailDigestService) Configured() bool {
|
||||
return s.apiKey != ""
|
||||
}
|
||||
|
||||
// SetupEmail validates the email works by sending a welcome/confirmation
|
||||
// message via Resend. Called when a user saves their email in notification settings.
|
||||
func (s *EmailDigestService) SetupEmail(toAddress string) error {
|
||||
if !s.Configured() {
|
||||
return fmt.Errorf("email service not configured: RESEND_API_KEY not set") //nolint:err113
|
||||
}
|
||||
|
||||
html := `
|
||||
<div style="font-family: sans-serif; max-width: 600px; margin: 0 auto;">
|
||||
<h2 style="color: #333;">Welcome to Koin Ping Email Alerts</h2>
|
||||
<p>Your email has been successfully configured for alert notifications.</p>
|
||||
<p>You will receive alert digests at this address when events are triggered
|
||||
on your watched addresses.</p>
|
||||
<hr style="border: none; border-top: 1px solid #eee; margin: 24px 0;" />
|
||||
<p style="font-size: 12px; color: #999;">Sent by Koin Ping</p>
|
||||
</div>`
|
||||
|
||||
return s.send(toAddress, "Koin Ping — Email Alerts Configured", html)
|
||||
}
|
||||
|
||||
// SendDigest compiles recent alert events for a user and sends a digest email.
|
||||
func (s *EmailDigestService) SendDigest(ctx context.Context, userID, toAddress string) error {
|
||||
if !s.Configured() {
|
||||
return fmt.Errorf("email service not configured: RESEND_API_KEY not set") //nolint:err113
|
||||
}
|
||||
|
||||
events, err := s.alertEvents.ListRecentByUser(ctx, userID, defaultDigestMaxItems)
|
||||
if err != nil {
|
||||
return fmt.Errorf("fetch alert events: %w", err)
|
||||
}
|
||||
|
||||
if len(events) == 0 {
|
||||
log.Printf("No recent alerts for user %s — skipping digest", userID)
|
||||
return nil
|
||||
}
|
||||
|
||||
var rows string
|
||||
for _, e := range events {
|
||||
label := "—"
|
||||
if e.AddressLabel != nil {
|
||||
label = *e.AddressLabel
|
||||
}
|
||||
txLink := "—"
|
||||
if e.TxHash != nil {
|
||||
txLink = fmt.Sprintf(
|
||||
`<a href="https://etherscan.io/tx/%s" style="color:#0066cc;">%s…</a>`,
|
||||
*e.TxHash, (*e.TxHash)[:10],
|
||||
)
|
||||
}
|
||||
rows += fmt.Sprintf(`
|
||||
<tr>
|
||||
<td style="padding:6px 8px; border-bottom:1px solid #eee;">%s</td>
|
||||
<td style="padding:6px 8px; border-bottom:1px solid #eee;">%s</td>
|
||||
<td style="padding:6px 8px; border-bottom:1px solid #eee;">%s</td>
|
||||
<td style="padding:6px 8px; border-bottom:1px solid #eee; font-size:12px; color:#666;">%s</td>
|
||||
</tr>`,
|
||||
label, e.Message, txLink,
|
||||
e.Timestamp.Format("Jan 2 15:04 UTC"),
|
||||
)
|
||||
}
|
||||
|
||||
html := fmt.Sprintf(`
|
||||
<div style="font-family: sans-serif; max-width: 700px; margin: 0 auto;">
|
||||
<h2 style="color: #333;">Koin Ping — Alert Digest</h2>
|
||||
<p>Here are your recent alerts (%d total):</p>
|
||||
<table style="width:100%%; border-collapse:collapse; font-size:14px;">
|
||||
<thead>
|
||||
<tr style="background:#f5f5f5;">
|
||||
<th style="padding:8px; text-align:left;">Address</th>
|
||||
<th style="padding:8px; text-align:left;">Alert</th>
|
||||
<th style="padding:8px; text-align:left;">Tx</th>
|
||||
<th style="padding:8px; text-align:left;">Time</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>%s</tbody>
|
||||
</table>
|
||||
<hr style="border:none; border-top:1px solid #eee; margin:24px 0;" />
|
||||
<p style="font-size:12px; color:#999;">Sent by Koin Ping</p>
|
||||
</div>`, len(events), rows)
|
||||
|
||||
subject := fmt.Sprintf("Koin Ping Digest — %d alerts", len(events))
|
||||
|
||||
return s.send(toAddress, subject, html)
|
||||
}
|
||||
|
||||
// SendDigestsForAllUsers sends a digest email to every user that has
|
||||
// notifications enabled and an email configured.
|
||||
func (s *EmailDigestService) SendDigestsForAllUsers(ctx context.Context) (int, error) {
|
||||
if !s.Configured() {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
configs, err := s.notifCfgs.ListEnabled(ctx)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("list enabled configs: %w", err)
|
||||
}
|
||||
|
||||
sent := 0
|
||||
for _, cfg := range configs {
|
||||
if cfg.Email == nil || *cfg.Email == "" {
|
||||
continue
|
||||
}
|
||||
if err := s.SendDigest(ctx, cfg.UserID, *cfg.Email); err != nil {
|
||||
log.Printf("Failed to send digest to user %s: %v", cfg.UserID, err)
|
||||
continue
|
||||
}
|
||||
sent++
|
||||
}
|
||||
|
||||
return sent, nil
|
||||
}
|
||||
|
||||
type resendEmailPayload struct {
|
||||
From string `json:"from"`
|
||||
To string `json:"to"`
|
||||
Subject string `json:"subject"`
|
||||
HTML string `json:"html"`
|
||||
}
|
||||
|
||||
func (s *EmailDigestService) send(to, subject, html string) error {
|
||||
payload := resendEmailPayload{
|
||||
From: s.fromAddress,
|
||||
To: to,
|
||||
Subject: subject,
|
||||
HTML: html,
|
||||
}
|
||||
|
||||
body, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return fmt.Errorf("marshal email payload: %w", err)
|
||||
}
|
||||
|
||||
req, err := http.NewRequest(http.MethodPost, resendAPIURL, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return fmt.Errorf("create request: %w", err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+s.apiKey)
|
||||
|
||||
resp, err := digestHTTPClient.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("send email via Resend: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return fmt.Errorf("Resend API returned HTTP %d", resp.StatusCode) //nolint:err113
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"github.com/kjannette/koin-ping/backend-go/internal/domain"
|
||||
"github.com/kjannette/koin-ping/backend-go/internal/models"
|
||||
@@ -12,12 +13,20 @@ import (
|
||||
"github.com/kjannette/koin-ping/backend-go/internal/wei"
|
||||
)
|
||||
|
||||
const (
|
||||
notificationTimeout = 30 * time.Second
|
||||
notificationMaxRetries = 3
|
||||
notificationRetryBase = time.Second
|
||||
)
|
||||
|
||||
type EvaluatorService struct {
|
||||
eth ethereum.EthereumObserver
|
||||
alertRules *models.AlertRuleModel
|
||||
alertEvents *models.AlertEventModel
|
||||
addresses *models.AddressModel
|
||||
notifConfigs *models.NotificationConfigModel
|
||||
resendAPIKey string
|
||||
emailFrom string
|
||||
}
|
||||
|
||||
func NewEvaluatorService(
|
||||
@@ -26,6 +35,8 @@ func NewEvaluatorService(
|
||||
alertEvents *models.AlertEventModel,
|
||||
addresses *models.AddressModel,
|
||||
notifConfigs *models.NotificationConfigModel,
|
||||
resendAPIKey string,
|
||||
emailFrom string,
|
||||
) *EvaluatorService {
|
||||
return &EvaluatorService{
|
||||
eth: eth,
|
||||
@@ -33,6 +44,8 @@ func NewEvaluatorService(
|
||||
alertEvents: alertEvents,
|
||||
addresses: addresses,
|
||||
notifConfigs: notifConfigs,
|
||||
resendAPIKey: resendAPIKey,
|
||||
emailFrom: emailFrom,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -161,25 +174,85 @@ func (s *EvaluatorService) fireAlert(ctx context.Context, rule domain.AlertRule,
|
||||
message := s.buildMessage(rule, obs)
|
||||
txHash := &obs.Hash
|
||||
|
||||
_, err = s.alertEvents.Create(ctx, rule.ID, message, &addressLabel, txHash)
|
||||
event, err := s.alertEvents.Create(ctx, rule.ID, message, &addressLabel, txHash)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if event == nil {
|
||||
log.Printf("[ALERT DEDUP] Rule %d (%s) - duplicate event skipped for TX: %s", rule.ID, rule.Type, obs.Hash)
|
||||
return nil
|
||||
}
|
||||
|
||||
log.Printf("[ALERT FIRED] Rule %d (%s) - %s - TX: %s", rule.ID, rule.Type, message, obs.Hash)
|
||||
|
||||
// Send Discord notification (non-fatal on failure)
|
||||
if addr != nil {
|
||||
userID := addr.UserID
|
||||
address := addr.Address
|
||||
go func() {
|
||||
s.sendNotification(
|
||||
ctx, addr.UserID, message, obs, addressLabel, rule, addr.Address,
|
||||
)
|
||||
notifCtx, cancel := context.WithTimeout(context.Background(), notificationTimeout)
|
||||
defer cancel()
|
||||
s.sendNotification(notifCtx, userID, message, obs, addressLabel, rule, address)
|
||||
}()
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *EvaluatorService) buildNotifiers(cfg *domain.NotificationConfig) []notifications.Notifier {
|
||||
var notifiers []notifications.Notifier
|
||||
|
||||
if cfg.DiscordWebhookURL != nil && *cfg.DiscordWebhookURL != "" {
|
||||
notifiers = append(notifiers, ¬ifications.DiscordNotifier{WebhookURL: *cfg.DiscordWebhookURL})
|
||||
}
|
||||
|
||||
if cfg.TelegramBotToken != nil && *cfg.TelegramBotToken != "" &&
|
||||
cfg.TelegramChatID != nil && *cfg.TelegramChatID != "" {
|
||||
notifiers = append(notifiers, ¬ifications.TelegramNotifier{
|
||||
BotToken: *cfg.TelegramBotToken,
|
||||
ChatID: *cfg.TelegramChatID,
|
||||
})
|
||||
}
|
||||
|
||||
if cfg.SlackWebhookURL != nil && *cfg.SlackWebhookURL != "" {
|
||||
notifiers = append(notifiers, ¬ifications.SlackNotifier{WebhookURL: *cfg.SlackWebhookURL})
|
||||
}
|
||||
|
||||
if cfg.Email != nil && *cfg.Email != "" {
|
||||
notifiers = append(notifiers, ¬ifications.EmailNotifier{
|
||||
APIKey: s.resendAPIKey,
|
||||
From: s.emailFrom,
|
||||
To: *cfg.Email,
|
||||
})
|
||||
}
|
||||
|
||||
return notifiers
|
||||
}
|
||||
|
||||
func sendWithRetry(ctx context.Context, n notifications.Notifier, message string, meta notifications.AlertMetadata) error {
|
||||
var lastErr error
|
||||
for attempt := range notificationMaxRetries {
|
||||
if attempt > 0 {
|
||||
wait := notificationRetryBase * time.Duration(1<<(attempt-1))
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-time.After(wait):
|
||||
}
|
||||
}
|
||||
|
||||
if err := n.Send(ctx, message, meta); err != nil {
|
||||
log.Printf("Notification attempt %d/%d failed: %v", attempt+1, notificationMaxRetries, err)
|
||||
lastErr = err
|
||||
continue
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
return lastErr
|
||||
}
|
||||
|
||||
func (s *EvaluatorService) sendNotification(ctx context.Context, userID, message string, obs domain.ObservedTx, addressLabel string, rule domain.AlertRule, address string) {
|
||||
notifConfig, err := s.notifConfigs.GetConfig(ctx, userID)
|
||||
if err != nil {
|
||||
@@ -187,25 +260,23 @@ func (s *EvaluatorService) sendNotification(ctx context.Context, userID, message
|
||||
return
|
||||
}
|
||||
|
||||
if notifConfig == nil || !notifConfig.NotificationEnabled || notifConfig.DiscordWebhookURL == nil {
|
||||
if notifConfig == nil || !notifConfig.NotificationEnabled {
|
||||
return
|
||||
}
|
||||
|
||||
sent, err := notifications.SendDiscordNotification(
|
||||
*notifConfig.DiscordWebhookURL,
|
||||
message,
|
||||
notifications.AlertMetadata{
|
||||
TxHash: obs.Hash,
|
||||
AddressLabel: addressLabel,
|
||||
AlertType: string(rule.Type),
|
||||
Address: address,
|
||||
},
|
||||
)
|
||||
meta := notifications.AlertMetadata{
|
||||
TxHash: obs.Hash,
|
||||
AddressLabel: addressLabel,
|
||||
AlertType: string(rule.Type),
|
||||
Address: address,
|
||||
}
|
||||
|
||||
if err != nil || !sent {
|
||||
log.Printf("Discord notification failed for user %s: %v", userID, err)
|
||||
} else {
|
||||
log.Printf("Discord notification sent to user %s", userID)
|
||||
for _, n := range s.buildNotifiers(notifConfig) {
|
||||
if err := sendWithRetry(ctx, n, message, meta); err != nil {
|
||||
log.Printf("Notification channel failed for user %s after retries: %v", userID, err)
|
||||
} else {
|
||||
log.Printf("Notification sent to user %s via %T", userID, n)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -80,6 +80,41 @@ export async function getAddresses() {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update an address (e.g. change its label)
|
||||
* @param {number} addressId - Address ID to update
|
||||
* @param {Object} data - Fields to update (e.g. { label: "New Label" })
|
||||
* @returns {Promise<Object>} Updated address
|
||||
*/
|
||||
export async function updateAddress(addressId, data) {
|
||||
try {
|
||||
const headers = await getAuthHeaders();
|
||||
const response = await fetch(`${API_BASE}/addresses/${addressId}`, {
|
||||
method: "PATCH",
|
||||
headers: headers,
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
let errorMessage = "Failed to update address";
|
||||
try {
|
||||
const error = await response.json();
|
||||
errorMessage = error.message || errorMessage;
|
||||
} catch {
|
||||
errorMessage = `Server error: ${response.status} ${response.statusText}`;
|
||||
}
|
||||
throw new Error(errorMessage);
|
||||
}
|
||||
|
||||
return response.json();
|
||||
} catch (error) {
|
||||
if (error.message.includes("fetch")) {
|
||||
throw new Error("Cannot connect to server. Is the backend running?");
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a tracked address
|
||||
* @param {number} addressId - Address ID to delete
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
// API client for notification configuration
|
||||
|
||||
import { getAuthHeaders } from "./authHeaders";
|
||||
import { API_BASE } from "./config";
|
||||
|
||||
@@ -38,11 +36,13 @@ export async function getNotificationConfig() {
|
||||
|
||||
/**
|
||||
* Update notification configuration
|
||||
* @param {Object} config - Configuration to update
|
||||
* @param {string} [config.discord_webhook_url] - Discord webhook URL
|
||||
* @param {string} [config.telegram_chat_id] - Telegram chat ID
|
||||
* @param {string} [config.email] - Email address
|
||||
* @param {boolean} [config.notification_enabled] - Enable/disable notifications
|
||||
* @param {Object} config
|
||||
* @param {string} [config.discord_webhook_url]
|
||||
* @param {string} [config.telegram_chat_id]
|
||||
* @param {string} [config.telegram_bot_token]
|
||||
* @param {string} [config.email]
|
||||
* @param {string} [config.slack_webhook_url]
|
||||
* @param {boolean} [config.notification_enabled]
|
||||
* @returns {Promise<Object>} Updated config
|
||||
*/
|
||||
export async function updateNotificationConfig(config) {
|
||||
@@ -77,27 +77,107 @@ export async function updateNotificationConfig(config) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Test a Discord webhook URL
|
||||
* Sends a test message to verify the webhook works
|
||||
* @param {string} webhookUrl - Discord webhook URL to test
|
||||
* @returns {Promise<boolean>} True if test successful
|
||||
* Set up email notifications via Resend.
|
||||
* Reads the user's saved email from their config and sends a confirmation.
|
||||
* @returns {Promise<Object>} Setup result
|
||||
*/
|
||||
export async function testDiscordWebhook(webhookUrl) {
|
||||
export async function setupEmail() {
|
||||
try {
|
||||
const payload = {
|
||||
content:
|
||||
"Koin Ping test notification - Your Discord webhook is configured correctly!",
|
||||
};
|
||||
|
||||
const response = await fetch(webhookUrl, {
|
||||
const headers = await getAuthHeaders();
|
||||
const response = await fetch(`${API_BASE}/email/setup`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(payload),
|
||||
headers: headers,
|
||||
});
|
||||
|
||||
return response.ok;
|
||||
if (!response.ok) {
|
||||
let errorMessage = "Failed to set up email";
|
||||
try {
|
||||
const error = await response.json();
|
||||
errorMessage = error.message || errorMessage;
|
||||
} catch {
|
||||
errorMessage = `Server error: ${response.status} ${response.statusText}`;
|
||||
}
|
||||
throw new Error(errorMessage);
|
||||
}
|
||||
|
||||
return response.json();
|
||||
} catch (error) {
|
||||
console.error("Discord webhook test failed:", error);
|
||||
return false;
|
||||
if (error.message.includes("fetch")) {
|
||||
throw new Error(
|
||||
"Cannot connect to server. Is the backend running?",
|
||||
);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send an alert digest email to the user's configured email address.
|
||||
* @returns {Promise<Object>} Digest send result
|
||||
*/
|
||||
export async function sendEmailDigest() {
|
||||
try {
|
||||
const headers = await getAuthHeaders();
|
||||
const response = await fetch(`${API_BASE}/email/digest`, {
|
||||
method: "POST",
|
||||
headers: headers,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
let errorMessage = "Failed to send digest";
|
||||
try {
|
||||
const error = await response.json();
|
||||
errorMessage = error.message || errorMessage;
|
||||
} catch {
|
||||
errorMessage = `Server error: ${response.status} ${response.statusText}`;
|
||||
}
|
||||
throw new Error(errorMessage);
|
||||
}
|
||||
|
||||
return response.json();
|
||||
} catch (error) {
|
||||
if (error.message.includes("fetch")) {
|
||||
throw new Error(
|
||||
"Cannot connect to server. Is the backend running?",
|
||||
);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Test all configured notification channels via the backend
|
||||
* @returns {Promise<Object>} Results per channel
|
||||
*/
|
||||
export async function testNotificationChannels() {
|
||||
try {
|
||||
const headers = await getAuthHeaders();
|
||||
const response = await fetch(
|
||||
`${API_BASE}/notification-config/test`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: headers,
|
||||
},
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
let errorMessage = "Failed to test notification channels";
|
||||
try {
|
||||
const error = await response.json();
|
||||
errorMessage = error.message || errorMessage;
|
||||
} catch {
|
||||
errorMessage = `Server error: ${response.status} ${response.statusText}`;
|
||||
}
|
||||
throw new Error(errorMessage);
|
||||
}
|
||||
|
||||
return response.json();
|
||||
} catch (error) {
|
||||
if (error.message.includes("fetch")) {
|
||||
throw new Error(
|
||||
"Cannot connect to server. Is the backend running?",
|
||||
);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import AddressForm from "../components/AddressForm";
|
||||
import { getAddresses, createAddress } from "../api/addresses";
|
||||
import { getAddresses, createAddress, deleteAddress, updateAddress } from "../api/addresses";
|
||||
|
||||
export default function Addresses() {
|
||||
const [addresses, setAddresses] = useState([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState(null);
|
||||
const [editingId, setEditingId] = useState(null);
|
||||
const [editLabel, setEditLabel] = useState("");
|
||||
|
||||
// Load addresses on mount
|
||||
useEffect(() => {
|
||||
@@ -29,15 +31,52 @@ export default function Addresses() {
|
||||
async function handleAddressSubmit(data) {
|
||||
try {
|
||||
const newAddress = await createAddress(data);
|
||||
// Append new address to state
|
||||
setAddresses((prev) => [...prev, newAddress]);
|
||||
setError(null); // Clear any previous errors
|
||||
setError(null);
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
console.error("Failed to create address:", err);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleDelete(id, label) {
|
||||
const displayName = label || "this address";
|
||||
if (!window.confirm(`Remove "${displayName}"? This will also delete all associated alert rules.`)) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await deleteAddress(id);
|
||||
setAddresses((prev) => prev.filter((a) => a.id !== id));
|
||||
setError(null);
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
console.error("Failed to delete address:", err);
|
||||
}
|
||||
}
|
||||
|
||||
function handleEditStart(addr) {
|
||||
setEditingId(addr.id);
|
||||
setEditLabel(addr.label ?? "");
|
||||
}
|
||||
|
||||
async function handleEditSave(id) {
|
||||
try {
|
||||
const updated = await updateAddress(id, { label: editLabel || null });
|
||||
setAddresses((prev) => prev.map((a) => (a.id === id ? updated : a)));
|
||||
setEditingId(null);
|
||||
setEditLabel("");
|
||||
setError(null);
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
console.error("Failed to update address:", err);
|
||||
}
|
||||
}
|
||||
|
||||
function handleEditCancel() {
|
||||
setEditingId(null);
|
||||
setEditLabel("");
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={{ maxWidth: "800px", margin: "0 auto", padding: "2rem" }}>
|
||||
<h1>Tracked Addresses</h1>
|
||||
@@ -68,22 +107,88 @@ export default function Addresses() {
|
||||
backgroundColor: "#333",
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
fontWeight: "bold",
|
||||
marginBottom: "0.25rem",
|
||||
}}
|
||||
>
|
||||
{addr.label || "Unlabeled"}
|
||||
</div>
|
||||
<div
|
||||
style={{
|
||||
fontFamily: "monospace",
|
||||
fontSize: "1.035rem",
|
||||
color: "#b3b3b3",
|
||||
}}
|
||||
>
|
||||
{addr.address}
|
||||
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
|
||||
<div style={{ flex: 1 }}>
|
||||
{editingId === addr.id ? (
|
||||
<div style={{ display: "flex", gap: "0.5rem", alignItems: "center", marginBottom: "0.25rem" }}>
|
||||
<input
|
||||
value={editLabel}
|
||||
onChange={(e) => setEditLabel(e.target.value)}
|
||||
placeholder="Label (optional)"
|
||||
style={{
|
||||
background: "#444",
|
||||
border: "1px solid #666",
|
||||
borderRadius: "3px",
|
||||
color: "#fff",
|
||||
padding: "0.25rem 0.5rem",
|
||||
fontSize: "0.9rem",
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter") handleEditSave(addr.id);
|
||||
if (e.key === "Escape") handleEditCancel();
|
||||
}}
|
||||
autoFocus
|
||||
/>
|
||||
<button
|
||||
onClick={() => handleEditSave(addr.id)}
|
||||
style={{ cursor: "pointer", padding: "0.25rem 0.6rem", fontSize: "0.85rem" }}
|
||||
>
|
||||
Save
|
||||
</button>
|
||||
<button
|
||||
onClick={handleEditCancel}
|
||||
style={{ cursor: "pointer", padding: "0.25rem 0.6rem", fontSize: "0.85rem", background: "transparent", color: "#aaa", border: "1px solid #555" }}
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div style={{ display: "flex", alignItems: "center", gap: "0.5rem", marginBottom: "0.25rem" }}>
|
||||
<span style={{ fontWeight: "bold" }}>
|
||||
{addr.label || "Unlabeled"}
|
||||
</span>
|
||||
<button
|
||||
onClick={() => handleEditStart(addr)}
|
||||
style={{
|
||||
cursor: "pointer",
|
||||
background: "transparent",
|
||||
border: "none",
|
||||
color: "#6699cc",
|
||||
fontSize: "0.8rem",
|
||||
padding: "0",
|
||||
textDecoration: "underline",
|
||||
}}
|
||||
>
|
||||
Edit
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
<div
|
||||
style={{
|
||||
fontFamily: "monospace",
|
||||
fontSize: "1.035rem",
|
||||
color: "#b3b3b3",
|
||||
}}
|
||||
>
|
||||
{addr.address}
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => handleDelete(addr.id, addr.label)}
|
||||
style={{
|
||||
cursor: "pointer",
|
||||
background: "transparent",
|
||||
border: "1px solid #884444",
|
||||
color: "#cc6666",
|
||||
borderRadius: "3px",
|
||||
padding: "0.3rem 0.7rem",
|
||||
fontSize: "0.85rem",
|
||||
marginLeft: "1rem",
|
||||
flexShrink: 0,
|
||||
}}
|
||||
>
|
||||
Remove
|
||||
</button>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import AlertForm from "../components/AlertForm";
|
||||
import Button from "../components/Button";
|
||||
import Input from "../components/Input";
|
||||
import { getAddresses } from "../api/addresses";
|
||||
import {
|
||||
getAlerts,
|
||||
@@ -12,9 +11,40 @@ import {
|
||||
import {
|
||||
getNotificationConfig,
|
||||
updateNotificationConfig,
|
||||
testDiscordWebhook,
|
||||
testNotificationChannels,
|
||||
setupEmail,
|
||||
sendEmailDigest,
|
||||
} from "../api/notificationConfig";
|
||||
|
||||
const inputStyle = {
|
||||
width: "100%",
|
||||
padding: "0.5rem",
|
||||
fontSize: "0.9rem",
|
||||
backgroundColor: "#1a1a1a",
|
||||
border: "1px solid #444",
|
||||
borderRadius: "4px",
|
||||
color: "white",
|
||||
fontFamily: "monospace",
|
||||
boxSizing: "border-box",
|
||||
};
|
||||
|
||||
const labelStyle = {
|
||||
display: "block",
|
||||
marginBottom: "0.25rem",
|
||||
fontSize: "0.9rem",
|
||||
color: "#ccc",
|
||||
};
|
||||
|
||||
const helpLinkStyle = { color: "#0066cc", fontSize: "0.85rem" };
|
||||
|
||||
const sectionStyle = {
|
||||
marginBottom: "1.5rem",
|
||||
padding: "1rem",
|
||||
backgroundColor: "#2a2a2a",
|
||||
borderRadius: "6px",
|
||||
border: "1px solid #3a3a3a",
|
||||
};
|
||||
|
||||
export default function Alerts() {
|
||||
const [addresses, setAddresses] = useState([]);
|
||||
const [selectedAddressId, setSelectedAddressId] = useState(null);
|
||||
@@ -23,34 +53,48 @@ export default function Alerts() {
|
||||
const [error, setError] = useState(null);
|
||||
|
||||
// Notification config state
|
||||
const [notificationConfig, setNotificationConfig] = useState(null);
|
||||
const [notificationEnabled, setNotificationEnabled] = useState(false);
|
||||
const [discordWebhookUrl, setDiscordWebhookUrl] = useState("");
|
||||
const [notificationEnabled, setNotificationEnabled] = useState(true);
|
||||
const [telegramBotToken, setTelegramBotToken] = useState("");
|
||||
const [telegramChatId, setTelegramChatId] = useState("");
|
||||
const [email, setEmail] = useState("");
|
||||
const [slackWebhookUrl, setSlackWebhookUrl] = useState("");
|
||||
const [notificationLoading, setNotificationLoading] = useState(false);
|
||||
const [notificationError, setNotificationError] = useState(null);
|
||||
const [notificationSuccess, setNotificationSuccess] = useState(null);
|
||||
const [testingWebhook, setTestingWebhook] = useState(false);
|
||||
const [testingChannels, setTestingChannels] = useState(false);
|
||||
const [settingUpEmail, setSettingUpEmail] = useState(false);
|
||||
const [sendingDigest, setSendingDigest] = useState(false);
|
||||
const [hasExistingConfig, setHasExistingConfig] = useState(false);
|
||||
|
||||
// Load addresses and notification config on mount
|
||||
useEffect(() => {
|
||||
async function fetchData() {
|
||||
try {
|
||||
setLoading(true);
|
||||
|
||||
// Fetch addresses
|
||||
const addressData = await getAddresses();
|
||||
setAddresses(addressData);
|
||||
if (addressData.length > 0) {
|
||||
setSelectedAddressId(addressData[0].id);
|
||||
}
|
||||
|
||||
// Fetch notification config
|
||||
const configData = await getNotificationConfig();
|
||||
setNotificationConfig(configData);
|
||||
setDiscordWebhookUrl(configData.discord_webhook_url || "");
|
||||
setNotificationEnabled(
|
||||
configData.notification_enabled !== false,
|
||||
);
|
||||
setDiscordWebhookUrl(configData.discord_webhook_url || "");
|
||||
setTelegramBotToken(configData.telegram_bot_token || "");
|
||||
setTelegramChatId(configData.telegram_chat_id || "");
|
||||
setEmail(configData.email || "");
|
||||
setSlackWebhookUrl(configData.slack_webhook_url || "");
|
||||
|
||||
const hasSaved =
|
||||
!!configData.discord_webhook_url ||
|
||||
!!configData.telegram_bot_token ||
|
||||
!!configData.telegram_chat_id ||
|
||||
!!configData.email ||
|
||||
!!configData.slack_webhook_url;
|
||||
setHasExistingConfig(hasSaved);
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
console.error("Failed to fetch data:", err);
|
||||
@@ -62,7 +106,6 @@ export default function Alerts() {
|
||||
fetchData();
|
||||
}, []);
|
||||
|
||||
// Load alerts when address is selected
|
||||
useEffect(() => {
|
||||
if (!selectedAddressId) {
|
||||
setAlerts([]);
|
||||
@@ -73,7 +116,7 @@ export default function Alerts() {
|
||||
try {
|
||||
const data = await getAlerts(selectedAddressId);
|
||||
setAlerts(data);
|
||||
setError(null); // Clear any previous errors
|
||||
setError(null);
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
console.error("Failed to fetch alerts:", err);
|
||||
@@ -83,63 +126,68 @@ export default function Alerts() {
|
||||
fetchAlerts();
|
||||
}, [selectedAddressId]);
|
||||
|
||||
// Handle new alert submission
|
||||
async function handleAlertSubmit(data) {
|
||||
if (!selectedAddressId) return;
|
||||
|
||||
try {
|
||||
const newAlert = await createAlert(selectedAddressId, data);
|
||||
setAlerts((prev) => [...prev, newAlert]);
|
||||
setError(null); // Clear any previous errors
|
||||
setError(null);
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
console.error("Failed to create alert:", err);
|
||||
}
|
||||
}
|
||||
|
||||
// Toggle alert enabled/disabled
|
||||
async function handleToggleAlert(alertId, currentStatus) {
|
||||
try {
|
||||
const updated = await updateAlertStatus(alertId, !currentStatus);
|
||||
setAlerts((prev) =>
|
||||
prev.map((alert) => (alert.id === alertId ? updated : alert)),
|
||||
);
|
||||
setError(null); // Clear any previous errors
|
||||
setError(null);
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
console.error("Failed to update alert:", err);
|
||||
}
|
||||
}
|
||||
|
||||
// Delete alert
|
||||
async function handleDeleteAlert(alertId) {
|
||||
try {
|
||||
await deleteAlert(alertId);
|
||||
setAlerts((prev) => prev.filter((alert) => alert.id !== alertId));
|
||||
setError(null); // Clear any previous errors
|
||||
setError(null);
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
console.error("Failed to delete alert:", err);
|
||||
}
|
||||
}
|
||||
|
||||
// Save notification config
|
||||
async function handleSaveNotificationConfig() {
|
||||
if (hasExistingConfig) {
|
||||
const confirmed = window.confirm(
|
||||
"This will overwrite your previously saved notification settings. Continue?",
|
||||
);
|
||||
if (!confirmed) return;
|
||||
}
|
||||
|
||||
try {
|
||||
setNotificationLoading(true);
|
||||
setNotificationError(null);
|
||||
setNotificationSuccess(null);
|
||||
|
||||
const config = {
|
||||
discord_webhook_url: discordWebhookUrl || null,
|
||||
notification_enabled: notificationEnabled,
|
||||
discord_webhook_url: discordWebhookUrl || null,
|
||||
telegram_bot_token: telegramBotToken || null,
|
||||
telegram_chat_id: telegramChatId || null,
|
||||
email: email || null,
|
||||
slack_webhook_url: slackWebhookUrl || null,
|
||||
};
|
||||
|
||||
const updated = await updateNotificationConfig(config);
|
||||
setNotificationConfig(updated);
|
||||
await updateNotificationConfig(config);
|
||||
setHasExistingConfig(true);
|
||||
setNotificationSuccess("Notification settings saved!");
|
||||
|
||||
// Clear success message after 3 seconds
|
||||
setTimeout(() => setNotificationSuccess(null), 3000);
|
||||
} catch (err) {
|
||||
setNotificationError(err.message);
|
||||
@@ -149,32 +197,76 @@ export default function Alerts() {
|
||||
}
|
||||
}
|
||||
|
||||
// Test Discord webhook
|
||||
async function handleTestWebhook() {
|
||||
if (!discordWebhookUrl) {
|
||||
setNotificationError("Please enter a Discord webhook URL first");
|
||||
return;
|
||||
}
|
||||
|
||||
async function handleTestChannels() {
|
||||
try {
|
||||
setTestingWebhook(true);
|
||||
setTestingChannels(true);
|
||||
setNotificationError(null);
|
||||
setNotificationSuccess(null);
|
||||
|
||||
const success = await testDiscordWebhook(discordWebhookUrl);
|
||||
const data = await testNotificationChannels();
|
||||
const results = data.results || [];
|
||||
|
||||
if (success) {
|
||||
const failed = results.filter((r) => !r.success);
|
||||
const succeeded = results.filter((r) => r.success);
|
||||
|
||||
if (failed.length === 0 && succeeded.length > 0) {
|
||||
setNotificationSuccess(
|
||||
"Test notification sent! Check your Discord channel.",
|
||||
`Test sent to: ${succeeded.map((r) => r.channel).join(", ")}`,
|
||||
);
|
||||
} else if (failed.length > 0 && succeeded.length > 0) {
|
||||
setNotificationSuccess(
|
||||
`Sent: ${succeeded.map((r) => r.channel).join(", ")}. Failed: ${failed.map((r) => `${r.channel} (${r.error})`).join(", ")}`,
|
||||
);
|
||||
} else if (failed.length > 0) {
|
||||
setNotificationError(
|
||||
`Test failed: ${failed.map((r) => `${r.channel} (${r.error})`).join(", ")}`,
|
||||
);
|
||||
setTimeout(() => setNotificationSuccess(null), 5000);
|
||||
} else {
|
||||
setNotificationError("Test failed. Check your webhook URL.");
|
||||
}
|
||||
|
||||
setTimeout(() => {
|
||||
setNotificationSuccess(null);
|
||||
setNotificationError(null);
|
||||
}, 6000);
|
||||
} catch (err) {
|
||||
setNotificationError("Test failed: " + err.message);
|
||||
setNotificationError(err.message);
|
||||
} finally {
|
||||
setTestingWebhook(false);
|
||||
setTestingChannels(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSetupEmail() {
|
||||
try {
|
||||
setSettingUpEmail(true);
|
||||
setNotificationError(null);
|
||||
setNotificationSuccess(null);
|
||||
|
||||
await handleSaveNotificationConfig();
|
||||
|
||||
const result = await setupEmail();
|
||||
setNotificationSuccess(
|
||||
result.message || "Confirmation email sent!",
|
||||
);
|
||||
setTimeout(() => setNotificationSuccess(null), 5000);
|
||||
} catch (err) {
|
||||
setNotificationError(err.message);
|
||||
} finally {
|
||||
setSettingUpEmail(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSendDigest() {
|
||||
try {
|
||||
setSendingDigest(true);
|
||||
setNotificationError(null);
|
||||
setNotificationSuccess(null);
|
||||
|
||||
const result = await sendEmailDigest();
|
||||
setNotificationSuccess(result.message || "Digest email sent!");
|
||||
setTimeout(() => setNotificationSuccess(null), 5000);
|
||||
} catch (err) {
|
||||
setNotificationError(err.message);
|
||||
} finally {
|
||||
setSendingDigest(false);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -201,19 +293,18 @@ export default function Alerts() {
|
||||
Alert Rules & Notifications
|
||||
</h1>
|
||||
|
||||
{/* Two-column layout */}
|
||||
<div
|
||||
style={{
|
||||
display: "grid",
|
||||
gridTemplateColumns: "1fr 1fr",
|
||||
gap: "2rem",
|
||||
alignItems: "start",
|
||||
}}
|
||||
>
|
||||
{/* LEFT COLUMN: Alert Rules */}
|
||||
<div>
|
||||
<h2 style={{ marginTop: 0 }}>Alert Rules</h2>
|
||||
|
||||
{/* Address selector */}
|
||||
<div style={{ marginBottom: "2rem" }}>
|
||||
<label
|
||||
style={{ display: "block", marginBottom: "0.5rem" }}
|
||||
@@ -245,7 +336,6 @@ export default function Alerts() {
|
||||
|
||||
{selectedAddress && (
|
||||
<>
|
||||
{/* Current address info */}
|
||||
<div
|
||||
style={{
|
||||
padding: "1rem",
|
||||
@@ -282,13 +372,11 @@ export default function Alerts() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Alert creation form */}
|
||||
<div style={{ marginBottom: "2rem" }}>
|
||||
<h3>Create New Alert</h3>
|
||||
<AlertForm onSubmit={handleAlertSubmit} />
|
||||
</div>
|
||||
|
||||
{/* Existing alerts list */}
|
||||
<div>
|
||||
<h3>Active Alert Rules</h3>
|
||||
{error && (
|
||||
@@ -316,7 +404,7 @@ export default function Alerts() {
|
||||
marginBottom: "0.5rem",
|
||||
border: "1px solid #444",
|
||||
borderRadius: "4px",
|
||||
backgroundColor: "#333",
|
||||
backgroundColor: "#333",
|
||||
opacity: alert.enabled
|
||||
? 1
|
||||
: 0.6,
|
||||
@@ -449,7 +537,7 @@ export default function Alerts() {
|
||||
{/* Master toggle */}
|
||||
<div
|
||||
style={{
|
||||
marginBottom: "2rem",
|
||||
marginBottom: "1.5rem",
|
||||
padding: "1rem",
|
||||
backgroundColor: "#333",
|
||||
borderRadius: "4px",
|
||||
@@ -490,57 +578,208 @@ export default function Alerts() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Discord Section */}
|
||||
<div style={{ marginBottom: "2rem" }}>
|
||||
<h3 style={{ marginBottom: "1rem" }}>Discord</h3>
|
||||
{/* All channel settings — hidden when master toggle is off */}
|
||||
<div
|
||||
style={{
|
||||
display: notificationEnabled ? "block" : "none",
|
||||
}}
|
||||
>
|
||||
{/* Telegram */}
|
||||
<div style={sectionStyle}>
|
||||
<h3 style={{ marginTop: 0, marginBottom: "1rem" }}>
|
||||
Telegram
|
||||
</h3>
|
||||
|
||||
<div style={{ marginBottom: "1rem" }}>
|
||||
<label
|
||||
style={{
|
||||
display: "block",
|
||||
marginBottom: "0.5rem",
|
||||
}}
|
||||
<div style={{ marginBottom: "0.75rem" }}>
|
||||
<label style={labelStyle}>Bot Token</label>
|
||||
<input
|
||||
type="text"
|
||||
value={telegramBotToken}
|
||||
onChange={(e) =>
|
||||
setTelegramBotToken(e.target.value)
|
||||
}
|
||||
placeholder="123456789:ABCdefGHIjklMNOpqrSTUvwxYZ"
|
||||
style={inputStyle}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div style={{ marginBottom: "0.5rem" }}>
|
||||
<label style={labelStyle}>Chat ID</label>
|
||||
<input
|
||||
type="text"
|
||||
value={telegramChatId}
|
||||
onChange={(e) =>
|
||||
setTelegramChatId(e.target.value)
|
||||
}
|
||||
placeholder="-1001234567890"
|
||||
style={inputStyle}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<a
|
||||
href="https://core.telegram.org/bots#how-do-i-create-a-bot"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
style={helpLinkStyle}
|
||||
>
|
||||
Discord Webhook URL
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={discordWebhookUrl}
|
||||
onChange={(e) =>
|
||||
setDiscordWebhookUrl(e.target.value)
|
||||
}
|
||||
placeholder="https://discord.com/api/webhooks/..."
|
||||
style={{
|
||||
width: "100%",
|
||||
padding: "0.5rem",
|
||||
fontSize: "1rem",
|
||||
backgroundColor: "#1a1a1a",
|
||||
border: "1px solid #444",
|
||||
borderRadius: "4px",
|
||||
color: "white",
|
||||
fontFamily: "monospace",
|
||||
fontSize: "0.9rem",
|
||||
}}
|
||||
/>
|
||||
How to create a Telegram bot & get your Chat ID
|
||||
</a>
|
||||
</div>
|
||||
|
||||
{/* Email */}
|
||||
<div style={sectionStyle}>
|
||||
<h3 style={{ marginTop: 0, marginBottom: "1rem" }}>
|
||||
Email
|
||||
</h3>
|
||||
|
||||
<div style={{ marginBottom: "0.75rem" }}>
|
||||
<label style={labelStyle}>Email Address</label>
|
||||
<input
|
||||
type="email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
placeholder="you@example.com"
|
||||
style={inputStyle}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div
|
||||
style={{
|
||||
fontSize: "0.978rem",
|
||||
color: "#b3b3b3",
|
||||
marginTop: "0.5rem",
|
||||
fontSize: "0.85rem",
|
||||
color: "#808080",
|
||||
marginBottom: "0.75rem",
|
||||
}}
|
||||
>
|
||||
<a
|
||||
href="https://support.discord.com/hc/en-us/articles/228383668-Intro-to-Webhooks"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
style={{ color: "#0066cc" }}
|
||||
Alert notifications and digests will be sent to
|
||||
this address
|
||||
</div>
|
||||
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
gap: "0.5rem",
|
||||
}}
|
||||
>
|
||||
<button
|
||||
onClick={handleSetupEmail}
|
||||
disabled={settingUpEmail || !email}
|
||||
style={{
|
||||
padding: "0.5rem 1rem",
|
||||
fontSize: "0.85rem",
|
||||
backgroundColor:
|
||||
settingUpEmail || !email
|
||||
? "#333"
|
||||
: "#0066cc",
|
||||
color: "white",
|
||||
border: "none",
|
||||
borderRadius: "4px",
|
||||
cursor:
|
||||
settingUpEmail || !email
|
||||
? "not-allowed"
|
||||
: "pointer",
|
||||
}}
|
||||
>
|
||||
How to get a Discord webhook URL
|
||||
</a>
|
||||
{settingUpEmail
|
||||
? "Setting up..."
|
||||
: "Verify Email"}
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={handleSendDigest}
|
||||
disabled={sendingDigest || !email}
|
||||
style={{
|
||||
padding: "0.5rem 1rem",
|
||||
fontSize: "0.85rem",
|
||||
backgroundColor:
|
||||
sendingDigest || !email
|
||||
? "#333"
|
||||
: "#6c757d",
|
||||
color: "white",
|
||||
border: "none",
|
||||
borderRadius: "4px",
|
||||
cursor:
|
||||
sendingDigest || !email
|
||||
? "not-allowed"
|
||||
: "pointer",
|
||||
}}
|
||||
>
|
||||
{sendingDigest
|
||||
? "Sending..."
|
||||
: "Send Digest Now"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style={{ display: "flex", gap: "0.5rem" }}>
|
||||
{/* Discord */}
|
||||
<div style={sectionStyle}>
|
||||
<h3 style={{ marginTop: 0, marginBottom: "1rem" }}>
|
||||
Discord
|
||||
</h3>
|
||||
|
||||
<div style={{ marginBottom: "0.5rem" }}>
|
||||
<label style={labelStyle}>
|
||||
Discord Webhook URL
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={discordWebhookUrl}
|
||||
onChange={(e) =>
|
||||
setDiscordWebhookUrl(e.target.value)
|
||||
}
|
||||
placeholder="https://discord.com/api/webhooks/..."
|
||||
style={inputStyle}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<a
|
||||
href="https://support.discord.com/hc/en-us/articles/228383668-Intro-to-Webhooks"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
style={helpLinkStyle}
|
||||
>
|
||||
How to get a Discord webhook URL
|
||||
</a>
|
||||
</div>
|
||||
|
||||
{/* Slack */}
|
||||
<div style={sectionStyle}>
|
||||
<h3 style={{ marginTop: 0, marginBottom: "1rem" }}>
|
||||
Slack
|
||||
</h3>
|
||||
|
||||
<div style={{ marginBottom: "0.5rem" }}>
|
||||
<label style={labelStyle}>
|
||||
Slack Webhook URL
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={slackWebhookUrl}
|
||||
onChange={(e) =>
|
||||
setSlackWebhookUrl(e.target.value)
|
||||
}
|
||||
placeholder="https://hooks.slack.com/services/..."
|
||||
style={inputStyle}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<a
|
||||
href="https://api.slack.com/messaging/webhooks"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
style={helpLinkStyle}
|
||||
>
|
||||
How to set up Slack Incoming Webhooks
|
||||
</a>
|
||||
</div>
|
||||
|
||||
{/* Save & Test buttons at the bottom */}
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
gap: "0.75rem",
|
||||
marginTop: "1rem",
|
||||
}}
|
||||
>
|
||||
<button
|
||||
onClick={handleSaveNotificationConfig}
|
||||
disabled={notificationLoading}
|
||||
@@ -564,67 +803,34 @@ export default function Alerts() {
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={handleTestWebhook}
|
||||
disabled={testingWebhook || !discordWebhookUrl}
|
||||
onClick={handleTestChannels}
|
||||
disabled={testingChannels}
|
||||
style={{
|
||||
padding: "0.75rem 1.5rem",
|
||||
fontSize: "1rem",
|
||||
backgroundColor:
|
||||
testingWebhook || !discordWebhookUrl
|
||||
? "#333"
|
||||
: "#28a745",
|
||||
backgroundColor: testingChannels
|
||||
? "#333"
|
||||
: "#28a745",
|
||||
color: "white",
|
||||
border: "none",
|
||||
borderRadius: "4px",
|
||||
cursor:
|
||||
testingWebhook || !discordWebhookUrl
|
||||
? "not-allowed"
|
||||
: "pointer",
|
||||
cursor: testingChannels
|
||||
? "not-allowed"
|
||||
: "pointer",
|
||||
}}
|
||||
>
|
||||
{testingWebhook ? "Testing..." : "Test Webhook"}
|
||||
{testingChannels
|
||||
? "Testing..."
|
||||
: "Test All Channels"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Telegram Section (Coming Soon) */}
|
||||
<div style={{ marginBottom: "2rem", opacity: 0.5 }}>
|
||||
<h3 style={{ marginBottom: "1rem" }}>Telegram</h3>
|
||||
<div
|
||||
style={{
|
||||
padding: "1rem",
|
||||
backgroundColor: "#333",
|
||||
borderRadius: "4px",
|
||||
color: "#999",
|
||||
textAlign: "center",
|
||||
}}
|
||||
>
|
||||
Coming Soon
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Email Section (Coming Soon) */}
|
||||
<div style={{ opacity: 0.5 }}>
|
||||
<h3 style={{ marginBottom: "1rem" }}>Email</h3>
|
||||
<div
|
||||
style={{
|
||||
padding: "1rem",
|
||||
backgroundColor: "#333",
|
||||
borderRadius: "4px",
|
||||
color: "#999",
|
||||
textAlign: "center",
|
||||
}}
|
||||
>
|
||||
Coming Soon
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Helper to format alert type for display
|
||||
function formatAlertType(type) {
|
||||
const labels = {
|
||||
incoming_tx: "Incoming transaction",
|
||||
|
||||
Reference in New Issue
Block a user