Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

(1CT) Add events when creating 1CT session in swap review #3971

Merged
merged 2 commits into from
Nov 26, 2024

Conversation

JoseRFelix
Copy link
Collaborator

Testing and Verifying

  • Can create 1CT session in swap review

Copy link

vercel bot commented Nov 26, 2024

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

Name Status Preview Comments Updated (UTC)
osmosis-frontend ✅ Ready (Inspect) Visit Preview 💬 Add feedback Nov 26, 2024 10:50pm
4 Skipped Deployments
Name Status Preview Comments Updated (UTC)
osmosis-frontend-datadog ⬜️ Ignored (Inspect) Visit Preview Nov 26, 2024 10:50pm
osmosis-frontend-dev ⬜️ Ignored (Inspect) Visit Preview Nov 26, 2024 10:50pm
osmosis-frontend-edgenet ⬜️ Ignored (Inspect) Nov 26, 2024 10:50pm
osmosis-testnet ⬜️ Ignored (Inspect) Visit Preview Nov 26, 2024 10:50pm

@JoseRFelix JoseRFelix requested review from a team November 26, 2024 17:47
Copy link
Contributor

coderabbitai bot commented Nov 26, 2024

Caution

Review failed

The pull request is closed.

Walkthrough

The pull request introduces several enhancements to the one-click trading functionality across multiple files. It adds a new function, onEnd1CTSession, to manage the termination of one-click trading sessions and incorporates logging capabilities for session events. The placeLimit function is updated to handle specific session messages, while other hooks are modified to ensure consistent event logging and error handling during session creation and trading processes. Overall, these changes aim to improve the management and tracking of one-click trading sessions.

Changes

File Change Summary
packages/web/hooks/limit-orders/use-place-limit.ts Added import for onEnd1CTSession. Modified placeLimit to check for oneClickMessages type "remove-1ct-session" and call onEnd1CTSession. Updated limitMessages population based on whether the account is a Ledger device.
packages/web/hooks/mutations/one-click-trading/use-create-one-click-trading-session.tsx Updated onAdd1CTSession to include a logEvent parameter for logging session start details. Removed inline logging from onSuccess and integrated logEvent in session creation workflow.
packages/web/hooks/mutations/one-click-trading/use-remove-one-click-trading-session.ts Added onEnd1CTSession function for ending sessions, which clears session data and logs the event. Updated useRemoveOneClickTradingSession to call onEnd1CTSession post-transaction.
packages/web/hooks/one-click-trading/use-one-click-trading-swap-review.ts Added authenticatorId to the return object in use1CTSwapReviewMessages for session identification during removal.
packages/web/hooks/use-swap.tsx Added import for onEnd1CTSession. Integrated logEvent from useAmplitudeAnalytics for logging during one-click trading sessions. Updated error handling related to overspending and network fees.
packages/stores/src/account/base.ts Updated signAndBroadcast method to allow onTxEvents to return a Promise<void>. Awaited onFulfill callback to ensure asynchronous operations are completed before proceeding.

Possibly related PRs

Suggested reviewers

  • CryptoAssassin1
  • jonator

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 eslint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

packages/stores/src/account/base.ts

Oops! Something went wrong! :(

ESLint: 8.50.0

ESLint couldn't find the config "prettier" to extend from. Please check that the name of the config is correct.

The config "prettier" was referenced from the config file in "/packages/stores/.eslintrc.js".

If you still have problems, please stop by https://eslint.org/chat/help to chat with the team.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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 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 and nitpick comments (6)
packages/web/hooks/mutations/one-click-trading/use-remove-one-click-trading-session.ts (2)

17-40: Consider refining event logging and error handling.

The implementation could be improved in two areas:

  1. Event logging should be conditional on successful session cleanup
  2. Error handling for async operations should be added

Consider this improved implementation:

 export async function onEnd1CTSession({
   accountStore,
   authenticatorId,
   logEvent,
 }: {
   accountStore: ReturnType<typeof useStore>["accountStore"];
   authenticatorId: string;
   logEvent: ReturnType<typeof useAmplitudeAnalytics>["logEvent"];
 }) {
-  const oneClickTradingInfo = await accountStore.getOneClickTradingInfo();
+  try {
+    const oneClickTradingInfo = await accountStore.getOneClickTradingInfo();

     if (oneClickTradingInfo?.authenticatorId === authenticatorId) {
       accountStore.setOneClickTradingInfo(undefined);
       accountStore.setShouldUseOneClickTrading({ nextValue: false });
       displayToast(
         {
           titleTranslationKey: "oneClickTrading.toast.oneClickTradingDisabled",
           captionTranslationKey: "oneClickTrading.toast.sessionEnded",
         },
         ToastType.ONE_CLICK_TRADING
       );
+      logEvent([EventName.OneClickTrading.endSession]);
     }
-  }
-  logEvent([EventName.OneClickTrading.endSession]);
+  } catch (error) {
+    console.error('Failed to end 1CT session:', error);
+    throw error;
+  }
 }

74-81: Enhance transaction error handling.

The current error message "Transaction failed" doesn't provide enough context for debugging or user feedback.

Consider this improvement:

             onFulfill: (tx) => {
               if (tx.code === 0) {
                 resolve(tx);
               } else {
-                reject(new Error("Transaction failed"));
+                reject(new Error(`Transaction failed with code ${tx.code}: ${tx.rawLog || 'No error details available'}`));
               }
             },
packages/web/hooks/one-click-trading/use-one-click-trading-swap-review.ts (1)

230-230: LGTM with a minor suggestion for type safety.

The addition of authenticatorId is correct and necessary for proper session tracking. While the non-null assertion is safe in this context (as this code path is only reached when removing an existing session), consider adding a runtime check for better type safety:

-authenticatorId: oneClickTradingInfo!.authenticatorId,
+authenticatorId: oneClickTradingInfo?.authenticatorId ?? (() => {
+  throw new Error('Attempting to remove 1CT session without authenticator ID');
+})(),
packages/web/hooks/mutations/one-click-trading/use-create-one-click-trading-session.tsx (3)

248-254: Add error handling for event logging

While the event logging implementation captures the essential session parameters, consider wrapping it in a try-catch block to ensure that any logging failures don't affect the session creation flow.

-  logEvent([
-    EventName.OneClickTrading.startSession,
-    {
-      spendLimit: Number(transaction1CTParams.spendLimit.toDec().toString()),
-      sessionPeriod: transaction1CTParams.sessionPeriod.end,
-    },
-  ]);
+  try {
+    logEvent([
+      EventName.OneClickTrading.startSession,
+      {
+        spendLimit: Number(transaction1CTParams.spendLimit.toDec().toString()),
+        sessionPeriod: transaction1CTParams.sessionPeriod.end,
+      },
+    ]);
+  } catch (error) {
+    console.warn('Failed to log one-click trading session start:', error);
+    // Session creation succeeded, so we don't want to throw the error
+  }

Line range hint 319-358: Consider using an enum for session periods

The switch statement for session periods could benefit from using an enum to make the code more maintainable and type-safe.

enum SessionPeriod {
  FIVE_MIN = '5min',
  TEN_MIN = '10min',
  THIRTY_MIN = '30min',
  ONE_HOUR = '1hour',
  THREE_HOURS = '3hours',
  TWELVE_HOURS = '12hours'
}

const SESSION_PERIOD_DURATIONS: Record<SessionPeriod, { value: number; unit: dayjs.ManipulateType }> = {
  [SessionPeriod.FIVE_MIN]: { value: 5, unit: 'minute' },
  [SessionPeriod.TEN_MIN]: { value: 10, unit: 'minute' },
  // ... other periods
};
🧰 Tools
🪛 Gitleaks (8.21.2)

188-188: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


Line range hint 411-447: Consider adding transaction error details

The error handling for transaction broadcasting could provide more specific error information to help with debugging.

-                  reject(new Error("Transaction failed"));
+                  reject(new Error(`Transaction failed with code ${tx.code}: ${tx.rawLog}`));
🧰 Tools
🪛 Gitleaks (8.21.2)

188-188: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 1df4386 and 73d5aa7.

📒 Files selected for processing (5)
  • packages/web/hooks/limit-orders/use-place-limit.ts (2 hunks)
  • packages/web/hooks/mutations/one-click-trading/use-create-one-click-trading-session.tsx (4 hunks)
  • packages/web/hooks/mutations/one-click-trading/use-remove-one-click-trading-session.ts (2 hunks)
  • packages/web/hooks/one-click-trading/use-one-click-trading-swap-review.ts (1 hunks)
  • packages/web/hooks/use-swap.tsx (3 hunks)
🔇 Additional comments (10)
packages/web/hooks/mutations/one-click-trading/use-create-one-click-trading-session.tsx (2)

186-186: LGTM: Well-typed event logging parameter addition

The addition of the logEvent parameter with proper typing ensures type safety and maintains consistency with the analytics system.

Also applies to: 201-201


483-483: LGTM: Proper event logging integration

The logEvent is correctly obtained from the analytics hook and properly passed to the session creation function.

packages/web/hooks/limit-orders/use-place-limit.ts (3)

20-20: LGTM: Clean import addition

The import statement for onEnd1CTSession is properly added and aligns with the PR's objective of implementing event logging for 1CT sessions.


406-407: LGTM: Event logging integration

The logEvent parameter is correctly passed to both session creation and termination functions, ensuring consistent event tracking.


408-416: Verify error handling for session termination

While the session termination logic is implemented correctly, we should ensure proper error handling for failed session terminations to maintain system stability.

Let's check for existing error handling patterns in the codebase:

Consider wrapping the session termination in a try-catch block to handle potential failures gracefully:

             } else if (
               shouldSend1CTTx &&
               oneClickMessages &&
               oneClickMessages.type === "remove-1ct-session"
             ) {
+              try {
                 onEnd1CTSession({
                   accountStore,
                   authenticatorId: oneClickMessages.authenticatorId,
                   logEvent,
                 });
+              } catch (error) {
+                console.error("Failed to end 1CT session:", error);
+                logEvent([EventName.OneClickTrading.sessionEndFailed, { error }]);
+              }
             }
packages/web/hooks/use-swap.tsx (5)

50-50: Import onEnd1CTSession Correctly Added

The import statement for onEnd1CTSession aligns with its usage in the code.


56-56: Import useAmplitudeAnalytics for Event Logging

The addition of useAmplitudeAnalytics is appropriate for analytics integration.


117-117: Extract logEvent from Analytics Hook

Initializing logEvent from useAmplitudeAnalytics is correctly implemented.


565-567: Pass logEvent to onAdd1CTSession

Passing logEvent ensures that session creation events are logged.


568-578: Pass logEvent to onEnd1CTSession

Including logEvent in onEnd1CTSession parameters ensures proper event logging when ending a 1CT session.

});
});

onEnd1CTSession({ accountStore, authenticatorId, logEvent });
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add error handling for session cleanup.

The onEnd1CTSession call should be wrapped in error handling to prevent silent failures and ensure consistent state.

Consider this improvement:

-    onEnd1CTSession({ accountStore, authenticatorId, logEvent });
+    try {
+      await onEnd1CTSession({ accountStore, authenticatorId, logEvent });
+    } catch (error) {
+      console.error('Failed to cleanup 1CT session:', error);
+      // Optionally show error toast to user
+      displayToast(
+        {
+          titleTranslationKey: "oneClickTrading.toast.cleanupError",
+          captionTranslationKey: "oneClickTrading.toast.tryAgain",
+        },
+        ToastType.ERROR
+      );
+    }

Committable suggestion skipped: line range outside the PR's diff.

@JoseRFelix JoseRFelix changed the title (Deposit/Withdraw) Add events when creating 1CT session in swap review (1CT) Add events when creating 1CT session in swap review Nov 26, 2024
* feat: split txs for Ledger

* fix: wrong override

* feat: default to non ledger behavior

* improvement: naming

* improvement: typos
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants