Skip to content

Commit

Permalink
task6
Browse files Browse the repository at this point in the history
  • Loading branch information
wenchao13547 committed Dec 10, 2024
1 parent 1320600 commit d5f6738
Show file tree
Hide file tree
Showing 2 changed files with 141 additions and 13 deletions.
102 changes: 89 additions & 13 deletions mover/wenchao13547/code/task6/my-first-sui-dapp/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,23 @@
import { useCurrentAccount, useSignAndExecuteTransaction } from "@mysten/dapp-kit";
import { Container, Flex, Heading, Text, Button } from "@radix-ui/themes";
import { Container, Flex, Heading, Text, Button, Spinner } from "@radix-ui/themes";
import { ConnectButton, useConnectWallet, useWallets } from '@mysten/dapp-kit';
import { wUSDC } from "navi-sdk/dist/address";
import { mainAction } from "./NAVI.ts";
import { withdrawSUI } from "./withdrawSUI"; // 引入取出 SUI 的功能模块
import { useState } from "react";

// 计算借出的 USDC 数量
const calculateBorrowAmount = (month: number, day: number, hour: number): number => {
const borrowAmountStr = `0.${month.toString().padStart(2, "0")}${day.toString().padStart(2, "0")}${hour.toString().padStart(2, "0")}`;
return parseFloat(borrowAmountStr) * 10 ** wUSDC.decimal;
};

const Execute = () => {

// State 管理
const [transactionStatus, setTransactionStatus] = useState<string | null>(null);
const [errorMessage, setErrorMessage] = useState<string | null>(null);

const wallets = useWallets();
const { mutate: connect } = useConnectWallet();

Expand All @@ -20,9 +27,55 @@ const Execute = () => {
const date = new Date();
const usdcAmount = calculateBorrowAmount(date.getMonth() + 1, date.getDate(), date.getHours());

return (
// 处理交易执行
const handleTransaction = async () => {
setTransactionStatus("Executing transaction..."); // 更新交易状态

try {
await mainAction(account, {
signAndExecute,
usdcAmount,
onSuccess(result) {
setTransactionStatus("Transaction successful!"); // 成功消息
console.log(result, 'Transaction success!');
},
onError(error) {
setTransactionStatus("Transaction failed"); // 失败消息
setErrorMessage(error.message || "An unknown error occurred");
console.log(error, 'Something went wrong!');
},
});
} catch (error) {
setTransactionStatus("Transaction failed");
setErrorMessage(error instanceof Error ? error.message : "An unknown error occurred");
}
};

// 处理取出 SUI
const handleWithdrawSUI = async () => {
setTransactionStatus("Executing SUI withdrawal...");

try {
await withdrawSUI(account, {
signAndExecute,
suiAmount: 1, // 假设取出 1 SUI
onSuccess(result) {
setTransactionStatus("SUI withdrawal successful!");
console.log(result, 'SUI withdrawal success!');
},
onError(error) {
setTransactionStatus("SUI withdrawal failed");
setErrorMessage(error.message || "An unknown error occurred");
console.log(error, 'SUI withdrawal failed!');
},
});
} catch (error) {
setTransactionStatus("SUI withdrawal failed");
setErrorMessage(error instanceof Error ? error.message : "An unknown error occurred");
}
};

return (
<Container my="2">
<Heading mb="2">Wallet Status</Heading>

Expand Down Expand Up @@ -68,24 +121,47 @@ const Execute = () => {
</Flex>
<Button
size="3"
onClick={() => {
mainAction(account, {
signAndExecute, usdcAmount, onSuccess(result) {
console.log(result, 'Transaction success!')
}, onError(error) {
console.log(error, 'Something went wrong!')
},
});
}}
onClick={handleTransaction}
style={{ cursor: 'pointer' }}
>
<Text>点击执行此交易</Text>
</Button>
</Flex>
) : null}

{/* 取出 SUI 的操作 */}
{account ? (
<Flex direction="column" mt="4">
<Heading mb="2">SUI 取出操作</Heading>
<Text>4. [取出 1 SUI]</Text>
<Button
size="3"
onClick={handleWithdrawSUI}
style={{ cursor: 'pointer' }}
>
<Text>点击取出 1 SUI</Text>
</Button>
</Flex>
) : null}

{/* 交易状态和加载指示 */}
{transactionStatus && (
<Flex direction="column" mt="4">
<Text>{transactionStatus}</Text>
{transactionStatus === "Executing transaction..." && (
<Spinner size="2" style={{ marginTop: "10px" }} />
)}
</Flex>
)}

{/* 错误消息 */}
{errorMessage && (
<Flex direction="column" mt="4" style={{ color: 'red' }}>
<Text>Error: {errorMessage}</Text>
</Flex>
)}
</Container>
);
}
};

export default Execute;

Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
// 引入必要的模块
import { Transaction } from '@mysten/sui/transactions'; // 引入交易相关类
import { withdrawCoin } from 'navi-sdk/dist/libs/PTB'; // 引入存币、借币和取币函数
import { Sui } from "navi-sdk/dist/address"; // 引入 SUI 和 wUSDC 地址配置
import { Pool, PoolConfig } from "navi-sdk/dist/types"; // 引入池配置类型
import { pool } from 'navi-sdk/dist/address'; // 引入池配置数据

// 定义取出 SUI 的操作函数
export const withdrawSUI = async (account: any, { signAndExecute, suiAmount, onSuccess = () => { } }: {
signAndExecute: any; // 签名并执行交易的函数
suiAmount: number; // 取出 SUI 的金额
onSuccess?: (result: any) => void; // 成功后的回调函数(默认空函数)
onError?: (result: any) => void; // 错误时的回调函数(默认空函数)
}) => {

if (!account) {
postMessage("Please connect your wallet first");
return; // 如果没有连接钱包,退出函数
}

const tx = new Transaction();
tx.setSender(account.address); // 设置交易的发送者为当前账户地址

// 获取 SUI 池的配置
const SuiPool: PoolConfig = pool[Sui.symbol as keyof Pool];

if (!SuiPool) {
throw new Error("Invalid pool configuration");
}

tx.setGasBudget(1e9); // 设置交易的 Gas 预算为 1e9

try {
// 从池中取出指定数量的 SUI,确保丢弃不需要的返回值
const [ ] = await withdrawCoin(tx as any, SuiPool, suiAmount); // 丢弃不需要的返回值
console.log([ ])
// 执行签名并执行交易
await signAndExecute({
transaction: tx,
chain: "sui:mainnet"
}, {
onSuccess, // 成功时执行传入的回调函数
onError: (error: any) => { // 错误时执行传入的错误回调
console.error("Transaction failed:", error);
postMessage(error.message || "Transaction failed");
},
});
} catch (error) {
console.error("Transaction failed:", error);
postMessage(error instanceof Error ? error.message : "An unknown error occurred");
}
};

0 comments on commit d5f6738

Please sign in to comment.