Skip to content

Commit

Permalink
Merge remote-tracking branch 'upstream/main' into JasonRUAN
Browse files Browse the repository at this point in the history
  • Loading branch information
JasonRUAN committed Dec 9, 2024
2 parents 4585b97 + 8503185 commit 4fb2ab9
Show file tree
Hide file tree
Showing 210 changed files with 26,026 additions and 148 deletions.
40 changes: 40 additions & 0 deletions mover/Azhan1431/code/task06/App.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { ConnectButton } from "@mysten/dapp-kit";
import { Box, Container, Flex, Heading } from "@radix-ui/themes";
//import { WalletStatus } from "./WalletStatus";
import NaviPTB from "./NaviPTB.tsx";

function App() {
return (
<>
<Flex
position="sticky"
px="4"
py="2"
justify="between"
style={{
borderBottom: "1px solid var(--gray-a2)",
}}
>
<Box>
<Heading>dApp Starter Template</Heading>
</Box>

<Box>
<ConnectButton />
</Box>
</Flex>
<Container>
<Container
mt="5"
pt="2"
px="4"
style={{ background: "var(--gray-a2)", minHeight: 500 }}
>
<NaviPTB />
</Container>
</Container>
</>
);
}

export default App;
101 changes: 101 additions & 0 deletions mover/Azhan1431/code/task06/NaviPTB.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
import { Button, Container, Flex, Text, Box, Heading } from "@radix-ui/themes";
import { useCurrentAccount, useSignAndExecuteTransaction } from "@mysten/dapp-kit";
import { Transaction } from "@mysten/sui/transactions";
import { Pool, PoolConfig } from "navi-sdk/dist/types";
import { pool, Sui, wUSDC } from "navi-sdk/dist/address";
import { borrowCoin, depositCoin } from "navi-sdk/dist/libs/PTB";
import { useState } from "react";

// 计算借款金额
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 depositAndBorrowSui = async (account: any, signAndExecuteTransaction: any, setMessage: any, setDigest: any) => {
if (!account) {
setMessage("Please connect your wallet first");
return;
}

try {
const date = new Date(); // 获取当前日期
const borrowAmount = calculateBorrowAmount(date.getMonth() + 1, date.getDate(), date.getHours());

// 创建新的交易对象
const tx = new Transaction();
tx.setSender(account.address);

// 获取池配置
const suiPool: PoolConfig = pool[Sui.symbol as keyof Pool];
const wusdcPool: PoolConfig = pool[wUSDC.symbol as keyof Pool];

if (!suiPool || !wusdcPool) {
throw new Error("Invalid pool configuration");
}

// 存款 SUI
const [suiCoin] = tx.splitCoins(tx.gas, [1_000_000_000]); // 分割 SUI 代币
if (!suiCoin) throw new Error("Failed to split SUI coins");

await depositCoin(tx, suiPool, suiCoin, 1_000_000_000); // 存款 SUI

// 借款 USDC
const [toBorrowCoin] = await borrowCoin(tx, wusdcPool, borrowAmount);
if (!toBorrowCoin) throw new Error("Failed to borrow USDC");

// 存款借出的 USDC
await depositCoin(tx, wusdcPool, toBorrowCoin, borrowAmount);

// 清除之前的消息
setMessage("");
setDigest("");

// 签名并执行交易
signAndExecuteTransaction(
{ transaction: tx, chain: "sui:mainnet" },
{
// onSuccess: (result: any) => { // 移除或注释掉
// console.log("Transaction successful:", result);
// setDigest(result.digest);
// },
onError: (error: any) => { // 为 error 参数指定类型
console.error("Transaction failed:", error);
setMessage(error.message || "Transaction failed");
},
}
);
} catch (error) {
console.error("Error in depositAndBorrowSui:", error);
setMessage(error instanceof Error ? error.message : "An unknown error occurred");
}
};

export function NaviPTB() {
const account = useCurrentAccount();
const { mutate: signAndExecuteTransaction } = useSignAndExecuteTransaction();
const [digest, setDigest] = useState<string>("");
const [message, setMessage] = useState<string>("");

return (
<Container>
<Box>
<Heading as="h2">Task06 任务</Heading>
<Text>
按照任务存入和借出相应的金额
</Text>
<Flex gap="3" direction={"column"}>
<Button onClick={() => depositAndBorrowSui(account, signAndExecuteTransaction, setMessage, setDigest)} variant="solid">
开始交易
</Button>
{digest && <Text>Transaction submitted: {digest}</Text>} {/* 显示交易摘要 */}
{message && <Text>Error: {message}</Text>} {/* 显示错误消息 */}
</Flex>
</Box>
</Container>
);
}

export default NaviPTB;

26 changes: 26 additions & 0 deletions mover/Azhan1431/code/task06/main.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import React from "react";
import ReactDOM from "react-dom/client";
import "@mysten/dapp-kit/dist/index.css";
import "@radix-ui/themes/styles.css";

import { SuiClientProvider, WalletProvider } from "@mysten/dapp-kit";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { Theme } from "@radix-ui/themes";
import App from "./App.tsx";
import { networkConfig } from "./networkConfig.ts";

const queryClient = new QueryClient();

ReactDOM.createRoot(document.getElementById("root")!).render(
<React.StrictMode>
<Theme appearance="dark">
<QueryClientProvider client={queryClient}>
<SuiClientProvider networks={networkConfig} defaultNetwork="mainnet">
<WalletProvider autoConnect>
<App />
</WalletProvider>
</SuiClientProvider>
</QueryClientProvider>
</Theme>
</React.StrictMode>,
);
File renamed without changes
4 changes: 2 additions & 2 deletions mover/Azhan1431/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
- [x] nft package id : 0x9cc630e0365e19f07076c3e0008e18376ae29c24a4726efaaae5d75897d87aba
- [x] nft object id : 0x3aa9bf700023bc0ec028c0f83d677a28b4a7580a5ec08f880f69ab70685a3e6c
- [x] 转账 nft hash: B586ccPv5bvEZtpoNynTEhYFMCbhdWt7P4s1ai9xKsct
- [x] scan上的NFT截图:![Scan截图](./image/nft.png)
- [x] scan上的NFT截图:![Scan截图](./image/My_nft.png)

## 04 Move Game
- [x] game package id : 0x385e8128003d4c29e6a37e0f1b210ae956ae4c40b571f320ef93329fe8986783
Expand All @@ -43,7 +43,7 @@
- [x] call swap CoinB-> CoinA hash : 9ripiwMGxid2oUtdvQ1dbMGvX1TKRdrocEYMBfskGikY

## 06 Dapp-kit SDK PTB
- [] save hash :
- [x] save hash : B6YN1B1i1FmwdZrrndUXWKaE2ritEMdwW3y5bDQdEWcE

## 07 Move CTF Check In
- [x] CLI call 截图 : ![截图](./image/task07.png)
Expand Down
37 changes: 37 additions & 0 deletions mover/Heemale/code/task5/Move.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
[package]
name = "task5"
edition = "2024.beta" # edition = "legacy" to use legacy (pre-2024) Move
# license = "" # e.g., "MIT", "GPL", "Apache 2.0"
# authors = ["..."] # e.g., ["Joe Smith ([email protected])", "John Snow ([email protected])"]

[dependencies]
Sui = { git = "https://github.com/MystenLabs/sui.git", subdir = "crates/sui-framework/packages/sui-framework", rev = "framework/testnet" }

# For remote import, use the `{ git = "...", subdir = "...", rev = "..." }`.
# Revision can be a branch, a tag, and a commit hash.
# MyRemotePackage = { git = "https://some.remote/host.git", subdir = "remote/path", rev = "main" }

# For local dependencies use `local = path`. Path is relative to the package root
# Local = { local = "../path/to" }

# To resolve a version conflict and force a specific version for dependency
# override use `override = true`
# Override = { local = "../conflicting/version", override = true }

[addresses]
task5 = "0x0"

# Named addresses will be accessible in Move as `@name`. They're also exported:
# for example, `std = "0x1"` is exported by the Standard Library.
# alice = "0xA11CE"

[dev-dependencies]
# The dev-dependencies section allows overriding dependencies for `--test` and
# `--dev` modes. You can introduce test-only dependencies here.
# Local = { local = "../path/to/dev-build" }

[dev-addresses]
# The dev-addresses section allows overwriting named addresses for the `--test`
# and `--dev` modes.
# alice = "0xB0B"

49 changes: 49 additions & 0 deletions mover/Heemale/code/task5/sources/faucet_coin.move
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
module task5::faucet_coin {

use std::string;
use sui::coin::{Self, TreasuryCap};
use sui::url;

public struct FAUCET_COIN has drop {}

fun init(witness: FAUCET_COIN, ctx: &mut TxContext) {
let (treasury, meta_data) = coin::create_currency<FAUCET_COIN>(
witness,
6,
b"Heemale Faucet",
b"Heemale Faucet Coin",
b"相信的心是我们的魔法",
option::some(
url::new_unsafe(
string::to_ascii(
string::utf8(
b"https://avatars.githubusercontent.com/u/57651639?s=400&u=25e8d8a5c8eed5d1408617994c5d8ea8ec0ac5c2&v=4"
)
)
)
),
ctx
);

transfer::public_share_object(treasury);
transfer::public_freeze_object(meta_data);
}

entry fun mint(
treasury_cap: &mut TreasuryCap<FAUCET_COIN>,
amount: u64,
recipient: address,
ctx: &mut TxContext
) {
let coin = coin::mint(treasury_cap, amount, ctx);
transfer::public_transfer(coin, recipient);
}

// === Testing ===

#[test_only]
public fun init_for_testing(ctx: &mut TxContext){
let witness = FAUCET_COIN {};
init(witness, ctx);
}
}
49 changes: 49 additions & 0 deletions mover/Heemale/code/task5/sources/my_coin.move
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
module task5::my_coin {

use std::string;
use sui::coin::{Self, TreasuryCap};
use sui::url;

public struct MY_COIN has drop {}

fun init(witness: MY_COIN, ctx: &mut TxContext) {
let (treasury, meta_data) = coin::create_currency<MY_COIN>(
witness,
6,
b"Heemale",
b"Heemale Coin",
b"相信的心是我们的魔法",
option::some(
url::new_unsafe(
string::to_ascii(
string::utf8(
b"https://avatars.githubusercontent.com/u/57651639?s=400&u=25e8d8a5c8eed5d1408617994c5d8ea8ec0ac5c2&v=4"
)
)
)
),
ctx
);

transfer::public_transfer(treasury, tx_context::sender(ctx));
transfer::public_freeze_object(meta_data);
}

entry fun mint(
treasury_cap: &mut TreasuryCap<MY_COIN>,
amount: u64,
recipient: address,
ctx: &mut TxContext
) {
let coin = coin::mint(treasury_cap, amount, ctx);
transfer::public_transfer(coin, recipient);
}

// === Testing ===

#[test_only]
public fun init_for_testing(ctx: &mut TxContext){
let witness = MY_COIN {};
init(witness, ctx);
}
}
66 changes: 66 additions & 0 deletions mover/Heemale/code/task5/sources/swap.move
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
module task5::swap {

use sui::coin::{Self, Coin};
use sui::balance::{Self, Balance};

const ETreasuryNotEnough: u64 = 0;

public struct Treasury<phantom T, phantom V> has key {
id: UID,
coin_a: Balance<T>,
coin_b: Balance<V>,
}

public fun new<T, V>(ctx: &mut TxContext) {
let treasury = Treasury {
id: object::new(ctx),
coin_a: balance::zero<T>(),
coin_b: balance::zero<V>(),
};
transfer::share_object(treasury);
}

public fun add_liquidity<T, V>(treasury: &mut Treasury<T, V>, coin_a: Coin<T>, coin_b: Coin<V>) {
let (treasury_coin_a, treasury_coin_b) = get_coin_mut<T, V>(treasury);
balance::join(treasury_coin_a, coin::into_balance(coin_a));
balance::join(treasury_coin_b, coin::into_balance(coin_b));
}

public fun swap_a_to_b<T, V>(treasury: &mut Treasury<T, V>, coin_a: Coin<T>, ctx: &mut TxContext): Coin<V> {
let (treasury_coin_a, treasury_coin_b) = get_coin_mut<T, V>(treasury);

let coin_value = coin::value(&coin_a);
let treasury_coin_b_value = balance::value(treasury_coin_b);
assert!(treasury_coin_b_value >= coin_value, ETreasuryNotEnough);

balance::join(treasury_coin_a, coin::into_balance(coin_a));

let balance_out = balance::split(treasury_coin_b, coin_value);
let coin_out = coin::from_balance(balance_out, ctx);

coin_out
}

public fun swap_b_to_a<T, V>(treasury: &mut Treasury<T, V>, coin_b: Coin<V>, ctx: &mut TxContext): Coin<T> {
let (treasury_coin_a, treasury_coin_b) = get_coin_mut<T, V>(treasury);

let coin_value = coin::value(&coin_b);
let treasury_coin_a_value = balance::value(treasury_coin_a);
assert!(treasury_coin_a_value >= coin_value, ETreasuryNotEnough);

balance::join(treasury_coin_b, coin::into_balance(coin_b));

let balance_out = balance::split(treasury_coin_a, coin_value);
let coin_out = coin::from_balance(balance_out, ctx);

coin_out
}

public(package) fun get_coin_mut<T, V>(treasury: &mut Treasury<T, V>): (&mut Balance<T>, &mut Balance<V>) {
(&mut treasury.coin_a, &mut treasury.coin_b)
}

public(package) fun get_coin<T, V>(treasury: &Treasury<T, V>): (&Balance<T>, &Balance<V>) {
(&treasury.coin_a, &treasury.coin_b)
}
}
Loading

0 comments on commit 4fb2ab9

Please sign in to comment.