Skip to content

Comments

add okx provider#726

Merged
kvhnuke merged 4 commits intoenkryptcom:feat/okx-sol-swapfrom
Julian-dev28:add-okx-provider
Jul 9, 2025
Merged

add okx provider#726
kvhnuke merged 4 commits intoenkryptcom:feat/okx-sol-swapfrom
Julian-dev28:add-okx-provider

Conversation

@Julian-dev28
Copy link
Contributor

@Julian-dev28 Julian-dev28 commented Jul 8, 2025

Add OKX Provider Integration

Description

This PR adds integration with OKX's DEX aggregator API for token swaps on Solana. The implementation includes a new provider class that handles token swaps through OKX's API endpoints.

Changes

  • Added new OKX provider implementation in packages/swap/src/providers/okx/index.ts
  • Updated API endpoint from www.okx.com to web3.okx.com
  • Added required dependencies:
    • crypto-js for API authentication
    • dotenv for environment variable management
    • @types/crypto-js for TypeScript support

Technical Details

  • Implements the ProviderClass interface for OKX DEX aggregator
  • Supports token swaps on Solana network
  • Handles both native SOL and SPL tokens
  • Includes proper error handling and logging
  • Implements quote fetching and swap execution
  • Supports transaction status tracking

Dependencies Added

{
  "dependencies": {
    "crypto-js": "^4.2.0",
    "dotenv": "^16.4.1"
  },
  "devDependencies": {
    "@types/crypto-js": "^4.2.2"
  }
}

Testing

  • Test token swaps with native SOL
  • Test token swaps with SPL tokens
  • Verify quote accuracy

Documentation

  • Updated API documentation links to point to web3.okx.com
  • Added inline documentation for key methods and functionality

Security

  • Implements API authentication using HMAC-SHA256
  • Uses environment variables for sensitive API credentials
  • Properly handles API keys and secrets

Summary by CodeRabbit

  • New Features

    • Added support for the OKX DEX aggregator as a provider for Solana token swaps, including integration with OKX's Web3 API for quotes, swaps, and transaction status.
    • Introduced referral fee configurations for the OKX provider.
    • Extended transaction handling to support raw Solana transaction data.
    • Added new environment variable support for OKX API credentials.
  • Improvements

    • Enhanced fee calculation logic to handle raw Solana transactions gracefully.
    • Improved logging and debugging output for swap operations and transaction handling.
  • Dependencies

    • Added crypto-js and dotenv as new dependencies.
  • Types

    • Added new TypeScript interfaces for OKX API integration and updated enums to include OKX as a provider.

kvhnuke and others added 2 commits June 30, 2025 19:53
commit 0928965
Author: julian.martinez <julian_martinez28@outlook.com>
Date:   Mon Jul 7 17:08:14 2025 -0700

    end of buffer

commit 2f286c9
Author: julian.martinez <julian_martinez28@outlook.com>
Date:   Mon Jul 7 15:59:32 2025 -0700

    update okx provider logic

commit 12b50c2
Merge: a687ae4 98ad4a2
Author: julian.martinez <julian_martinez28@outlook.com>
Date:   Mon Jul 7 15:49:53 2025 -0700

    Merge branch 'main' of https://github.com/Julian-dev28/enKrypt

commit a687ae4
Author: Julian Martinez <julian.martinez@okg.com>
Date:   Mon Jun 16 21:50:08 2025 -0700

    update request/response params

commit 98ad4a2
Author: julian.martinez <julian_martinez28@outlook.com>
Date:   Mon Jun 16 19:18:08 2025 -0700

    update request/response params

commit eff5837
Author: julian.martinez <julian_martinez28@outlook.com>
Date:   Thu Jun 12 18:39:25 2025 -0700

    add okx provider

commit 934e55b
Author: julian.martinez <julian_martinez28@outlook.com>
Date:   Wed Jun 11 10:29:01 2025 -0700

    add okx provider
@coderabbitai
Copy link

coderabbitai bot commented Jul 8, 2025

Walkthrough

These changes introduce full support for the OKX DEX aggregator as a swap provider for the Solana network. This includes a new provider implementation with robust API integration, environment variable configuration, and fee/referral logic. The transaction processing pipeline is updated to handle raw Solana transactions, default fee calculation, and improved logging for debugging and traceability.

Changes

File(s) Change Summary
.../swap/libs/solana-gasvals.ts Added support for a new RawTransaction type, updated transaction handling and fee calculation logic to accommodate raw Solana transactions, and adjusted function signatures to reflect these changes.
.../swap/libs/swap-txs.ts Simplified Solana transaction handling by returning raw transaction data with flags, removing deserialization and class instance checks.
.../swap/views/swap-best-offer/index.vue Added type assertion for transaction fees, introduced debug logging for trade properties, and made minor formatting adjustments without altering core logic.
.../vite.config.ts Injected environment variables from .env using dotenv, logged them for debugging, and made them accessible in the client build via globalThis.importMetaEnv.
.../package.json Added crypto-js and dotenv as dependencies, and @types/crypto-js as a dev dependency.
.../src/configs.ts Added fee/referral configuration for the OKX provider with wallet-specific settings.
.../src/index.ts Registered the OKX provider in the swap initialization logic for Solana.
.../src/providers/okx/index.ts Introduced the OKX provider class with API integration, token/quote/swap/status logic, rate limiting, error handling, and referral fee support.
.../src/providers/okx/types.ts Added TypeScript interfaces for OKX API token, quote, swap parameters, and swap response data structures.
.../src/types/index.ts Extended the ProviderName enum to include okx.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant SwapUI
    participant SwapCore
    participant OKXProvider
    participant OKXAPI
    participant SolanaRPC

    User->>SwapUI: Initiate swap (select tokens, amount)
    SwapUI->>SwapCore: Request quote/providers
    SwapCore->>OKXProvider: getQuote()
    OKXProvider->>OKXAPI: Fetch quote
    OKXAPI-->>OKXProvider: Return quote data
    OKXProvider-->>SwapCore: Return quote
    SwapCore-->>SwapUI: Display quote

    User->>SwapUI: Confirm swap
    SwapUI->>SwapCore: Execute swap
    SwapCore->>OKXProvider: getSwap()
    OKXProvider->>OKXAPI: Request swap transaction
    OKXAPI-->>OKXProvider: Return base64 transaction
    OKXProvider-->>SwapCore: Return raw transaction
    SwapCore->>SolanaRPC: Broadcast transaction
    SolanaRPC-->>SwapCore: Transaction signature

    SwapCore->>OKXProvider: getStatus()
    OKXProvider->>SolanaRPC: Check transaction status
    SolanaRPC-->>OKXProvider: Status info
    OKXProvider-->>SwapCore: Status result
    SwapCore-->>SwapUI: Update status
Loading

Suggested reviewers

  • SemajaM
  • NickKelly1
✨ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.

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.

@kvhnuke kvhnuke changed the base branch from main to develop July 9, 2025 15:51
@kvhnuke kvhnuke marked this pull request as ready for review July 9, 2025 17:01
Copy link

@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: 6

🧹 Nitpick comments (4)
packages/extension/src/ui/action/views/swap/libs/solana-gasvals.ts (1)

151-153: Consider making the default fee configurable

The hardcoded default fee of 10000 lamports might need adjustment based on network conditions.

+// Default fee for raw transactions in lamports
+const DEFAULT_RAW_TRANSACTION_FEE = 10000; // 0.00001 SOL
+
 // Handle raw transactions differently
 if ('isRawData' in tx && tx.isRawData) {
   // Use a reasonable default fee for raw transactions
   // Most Solana transactions cost around 5000-10000 lamports
-  const defaultFee = 10000; // 0.00001 SOL
+  const defaultFee = DEFAULT_RAW_TRANSACTION_FEE;
   feesumlamp = feesumlamp.add(toBN(defaultFee));
packages/swap/src/providers/okx/index.ts (3)

132-145: Simplify optional chaining as suggested by static analysis

The nested if statements can be simplified using optional chaining.

-      // Check for Retry-After header if available
-      if (error.response && error.response.headers) {
-        const retryAfter =
-          error.response.headers.get &&
-          error.response.headers.get("Retry-After");
-        if (retryAfter) {
+      // Check for Retry-After header if available
+      const retryAfter = error.response?.headers?.get?.("Retry-After");
+      if (retryAfter) {
         const retryAfterMs = parseInt(retryAfter, 10) * 1000;
         if (!isNaN(retryAfterMs)) {
           delay = Math.max(delay, retryAfterMs);
           logger.info(
             `OKX API Retry-After header present, waiting ${delay}ms`,
           );
         }
-        }
       }

831-838: Simplify native SOL address checking

The repeated ternary operations for native SOL address checking can be extracted to a helper function.

+    // Helper to convert native SOL address to wrapped SOL for quotes
+    const toWrappedAddress = (address: string): string => 
+      address === OKX_NATIVE_SOL_ADDRESS ? WRAPPED_SOL_ADDRESS : address;
+
     // Get quote first (using wrapped SOL addresses for quote API)
-    const srcMint = new PublicKey(
-      srcTokenAddress === "11111111111111111111111111111111"
-        ? WRAPPED_SOL_ADDRESS
-        : srcTokenAddress,
-    );
-    const dstMint = new PublicKey(
-      dstTokenAddress === "11111111111111111111111111111111"
-        ? WRAPPED_SOL_ADDRESS
-        : dstTokenAddress,
-    );
+    const srcMint = new PublicKey(toWrappedAddress(srcTokenAddress));
+    const dstMint = new PublicKey(toWrappedAddress(dstTokenAddress));

343-343: Consider externalizing the default rent fee

The hardcoded default rent fee of 2039280 lamports appears in multiple places and should be defined as a constant.

+// Default rent exemption for SPL token account in lamports
+const DEFAULT_SPL_TOKEN_RENT_EXEMPTION = 2039280;
+
           logger.warn(`Could not get rent exemption: ${rentError}`);
           // Use a default rent fee if we can't get it
-          rentFees += 2039280; // Default SOL rent exemption for token account
+          rentFees += DEFAULT_SPL_TOKEN_RENT_EXEMPTION;

Apply the same change at line 931:

-      rentFees += 2039280; // Default SOL rent exemption
+      rentFees += DEFAULT_SPL_TOKEN_RENT_EXEMPTION;
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between dc24615 and 17051da.

⛔ Files ignored due to path filters (1)
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (10)
  • packages/extension/src/ui/action/views/swap/libs/solana-gasvals.ts (3 hunks)
  • packages/extension/src/ui/action/views/swap/libs/swap-txs.ts (1 hunks)
  • packages/extension/src/ui/action/views/swap/views/swap-best-offer/index.vue (3 hunks)
  • packages/extension/vite.config.ts (3 hunks)
  • packages/swap/package.json (2 hunks)
  • packages/swap/src/configs.ts (1 hunks)
  • packages/swap/src/index.ts (2 hunks)
  • packages/swap/src/providers/okx/index.ts (1 hunks)
  • packages/swap/src/providers/okx/types.ts (1 hunks)
  • packages/swap/src/types/index.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
packages/swap/src/index.ts (1)
packages/swap/src/providers/okx/index.ts (1)
  • OKX (172-941)
packages/swap/src/providers/okx/index.ts (6)
packages/utils/src/debug-logger.ts (1)
  • error (388-392)
packages/swap/src/types/index.ts (10)
  • TokenType (49-60)
  • TokenNetworkType (74-77)
  • getQuoteOptions (142-148)
  • QuoteMetaOptions (107-114)
  • ProviderQuoteResponse (212-224)
  • SwapQuote (206-210)
  • ProviderSwapResponse (243-257)
  • SolanaTransaction (166-185)
  • StatusOptions (233-236)
  • StatusOptionsResponse (238-241)
packages/swap/src/providers/okx/types.ts (3)
  • OKXTokenInfo (5-16)
  • OKXQuoteResponse (18-89)
  • OKXSwapResponse (144-160)
packages/swap/src/configs.ts (3)
  • NATIVE_TOKEN_ADDRESS (133-133)
  • FEE_CONFIGS (131-131)
  • DEFAULT_SLIPPAGE (137-137)
packages/swap/src/utils/solana.ts (6)
  • WRAPPED_SOL_ADDRESS (49-50)
  • isValidSolanaAddressAsync (469-473)
  • getTokenProgramOfMint (280-304)
  • getSPLAssociatedTokenAccountPubkey (309-321)
  • solAccountExists (484-491)
  • SPL_TOKEN_ATA_ACCOUNT_SIZE_BYTES (43-43)
packages/swap/src/utils/approvals.ts (1)
  • TOKEN_AMOUNT_INFINITY_AND_BEYOND (7-8)
🪛 Biome (1.9.4)
packages/swap/src/providers/okx/index.ts

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

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 134-135: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


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

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


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

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (12)
packages/swap/package.json (2)

30-31: LGTM: Appropriate dependencies for OKX integration.

The crypto-js and dotenv dependencies are correctly added to support the OKX provider's cryptographic signing and environment variable management requirements.


44-44: LGTM: TypeScript types added for crypto-js.

The development dependency for @types/crypto-js is properly added to provide TypeScript support.

packages/swap/src/types/index.ts (1)

131-131: LGTM: Provider name enum updated correctly.

The addition of okx to the ProviderName enum follows the established pattern and properly integrates with the provider system.

packages/swap/src/index.ts (2)

50-50: LGTM: Clean import statement for OKX provider.

The import follows the established pattern and properly integrates the OKX provider into the system.


123-123: LGTM: OKX provider properly integrated into Solana providers.

The OKX provider is correctly instantiated and added to the Solana providers array with appropriate type casting.

packages/swap/src/configs.ts (1)

68-77: Please confirm OKX should share Jupiter’s referrer addresses

Our search in packages/swap/src/configs.ts shows OKX’s referrer values are identical to Jupiter’s:

  [ProviderName.jupiter]: {
    [WalletIdentifier.enkrypt]: { referrer: "HXWkRK9a4H1EuBiqP4sVfFsEpd2NasoQPScoXL1NgSE2", fee: 0.01 },
    [WalletIdentifier.mew]:     { referrer: "CmrkoXWiTW37ZqUZcfJtxiKhy9eRMBQHq1nm8HpmRXH4", fee: 0.03 },
  },
  [ProviderName.okx]: {
    [WalletIdentifier.enkrypt]: { referrer: "HXWkRK9a4H1EuBiqP4sVfFsEpd2NasoQPScoXL1NgSE2", fee: 0.01 },
    [WalletIdentifier.mew]:     { referrer: "CmrkoXWiTW37ZqUZcfJtxiKhy9eRMBQHq1nm8HpmRXH4", fee: 0.03 },
  },

No OKX-specific referrer docs were found. Please confirm that OKX is intended to use the same fee-collection setup as Jupiter.

packages/extension/vite.config.ts (2)

1-2: LGTM: Dotenv configuration properly set up.

The dotenv configuration is correctly implemented to load environment variables from the .env file.


68-73: LGTM: Environment variables properly injected into build.

The OKX environment variables are correctly injected into the build process using the globalThis.importMetaEnv pattern, making them accessible to the client-side code.

packages/extension/src/ui/action/views/swap/libs/swap-txs.ts (1)

112-127: No further action needed for Solana raw transactions

We verified that getSwapTransactions is only consumed in swap-best-offer/index.vue’s fee calculation and that getSolanaTransactionFees explicitly handles the isRawData flag by applying a default fee. Consumers will continue to work as expected with raw transaction data.

packages/swap/src/providers/okx/types.ts (1)

1-161: Well-structured type definitions

The TypeScript interfaces are comprehensive and properly documented. Using strings for numeric values is appropriate for API responses to maintain precision.

packages/extension/src/ui/action/views/swap/libs/solana-gasvals.ts (1)

204-210: LGTM! Good error handling for null messages

The code properly handles the case where getTxMessage returns null for raw transactions by using a default fee.

packages/swap/src/providers/okx/index.ts (1)

764-770: Avoid logging sensitive information

While the code correctly checks for presence/absence of credentials, ensure no sensitive data is accidentally logged in other debug statements.

The implementation correctly masks API credentials in logs by only showing "present" or "missing" status.

Comment on lines +313 to +320
swapData.trades.forEach((trade, index) => {
console.log(`Trade ${index + 1}:`, {
provider: trade.provider,
fromAmount: trade.fromTokenAmount.toString(),
toAmount: trade.toTokenAmount.toString(),
additionalFees: trade.additionalNativeFees.toString(),
});
});
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Remove or conditionally enable debug logging

Debug console.log statements should not be in production code.

-  swapData.trades.forEach((trade, index) => {
-    console.log(`Trade ${index + 1}:`, {
-      provider: trade.provider,
-      fromAmount: trade.fromTokenAmount.toString(),
-      toAmount: trade.toTokenAmount.toString(),
-      additionalFees: trade.additionalNativeFees.toString(),
-    });
-  });
+  if (import.meta.env.DEV) {
+    swapData.trades.forEach((trade, index) => {
+      console.log(`Trade ${index + 1}:`, {
+        provider: trade.provider,
+        fromAmount: trade.fromTokenAmount.toString(),
+        toAmount: trade.toTokenAmount.toString(),
+        additionalFees: trade.additionalNativeFees.toString(),
+      });
+    });
+  }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
swapData.trades.forEach((trade, index) => {
console.log(`Trade ${index + 1}:`, {
provider: trade.provider,
fromAmount: trade.fromTokenAmount.toString(),
toAmount: trade.toTokenAmount.toString(),
additionalFees: trade.additionalNativeFees.toString(),
});
});
if (import.meta.env.DEV) {
swapData.trades.forEach((trade, index) => {
console.log(`Trade ${index + 1}:`, {
provider: trade.provider,
fromAmount: trade.fromTokenAmount.toString(),
toAmount: trade.toTokenAmount.toString(),
additionalFees: trade.additionalNativeFees.toString(),
});
});
}
🤖 Prompt for AI Agents
In packages/extension/src/ui/action/views/swap/views/swap-best-offer/index.vue
around lines 313 to 320, the code contains console.log statements used for
debugging. Remove these console.log calls or wrap them in a conditional check
that ensures they only run in a development environment to prevent debug logs
from appearing in production.

Comment on lines +56 to +77
logger.info(`getEnvVar(${name}) - checking environment variables`);

if (typeof process !== "undefined" && process.env && process.env[name]) {
logger.info(`getEnvVar(${name}) - found in process.env`);
return process.env[name];
}

// For Vite/browser builds, use globalThis.importMetaEnv (set in vite.config.ts)
if (
typeof globalThis !== "undefined" &&
(globalThis as any).importMetaEnv &&
(globalThis as any).importMetaEnv[`VITE_${name}`]
) {
logger.info(
`getEnvVar(${name}) - found in globalThis.importMetaEnv.VITE_${name}`,
);
return (globalThis as any).importMetaEnv[`VITE_${name}`];
}

logger.info(`getEnvVar(${name}) - not found in any environment`);
return undefined;
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Reduce verbose logging in production

The logger.info calls for environment variable checking are too verbose and could expose sensitive information.

 function getEnvVar(name: string): string | undefined {
-  logger.info(`getEnvVar(${name}) - checking environment variables`);
+  logger.debug(`getEnvVar(${name}) - checking environment variables`);

   if (typeof process !== "undefined" && process.env && process.env[name]) {
-    logger.info(`getEnvVar(${name}) - found in process.env`);
+    logger.debug(`getEnvVar(${name}) - found in process.env`);
     return process.env[name];
   }

   // For Vite/browser builds, use globalThis.importMetaEnv (set in vite.config.ts)
   if (
     typeof globalThis !== "undefined" &&
     (globalThis as any).importMetaEnv &&
     (globalThis as any).importMetaEnv[`VITE_${name}`]
   ) {
-    logger.info(
+    logger.debug(
       `getEnvVar(${name}) - found in globalThis.importMetaEnv.VITE_${name}`,
     );
     return (globalThis as any).importMetaEnv[`VITE_${name}`];
   }

-  logger.info(`getEnvVar(${name}) - not found in any environment`);
+  logger.debug(`getEnvVar(${name}) - not found in any environment`);
   return undefined;
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
logger.info(`getEnvVar(${name}) - checking environment variables`);
if (typeof process !== "undefined" && process.env && process.env[name]) {
logger.info(`getEnvVar(${name}) - found in process.env`);
return process.env[name];
}
// For Vite/browser builds, use globalThis.importMetaEnv (set in vite.config.ts)
if (
typeof globalThis !== "undefined" &&
(globalThis as any).importMetaEnv &&
(globalThis as any).importMetaEnv[`VITE_${name}`]
) {
logger.info(
`getEnvVar(${name}) - found in globalThis.importMetaEnv.VITE_${name}`,
);
return (globalThis as any).importMetaEnv[`VITE_${name}`];
}
logger.info(`getEnvVar(${name}) - not found in any environment`);
return undefined;
}
function getEnvVar(name: string): string | undefined {
logger.debug(`getEnvVar(${name}) - checking environment variables`);
if (typeof process !== "undefined" && process.env && process.env[name]) {
logger.debug(`getEnvVar(${name}) - found in process.env`);
return process.env[name];
}
// For Vite/browser builds, use globalThis.importMetaEnv (set in vite.config.ts)
if (
typeof globalThis !== "undefined" &&
(globalThis as any).importMetaEnv &&
(globalThis as any).importMetaEnv[`VITE_${name}`]
) {
logger.debug(
`getEnvVar(${name}) - found in globalThis.importMetaEnv.VITE_${name}`,
);
return (globalThis as any).importMetaEnv[`VITE_${name}`];
}
logger.debug(`getEnvVar(${name}) - not found in any environment`);
return undefined;
}
🤖 Prompt for AI Agents
In packages/swap/src/providers/okx/index.ts between lines 56 and 77, the
logger.info calls that log environment variable checks are too verbose and may
expose sensitive data. Replace these logger.info calls with a less verbose
logging level such as logger.debug or remove them entirely for production
builds. Ensure that sensitive environment variable names or values are not
logged to avoid security risks.

Comment on lines +862 to +863
autoSlippage: "true", // STRING, not boolean - CRITICAL
maxAutoSlippageBps: "100", // Add this parameter - REQUIRED
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Make critical parameters more maintainable

The hardcoded string "true" for autoSlippage and "100" for maxAutoSlippageBps are error-prone and should be constants.

+// OKX API specific constants
+const OKX_AUTO_SLIPPAGE = "true"; // Must be string, not boolean
+const OKX_MAX_AUTO_SLIPPAGE_BPS = "100";
+
     const swapParams: any = {
       chainId: "501",
       amount: options.amount.toString(10),
       fromTokenAddress: srcTokenAddress, // Use native format for swap
       toTokenAddress: dstTokenAddress, // Use native format for swap
       userWalletAddress: options.fromAddress,
       slippage: parseFloat(meta.slippage || DEFAULT_SLIPPAGE).toString(),
-      autoSlippage: "true", // STRING, not boolean - CRITICAL
-      maxAutoSlippageBps: "100", // Add this parameter - REQUIRED
+      autoSlippage: OKX_AUTO_SLIPPAGE,
+      maxAutoSlippageBps: OKX_MAX_AUTO_SLIPPAGE_BPS,
     };
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
autoSlippage: "true", // STRING, not boolean - CRITICAL
maxAutoSlippageBps: "100", // Add this parameter - REQUIRED
// OKX API specific constants
const OKX_AUTO_SLIPPAGE = "true"; // Must be string, not boolean
const OKX_MAX_AUTO_SLIPPAGE_BPS = "100";
const swapParams: any = {
chainId: "501",
amount: options.amount.toString(10),
fromTokenAddress: srcTokenAddress, // Use native format for swap
toTokenAddress: dstTokenAddress, // Use native format for swap
userWalletAddress: options.fromAddress,
slippage: parseFloat(meta.slippage || DEFAULT_SLIPPAGE).toString(),
autoSlippage: OKX_AUTO_SLIPPAGE,
maxAutoSlippageBps: OKX_MAX_AUTO_SLIPPAGE_BPS,
};
🤖 Prompt for AI Agents
In packages/swap/src/providers/okx/index.ts at lines 862 to 863, the values for
autoSlippage and maxAutoSlippageBps are hardcoded as strings "true" and "100".
To improve maintainability and reduce errors, define these values as constants
at the top of the file or in a relevant constants module, then replace the
hardcoded strings with references to these constants.

Comment on lines +816 to +827
if (options.fromToken.address === NATIVE_TOKEN_ADDRESS) {
srcTokenAddress = "11111111111111111111111111111111"; // Native SOL format
} else {
srcTokenAddress = options.fromToken.address;
}

let dstTokenAddress: string;
if (options.toToken.address === NATIVE_TOKEN_ADDRESS) {
dstTokenAddress = "11111111111111111111111111111111"; // Native SOL format
} else {
dstTokenAddress = options.toToken.address;
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Extract native SOL address as a constant

The hardcoded native SOL address should be defined as a constant for maintainability.

+// Native SOL address format used by OKX API
+const OKX_NATIVE_SOL_ADDRESS = "11111111111111111111111111111111";
+
     // CRITICAL FIX: Use native SOL format for swap API calls (not wrapped SOL)
     let srcTokenAddress: string;
     if (options.fromToken.address === NATIVE_TOKEN_ADDRESS) {
-      srcTokenAddress = "11111111111111111111111111111111"; // Native SOL format
+      srcTokenAddress = OKX_NATIVE_SOL_ADDRESS; // Native SOL format
     } else {
       srcTokenAddress = options.fromToken.address;
     }

     let dstTokenAddress: string;
     if (options.toToken.address === NATIVE_TOKEN_ADDRESS) {
-      dstTokenAddress = "11111111111111111111111111111111"; // Native SOL format
+      dstTokenAddress = OKX_NATIVE_SOL_ADDRESS; // Native SOL format
     } else {
       dstTokenAddress = options.toToken.address;
     }

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

🤖 Prompt for AI Agents
In packages/swap/src/providers/okx/index.ts around lines 816 to 827, the native
SOL address is hardcoded as a string literal in multiple places. Define this
native SOL address as a constant at the top of the file or in an appropriate
constants section, then replace all occurrences of the hardcoded string with
this constant to improve maintainability and avoid duplication.

@kvhnuke kvhnuke changed the base branch from develop to feat/okx-sol-swap July 9, 2025 17:08
@kvhnuke kvhnuke merged commit 8178216 into enkryptcom:feat/okx-sol-swap Jul 9, 2025
2 checks passed
@coderabbitai coderabbitai bot mentioned this pull request Jul 9, 2025
@coderabbitai coderabbitai bot mentioned this pull request Aug 4, 2025
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