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

add benfen&ton&sui&sol token transfer #266

Merged
merged 1 commit into from
Dec 16, 2024

Conversation

xixixueling
Copy link
Contributor

@xixixueling xixixueling commented Dec 16, 2024

add benfen&ton&sui&sol token transfer case

Summary by CodeRabbit

  • 新功能

    • 增强了交易功能,支持自定义收款地址和 BUSD 代币交易。
    • 新增了处理 USDC 和 Jetton 交易的 API 负载。
    • 引入了新的状态管理和异步操作以改善代币交易流程。
  • 文档

    • 更新了导入路径以反映新的目录结构。
  • 修复

    • 改进了错误处理机制,确保用户在余额不足时得到通知。

Copy link

coderabbitai bot commented Dec 16, 2024

概述

遍历

此次更新主要增强了多个区块链组件的代码,重点是改进代码结构和添加代币交易功能。在 Benfen、Solana、Sui、TON 等链的示例组件中,开发者引入了新的状态管理、交易参数生成和代币转账逻辑,提升了应用程序的交易处理能力。

变更

文件路径 变更摘要
packages/example/components/chains/*/example.tsx 新增代币交易 API Payload,添加状态管理,优化导入路径
packages/example/components/chains/*/params.ts 添加 signTokenTransactionsendTokenTransaction 方法,定义代币列表
packages/example/components/chains/solana/builder.ts 新增 createTokenTransferTransaction 函数,支持代币转账

序列图

sequenceDiagram
    participant User
    participant Wallet
    participant TokenContract
    User->>Wallet: 发起代币转账
    Wallet->>TokenContract: 创建转账交易
    TokenContract-->>Wallet: 验证交易
    Wallet-->>User: 返回交易结果
Loading

Tip

CodeRabbit's docstrings feature is now available as part of our Early Access Program! Simply use the command @coderabbitai generate docstrings to have CodeRabbit automatically generate docstrings for your pull request.


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

🔭 Outside diff range comments (2)
packages/example/components/chains/benfen/example.tsx (1)

Line range hint 75-102: 移除不必要的注释代码

请考虑删除已弃用的 signMessage 代码,以保持代码清洁和可维护性。

- {/* <ApiPayload
-   title="signMessage"
-   description="签名消息, signMessage 不安全已经弃用, 目前(OneKey、Suiet、Sui Wallet、Martian) signMessage 实际实现已经变成了 signPersonalMessage"
-   presupposeParams={params.signMessage}
-   onExecute={async (request: string) => {
-     const res = await signMessage({
-       message: hexToBytes(request),
-       account: currentAccount,
-     });
-     return JSON.stringify(res);
-   }}
-   onValidate={async (request: string, result: string) => {
-     const {
-       bytes,
-       signature,
-     }: {
-       bytes: string;
-       signature: string;
-     } = JSON.parse(result);
- 
-     // const publicKey = await verifySignature(hexToBytes(request), signature);
-     const publicKey = await verifyPersonalMessage(Buffer.from(bytes, 'base64'), signature);
- 
-     return (
-       bytesToHex(currentAccount.publicKey) === bytesToHex(publicKey.toRawBytes())
-     ).toString();
-   }}
- /> */}
packages/example/components/chains/suiStandard/example.tsx (1)

Line range hint 246-271: 移除不必要的注释代码

请考虑删除已弃用的 signMessage 代码,以保持代码清洁和可维护性。

- {/* <ApiPayload
-   title="signMessage"
-   description="签名消息, signMessage 不安全已经弃用, 目前(OneKey、Suiet、Sui Wallet、Martian) signMessage 实际实现已经变成了 signPersonalMessage"
-   presupposeParams={params.signMessage}
-   onExecute={async (request: string) => {
-     const res = await signMessage({
-       message: hexToBytes(request),
-       account: currentAccount,
-     });
-     return JSON.stringify(res);
-   }}
-   onValidate={async (request: string, result: string) => {
-     const {
-       bytes,
-       signature,
-     }: {
-       bytes: string;
-       signature: string;
-     } = JSON.parse(result);
- 
-     // const publicKey = await verifySignature(hexToBytes(request), signature);
-     const publicKey = await verifyPersonalMessage(Buffer.from(bytes, 'base64'), signature);
- 
-     return (currentAccount.address === publicKey.toSuiAddress()).toString();
-   }}
- /> */}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8465574 and 8348748.

📒 Files selected for processing (9)
  • packages/example/components/chains/benfen/example.tsx (5 hunks)
  • packages/example/components/chains/benfen/params.ts (1 hunks)
  • packages/example/components/chains/solana/builder.ts (2 hunks)
  • packages/example/components/chains/solana/example.tsx (4 hunks)
  • packages/example/components/chains/solana/params.ts (2 hunks)
  • packages/example/components/chains/suiStandard/example.tsx (5 hunks)
  • packages/example/components/chains/suiStandard/params.ts (1 hunks)
  • packages/example/components/chains/ton/example.tsx (6 hunks)
  • packages/example/components/chains/ton/params.ts (2 hunks)
🧰 Additional context used
🪛 Gitleaks (8.21.2)
packages/example/components/chains/solana/params.ts

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

(generic-api-key)


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

(generic-api-key)


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

(generic-api-key)

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

[error] 1-1: Require statement not part of import statement.

(@typescript-eslint/no-var-requires)


[error] 2-2: Require statement not part of import statement.

(@typescript-eslint/no-var-requires)

🔇 Additional comments (4)
packages/example/components/chains/ton/example.tsx (1)

32-32: 🧹 Nitpick (assertive)

scamEnable 转换为布尔值

scamEnable 可能返回字符串或 null。为了确保条件判断正确,建议将其转换为布尔值。

应用以下修改:

-const scamEnable = localStorage.getItem(TON_SCAM_DAPP_ENABLE_KEY);
+const scamEnable = Boolean(localStorage.getItem(TON_SCAM_DAPP_ENABLE_KEY));

Likely invalid or redundant comment.

packages/example/components/chains/solana/example.tsx (2)

13-13: 看起来不错!

成功导入了 createTokenTransferTransaction 函数。


235-247: 验证功能实现正确

代码逻辑正确,实现了签名验证和交易模拟。

packages/example/components/chains/benfen/params.ts (1)

37-48: 确认金额单位和注释

amount 的值为 1000,但注释显示为 0.000001 USD。请确认金额单位是否正确,或者更新注释以避免混淆。

return walletAddress.toString();
} catch (error) {
console.error('Error in getJettonWalletAddress:', error);
return null; // 或者根据需要返回其他值
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

建议统一代码中的语言

第23行的注释使用了中文,但代码中的其他注释大多为英文。为了保持一致性,建议统一所有注释的语言。

const usdtWallet = await getJettonWalletAddress(jettonMasters.USDT, address);

if (!scaleWallet || !usdtWallet) {
throw new Error('无法获取代币钱包地址');
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

建议统一错误信息的语言

第129行的错误信息为中文,而其他错误信息为英文。建议统一错误信息的语言,以提升代码的一致性和专业性。

throw new Error('Wallet address is empty');
}

console.log('Wallet Address:', walletAddress.toString());
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

考虑移除或调整调试日志

第19行的 console.log 可能在生产环境中不需要。建议在部署前移除或使用适当的日志工具。

Comment on lines +136 to +156
value: JSON.stringify({
validUntil: Math.floor(Date.now() / 1000) + 360,
messages: [{
address: scaleWallet,
amount: "150000000",
payload: beginCell()
.storeUint(0xf8a7ea5, 32)
.storeUint(0, 64)
.storeCoins(10000000000)
.storeAddress(Address.parse(address))
.storeAddress(Address.parse(address))
.storeCoins(0)
.storeBit(0)
.storeBit(0)
.storeRef(beginCell().endCell())
.endCell()
.toBoc()
.toString('base64'),
stateInit: null
}]
})
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

建议重构以减少重复代码

sendTokenTransaction 函数中,两个代币的交易构造逻辑相似。建议提取公共部分,减少代码重复,提高可维护性。

Also applies to: 161-181

Comment on lines +1 to +2
const { Address, beginCell } = require("@ton/core");
const { TonClient, JettonMaster } = require("@ton/ton");
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

require 替换为 import 语句

为了遵循 TypeScript 的最佳实践,请将第1-2行的 require 语句替换为 import 语句。

应用以下修改:

-const { Address, beginCell } = require("@ton/core");
-const { TonClient, JettonMaster } = require("@ton/ton");
+import { Address, beginCell } from "@ton/core";
+import { TonClient, JettonMaster } from "@ton/ton";
📝 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
const { Address, beginCell } = require("@ton/core");
const { TonClient, JettonMaster } = require("@ton/ton");
import { Address, beginCell } from "@ton/core";
import { TonClient, JettonMaster } from "@ton/ton";
🧰 Tools
🪛 eslint

[error] 1-1: Require statement not part of import statement.

(@typescript-eslint/no-var-requires)


[error] 2-2: Require statement not part of import statement.

(@typescript-eslint/no-var-requires)

Comment on lines +37 to +48
signTokenTransaction: (address: string) => [
{
id: 'signUSDCransaction',
name: 'USDC_TYPE',
value: JSON.stringify({
from: address,
to: address,
amount: 1000, // 0.000001 USD
token: '0x5d4b302506645c37ff133b98c4b50a5ae14841659738d6d733d59d0d217a93bf::coin::COIN'
}),
},
],
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

建议改进代码灵活性

代码中存在以下需要注意的地方:

  1. 金额被硬编码为1000
  2. Token地址被硬编码在代码中

建议进行如下修改:

  signTokenTransaction: (address: string) => [
    {
      id: 'signUSDCransaction',
      name: 'USDC_TYPE',
      value: JSON.stringify({
        from: address,
        to: address,
-       amount: 1000, // 0.000001 USD
-       token: '0x5d4b302506645c37ff133b98c4b50a5ae14841659738d6d733d59d0d217a93bf::coin::COIN'      
+       amount: process.env.DEFAULT_TOKEN_AMOUNT || 1000,
+       token: process.env.USDC_TOKEN_ADDRESS
      }),
    },
  ],

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

Comment on lines +82 to +89
transaction.add(
createTransferInstruction(
fromTokenAccount,
toTokenAccount,
fromPubkey,
BigInt(amount * Math.pow(10, decimals)),
)
);
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

建议添加错误处理和金额验证

当前实现缺少必要的错误处理和金额验证。

建议添加以下安全检查:

+ if (amount <= 0) {
+   throw new Error('Amount must be positive');
+ }
+ 
+ const adjustedAmount = amount * Math.pow(10, decimals);
+ if (!Number.isSafeInteger(adjustedAmount)) {
+   throw new Error('Amount overflow after decimal adjustment');
+ }

  transaction.add(
    createTransferInstruction(
      fromTokenAccount,
      toTokenAccount,
      fromPubkey,
-     BigInt(amount * Math.pow(10, decimals)),
+     BigInt(adjustedAmount),
    )
  );
📝 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
transaction.add(
createTransferInstruction(
fromTokenAccount,
toTokenAccount,
fromPubkey,
BigInt(amount * Math.pow(10, decimals)),
)
);
if (amount <= 0) {
throw new Error('Amount must be positive');
}
const adjustedAmount = amount * Math.pow(10, decimals);
if (!Number.isSafeInteger(adjustedAmount)) {
throw new Error('Amount overflow after decimal adjustment');
}
transaction.add(
createTransferInstruction(
fromTokenAccount,
toTokenAccount,
fromPubkey,
BigInt(adjustedAmount),
)
);

Comment on lines +60 to +61
// 将 async function 改为箭头函数形式的导出
export const createTokenTransferTransaction = async (
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

注意:请使用英文注释

当前代码包含中文注释,建议改为英文以保持一致性。

- // 将 async function 改为箭头函数形式的导出
+ // Convert async function to arrow function export
📝 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
// async function 改为箭头函数形式的导出
export const createTokenTransferTransaction = async (
// Convert async function to arrow function export
export const createTokenTransferTransaction = async (

Comment on lines +36 to +46
signAndSendTokenTransaction: (publicKey: string) =>
TOKEN_LIST.map(token => ({
id: `signAndSendTokenTransaction_${token.symbol}`,
name: `Send ${token.symbol} Token`,
value: JSON.stringify({
tokenMint: token.tokenMint,
toPubkey: publicKey,
amount: 0.000001,
decimals: token.decimals
}),
})),
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

建议添加金额验证和自定义选项

当前实现使用固定的小额转账值,建议增加灵活性。

建议添加以下改进:

  signAndSendTokenTransaction: (publicKey: string) => 
    TOKEN_LIST.map(token => ({
      id: `signAndSendTokenTransaction_${token.symbol}`,
      name: `Send ${token.symbol} Token`,
      value: JSON.stringify({
        tokenMint: token.tokenMint,
        toPubkey: publicKey,
-       amount: 0.000001,
+       amount: process.env[`DEFAULT_${token.symbol}_AMOUNT`] || 0.000001,
        decimals: token.decimals
      }),
    })),
📝 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
signAndSendTokenTransaction: (publicKey: string) =>
TOKEN_LIST.map(token => ({
id: `signAndSendTokenTransaction_${token.symbol}`,
name: `Send ${token.symbol} Token`,
value: JSON.stringify({
tokenMint: token.tokenMint,
toPubkey: publicKey,
amount: 0.000001,
decimals: token.decimals
}),
})),
signAndSendTokenTransaction: (publicKey: string) =>
TOKEN_LIST.map(token => ({
id: `signAndSendTokenTransaction_${token.symbol}`,
name: `Send ${token.symbol} Token`,
value: JSON.stringify({
tokenMint: token.tokenMint,
toPubkey: publicKey,
amount: process.env[`DEFAULT_${token.symbol}_AMOUNT`] || 0.000001,
decimals: token.decimals
}),
})),

Comment on lines +1 to +17
const TOKEN_LIST = [
{
symbol: 'USDT',
tokenMint: 'Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB',
decimals: 6
},
{
symbol: 'USDC',
tokenMint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
decimals: 6
},
// {
// symbol: 'RNDR',
// tokenMint: '7atgF8KQo4wJrD5ATGX7t1V2zVvykPJbFfNeVf1icFv1',
// decimals: 8
// },
];
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

建议改进代币列表管理

建议将代币列表移至配置文件,并添加地址验证。

  1. 创建专门的配置文件
  2. 添加地址格式验证
  3. 考虑使用环境变量
+ import { PublicKey } from '@solana/web3.js';
+
+ const validateTokenMint = (address: string): boolean => {
+   try {
+     new PublicKey(address);
+     return true;
+   } catch {
+     return false;
+   }
+ };

const TOKEN_LIST = [
  {
    symbol: 'USDT',
    tokenMint: 'Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB',
+   validate() {
+     if (!validateTokenMint(this.tokenMint)) {
+       throw new Error(`Invalid token mint for ${this.symbol}`);
+     }
+   },
    decimals: 6
  },
  // ... other tokens
];

+ TOKEN_LIST.forEach(token => token.validate());

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

🧰 Tools
🪛 Gitleaks (8.21.2)

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

(generic-api-key)


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

(generic-api-key)


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

(generic-api-key)

@originalix originalix merged commit 339d50e into OneKeyHQ:master Dec 16, 2024
4 of 5 checks passed
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