Skip to content

Commit

Permalink
Fix/decimals input on swap create (#119)
Browse files Browse the repository at this point in the history
* feat: swap with decimals

* feat: ada to lovelace and lovelace to ada function conversions removed

* fix: input

* fix: desired icon and withdraw page select all
  • Loading branch information
mikarasv authored Jan 11, 2024
1 parent 0c3c9b4 commit 21e74a7
Show file tree
Hide file tree
Showing 11 changed files with 82 additions and 89 deletions.
16 changes: 14 additions & 2 deletions src/components/CreateListing/CreateListing.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,13 @@ export const CreateListing = () => {
<div className="flex w-full flex-col content-start items-start gap-2">
<div className="font-bold">Details</div>
<TokenInputs
label="You will swap *"
label={
"You will swap " +
(Number(selectedOffered.decimals) > 0
? `(only ${selectedOffered.decimals} decimals allowed)`
: "") +
" *"
}
value={valueOffered}
setValue={setValueOffered}
selected={selectedOffered}
Expand All @@ -230,7 +236,13 @@ export const CreateListing = () => {
className="flex justify-center self-center"
/>
<TokenInputs
label="You will receive *"
label={
"You will receive " +
(Number(selectedDesired.decimals) > 0
? `(only ${selectedDesired.decimals} decimals allowed)`
: "") +
" *"
}
value={valueDesired}
setValue={setValueDesired}
selected={selectedDesired}
Expand Down
19 changes: 16 additions & 3 deletions src/components/CreateListing/TokenInputs.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,11 @@ export const TokenInputs = ({
const [loading, setLoading] = useState(true);

const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
setValue(e.target.value || "");
const inputSections = e.target.value.split(".");
const decimals = inputSections[1]?.substring(0, selected.decimals);
if (selected.decimals > 0 && decimals)
setValue(inputSections[0] + "." + decimals);
else setValue(e.target.value || "");
};

useEffect(() => {
Expand Down Expand Up @@ -101,8 +105,16 @@ export const TokenInputs = ({
if (runtimeLifecycle) {
void getOwnTokens();
}
const valueSections = value.split(".");
if (selected.decimals > 0 && valueSections.length > 1) {
setValue(
valueSections[0] +
"." +
valueSections[1]?.substring(0, selected.decimals),
);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [runtimeLifecycle]);
}, [runtimeLifecycle, selected]);

return (
<Input
Expand All @@ -113,9 +125,10 @@ export const TokenInputs = ({
pointerEvents
placeholder="0"
error={errors}
step={selected.decimals > 0 ? String(1 / 10 ** selected.decimals) : "any"}
endContent={
<TokensModal
assets={label === "You will swap *" ? ownTokens : undefined}
assets={label.startsWith("You will swap") ? ownTokens : undefined}
selected={selected}
setSelected={setSelected}
loading={loading}
Expand Down
20 changes: 10 additions & 10 deletions src/components/Deposit/Deposit.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,9 @@ import { TSSDKContext } from "~/contexts/tssdk.context";
import {
ICON_SIZES,
PAGES,
adaToLovelace,
dateTimeOptions,
decimalToInt,
getAddress,
isADA,
parseTokenName,
textToHexa,
waitTxConfirmation,
Expand Down Expand Up @@ -85,7 +83,7 @@ export const Deposit = () => {
/>,
);

if (tokensData[desiredToken as TOKENS]?.icon === <></>) {
if (desiredIcon === <></> || !desiredIcon) {
const desiredMetadata = await lookupTokenMetadata(
desiredPolicyId,
textToHexa(parseTokenName(desiredToken)),
Expand Down Expand Up @@ -128,12 +126,10 @@ export const Deposit = () => {
inputs: [
{
input_from_party: { address: myAddress },
that_deposits: isADA(offeredToken)
? (adaToLovelace(BigInt(offeredAmount)) as bigint)
: (decimalToInt(
BigInt(offeredAmount),
Number(offeredDecimals),
) as bigint),
that_deposits: decimalToInt(
Number(offeredAmount),
Number(offeredDecimals),
) as bigint,
of_token: {
currency_symbol: offeredPolicyId,
token_name: parseTokenName(offeredToken),
Expand Down Expand Up @@ -196,7 +192,11 @@ export const Deposit = () => {

<div className="flex flex-col items-center gap-3 pt-5 text-center text-sm text-m-blue">
<div className="w-36 text-base">
<Button size={SIZE.SMALL} onClick={handleApplyInput}>
<Button
size={SIZE.SMALL}
onClick={handleApplyInput}
disabled={loading}
>
Deposit
</Button>
</div>
Expand Down
2 changes: 1 addition & 1 deletion src/components/Information/CompleteSwap.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ export const CompleteSwap = () => {
</a>
<Link href={PAGES.LISTING}>
<Button size={SIZE.REGULAR} color={COLORS.BLACK}>
<div className="flex justify-center gap-3 whitespace-normal break-words text-sm sm:text-base">
<div className="flex items-center justify-center gap-3 whitespace-normal break-words text-sm sm:text-base">
<div className="hidden sm:block">
<Image
src={LeftArrowIcon as string}
Expand Down
2 changes: 2 additions & 0 deletions src/components/Input/Input.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ export const Input = ({
value,
onChange,
className: customClassName,
step,
}: InputProps) => {
const shadow = useShadow ? "shadow-md" : "";
const paddingLeftX = startContent ? "pl-12" : "pl-4";
Expand Down Expand Up @@ -57,6 +58,7 @@ export const Input = ({
onChange={onChange}
disabled={disabled}
required={required}
step={step}
className={`m-dark-grey w-full flex-grow rounded-md border p-3 focus:border-m-purple focus:ring-m-purple ${paddingLeftX} ${paddingRightX} ${shadow} focus:outline-none focus:ring-1 ${customClassName} ${errorStyle}`}
/>
<div className={`${pointerEvents} absolute right-0 p-4`}>
Expand Down
18 changes: 7 additions & 11 deletions src/components/SwapModals/SwapModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,9 @@ import {
COLORS,
ICON_SIZES,
PAGES,
adaToLovelace,
contractDetailsSchema,
decimalToInt,
isADA,
isEnoughBalance,
parseTokenName,
textToHexa,
waitTxConfirmation,
} from "~/utils";
Expand Down Expand Up @@ -103,15 +100,13 @@ export const SwapModal = ({
inputs: [
{
input_from_party: { role_token: "buyer" },
that_deposits: isADA(desired.tokenName)
? (adaToLovelace(BigInt(desired.amount)) as bigint)
: (decimalToInt(
BigInt(desired.amount),
tokenData.decimals!,
) as bigint),
that_deposits: decimalToInt(
Number(desired.amount),
tokenData.decimals!,
) as bigint,
of_token: {
currency_symbol: desired.policyId,
token_name: parseTokenName(desired.assetName),
token_name: desired.assetName,
},
into_account: { role_token: "buyer" },
},
Expand Down Expand Up @@ -232,6 +227,7 @@ export const SwapModal = ({
size={SIZE.SMALL}
color={COLORS.BLACK}
onClick={closeModal}
disabled={loading}
>
Cancel
</Button>
Expand All @@ -241,7 +237,7 @@ export const SwapModal = ({
size={SIZE.SMALL}
filled
onClick={acceptSwap}
disabled={!isEnoughBalance(balance, desired)}
disabled={!isEnoughBalance(balance, desired) || loading}
>
Confirm Swap
</Button>
Expand Down
6 changes: 3 additions & 3 deletions src/components/WalletWidget/Balance.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { useContext, useEffect, useState } from "react";
import { TSSDKContext } from "~/contexts/tssdk.context";
import { adaToLovelace, lovelaceToAda } from "~/utils";
import { decimalToInt, intToDecimal } from "~/utils";

export const Balance = () => {
const [balance, setBalance] = useState(BigInt(0));
Expand All @@ -18,10 +18,10 @@ export const Balance = () => {
}
};

const balanceInt = Math.floor(Number(lovelaceToAda(balance)));
const balanceInt = Math.floor(Number(intToDecimal(balance, 6)));

const balanceDecimals = Number(
balance - (adaToLovelace(BigInt(balanceInt)) as bigint),
balance - (decimalToInt(BigInt(balanceInt), 6) as bigint),
);

return (
Expand Down
12 changes: 3 additions & 9 deletions src/components/Withdraw/WithdrawPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -67,15 +67,12 @@ export const WithdrawPage = () => {

const selectAll = async () => {
const remainingWithdraws = possibleWithdraws
.filter((contract) => !contract.added)
.filter((contract) => !contract.added && isEmpty(contract.error))
.map((contract) => contract.contractId);

setPossibleWithdraws((prev) =>
prev.map((contract) => {
if (
remainingWithdraws.includes(contract.contractId) &&
isEmpty(contract.error)
) {
if (remainingWithdraws.includes(contract.contractId)) {
return { ...contract, adding: true };
}
return contract;
Expand All @@ -90,10 +87,7 @@ export const WithdrawPage = () => {
if (payoutIds) {
setPossibleWithdraws((prev) =>
prev.map((contract) => {
if (
remainingWithdraws.includes(contract.contractId) &&
isEmpty(contract.error)
) {
if (remainingWithdraws.includes(contract.contractId)) {
return {
...contract,
added: true,
Expand Down
4 changes: 2 additions & 2 deletions src/utils/cardano.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,11 +60,11 @@ export const getSwapContract = ({
providerAddress,
}: ISwapRequest) => {
const parsedValueOffered = decimalToInt(
BigInt(valueOffered),
Number(valueOffered),
selectedOffered.decimals,
) as bigint;
const parsedValueDesired = decimalToInt(
BigInt(valueDesired),
Number(valueDesired),
selectedDesired.decimals,
) as bigint;

Expand Down
8 changes: 0 additions & 8 deletions src/utils/numbers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,3 @@ export const intToDecimal = (int: number | bigint, decimals: number) => {
}
return int / BigInt(10 ** decimals);
};

export const adaToLovelace = (ada: number | bigint) => {
return decimalToInt(ada, 6);
};

export const lovelaceToAda = (lovelace: number | bigint) => {
return intToDecimal(lovelace, 6);
};
64 changes: 24 additions & 40 deletions src/utils/restApi/api.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,7 @@ import {
import {
ICON_SIZES,
intToDecimal,
isADA,
isEmpty,
lovelaceToAda,
parseState,
parseTokenName,
textToHexa,
Expand All @@ -53,12 +51,10 @@ const getOffered = async (data: OfferedType) => {
);

if (tokenFromLocal) {
const amount = isEmpty(data.of_token.token_name)
? (lovelaceToAda(Number(data.deposits)) as bigint)
: (intToDecimal(
Number(data.deposits),
tokenFromLocal.decimals,
) as bigint);
const amount = intToDecimal(
Number(data.deposits),
tokenFromLocal.decimals,
) as bigint;

return {
tokenName: tokenFromLocal.tokenName,
Expand All @@ -77,12 +73,10 @@ const getOffered = async (data: OfferedType) => {
);

if (tokenInfo) {
const amount = isEmpty(data.of_token.token_name)
? (lovelaceToAda(Number(data.deposits)) as number)
: (intToDecimal(
Number(data.deposits),
tokenInfo.decimals!,
) as number);
const amount = intToDecimal(
Number(data.deposits),
tokenInfo.decimals!,
) as number;

return {
tokenName: tokenInfo.ticker ?? tokenInfo.name,
Expand Down Expand Up @@ -129,12 +123,10 @@ const getDesired = async (data: DesiredType) => {
);

if (tokenFromLocal) {
const amount = isADA(data.when[0].case.of_token.token_name)
? (lovelaceToAda(Number(data.when[0].case.deposits)) as bigint)
: (intToDecimal(
Number(data.when[0].case.deposits),
tokenFromLocal.decimals,
) as bigint);
const amount = intToDecimal(
Number(data.when[0].case.deposits),
tokenFromLocal.decimals,
) as bigint;

return {
tokenName: tokenFromLocal.tokenName,
Expand All @@ -157,12 +149,10 @@ const getDesired = async (data: DesiredType) => {
? parseTokenName(tokenInfo.ticker)
: tokenInfo.name;

const amount = isADA(data.when[0].case.of_token.token_name)
? (lovelaceToAda(Number(data.when[0].case.deposits)) as number)
: (intToDecimal(
Number(data.when[0].case.deposits),
tokenInfo.decimals!,
) as number);
const amount = intToDecimal(
Number(data.when[0].case.deposits),
tokenInfo.decimals!,
) as number;

return {
tokenName,
Expand Down Expand Up @@ -359,20 +349,14 @@ const getInitialContract = async (contract: ContractDetails) => {
swapperToken = parseTokenName(
parsedPayout.data.when[0].then.when[0].case.of_token.token_name,
);
providerAmount = isADA(providerToken)
? (lovelaceToAda(parsedPayout.data.when[0].case.deposits) as bigint)
: (intToDecimal(
parsedPayout.data.when[0].case.deposits,
tokenOfferedInfo.decimals!,
) as bigint);
swapperAmount = isADA(swapperToken)
? (lovelaceToAda(
parsedPayout.data.when[0].then.when[0].case.deposits,
) as bigint)
: (intToDecimal(
parsedPayout.data.when[0].then.when[0].case.deposits,
tokenDesiredInfo.decimals!,
) as bigint);
providerAmount = intToDecimal(
parsedPayout.data.when[0].case.deposits,
tokenOfferedInfo.decimals!,
) as bigint;
swapperAmount = intToDecimal(
parsedPayout.data.when[0].then.when[0].case.deposits,
tokenDesiredInfo.decimals!,
) as bigint;
} else {
error = "Error obtaining amount";
}
Expand Down

0 comments on commit 21e74a7

Please sign in to comment.