Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix: show GiveBack Toast when token is eligible #4661

Merged
merged 8 commits into from
Sep 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion lang/ca.json
Original file line number Diff line number Diff line change
Expand Up @@ -632,7 +632,7 @@
"label.modify_stream_balance": "Modificar el Saldo de la Transmissió",
"label.month": "{count, plural, one { Mes} other { Mesos} }",
"label.monthly": "Mensualment",
"label.sign_in_with_your_eth_wallet_for_givebacks": "Inicia la sessió amb la teva cartera Ethereum per a GIVbacks",
"label.sign_in_with_your_eth_wallet_for_givebacks": "Inicia la sessió amb la teva cartera Ethereum per a GIVbacks.",
"label.monthly_across_all_projects": "mensualment a tots els projectes",
"label.months": "{count, plural, one { Mes} other { Mesos} }",
"label.more_about_us": "Més sobre nosaltres",
Expand Down Expand Up @@ -1237,6 +1237,7 @@
"page.project.donate_with_stellar": "Dona amb Stellar",
"label.try_donating_wuth_stellar": "Prova de donar amb Stellar.",
"label.check_donations": "Comprova les donacions",
"label.check_donation": "Comprova la donació",
"error.enter_amount": "La quantitat ha de ser superior a 0",
"label.enter_the_memo": "Introdueix el memo",
"label.be_carefull_some_exchanges": "Ves amb compte! Alguns intercanvis i carteres requereixen Memo per finançar el teu compte. Assegura't d'introduir-ho al formulari si la teva cartera admet un memo.",
Expand Down
3 changes: 2 additions & 1 deletion lang/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -635,7 +635,7 @@
"label.modify_stream_balance": "Modify Stream Balance",
"label.month": "{count, plural, one { Month} other { Months} }",
"label.monthly": "Monthly",
"label.sign_in_with_your_eth_wallet_for_givebacks": "Sign in with your ETH wallet to claim GIVbacks",
"label.sign_in_with_your_eth_wallet_for_givebacks": "Sign in with your ETH wallet to claim GIVbacks.",
"label.monthly_across_all_projects": "monthly, across all projects",
"label.months": "{count, plural, one { Month} other { Months} }",
"label.more_about_us": "More about us",
Expand Down Expand Up @@ -1241,6 +1241,7 @@
"page.project.donate_with_stellar": "Donate with Stellar",
"label.try_donating_wuth_stellar": "Try donating with Stellar.",
"label.check_donations": "View Donation Receipt",
"label.check_donation": "View Donation",
"error.enter_amount": "Amount must be greater than 0",
"label.enter_the_memo": "Enter the Memo",
"label.be_carefull_some_exchanges": "Be careful! Some exchanges and wallets requires Memo to fund your account. Make sure to put it in the form if your wallet supports a memo.",
Expand Down
3 changes: 2 additions & 1 deletion lang/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -632,7 +632,7 @@
"label.modify_stream_balance": "Modificar el Saldo de Transmisión",
"label.month": "{count, plural, one { Mes} other { Meses} }",
"label.monthly": "Mensualmente",
"label.sign_in_with_your_eth_wallet_for_givebacks": "Inicia sesión con tu billetera ETH para GIVbacks",
"label.sign_in_with_your_eth_wallet_for_givebacks": "Inicia sesión con tu billetera ETH para GIVbacks.",
"label.monthly_across_all_projects": "mensualmente en todos los proyectos",
"label.months": "{count, plural, one { Mes} other { Meses} }",
"label.more_about_us": "Más acerca de nosotros",
Expand Down Expand Up @@ -1237,6 +1237,7 @@
"page.project.donate_with_stellar": "Dona con Stellar",
"label.try_donating_wuth_stellar": "Intenta donar con Stellar.",
"label.check_donations": "Verificar donaciones",
"label.check_donation": "Verificar donación",
"error.enter_amount": "La cantidad debe ser mayor que 0",
"label.enter_the_memo": "Introduce el memo",
"label.be_carefull_some_exchanges": "¡Ten cuidado! Algunos intercambios y billeteras requieren Memo para financiar tu cuenta. Asegúrate de ingresarlo en el formulario si tu billetera admite un memo.",
Expand Down
16 changes: 14 additions & 2 deletions src/components/views/create/WalletAddressInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,14 @@ const WalletAddressInput: FC<IProps> = ({
const isProjectPrevAddress = (newAddress: string) => {
// Do not validate if the input address is the same as project prev wallet address
if (userAddresses.length === 0) return false;
if (isStellarChain) {
const isAddressMatch = userAddresses.some(
address =>
address === newAddress &&
(!memoValue || memoValue === prevMemo),
);
return isAddressMatch;
}
return userAddresses
.map(prevAddress => prevAddress.toLowerCase())
.includes(newAddress.toLowerCase());
Expand Down Expand Up @@ -345,14 +353,18 @@ const Container = styled.div`
background: ${neutralColors.gray[100]};
border-radius: 12px;
padding: 16px;

${mediaQueries.tablet} {
position: relative;
}
`;

const ButtonWrapper = styled.div`
position: absolute;
right: 20px; // Adjust the distance from the right edge as per your need
right: 15px; // Adjust the distance from the right edge as per your need
bottom: 78px; // Adjust the distance from the bottom edge as per your need
${mediaQueries.tablet} {
bottom: 20px;
bottom: -50px;
}
`;

Expand Down
3 changes: 2 additions & 1 deletion src/components/views/donate/DonateIndex.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,8 @@ const DonateIndex: FC = () => {
setPendingDonationExists,
startTimer,
} = useDonateData();
const { renewExpirationDate, retrieveDraftDonation } = useQRCodeDonation();
const { renewExpirationDate, retrieveDraftDonation } =
useQRCodeDonation(project);
const { isSignedIn, isEnabled } = useAppSelector(state => state.user);

const alreadyDonated = useAlreadyDonatedToProject(project);
Expand Down
2 changes: 1 addition & 1 deletion src/components/views/donate/DonationInfo.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ export const DonationInfo = () => {
)
}
>
{formatMessage({ id: 'label.check_donations' })}{' '}
{formatMessage({ id: 'label.check_donation' })}{' '}
<IconExternalLink24 />
</CheckDonation>
</span>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import {
IconArrowLeft,
brandColors,
mediaQueries,
IconGIVBack24,
} from '@giveth/ui-design-system';
import { useIntl } from 'react-intl';
import { formatUnits } from 'viem';
Expand All @@ -25,7 +24,11 @@ import { IProjectAcceptedToken } from '@/apollo/types/gqlTypes';
import { fetchPriceWithCoingeckoId } from '@/services/token';
import { ChainType } from '@/types/config';
import config from '@/configuration';
import { truncateToDecimalPlaces, formatBalance } from '@/lib/helpers';
import {
truncateToDecimalPlaces,
formatBalance,
showToastError,
} from '@/lib/helpers';
import { IDonationCardProps } from '../../../DonationCard';
import QRDonationCardContent from './QRDonationCardContent';
import { useQRCodeDonation } from '@/hooks/useQRCodeDonation';
Expand Down Expand Up @@ -58,14 +61,10 @@ const formatAmountToDisplay = (amount: bigint) => {

const GivBackToast: FC<IMessage> = ({ text, link, linkText }) => (
<GivBackWrapper>
<IconGIVBack24 color={brandColors.giv[500]} />
<B>
{text}
{'. '}
<StyledLink onClick={() => window.open(link, '_blank')}>
{linkText}.
</StyledLink>
</B>
<P>{text}</P>
<StyledLink onClick={() => window.open(link, '_blank')}>
{linkText}
</StyledLink>
</GivBackWrapper>
);

Expand All @@ -83,12 +82,6 @@ export const QRDonationCard: FC<QRDonationCardProps> = ({
setShowDonateModal(true),
);

const {
createDraftDonation,
markDraftDonationAsFailed,
checkDraftDonationStatus,
retrieveDraftDonation,
} = useQRCodeDonation();
const {
project,
setQRDonationStatus,
Expand All @@ -100,6 +93,12 @@ export const QRDonationCard: FC<QRDonationCardProps> = ({
draftDonationData,
draftDonationLoading,
} = useDonateData();
const {
createDraftDonation,
markDraftDonationAsFailed,
checkDraftDonationStatus,
retrieveDraftDonation,
} = useQRCodeDonation(project);

const { addresses, id } = project;
const draftDonationId = Number(router.query.draft_donation!);
Expand Down Expand Up @@ -193,20 +192,25 @@ export const QRDonationCard: FC<QRDonationCardProps> = ({
} else {
if (!stellarToken?.symbol || !projectAddress?.address) return;

const payload = {
walletAddress: projectAddress.address,
projectId: Number(id),
amount: Number(formatAmountToDisplay(amount)),
token: stellarToken,
anonymous: true,
symbol: stellarToken.symbol,
setFailedModalType: () => {},
useDonationBox: false,
chainId: stellarToken?.networkId,
memo: projectAddress.memo,
};

draftDonationId = await createDraftDonation(payload);
try {
const payload = {
walletAddress: projectAddress.address,
projectId: Number(id),
amount: Number(formatAmountToDisplay(amount)),
token: stellarToken,
anonymous: isSignedIn && isEnabled ? false : true,
symbol: stellarToken.symbol,
setFailedModalType: () => {},
useDonationBox: false,
chainId: stellarToken?.networkId,
memo: projectAddress.memo,
};

draftDonationId = await createDraftDonation(payload);
} catch (error) {
showToastError(error);
return;
}
setPendingDonationExists?.(false);
}

Expand Down Expand Up @@ -345,7 +349,7 @@ export const QRDonationCard: FC<QRDonationCardProps> = ({
onClick={handleNext}
disabled={amount === 0n}
/>
{!isSignedIn && (
{!isSignedIn && stellarToken?.isGivbackEligible && (
<GivBackToast
text={formatMessage({
id: 'label.sign_in_with_your_eth_wallet_for_givebacks',
Expand Down Expand Up @@ -458,9 +462,12 @@ const MarginLessInlineToast = styled(InlineToast)`

const GivBackWrapper = styled(Flex)`
align-items: center;
justify-content: space-between;
border-radius: 8px;
border: 1px solid ${brandColors.giv[500]};
padding: 16px 8px;
background: ${brandColors.giv[50]};
color: ${brandColors.giv[500]};
padding: 16px;
margin-top: 10px;
gap: 10px;

Expand All @@ -472,6 +479,6 @@ const GivBackWrapper = styled(Flex)`
const StyledLink = styled.div`
display: inline;
margin-left: 4px;
color: ${brandColors.pinky[500]};
font-weight: 500;
cursor: pointer;
`;
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ import { useQRCodeDonation } from '@/hooks/useQRCodeDonation';
const QRDonationDetails = () => {
const { formatMessage } = useIntl();
const router = useRouter();
const { checkDraftDonationStatus } = useQRCodeDonation();
const {
project,
draftDonationData,
Expand All @@ -38,8 +37,10 @@ const QRDonationDetails = () => {
setQRDonationStatus,
setDraftDonationData,
} = useDonateData();
const { checkDraftDonationStatus } = useQRCodeDonation(project);

const [tokenPrice, setTokenPrice] = useState(0);
const [stopTimer, setStopTimer] = React.useState<void | (() => void)>();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, but please address the static analysis hint.

The code change is approved. Defining stopTimer as a state variable using the useState hook enhances the control flow and allows the timer to be stopped based on the qrDonationStatus.

Please apply the following diff to fix the union type based on the static analysis hint:

-const [stopTimer, setStopTimer] = React.useState<void | (() => void)>();
+const [stopTimer, setStopTimer] = React.useState<undefined | (() => void)>();
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const [stopTimer, setStopTimer] = React.useState<void | (() => void)>();
const [stopTimer, setStopTimer] = React.useState<undefined | (() => void)>();
Tools
Biome

[error] 43-43: void is confusing inside a union type.

Unsafe fix: Use undefined instead.

(lint/suspicious/noConfusingVoidType)


const { title, addresses } = project;

Expand Down Expand Up @@ -71,20 +72,27 @@ const QRDonationDetails = () => {
};

useEffect(() => {
let stopTimer: void | (() => void);

if (
draftDonationData?.id === draftDonationId &&
draftDonationData?.expiresAt
) {
stopTimer = startTimer?.(new Date(draftDonationData?.expiresAt));
const stopTimerFun = startTimer?.(
new Date(draftDonationData?.expiresAt),
);
setStopTimer(() => stopTimerFun);
}

return () => {
stopTimer?.();
};
}, [draftDonationData?.expiresAt]);

useEffect(() => {
if (qrDonationStatus === 'failed') {
stopTimer?.();
}
}, [qrDonationStatus]);

useEffect(() => {
if (!stellarAddress) return;

Expand Down
4 changes: 3 additions & 1 deletion src/components/views/transaction/DonationStatusSection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import links from '@/lib/constants/links';
import { useQRCodeDonation } from '@/hooks/useQRCodeDonation';
import { client } from '@/apollo/apolloClient';
import { MARK_DRAFT_DONATION_AS_FAILED } from '@/apollo/gql/gqlDonations';
import { useDonateData } from '@/context/donate.context';

type IColor = 'golden' | 'jade' | 'punch' | 'blueSky';
interface TimerProps {
Expand Down Expand Up @@ -210,7 +211,8 @@ const DonationStatusSection: FC<TDonationStatusSectionProps> = ({
setStatus,
}) => {
const { locale, formatMessage } = useIntl();
const { checkDraftDonationStatus } = useQRCodeDonation();
const { project } = useDonateData();
const { checkDraftDonationStatus } = useQRCodeDonation(project);

return (
<DetailsWapper>
Expand Down
2 changes: 1 addition & 1 deletion src/context/donate.context.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ export const DonateProvider: FC<IProviderProps> = ({ children, project }) => {
setStatus,
loading,
setDraftDonation,
} = useQRCodeDonation();
} = useQRCodeDonation(project);

const hasActiveQFRound = hasActiveRound(project?.qfRounds);

Expand Down
12 changes: 5 additions & 7 deletions src/hooks/useQRCodeDonation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,11 @@ import {
import { ICreateDraftDonation } from '@/components/views/donate/helpers';
import StorageLabel from '@/lib/localStorage';
import { IDraftDonation } from '@/apollo/types/gqlTypes';
import { useDonateData } from '@/context/donate.context';
import { IProject } from '@/apollo/types/types';

export type TQRStatus = 'waiting' | 'failed' | 'success' | 'expired';

export const useQRCodeDonation = () => {
const { project } = useDonateData();

export const useQRCodeDonation = (project: IProject) => {
const [draftDonation, setDraftDonation] = useState<IDraftDonation | null>(
null,
);
Expand Down Expand Up @@ -112,7 +110,8 @@ export const useQRCodeDonation = () => {
}
return createDraftDonation;
} catch (error: any) {
console.error('Error creating draft donation', error);
console.error('Error creating draft donation', error.message);
throw error.message;
}
};

Expand Down Expand Up @@ -187,7 +186,6 @@ export const useQRCodeDonation = () => {
});

if (
!draftDonationId ||
!getDraftDonationById ||
getDraftDonationById.status !== 'pending' ||
getDraftDonationById.projectId != project.id
Expand Down Expand Up @@ -260,8 +258,8 @@ export const useQRCodeDonation = () => {
Number(draftDonation.id),
);
if (retDraftDonation?.status === 'matched') {
setDraftDonation(retDraftDonation);
setStatus('success');
setDraftDonation(draftDonation);
return;
} else {
await markDraftDonationAsFailed(draftDonation?.id!);
Expand Down
Loading