Skip to content

Commit

Permalink
withdraw
Browse files Browse the repository at this point in the history
  • Loading branch information
sfsf332 committed Oct 25, 2024
1 parent f2d7376 commit 2dbb79c
Show file tree
Hide file tree
Showing 9 changed files with 1,964 additions and 957 deletions.
1,418 changes: 1,063 additions & 355 deletions package-lock.json

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
"react": "^18",
"react-apexcharts": "^1.4.1",
"react-dom": "^18",
"react-spinners": "^0.14.1",
"react-tooltip": "^5.28.0"
},
"devDependencies": {
Expand Down
33 changes: 19 additions & 14 deletions src/app/components/IckbSwap.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,15 @@ const IckbSwap: React.FC<{ walletConfig: WalletConfig }> = ({ walletConfig }) =>
}
let progressId, txHash;
try {
// const cccTx = ccc.Transaction.fromLumosSkeleton(txInfo.tx);
// const signedTx = await signerCcc.signTransaction(cccTx);
const cccTx = ccc.Transaction.fromLumosSkeleton(txInfo.tx);
const signedTx = await signerCcc.signTransaction(cccTx);
// const signedTx = await signerCcc.signTransaction(cccTx);

txHash = await signerCcc.sendTransaction(cccTx);
progressId = await showNotification("progress", `Deposit in progress!`);

txHash = await signerCcc.sendTransaction(signedTx);
// txHash = await signerCcc.sendTransaction(signedTx);
} finally {
removeNotification(progressId + '')
// freezeTxInfo(txInfoFrom({}));
Expand Down Expand Up @@ -72,11 +76,11 @@ const IckbSwap: React.FC<{ walletConfig: WalletConfig }> = ({ walletConfig }) =>
<p className="text-2xl font-bold font-play mb-4">{ickbData && toText(ickbData?.ckbAvailable)} <span className="text-base font-normal">CKB</span></p>

</div>
<div className="basis-1/2">
{/* <div className="basis-1/2">
<p className="text-gray-400 mb-2 flex items-center ">Liquidity Availability <Info size={16} data-tooltip-id="my-tooltip" data-tooltip-content="Hello world!" /></p>
<p className="text-2xl font-bold font-play mb-4"> <span className="text-base font-normal">- iCKB</span></p>
</div>
</div> */}
</div>
<div className='relative mb-4 bg-gray-700 p-4 rounded'>
<label className="flex px-2 items-center"><img src="/svg/icon-ckb.svg" alt="CKB" className="mr-2" /> CKB</label>
Expand Down Expand Up @@ -108,9 +112,10 @@ const IckbSwap: React.FC<{ walletConfig: WalletConfig }> = ({ walletConfig }) =>
</p>
<div className="flex justify-between my-3 text-base">
<span>You will Receive <Info size={16} className="inline-block" data-tooltip-id="my-tooltip" data-tooltip-content="receive info" /></span>
<span>{amount ? <>{approxConversion(BigInt(Math.trunc(parseFloat(amount) * 100000000)))} iCKB</> : 'Calculated after entry'}</span>
{/* 扣除0.1% 交易bot fee */}
<span>{amount ? <>{approxConversion(BigInt(Math.trunc(parseFloat(amount) * 99900000)))} iCKB</> : 'Calculated after entry'}</span>
</div>
{txInfo && amount &&
{txInfo && Number(amount)>0 &&
<div className="rounded border-1 border-yellow-500 p-4 bg-yellow-500/[.12] my-3">
<h3 className="text-lg flex items-center">
<TriangleAlert size={24} className="block mr-1" />
Expand Down Expand Up @@ -138,14 +143,14 @@ const IckbSwap: React.FC<{ walletConfig: WalletConfig }> = ({ walletConfig }) =>
<button
onClick={handleSwap}
className="mt-4 w-full font-bold bg-btn-gradient text-gray-800 text-body-2 py-3 rounded-lg hover:bg-btn-gradient-hover transition duration-200 disabled:opacity-50 disabled:hover:bg-btn-gradient"
// disabled={(() => {
// try {
// ccc.numFrom(amount);
// } catch (error) {
// return true;
// }
// return amount === "";
// })()}
disabled={(() => {
try {
ccc.numFrom(amount);
} catch (error) {
return true;
}
return amount === "";
})()}
>
{amount ? 'Swap' : 'Enter an amount'}

Expand Down
161 changes: 148 additions & 13 deletions src/app/components/IckbWithDraw.tsx
Original file line number Diff line number Diff line change
@@ -1,43 +1,92 @@
import React, { useCallback, useState } from "react";
import React, { useCallback, useMemo, useState } from "react";
import { ccc } from "@ckb-ccc/connector-react";
import { useNotification } from "@/context/NotificationProvider";
import { ckb2Ickb, ickb2Ckb } from "@ickb/v1-core";
import { Info, ArrowDown, TriangleAlert } from "lucide-react";
import { Info, TriangleAlert, ArrowUp, ArrowDown, ChevronDown, ChevronUp } from "lucide-react";
import { toText } from "@/utils/stringUtils";

import { type WalletConfig } from "@/cores/config";
import { useQuery } from "@tanstack/react-query";
import { l1StateOptions } from "@/cores/queries";
import ClipLoader from "react-spinners/ClipLoader";
import UseSorter, { SortDirection, ArrowProps, Column, SorterObj } from "@/hooks/UseSorter";

const pendingIckbs: SorterObj[] = [
{
amount: 9999,
daterequested: 1729790007500,
remainingtime: 1729760007500
},
{
amount: 9998,
daterequested: 1729750006500,
remainingtime: 1729750006500
},
{
amount: 9997,
daterequested: 1729790003500,
remainingtime: 1735740003500
},
];

const columns: Column[] = [
{
name: "Amount",
key: 'amount'
},
{
name: "Date Requested",
key: "daterequested"
},
{
name: "Remaining Time",
key: "remainingtime"
}
];


const calculateDaysDifference = (timestamp1:number, timestamp2:number) => {

try {
const date1 = new Date(timestamp1);
const date2 = new Date(timestamp2);
const diffInMilliseconds = Math.abs(date2.getTime() - date1.getTime());
const diffInHoutrs = Math.floor(diffInMilliseconds / (1000 * 60 * 60));
return diffInHoutrs;
} catch (error) {
return "Error calculating days difference: " + error;
}
};
const IckbWithDraw: React.FC<{ walletConfig: WalletConfig }> = ({ walletConfig }) => {
const [amount, setAmount] = useState<string>("");
const [pendingShow, setPendingShow] = useState<boolean>(false);
const { data: ickbData, isStale, isFetching } = useQuery(
l1StateOptions(walletConfig, false),
);
const txInfo = ickbData?.txBuilder(true, ccc.fixedPointFrom(amount));
const signerCcc = ccc.useSigner();

const { showNotification, removeNotification } = useNotification();
async function handleWithDraw() {
if (!txInfo || !signerCcc) {
return
}
let progressId, txHash
try {
progressId = await showNotification("progress", `Deposit in progress!`);

const cccTx = ccc.Transaction.fromLumosSkeleton(txInfo.tx);
const signedTx = await signerCcc.signTransaction(cccTx);
txHash = await signerCcc.sendTransaction(signedTx);

txHash = await signerCcc.sendTransaction(cccTx);
console.log(txHash)
progressId = await showNotification("progress", `Deposit in progress!`);

} finally {
setAmount('0')
removeNotification(progressId + '')
showNotification("success", `Deposit Success: ${txHash}`);
}
}


function approxConversion(
amount: bigint,
) {
Expand All @@ -58,7 +107,49 @@ const IckbWithDraw: React.FC<{ walletConfig: WalletConfig }> = ({ walletConfig }
setAmount(e.target.value)
}, [])

const [sortedTable, setSortedTable, dir, setDir, key, setKey] = UseSorter<
SorterObj
>(pendingIckbs);
const handleOnClick = (
currentHead:Column
) => {
const currentSortDir =
dir?.valueOf() === SortDirection.Ascending.valueOf()
? SortDirection.Descending
: SortDirection.Ascending;

if (dir === undefined) {
setDir(SortDirection.Ascending);
} else {
setDir(currentSortDir);
}
if (currentHead) {
setKey(currentHead.key as keyof SorterObj);
}
};
const Arrow = (props: ArrowProps) => {
if (props.sortDir !== undefined && props.active) {
return SortDirection.Ascending.valueOf() === props.sortDir.valueOf() ? (
<div className="flex flex-col">
<ChevronUp color="rgba(255,255,255,0.4)" size={12} />
<ChevronDown color="rgba(255,255,255,1)" size={12} />
</div>
) : (
<div className="flex flex-col">
<ChevronUp color="rgba(255,255,255,1)" size={12} />
<ChevronDown color="rgba(255,255,255,0.4)" size={12} />
</div>
// <AArrowUp />
);
}
return (<div className="flex flex-col">
<ChevronUp color="rgba(255,255,255,0.4)" size={12} />
<ChevronDown color="rgba(255,255,255,0.4)" size={12} />
</div>);
};
const togglePendingShow = ()=>{
setPendingShow(!pendingShow)
}
return (
<>
<div className="flex flex-row font-play mb-4 mt-8 text-left">
Expand All @@ -84,15 +175,15 @@ const IckbWithDraw: React.FC<{ walletConfig: WalletConfig }> = ({ walletConfig }
MAX
</span>
</div>

<p className="text-center text-large font-bold text-center text-cyan-500 mb-4 pb-2 ">
1 iCKB ≈ {ickbData?.tipHeader && approxConversion(BigInt(1 * 100000000))}CKB
</p>
<div className="flex justify-between my-3 text-base">
<span>You will Receive <Info size={16} className="inline-block" data-tooltip-id="my-tooltip" data-tooltip-content="receive info" /></span>
<span>{amount ? <>{approxConversion(BigInt(Math.trunc(parseFloat(amount) * 100000000)))} iCKB</> : 'Calculated after entry'}</span>
</div>
{txInfo && Number(amount)>0 &&
{txInfo && Number(amount) > 0 &&
<div className="rounded border-1 border-yellow-500 p-4 bg-yellow-500/[.12] my-3">
<h3 className="text-lg flex items-center">
<TriangleAlert size={24} className="block mr-1" />
Expand All @@ -104,16 +195,60 @@ const IckbWithDraw: React.FC<{ walletConfig: WalletConfig }> = ({ walletConfig }
.join(". ")}
</p></div>
}


<button
onClick={handleWithDraw}
className="mt-4 w-full font-bold bg-btn-gradient text-gray-800 text-body-2 py-3 rounded-lg hover:bg-btn-gradient-hover transition duration-200 disabled:opacity-50 disabled:hover:bg-btn-gradient"

disabled={(() => {
try {
ccc.numFrom(amount);
} catch (error) {
return true;
}
return amount === "";
})()}
>
{amount ? 'WithDraw' : 'Enter an amount'}

</button></>
</button>
<div className="mt-8 w-full">
<div className="flex items-center" onClick={togglePendingShow}>
{pendingShow?<ChevronUp color="rgba(255,255,255,1)" size={18} />:<ChevronDown color="rgba(255,255,255,1)" size={18} />}
Pending iCKB Details</div>
{pendingShow&&<>
{columns&&columns.length>0?<table className="w-full mt-4 table-auto">
<thead className="border border-t-0 border-l-0 border-r-0 border-gray-500">
<tr>
{columns.map((c, index) => {
return (
<th key={index} className="text-body-2 text-left p-2 cursor-pointer" onClick={()=>handleOnClick(c)}>

<div className="w-full flex items-center justify-between ">
<span className="text-[rgba(255,255,255,0.7)]">{c.name}</span>
<Arrow sortDir={dir} active={c.key === key} />
</div>
</th>
);
})}
</tr>
</thead>
{/* Apply the table body props */}
<tbody>
{sortedTable.map((c, index) => {
return (
<tr key={index}>
<td className="text-body-2 text-left p-2 ">{c.amount}</td>
<td className="text-body-2 text-left p-2 ">{new Date(c.daterequested).toLocaleDateString()}</td>
<td className="text-body-2 text-left p-2 "><ClipLoader className="mr-2" size={16} color="#00FAED" />{calculateDaysDifference(c.daterequested,c.remainingtime)} hours left</td>
</tr>
);
})}
</tbody>
</table>:<p>You don’t have any pending iCKB </p>}


</>}
</div>
</>
);
};

Expand Down
22 changes: 22 additions & 0 deletions src/app/components/Sorter.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
export enum SortDirection {
Ascending,
Descending
}

export default function sortingObj<T>(
data: T[],
sortKey: keyof T,
direction: SortDirection
): T[] {
const d = data.sort((a: T, b: T) => {
if (direction === SortDirection.Ascending) {
return a[sortKey] < b[sortKey] ? -1 : 1;
}
if (direction === SortDirection.Descending) {
return a[sortKey] > b[sortKey] ? -1 : 1;
}
return 0;
});
return d;
}

8 changes: 4 additions & 4 deletions src/cores/queries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,9 +72,9 @@ async function getL1State(walletConfig: WalletConfig) {
const mixedCells = await getMixedCells(walletConfig);

// Prefetch feeRate and tipHeader
const feeRatePromise = rpc.getFeeRate(BigInt(61));
const feeRatePromise = rpc.getFeeRate(BigInt(1));
const tipHeaderPromise = rpc.getTipHeader();

// Prefetch headers
const wanted = new Set<HexNumber>();
const deferredGetHeader = (blockNumber: string) => {
Expand Down Expand Up @@ -187,8 +187,8 @@ async function getL1State(walletConfig: WalletConfig) {
);
}

const feeRate = await feeRatePromise;

const feeRate = BigInt(Number(await feeRatePromise)+1000);
console.log(feeRate)
const txBuilder = (isCkb2Udt: boolean, amount: bigint) => {
const txInfo = txInfoFrom({ tx: baseTx, info });

Expand Down
2 changes: 1 addition & 1 deletion src/cores/transaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,7 @@ export function addChange(
feeRate,
);
// Use a fee that is multiple of N=1249
const N = BigInt(1249);
const N = BigInt(2000);
return ((baseFee + (N - BigInt(1))) / N) * N;
},
config,
Expand Down
Loading

0 comments on commit 2dbb79c

Please sign in to comment.