Skip to content

Commit

Permalink
require wallet connection and fix error states
Browse files Browse the repository at this point in the history
  • Loading branch information
RedBeardEth committed Dec 20, 2023
1 parent 87f01ab commit bea5332
Show file tree
Hide file tree
Showing 7 changed files with 79 additions and 129 deletions.
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import type { VariantProps } from "class-variance-authority";
import React from "react";
import { useUIContext } from "@/app/providers/UIProvider";
import StarknetLogo from "@/icons/starknet.svg";
import { shortenHex } from "@/utils/utils";
import { useAccount as useL2Account } from "@starknet-react/core";
import type { VariantProps } from "class-variance-authority";

import type { buttonVariants } from "@realms-world/ui";
import { Button } from "@realms-world/ui";
Expand All @@ -25,14 +25,14 @@ export const StarknetLoginButton = ({
const onConnectClick = () => {
return !isConnected
? toggleStarknetLogin()
: openAccount && toggleAccount();
: openAccount && toggleAccount({ openAccount });
};

return (
<Button
className={
buttonClass +
" outline-bright-yellow rounded-none px-3 outline outline-2 outline-offset-[3px] " +
" rounded-none px-3 outline outline-2 outline-offset-[3px] outline-bright-yellow " +
(address && "!shadow-[0_0_10px_rgb(74,222,128)] ")
}
variant={variant ?? "outline"}
Expand Down
86 changes: 50 additions & 36 deletions apps/nextjs/src/app/collection/marketplace/buy/BuyModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import type {
import React, { useContext, useEffect, useState } from "react";
import Image from "next/image";
import NumberSelect from "@/app/_components/NumberSelect";
import { StarknetLoginButton } from "@/app/_components/wallet/StarknetLoginButton";
import { RenderExplorers } from "@/app/_components/wallet/utils";
import { useWalletsProviderContext } from "@/app/providers/WalletsProvider";
import Lords from "@/icons/lords.svg";
Expand All @@ -25,6 +26,7 @@ import { formatUnits } from "viem";

import type { RouterOutputs } from "@realms-world/api";
import {
Alert,
Button,
Dialog,
DialogContent,
Expand Down Expand Up @@ -246,7 +248,12 @@ export function BuyModal({

{buyStep === BuyStep.Checkout && !loading && (
<div className="flex flex-col">
{/*TODO Add error transactionError && <ErrorWell error={transactionError} />*/}
{transactionError && (
<Alert
variant={"warning"}
message={transactionError.message}
/>
)}
<ERC721LineItem
tokenDetails={token}
collection={collection}
Expand All @@ -269,7 +276,6 @@ export function BuyModal({
/>
</div>
)}

<div className="mt-4 flex items-start justify-between border-2 p-2 font-sans">
<div className="self-center">You Pay</div>
<div className="flex space-x-3">
Expand All @@ -280,51 +286,59 @@ export function BuyModal({
<Lords className="h-6 w-6 fill-current" />
</div>
</div>

<div className="w-full">
{hasEnoughCurrency ? (
<Button
disabled={!hasEnoughCurrency}
onClick={buyToken}
className="w-full"
color="primary"
>
{copy.ctaCheckout}
</Button>
{!address ? (
<StarknetLoginButton
openAccount={false}
buttonClass="w-full mt-4"
/>
) : (
<div className="flex flex-col items-center">
<div className="item-center my-1.5 flex flex-col">
<span className="mr-3 text-red-500">
Insufficient Balance
</span>
{/*<FormatCryptoCurrency
<>
{hasEnoughCurrency ? (
<Button
disabled={!hasEnoughCurrency}
onClick={buyToken}
className="w-full"
color="primary"
>
{copy.ctaCheckout}
</Button>
) : (
<div className="flex flex-col items-center">
<div className="item-center my-1.5 flex flex-col">
<span className="mr-3 text-red-500">
Insufficient Balance
</span>
{/*<FormatCryptoCurrency
amount={paymentCurrency?.balance}
textStyle="body3"
/>*/}
</div>
</div>

{gasCost > 0n && (
<div className="flex items-center">
<span className="mr-1.5 text-red-500">
Estimated Gas Cost
</span>
{/*<FormatCryptoCurrency
{gasCost > 0n && (
<div className="flex items-center">
<span className="mr-1.5 text-red-500">
Estimated Gas Cost
</span>
{/*<FormatCryptoCurrency
amount={gasCost}
textStyle="body3"
/>*/}
</div>
)}

<Button
onClick={() => {
window.open(addFundsLink, "_blank");
}}
variant={"outline"}
className="w-full"
>
{copy.ctaInsufficientFunds}
</Button>
</div>
)}

<Button
onClick={() => {
window.open(addFundsLink, "_blank");
}}
variant={"outline"}
className="w-full"
>
{copy.ctaInsufficientFunds}
</Button>
</div>
</>
)}
</div>
</div>
Expand Down
86 changes: 8 additions & 78 deletions apps/nextjs/src/app/collection/marketplace/buy/BuyModalRender.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,7 @@ export const BuyModalRender: FC<Props> = ({
const {
data,
writeAsync,
error: writeError,
// isLoading: isTxSubmitting,
} = useContractWrite({
calls: [
Expand Down Expand Up @@ -178,6 +179,13 @@ export const BuyModalRender: FC<Props> = ({
}
}
}, [data, transactionData, transactionError]);
useEffect(() => {
if (writeError) {
console.log(writeError);
setBuyStep(BuyStep.Checkout);
setTransactionError(writeError);
}
}, [writeError]);

const buyToken = useCallback(async () => {
const contract = collectionId?.split(":")[0];
Expand All @@ -197,83 +205,6 @@ export const BuyModalRender: FC<Props> = ({
items.push(item);

await writeAsync();

/* client.actions
.buyToken({
chainId: rendererChain?.id,
items: items,
expectedPrice: {
[paymentCurrency?.address || zeroAddress]: {
raw: totalPrice,
currencyAddress: paymentCurrency?.address,
currencyDecimals: paymentCurrency?.decimals || 18,
},
},
wallet,
onProgress: (steps: Execute["steps"]) => {
if (!steps) {
return;
}
setSteps(steps);
const executableSteps = steps.filter(
(step) => step.items && step.items.length > 0,
);
const stepCount = executableSteps.length;
let currentStepItem:
| NonNullable<Execute["steps"][0]["items"]>[0]
| undefined;
const currentStepIndex = executableSteps.findIndex((step) => {
currentStepItem = step.items?.find(
(item) => item.status === "incomplete",
);
return currentStepItem;
});
const currentStep =
currentStepIndex > -1
? executableSteps[currentStepIndex]
: executableSteps[stepCount - 1];
if (currentStepItem) {
setStepData({
totalSteps: stepCount,
stepProgress: currentStepIndex,
currentStep,
currentStepItem,
});
} else if (
steps.every(
(step) =>
!step.items ||
step.items.length == 0 ||
step.items?.every((item) => item.status === "complete"),
)
) {
setBuyStep(BuyStep.Complete);
}
},
options,
})
.catch((error: Error) => {
if (error && error?.message && error?.message.includes("ETH balance")) {
setHasEnoughCurrency(false);
} else {
setTransactionError(error);
if (orderId) {
mutateListings();
}
mutateCollection();
mutateTokens();
fetchPath();
}
setBuyStep(BuyStep.Checkout);
setStepData(null);
setSteps(null);
});*/
}, [
tokenId,
listing,
Expand Down Expand Up @@ -335,7 +266,6 @@ export const BuyModalRender: FC<Props> = ({
]);

useEffect(() => {
console.log(formatUnits(balances.l2.lords ?? 0n, 18));
if (
// !lords or lords balance < item total + gas
parseInt(formatUnits(balances.l2.lords ?? 0n, 18)) < totalIncludingFees
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ export function ListCancelModal({
{isListingAvailable && cancelStep === CancelStep.Cancel && (
<div className="flex flex-col">
{transactionError && (
<Alert message={transactionError.cause} />
<Alert message={transactionError.message} />
)}
<div className="border-b p-2">
<ERC721LineItem
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ export const ListCancelModalRender: FC<Props> = ({
const {
data,
writeAsync,
error: writeError,
// isLoading: isTxSubmitting,
} = useContractWrite({
calls: [
Expand All @@ -99,6 +100,13 @@ export const ListCancelModalRender: FC<Props> = ({
}
}
}, [data, transactionData, transactionError]);
useEffect(() => {
if (writeError) {
console.log(writeError);
setCancelStep(CancelStep.Cancel);
setTransactionError(writeError);
}
}, [writeError]);
const cancelOrder = useCallback(async () => {
if (!listing) {
const error = new Error("Missing list id to cancel");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ export function ListingEditModal({
editListingStep === EditListingStep.Edit && (
<div className="flex flex-col">
{transactionError && (
<Alert message={transactionError.cause} />
<Alert message={transactionError.message} />
)}
<div className="border-b p-2">
<ERC721LineItem
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,6 @@ interface ChildrenProps {

interface Props {
open: boolean;
listingId?: string;
tokenId?: string;
token?: RouterOutputs["erc721Tokens"]["byId"];
collectionId?: string;
Expand All @@ -72,7 +71,6 @@ interface Props {

export const ListingEditModalRender: FC<Props> = ({
open,
listingId,
tokenId,
token,
collectionId,
Expand Down Expand Up @@ -145,7 +143,7 @@ export const ListingEditModalRender: FC<Props> = ({
const {
data,
writeAsync,
error,
error: writeError,
// isLoading: isTxSubmitting,
} = useContractWrite({
calls: [
Expand All @@ -154,7 +152,7 @@ export const ListingEditModalRender: FC<Props> = ({
ChainId["SN_" + NETWORK_NAME]
] as `0x${string}`,
entrypoint: "edit",
calldata: [listingId, parseUnits(`${price}`, 18).toString()],
calldata: [listing?.id, parseUnits(`${price}`, 18).toString()],
},
],
});
Expand All @@ -169,6 +167,12 @@ export const ListingEditModalRender: FC<Props> = ({
}
}
}, [data, transactionData, transactionError]);
useEffect(() => {
if (writeError) {
setEditListingStep(EditListingStep.Edit);
setTransactionError(writeError);
}
}, [writeError]);

const editListing = useCallback(async () => {
if (!address) {
Expand All @@ -177,12 +181,6 @@ export const ListingEditModalRender: FC<Props> = ({
throw error;
}

if (!listingId) {
const error = new Error("Missing list id to edit");
setTransactionError(error);
throw error;
}

setTransactionError(null);

if (expirationOption.relativeTime && expirationOption.relativeTimeUnit) {
Expand Down

0 comments on commit bea5332

Please sign in to comment.