Skip to content

Conversation

@shoom3301
Copy link
Collaborator

@shoom3301 shoom3301 commented Apr 24, 2025

Summary

Needs cowprotocol/cms#60 to be merged first, before testing.
The bug was in the fact that we called POST /add-tg-subscription just if we have a Telegram auth session, which is not right.
Now we do:

  1. Check Telegram authentication
  2. If not authenticated, then display a toggle
  3. If authenticated, check the Telegram subscription for given account
  4. If the account is subscribed, then display "Connected", otherwise display a toggle

When we click on the toggle, we do:

  1. If Telegram is authenticated, just add a subscription to CMS
  2. Otherwise, authorize in telegram first and only then add a subscription to CMS

To Test

  1. Terminate all sessions in telegram and disconnect all accounts. Also will be great to remove all subscriptions in CMS (elegram subscription) of your account
  2. Open CoW Swap, open notifications settings
  • a toggle should be displayed
  1. Click on the toggle
  • it should initiate Telegram authorization, after successful authorization should subscribe your account
  • "connected" label should be displayed instead of the toggle
  1. Reload the page
  • "connected" label should be displayed
  1. Change an account in your wallet
  • a toggle should be displayed
  1. Click on the toggle
  • should not initiate a Telegram authorization
  • should subscribe your account
  • "connected" label should be displayed instead of the toggle

Summary by CodeRabbit

  • Refactor

    • Streamlined and reorganized the Telegram authentication and subscription process for notifications.
    • Unified subscription checks and actions into a single flow for improved reliability.
    • Updated terminology and button actions for a clearer user experience when connecting Telegram.
  • Bug Fixes

    • Improved handling of subscription status to prevent repeated or unnecessary subscription attempts.

@vercel
Copy link

vercel bot commented Apr 24, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Updated (UTC)
cowfi ✅ Ready (Inspect) Visit Preview Apr 24, 2025 0:59am
explorer-dev ✅ Ready (Inspect) Visit Preview Apr 24, 2025 0:59am
swap-dev ✅ Ready (Inspect) Visit Preview Apr 24, 2025 0:59am
3 Skipped Deployments
Name Status Preview Updated (UTC)
cosmos ⬜️ Ignored (Inspect) Visit Preview Apr 24, 2025 0:59am
sdk-tools ⬜️ Ignored (Inspect) Visit Preview Apr 24, 2025 0:59am
widget-configurator ⬜️ Ignored (Inspect) Visit Preview Apr 24, 2025 0:59am

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Apr 24, 2025

Walkthrough

This change refactors the Telegram authentication and subscription logic in the frontend application. The functions handling authentication and authorization are renamed and their responsibilities swapped for clarity. A new helper function is introduced to unify checking and adding Telegram subscriptions, and a new function manages the conditional subscription flow. The effect for managing subscription status is updated to use the new helper. The TelegramConnectionStatus component is updated to receive the new function as a prop, with corresponding interface changes. No other logic or control flow outside of these components is modified.

Changes

File(s) Change Summary
.../ConnectTelegram.tsx Refactored Telegram auth/subscription logic: swapped/renamed authorize and authenticate, added checkOrAddTgSubscription and subscribeAccount, updated effect to use new helper, removed isDataReceivedRef, updated prop for TelegramConnectionStatus.
.../pure/TelegramConnectionStatus/index.tsx Renamed prop and interface parameter from authenticate to subscribeAccount in TelegramConnectionStatus.
.../pure/TelegramConnectionStatus/index.cosmos.tsx Updated fixture prop from authenticate to subscribeAccount for TelegramConnectionStatus component.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant ConnectTelegram
    participant TelegramAPI
    participant CMS

    User->>ConnectTelegram: Clicks Subscribe
    ConnectTelegram->>ConnectTelegram: subscribeAccount()
    alt Not subscribed
        ConnectTelegram->>TelegramAPI: authorize()
        TelegramAPI-->>ConnectTelegram: Auth callback
        ConnectTelegram->>CMS: checkOrAddTgSubscription('POST')
        CMS-->>ConnectTelegram: Subscription status
    else Already subscribed
        ConnectTelegram->>CMS: checkOrAddTgSubscription('POST')
        CMS-->>ConnectTelegram: Subscription status
    end
    ConnectTelegram-->>User: Update subscription state
Loading

Possibly related PRs

  • cowprotocol/cowswap#5613: Introduces the initial Telegram authentication and subscription logic in the same files, making this PR a direct continuation and reorganization of that work.

Poem

A bunny taps the Telegram line,
With new names swapped, the functions align.
Subscriptions now check or add with flair,
Cleaner flows hop through the air.
The status toggles, the code feels light—
Telegram connections, working right!
🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 201642d and b1fe5b2.

📒 Files selected for processing (1)
  • apps/cowswap-frontend/src/modules/notifications/pure/TelegramConnectionStatus/index.cosmos.tsx (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • apps/cowswap-frontend/src/modules/notifications/pure/TelegramConnectionStatus/index.cosmos.tsx
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Lint
  • GitHub Check: Test
  • GitHub Check: Cypress
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🔭 Outside diff range comments (1)
apps/cowswap-frontend/src/modules/notifications/containers/ConnectTelegram.tsx (1)

64-74: 🛠️ Refactor suggestion

Missing fallback when the Telegram SDK is not yet injected

authorize bails out early if window.Telegram is undefined. In that case the user has no way to progress because the callback is never executed and the script may still load a few milliseconds later.

Consider:

  1. Moving setIsLoginInProgress(true) above the window.Telegram guard and
  2. Falling back to authenticate(callback) rather than returning immediately.

This keeps the UI in a predictable state and still honours the happy path once the widget finishes loading.

🧹 Nitpick comments (2)
apps/cowswap-frontend/src/modules/notifications/containers/ConnectTelegram.tsx (2)

55-60: Use optional chaining to simplify null-checks

The static-analysis hint is correct – the manual check response && response.user can be replaced by optional chaining to make the intent clearer and avoid the double read of response.user.

-    if (response && response.user) {
-      setTgData(response.user)
-    }
+    const user = response?.user
+    if (user) {
+      setTgData(user)
+    }
🧰 Tools
🪛 Biome (1.9.4)

[error] 56-56: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


98-108: Guard against duplicate subscription attempts

subscribeAccount always calls addSubscription() even if isTgSubscribed
is already truthy after authorize. This is harmless server-side but still
fires an unnecessary network request (and spinner) every time.

Add a check right before invoking addSubscription():

-      addSubscription()
+      if (!isTgSubscribed) {
+        addSubscription()
+      }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1350e61 and 1d5055a.

📒 Files selected for processing (2)
  • apps/cowswap-frontend/src/modules/notifications/containers/ConnectTelegram.tsx (4 hunks)
  • apps/cowswap-frontend/src/modules/notifications/pure/TelegramConnectionStatus/index.tsx (1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
apps/cowswap-frontend/src/modules/notifications/containers/ConnectTelegram.tsx

[error] 56-56: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Cypress
  • GitHub Check: Setup
🔇 Additional comments (1)
apps/cowswap-frontend/src/modules/notifications/pure/TelegramConnectionStatus/index.tsx (1)

22-32: Prop rename looks good – no further action required

The interface rename from authenticate to subscribeAccount aligns the presentational component with the new logic in the container, and the callback is still passed unchanged to the Toggle. No other regressions spotted in this hunk.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

♻️ Duplicate comments (1)
apps/cowswap-frontend/src/modules/notifications/containers/ConnectTelegram.tsx (1)

83-96: 🛠️ Refactor suggestion

Endpoints should be consistent with leading slashes.

The method parameter is receiving endpoints with inconsistent leading slashes ('add-tg-subscription' in one place and '/check-tg-subscription' elsewhere). This could cause request failures if the CMS client concatenates paths naively.

- const checkOrAddTgSubscription = (method: string) => {
+ const checkOrAddTgSubscription = (endpoint: string) => {

Also ensure all calls to this function use consistent leading slashes in the endpoints.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1d5055a and 0dd9682.

📒 Files selected for processing (1)
  • apps/cowswap-frontend/src/modules/notifications/containers/ConnectTelegram.tsx (4 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
apps/cowswap-frontend/src/modules/notifications/containers/ConnectTelegram.tsx

[error] 56-56: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🪛 GitHub Actions: CI
apps/cowswap-frontend/src/modules/notifications/containers/ConnectTelegram.tsx

[error] 127-127: ESLint: React Hook useEffect has a missing dependency: 'checkOrAddTgSubscription'. Either include it or remove the dependency array (react-hooks/exhaustive-deps)

🔇 Additional comments (5)
apps/cowswap-frontend/src/modules/notifications/containers/ConnectTelegram.tsx (5)

54-62: Improved naming to match actual functionality.

The function renaming from authorize to authenticate better reflects its actual purpose - checking the authentication status using getTelegramAuth. This aligns with the updated flow where we don't automatically subscribe users.

🧰 Tools
🪛 Biome (1.9.4)

[error] 56-56: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


64-81: Improved function naming and callback handling.

The function has been correctly renamed from authenticate to authorize to better reflect its purpose of initiating the Telegram login flow. The callback is now properly called in all code paths which ensures proper flow completion.


98-108: Well-implemented conditional subscription flow.

The new subscribeAccount function properly implements the required flow: initiating Telegram authorization first if needed, or directly adding a subscription if already authenticated. This resolves the core issue described in the PR objectives.


118-118: Correct update to use authenticate instead of authorize.

The initial authentication effect now properly calls authenticate instead of authorize, which aligns with the new flow of checking authentication status first without automatic subscription.


153-157: Correct prop update for TelegramConnectionStatus component.

The component now correctly receives the subscribeAccount function as a prop instead of the previous authenticate function, which aligns with the updated subscription handling flow.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🔭 Outside diff range comments (1)
apps/cowswap-frontend/src/modules/notifications/containers/ConnectTelegram.tsx (1)

64-73: ⚠️ Potential issue

Guard against window.Telegram.Login being undefined

window.Telegram might be present while window.Telegram.Login is still unavailable (e.g. partial script load or bot being blocked by CSP).
Calling window.Telegram.Login.auth without checking will throw a runtime error that cannot be caught by React’s error boundary.

-  if (!window.Telegram) return
+  if (!window.Telegram?.Login?.auth) {
+    // Fallback to a passive auth check
+    authenticate(callback)
+    return
+  }
♻️ Duplicate comments (1)
apps/cowswap-frontend/src/modules/notifications/containers/ConnectTelegram.tsx (1)

83-87: Rename misleading parameter methodendpoint

This util always issues an HTTP POST; the variable holds the CMS endpoint path, not the HTTP method. Renaming avoids confusion for future readers.

- const checkOrAddTgSubscription = useCallback(
-   (method: string) => {
+ const checkOrAddTgSubscription = useCallback(
+   (endpoint: string) => {-     getCmsClient().POST(method, { body: { account, data: tgData } })
+     getCmsClient().POST(endpoint, { body: { account, data: tgData } })
🧹 Nitpick comments (1)
apps/cowswap-frontend/src/modules/notifications/containers/ConnectTelegram.tsx (1)

55-60: Prefer optional–chaining for terser, safer null-checks

response && response.user is functionally fine but the linter has already flagged it (lint/complexity/useOptionalChain). Using optional–chaining keeps the code concise and prevents accidental mistakes when the object shape changes.

-  if (response && response.user) {
+  if (response?.user) {
🧰 Tools
🪛 Biome (1.9.4)

[error] 56-56: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0dd9682 and 201642d.

📒 Files selected for processing (1)
  • apps/cowswap-frontend/src/modules/notifications/containers/ConnectTelegram.tsx (5 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
apps/cowswap-frontend/src/modules/notifications/containers/ConnectTelegram.tsx

[error] 56-56: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Cypress
  • GitHub Check: Setup
🔇 Additional comments (1)
apps/cowswap-frontend/src/modules/notifications/containers/ConnectTelegram.tsx (1)

124-131: Possible race condition when switching accounts fast

setTgSubscribed(false) fires before launching the CMS request.
If the user changes wallets rapidly, an earlier request can finish after the newer one and overwrite state with a stale value.

Consider tracking the requested account in a ref and discarding late responses, or use an AbortController.

- .then(({ data: result }) => {
-   setTgSubscribed(result)
- })
+ .then(({ data: result }) => {
+   if (currentAccountRef.current === account) {
+     setTgSubscribed(result)
+   }
+ })

(Where currentAccountRef is updated on every account change.)
This prevents flickering “Connected” labels for the wrong account.

@shoom3301 shoom3301 merged commit 0f13e32 into develop Apr 24, 2025
14 of 15 checks passed
@shoom3301 shoom3301 deleted the fix/tg-account-sub branch April 24, 2025 12:59
@github-actions github-actions bot locked and limited conversation to collaborators Apr 24, 2025
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants