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

Bugfix/cosmos #286

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open

Conversation

xixixueling
Copy link
Contributor

@xixixueling xixixueling commented Jan 14, 2025

Summary by CodeRabbit

  • Dependencies

    • Updated Node.js type definitions version
    • Added new blockchain-related SDK dependencies
    • Reorganized package dependencies
  • Blockchain Support

    • Enhanced support for Aptos, Cardano, Conflux, Cosmos, and SCDO blockchain interactions
    • Added token transfer capabilities for multiple blockchain networks
    • Improved transaction signing and validation processes
  • Error Handling

    • Implemented more robust error checking in transaction processing
    • Added comprehensive error logging and validation mechanisms
  • RPC Improvements

    • Updated RPC client configurations
    • Enhanced transaction submission methods
    • Improved flexibility in blockchain network connections

Copy link

coderabbitai bot commented Jan 14, 2025

Walkthrough

This pull request introduces multiple changes across various components and configuration files, primarily focusing on dependency management, transaction handling, and error management for different blockchain platforms. The modifications span package dependencies, transaction signing processes, token transfers, and RPC client configurations. The changes aim to enhance flexibility, improve error handling, and add support for new transaction types across Aptos, Cardano, Conflux, Cosmos, SCDO, and other blockchain ecosystems.

Changes

File Change Summary
package.json - Downgraded @types/node to ^16.9.0
- Removed lodash-es from devDependencies
- Added new dependencies in dependencies section
packages/example/components/chains/aptos/... - Added commented-out transferToken method
- Updated params.ts with new transaction signing entries for USDC and DooDoo
packages/example/components/chains/aptosStandard/params.ts - Modified transaction amount from 100000 to 10000
packages/example/components/chains/cardano/example.tsx - Introduced TOKENS constant
- Updated transaction signing logic with dynamic token selection
packages/example/components/chains/conflux/params.ts - Added input validation for sendTransaction
- Updated transaction descriptions
- Added new CRC20 token transfer types
packages/example/components/chains/cosmos/example.tsx - Enhanced error handling in signAmino and signDirect payloads
packages/example/components/chains/scdo/... - Updated token transfer details
- Improved nonce retrieval and error handling
- Enhanced RPC client with configurable URL and improved transaction pushing

Sequence Diagram

sequenceDiagram
    participant User
    participant WalletAdapter
    participant BlockchainClient
    participant RPCNode

    User->>WalletAdapter: Initiate Transaction
    WalletAdapter->>BlockchainClient: Prepare Transaction
    BlockchainClient->>BlockchainClient: Validate Parameters
    BlockchainClient->>RPCNode: Send Transaction
    RPCNode-->>BlockchainClient: Transaction Response
    BlockchainClient-->>WalletAdapter: Transaction Result
    WalletAdapter-->>User: Transaction Confirmation
Loading

Finishing Touches

  • 📝 Generate Docstrings (Beta)

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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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 or 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

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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4b4d54c and 8ce22af.

⛔ Files ignored due to path filters (2)
  • packages/example/yarn.lock is excluded by !**/yarn.lock, !**/*.lock
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (9)
  • package.json (2 hunks)
  • packages/example/components/chains/aptos/example.tsx (1 hunks)
  • packages/example/components/chains/aptos/params.ts (2 hunks)
  • packages/example/components/chains/aptosStandard/params.ts (2 hunks)
  • packages/example/components/chains/cardano/example.tsx (5 hunks)
  • packages/example/components/chains/conflux/params.ts (3 hunks)
  • packages/example/components/chains/cosmos/example.tsx (2 hunks)
  • packages/example/components/chains/scdo/example.tsx (5 hunks)
  • packages/example/components/chains/scdo/rpc.ts (2 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
packages/example/components/chains/conflux/params.ts

[error] 189-195: Template literals are preferred over string concatenation.

Unsafe fix: Use a template literal.

(lint/style/useTemplate)

packages/example/components/chains/scdo/rpc.ts

[error] 9-9: This type annotation is trivially inferred from its initialization.

Safe fix: Remove the type annotation.

(lint/style/noInferrableTypes)

packages/example/components/chains/cardano/example.tsx

[error] 452-453: Use Number.parseInt instead of the equivalent global.

ES2015 moved some globals into the Number namespace for consistency.
Safe fix: Use Number.parseInt instead.

(lint/style/useNumberNamespace)

🪛 eslint
packages/example/components/chains/conflux/params.ts

[error] 188-190: Unexpected string concatenation.

(prefer-template)


[error] 200-202: Unexpected string concatenation.

(prefer-template)

packages/example/components/chains/scdo/rpc.ts

[error] 9-9: Type string trivially inferred from a string literal, remove type annotation.

(@typescript-eslint/no-inferrable-types)

⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: test_build_web
  • GitHub Check: lint (ubuntu-latest, 20)
🔇 Additional comments (12)
packages/example/components/chains/scdo/example.tsx (1)

111-116: Fetch the latest nonce and handle errors properly.

Good job fetching the latest nonce and throwing an error when it fails. This ensures transactions use the correct nonce.

packages/example/components/chains/scdo/rpc.ts (1)

51-87: Improved transaction pushing with better error handling.

Switching to fetch and enhancing error handling make the pushTransaction method more robust.

packages/example/components/chains/conflux/params.ts (3)

156-158: Good addition of input validation!

Early return on missing parameters improves function robustness.


164-164: Clear description updates.

Updated Chinese descriptions improve clarity for users.

Also applies to: 174-174


181-204: 🧹 Nitpick (assertive)

Replace string concatenation with template literals.

Use template literals for better readability and maintainability.

Apply this diff:

-          data: "0xa9059cbb" +
-                address.decodeCfxAddress(to).hexAddress.toString('hex').slice(2).padStart(64, '0') +
-                "00000000000000000000000000000000000000000000000000005af3107a4000",
+          data: `0xa9059cbb${
+                address.decodeCfxAddress(to).hexAddress.toString('hex').slice(2).padStart(64, '0')
+                }00000000000000000000000000000000000000000000000000005af3107a4000`,

Also, verify the hardcoded token contract addresses:

✅ Verification successful

Template literal refactoring is safe, token addresses are consistent

The suggested template literal refactoring improves readability without affecting functionality. Token contract addresses are consistently used and appear only in the params.ts file.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for token contract addresses to verify consistency

rg "cfx:a[a-z0-9]{38}"

Length of output: 258

🧰 Tools
🪛 Biome (1.9.4)

[error] 189-195: Template literals are preferred over string concatenation.

Unsafe fix: Use a template literal.

(lint/style/useTemplate)

🪛 eslint

[error] 188-190: Unexpected string concatenation.

(prefer-template)


[error] 200-202: Unexpected string concatenation.

(prefer-template)

packages/example/components/chains/cardano/example.tsx (3)

29-38: Well-structured token configuration.

The TOKENS constant improves maintainability and scalability.


417-425: Good UI enhancement with token selection.

The dropdown makes token selection user-friendly.


449-460: Verify MIN token configuration.

Please confirm the MIN token unit value is correct:

✅ Verification successful

MIN token unit value is correctly configured

The MIN token configuration is properly defined with the correct unit value and consistent decimal places in the TOKENS object.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for MIN token unit references

rg "29d222ce763455e3d7a09a665ce554f00ac89d2e99a1a83d267170c64d494e"

Length of output: 198


Script:

#!/bin/bash
# Search for TOKENS definition and structure
ast-grep --pattern 'const TOKENS = {
  $$$
}'

# Search for any MIN related configurations
rg -i "MIN.*token|token.*MIN" -A 3 -B 3

# Search for token unit pattern to find similar configurations
rg "[0-9a-f]{56}"

Length of output: 71340


Script:

#!/bin/bash
# Search for TOKENS definition in cardano files
rg -A 10 "const TOKENS = {" packages/example/components/chains/cardano/

# Search for MIN token references in cardano context
rg -B 3 -A 3 "MIN.*token|token.*MIN" packages/example/components/chains/cardano/

Length of output: 252


Script:

#!/bin/bash
# Find TOKENS object definition
ast-grep --pattern 'const TOKENS = {
  $$$
}'

# Search for MIN references with simpler pattern
rg "MIN" packages/example/components/chains/cardano/

# Search for the specific unit value in a different way
rg -l "29d222ce763455e3d7a09a665ce554f00ac89d2e99a1a83d267170c64d494e" packages/example/components/chains/cardano/

Length of output: 334


Script:

#!/bin/bash
# Get more context around the MIN token definition
rg -B 2 -A 5 "MIN: {" packages/example/components/chains/cardano/example.tsx

# Get the complete TOKENS object structure
ast-grep --pattern 'const TOKENS = {
  $$$
  MIN: {
    $$$
  }
  $$$
}'

Length of output: 229


Script:

#!/bin/bash
# Search for MIN token configuration with fixed string and more context
rg -F "29d222ce763455e3d7a09a665ce554f00ac89d2e99a1a83d267170c64d494e" -B 5 -A 5 packages/example/components/chains/cardano/example.tsx

# Get context around MIN token reference
rg -F "MIN:" -B 5 -A 5 packages/example/components/chains/cardano/example.tsx

Length of output: 640

🧰 Tools
🪛 Biome (1.9.4)

[error] 452-453: Use Number.parseInt instead of the equivalent global.

ES2015 moved some globals into the Number namespace for consistency.
Safe fix: Use Number.parseInt instead.

(lint/style/useNumberNamespace)

packages/example/components/chains/cosmos/example.tsx (3)

278-306: Excellent error handling in signAmino.

The improvements include:

  • Clear validation checks
  • Detailed error messages
  • Comprehensive error response structure

415-443: Robust error handling in signDirect.

Good improvements:

  • Structured try-catch block
  • Detailed error logging
  • Clear error response format

450-450: Clear placeholder text.

The updated placeholder text provides better guidance to users.

package.json (1)

37-37: Verify Node.js type definitions version compatibility

The @types/node version (^16.9.0) seems low compared to the supported Node.js engines (^16 || ^18 || ^20). Consider using a more recent version that matches your minimum supported Node.js version.

✅ Verification successful

Node.js type definitions version is appropriate

The @types/node@^16.9.0 matches your minimum supported Node.js version (^16). This is good practice and ensures compatibility across all supported Node versions.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if package.json engine requirements match @types/node version
node -e 'const pkg = require("./package.json"); console.log(`Engine requirement: ${pkg.engines.node}\nTypes version: ${pkg.devDependencies["@types/node"]}`)'

Length of output: 220

Comment on lines +294 to +342
try {
console.log('签名交易请求:', request);
console.log('签名交易响应:', response);

const tx = JSON.parse(response);
console.log('解析后的交易数据:', tx);

// 检查交易数据结构
if (!tx.Data || !tx.Hash || !tx.Signature?.Sig) {
throw new Error('交易数据格式不正确');
}

// 检查必要字段
const requiredFields = ['From', 'To', 'Amount', 'AccountNonce', 'GasPrice', 'GasLimit'];
for (const field of requiredFields) {
if (tx.Data[field] === undefined) {
throw new Error(`缺少必要字段: ${field}`);
}
}

// 检查 nonce 值
const currentNonce = await client.getNonce(tx.Data.From);
console.log('当前 nonce:', currentNonce, '交易 nonce:', tx.Data.AccountNonce);

if (tx.Data.AccountNonce < currentNonce) {
throw new Error(`Nonce 值过低,当前 nonce: ${currentNonce}`);
}

// 使用 client 广播交易
const success = await client.pushTransaction(tx.Data.From, tx);
console.log('广播交易结果:', success);

if (!success) {
throw new Error('交易广播失败,请检查:\n1. 账户余额是否充足\n2. Gas 费用是否足够\n3. Nonce 值是否正确');
}

toast({
title: '交易广播成功',
description: `交易哈希: ${tx.Hash}`,
});
return true;
} catch (error) {
console.error('验证交易失败:', error);
toast({
title: '广播交易失败',
description: '请检查交易是否正确',
title: '验证交易失败',
description: error instanceof Error ? error.message : '未知错误',
variant: 'destructive',
});
return false;
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Refactor the onValidate function for clarity.

The onValidate function is lengthy and handles multiple tasks. Splitting it into smaller helper functions can improve readability and maintainability.

Comment on lines +63 to +65
name: ' SCDO TEST0',
// address: '1S015daca201b66f96f74b4230916f9db8db0c0002',
address:'1S01f0daaf7a59fb5eb90256112bf5d080ff290022'
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Trim the token name and remove commented code.

There's an unnecessary space at the beginning of ' SCDO TEST0'. Also, consider removing the commented-out address if it's no longer needed.

Apply this diff to clean up the code:

-          name: ' SCDO TEST0',
+          name: 'SCDO TEST0',
-          // address: '1S015daca201b66f96f74b4230916f9db8db0c0002',
📝 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
name: ' SCDO TEST0',
// address: '1S015daca201b66f96f74b4230916f9db8db0c0002',
address:'1S01f0daaf7a59fb5eb90256112bf5d080ff290022'
name: 'SCDO TEST0',
address:'1S01f0daaf7a59fb5eb90256112bf5d080ff290022'


constructor() {
constructor(rpcUrl: string = 'https://mainnet.scdo.org:8137') {
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 unnecessary type annotation.

The type string for rpcUrl is inferred from the default value. Removing it satisfies linting rules and cleans up the code.

Apply this diff to fix the issue:

-      constructor(rpcUrl: string = 'https://mainnet.scdo.org:8137') {
+      constructor(rpcUrl = 'https://mainnet.scdo.org:8137') {
📝 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
constructor(rpcUrl: string = 'https://mainnet.scdo.org:8137') {
constructor(rpcUrl = 'https://mainnet.scdo.org:8137') {
🧰 Tools
🪛 Biome (1.9.4)

[error] 9-9: This type annotation is trivially inferred from its initialization.

Safe fix: Remove the type annotation.

(lint/style/noInferrableTypes)

🪛 eslint

[error] 9-9: Type string trivially inferred from a string literal, remove type annotation.

(@typescript-eslint/no-inferrable-types)

Comment on lines +58 to +76
id: 'transferUSDC',
name: 'transferUSDC',
value: JSON.stringify({
arguments: [address, '1000'],
function: '0x1::coin::transfer',
type: 'entry_function_payload',
type_arguments: ['0xf22bede237a07e121b56d91a491eb7bcdfd1f5907926a9e58338f964a01b17fa::asset::USDC'],
}),
},
{
id: 'transferDooDoo',
name: 'transferDooDoo',
value: JSON.stringify({
arguments: [address, '1000'],
function: '0x1::coin::transfer',
type: 'entry_function_payload',
type_arguments: ['0x73eb84966be67e4697fc5ae75173ca6c35089e802650f75422ab49a8729704ec::coin::DooDoo'],
}),
},
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Ensure consistent parameter names in signGenericTransaction.

The existing entry uses args, func, and type_args, but the new entries use arguments, function, and type_arguments. This inconsistency might cause errors. Standardize the parameter names.

Apply this diff to align the new entries with the existing structure:

-          value: JSON.stringify({
-            arguments: [address, '1000'],
-            function: '0x1::coin::transfer',
-            type: 'entry_function_payload',
-            type_arguments: ['...'],
-          }),
+          value: JSON.stringify({
+            args: [address, '1000'],
+            func: '0x1::coin::transfer',
+            type_args: ['...'],
+          }),

Replace '...' with the appropriate type arguments.

📝 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
id: 'transferUSDC',
name: 'transferUSDC',
value: JSON.stringify({
arguments: [address, '1000'],
function: '0x1::coin::transfer',
type: 'entry_function_payload',
type_arguments: ['0xf22bede237a07e121b56d91a491eb7bcdfd1f5907926a9e58338f964a01b17fa::asset::USDC'],
}),
},
{
id: 'transferDooDoo',
name: 'transferDooDoo',
value: JSON.stringify({
arguments: [address, '1000'],
function: '0x1::coin::transfer',
type: 'entry_function_payload',
type_arguments: ['0x73eb84966be67e4697fc5ae75173ca6c35089e802650f75422ab49a8729704ec::coin::DooDoo'],
}),
},
id: 'transferUSDC',
name: 'transferUSDC',
value: JSON.stringify({
args: [address, '1000'],
func: '0x1::coin::transfer',
type: 'entry_function_payload',
type_args: ['0xf22bede237a07e121b56d91a491eb7bcdfd1f5907926a9e58338f964a01b17fa::asset::USDC'],
}),
},
{
id: 'transferDooDoo',
name: 'transferDooDoo',
value: JSON.stringify({
args: [address, '1000'],
func: '0x1::coin::transfer',
type: 'entry_function_payload',
type_args: ['0x73eb84966be67e4697fc5ae75173ca6c35089e802650f75422ab49a8729704ec::coin::DooDoo'],
}),
},

@@ -54,7 +54,7 @@ export default {
type_arguments: [
'0xf22bede237a07e121b56d91a491eb7bcdfd1f5907926a9e58338f964a01b17fa::asset::USDC',
],
arguments: [address, 100000],
arguments: [address, 10000],
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

Transaction amounts are inconsistent across files

The codebase shows mixed usage of transaction amounts:

  • 100000 in aptosMartian/example.tsx
  • 100000 in aptos/params.ts
  • 10000 in tools/multipleCallSignTx.tsx

Please standardize the transaction amount across all files to maintain consistency.

🔗 Analysis chain

Verify transaction amount reductions.

The transaction amounts have been reduced from 100000 to 10000. Please confirm this aligns with business requirements.

Also applies to: 72-72

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for other occurrences of these transaction amounts
# to ensure consistency across the codebase.

rg -A 1 "arguments: \[.*address.*100000" 

Length of output: 816


Script:

#!/bin/bash
# Check for occurrences of the new transaction amount (10000)
rg -A 1 "arguments: \[.*address.*10000[^0]"

Length of output: 420

Comment on lines +61 to +69
"dependencies": {
"@aptos-labs/ts-sdk": "^1.33.1",
"@aptos-labs/wallet-adapter-core": "^4.23.0",
"@aptos-labs/wallet-adapter-react": "^3.7.9",
"@benfen/bfc.js": "^0.2.7",
"@solana/spl-token": "^0.4.9",
"ethereumjs-util": "^7.1.5",
"lodash-es": "^4.17.21"
},
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

Add missing peer dependency @solana/web3.js

@solana/spl-token requires @solana/web3.js ^1.95.3 as a peer dependency. Add it to your package.json.

🔗 Analysis chain

Verify compatibility between blockchain dependencies

The new blockchain dependencies might have peer dependency requirements. Let's verify their compatibility.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for peer dependency warnings and version conflicts
yarn info @aptos-labs/[email protected] peerDependencies
yarn info @aptos-labs/[email protected] peerDependencies
yarn info @solana/[email protected] peerDependencies

Length of output: 1993


Script:

#!/bin/bash
# Check dependencies and peer dependencies using npm
echo "Checking @aptos-labs/[email protected]"
npm view @aptos-labs/[email protected] peerDependencies dependencies

echo -e "\nChecking @aptos-labs/[email protected]"
npm view @aptos-labs/[email protected] peerDependencies dependencies

echo -e "\nChecking @solana/[email protected]"
npm view @solana/[email protected] peerDependencies dependencies

Length of output: 1196


Script:

#!/bin/bash
# Check if @solana/web3.js is present in package.json
cat package.json | grep -A 2 -B 2 "@solana/web3.js"

Length of output: 51

Comment on lines +232 to +249
{/* <ApiPayload
title="transferToken"
description="代币转账"
presupposeParams={params.transferToken(account?.address ?? '')}
onExecute={async (request: string) => {
const payload = JSON.parse(request);
// 将amount转换为原子单位 (1 APT = 100000000 原子单位)
const amount = Number(payload.arguments[1]) * 100000000;

const transaction = {
...payload,
arguments: [payload.arguments[0], amount.toString()],
};

const res = await provider?.signAndSubmitTransaction(transaction);
return JSON.stringify(res);
}}
/> */}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add validation and error handling to token transfer

The commented-out token transfer code needs improvements:

  1. Add input validation
  2. Handle potential errors
  3. Make the conversion factor configurable

Here's a safer implementation:

 <ApiPayload
   title="transferToken"
   description="代币转账"
   presupposeParams={params.transferToken(account?.address ?? '')}
   onExecute={async (request: string) => {
-    const payload = JSON.parse(request);
-    // 将amount转换为原子单位 (1 APT = 100000000 原子单位)
-    const amount = Number(payload.arguments[1]) * 100000000;
-    
-    const transaction = {
-      ...payload,
-      arguments: [payload.arguments[0], amount.toString()],
-    };
+    try {
+      const APTOS_DECIMALS = 100000000; // Consider moving to constants
+      const payload = JSON.parse(request);
+      
+      if (!Array.isArray(payload.arguments) || payload.arguments.length < 2) {
+        throw new Error('Invalid payload structure');
+      }
+      
+      const amount = Number(payload.arguments[1]);
+      if (isNaN(amount) || amount <= 0) {
+        throw new Error('Invalid amount');
+      }
+      
+      const atomicAmount = amount * APTOS_DECIMALS;
+      
+      const transaction = {
+        ...payload,
+        arguments: [payload.arguments[0], atomicAmount.toString()],
+      };
+      
+      const res = await provider?.signAndSubmitTransaction(transaction);
+      return JSON.stringify(res);
+    } catch (error) {
+      console.error('Token transfer failed:', error);
+      throw error;
+    }
-    const res = await provider?.signAndSubmitTransaction(transaction);
-    return JSON.stringify(res);
   }}
 />
📝 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
{/* <ApiPayload
title="transferToken"
description="代币转账"
presupposeParams={params.transferToken(account?.address ?? '')}
onExecute={async (request: string) => {
const payload = JSON.parse(request);
// 将amount转换为原子单位 (1 APT = 100000000 原子单位)
const amount = Number(payload.arguments[1]) * 100000000;
const transaction = {
...payload,
arguments: [payload.arguments[0], amount.toString()],
};
const res = await provider?.signAndSubmitTransaction(transaction);
return JSON.stringify(res);
}}
/> */}
<ApiPayload
title="transferToken"
description="代币转账"
presupposeParams={params.transferToken(account?.address ?? '')}
onExecute={async (request: string) => {
try {
const APTOS_DECIMALS = 100000000; // Consider moving to constants
const payload = JSON.parse(request);
if (!Array.isArray(payload.arguments) || payload.arguments.length < 2) {
throw new Error('Invalid payload structure');
}
const amount = Number(payload.arguments[1]);
if (isNaN(amount) || amount <= 0) {
throw new Error('Invalid amount');
}
const atomicAmount = amount * APTOS_DECIMALS;
const transaction = {
...payload,
arguments: [payload.arguments[0], atomicAmount.toString()],
};
const res = await provider?.signAndSubmitTransaction(transaction);
return JSON.stringify(res);
} catch (error) {
console.error('Token transfer failed:', error);
throw error;
}
}}
/>

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