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: change estimated matching to a range #4305

Merged
merged 2 commits into from
Jun 21, 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
2 changes: 1 addition & 1 deletion lang/ca.json
Original file line number Diff line number Diff line change
Expand Up @@ -1253,7 +1253,7 @@
"page.about_us.desc.one": "Giveth és una comunitat centrada en la construcció del Futur de les Donacions utilitzant la tecnologia blockchain. La nostra intenció és donar suport i recompensar la finançament de béns públics creant accés obert, transparent i gratuït a les oportunitats de finançament innovadores en l'ecosistema d'Ethereum.",
"page.about_us.desc.two": "Giveth està construint una cultura de donació que capacita i recompensa als qui donen, als projectes, a la societat i al món. El nostre objectiu és inspirar la nostra comunitat a participar en un ecosistema de suport col·lectiu, d'abundància i de creació de valor. Comproveu el nostre",
"page.donate.bank_fees": "Comissions Bancàries",
"page.donate.matching_toast.bottom_valid": "Els fons d'emparellament s'enviaran al projecte seleccionat després que acabi la ronda.",
"page.donate.matching_toast.bottom_valid": "Els fons de finançament es destinaran al projecte seleccionat després que acabi la ronda. Dona a més projectes per rebre més finançament!",
"page.donate.matching_toast.bottom_invalid_p1": "Només donacions de més de",
"page.donate.matching_toast.bottom_invalid_p2": "són elegibles per a l'aparellament.",
"page.donate.matching_toast.upper_valid": "Emparellament estimat",
Expand Down
2 changes: 1 addition & 1 deletion lang/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -1253,7 +1253,7 @@
"page.about_us.desc.one": "Giveth is a community focused on Building the Future of Giving using blockchain technology. Our intention is to support and reward the funding of public goods by creating open, transparent and free access to the revolutionary funding opportunities available within the Ethereum ecosystem.",
"page.about_us.desc.two": "Giveth is building a culture of giving that empowers and rewards those who give -- to projects, to society, and to the world. We aim to inspire our community to participate in an ecosystem of collective support, abundance and value-creation. Check out our",
"page.donate.bank_fees": "Bank Fees",
"page.donate.matching_toast.bottom_valid": "Matching funds will be sent to the selected project after the round ends.",
"page.donate.matching_toast.bottom_valid": "Matching funds will be sent to the selected project after the round ends. Donate to more projects to receive higher matching!",
"page.donate.matching_toast.bottom_invalid_p1": "Only donations more than",
"page.donate.matching_toast.bottom_invalid_p2": "are eligible for matching.",
"page.donate.matching_toast.upper_valid": "Estimated matching",
Expand Down
2 changes: 1 addition & 1 deletion lang/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -1253,7 +1253,7 @@
"page.about_us.desc.one": "Giveth es una comunidad enfocada en construir el Futuro de las Donaciones utilizando la tecnología blockchain. Nuestra intención es apoyar y recompensar la financiación de bienes públicos creando un acceso abierto, transparente y gratuito a las oportunidades de financiación innovadoras en el ecosistema de Ethereum.",
"page.about_us.desc.two": "Giveth está construyendo una cultura de donación que empodera y recompensa a los que donan, a los proyectos, a la sociedad y al mundo. Nuestro objetivo es inspirar a nuestra comunidad a participar en un ecosistema de apoyo colectivo, de abundancia y creación de valor. Echa un vistazo a nuestro",
"page.donate.bank_fees": "Comisiones Bancarias",
"page.donate.matching_toast.bottom_valid": "Los fondos complementarios se enviarán al proyecto seleccionado después de que termine la ronda.",
"page.donate.matching_toast.bottom_valid": "Los fondos de emparejamiento se enviarán al proyecto seleccionado después de que termine la ronda. ¡Dona a más proyectos para recibir un mayor emparejamiento!",
"page.donate.matching_toast.bottom_invalid_p1": "Sólo las donaciones superiores a",
"page.donate.matching_toast.bottom_invalid_p2": "son subvencionables.",
"page.donate.matching_toast.upper_valid": "Estimado del monto complementado",
Expand Down
4 changes: 2 additions & 2 deletions lang/t_ca.json
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@
"label.you_can_view_them_on_a_blockchain_explorer_here": "Pots veure-les en un explorador de blocs aquí:",
"other": "Altres",
"other_desc": " ",
"page.donate.matching_toast.bottom_valid": "Els fons de coincidència es enviaran al projecte seleccionat quan acabi la ronda.",
"page.donate.matching_toast.bottom_valid": "Els fons de finançament es destinaran al projecte seleccionat després que acabi la ronda. Dona a més projectes per rebre més finançament!",
"page.donate.matching_toast.upper_valid": "Coincidència estimada",
"page.donate.passport_toast.description.eligible": "La teva donació és elegible per ser coincidida! Després de la",
"page.donate.passport_toast.description.eligible_2": ", totes les donacions seran revisades per a la protecció contra el frau i els fons de coincidència es enviaran als projectes. Estigueu atents a les notificacions :)",
Expand All @@ -170,5 +170,5 @@
"project.givback_toast.title.verified_public_2": " del valor de la teva donació!",
"refi": "Refi",
"testfilter": "testfilter",
"tooltip.donation.matching": "Aquesta estimació es basa en les donacions fetes fins ara aquesta ronda de finançament quadràtic i no està considerant l'anàlisi de frau. La quantitat real de coincidència pot variar.",
"tooltip.donation.matching": "Aquesta estimació es basa en les donacions fetes fins ara aquesta ronda de finançament quadràtic i no està considerant l'anàlisi de frau. La quantitat real de coincidència pot variar."
}
2 changes: 1 addition & 1 deletion lang/t_es.json
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@
"label.your_transactions_have_been_submitted": "Tus transacciones han sido enviadas",
"label.you_can_view_them_on_a_blockchain_explorer_here": "Puedes verlas en un explorador de blockchain aquí:",
"other_desc": " ",
"page.donate.matching_toast.bottom_valid": "Los fondos de igualación se enviarán al proyecto seleccionado después de que termine la ronda.",
"page.donate.matching_toast.bottom_valid": "Los fondos de emparejamiento se enviarán al proyecto seleccionado después de que termine la ronda. ¡Dona a más proyectos para recibir un mayor emparejamiento!",
"page.donate.matching_toast.upper_valid": "Igualación estimada",
"page.donate.passport_toast.description.eligible": "¡Tu donación es elegible para ser igualada! Después de la",
"page.donate.passport_toast.description.eligible_2": ", todas las donaciones serán revisadas para la protección contra fraudes y los fondos de igualación serán enviados a los proyectos. Mantente atento a las notificaciones :)",
Expand Down
29 changes: 23 additions & 6 deletions src/components/views/donate/EstimatedMatchingToast.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -79,13 +79,30 @@ const EstimatedMatchingToast: React.FC<IEstimatedMatchingToast> = ({
<IconAlertTriangleFilled color={textColor} />
);

const formatWithCurrency = (
amount: number,
currency: string,
locale: string,
) => {
return (
formatDonation(amount, currency, locale, true) +
(currency ? '' : ` ${allocatedTokenSymbol}`)
);
};

const getEstimatedMatchingRange = (esMatching: number) => {
if (esMatching >= 1) {
return `${formatWithCurrency((esMatching * 30) / 100, allocatedFundUSDPreferred ? '$' : '', locale)} - ${formatWithCurrency(esMatching, allocatedFundUSDPreferred ? '$' : '', locale)}`;
}
return formatWithCurrency(
esMatching,
allocatedFundUSDPreferred ? '$' : '',
locale,
);
};

const formattedDonation = isAboveMinValidUsdValue
? formatDonation(
esMatching,
allocatedFundUSDPreferred ? '$' : '',
locale,
true,
) + (allocatedFundUSDPreferred ? '' : ' ' + allocatedTokenSymbol)
? getEstimatedMatchingRange(esMatching)
: '---';

const bottomText = isAboveMinValidUsdValue
Expand Down
144 changes: 49 additions & 95 deletions src/components/views/project/projectActionCard/QFSection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -78,18 +78,33 @@ const QFSection: FC<IQFSectionProps> = ({ projectData }) => {
const isForeignOrg =
orgLabel !== ORGANIZATION.trace && orgLabel !== ORGANIZATION.giveth;

const formatWithCurrency = (
amount: number,
currency: string,
locale: string,
) => {
return (
formatDonation(amount, currency, locale, true) +
(currency ? '' : ` ${allocatedTokenSymbol}`)
);
};

const getEstimatedMatchingRange = (esMatching: number) => {
if (esMatching >= 1) {
return `${formatWithCurrency((esMatching * 30) / 100, allocatedFundUSDPreferred ? '$' : '', locale)} - ${formatWithCurrency(esMatching, allocatedFundUSDPreferred ? '$' : '', locale)}`;
}
return formatWithCurrency(
esMatching,
allocatedFundUSDPreferred ? '$' : '',
locale,
);
Comment on lines +92 to +100
Copy link
Contributor

Choose a reason for hiding this comment

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

Tip

Codebase Verification

The implementation of the getEstimatedMatchingRange function has been located. The function currently does not include explicit error handling for edge cases, such as negative values for esMatching.

  • File: src/components/views/project/projectActionCard/QFSection.tsx
  • Lines: 91-100

Recommendation: Add error handling to manage edge cases like negative esMatching values.

const getEstimatedMatchingRange = (esMatching: number) => {
    if (esMatching < 0) {
        throw new Error("esMatching cannot be negative");
    }
    if (esMatching >= 1) {
        return `${formatWithCurrency((esMatching * 30) / 100, allocatedFundUSDPreferred ? '$' : '', locale)} - ${formatWithCurrency(esMatching, allocatedFundUSDPreferred ? '$' : '', locale)}`;
    }
    return formatWithCurrency(
        esMatching,
        allocatedFundUSDPreferred ? '$' : '',
        locale,
    );
};
  • Category:
Analysis chain

Ensure robust error handling in getEstimatedMatchingRange function.

The function getEstimatedMatchingRange calculates a range for estimated matching. It's crucial to ensure that the function handles possible edge cases or unusual inputs robustly, such as negative values for esMatching.


The initial check using ast-grep did not return any results, which means we need to gather more information. First, let's examine the implementation of the getEstimatedMatchingRange function for any built-in error handling.


Let's refine our search to ensure we capture the function definition accurately. We'll look for all function definitions in the QFSection.tsx file and specifically for the getEstimatedMatchingRange function.


Let's expand our search to include arrow functions and traditional function definitions within QFSection.tsx.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify handling of edge cases in `getEstimatedMatchingRange`.

# Test: Search for any additional calls to `getEstimatedMatchingRange`. Expect: Proper handling of edge cases.
ast-grep --lang typescript --pattern $'getEstimatedMatchingRange($_)'

Length of output: 70



Script:

#!/bin/bash
# Locate the implementation of the getEstimatedMatchingRange function to check for error handling.
ast-grep --lang typescript --pattern $'const getEstimatedMatchingRange = ($_)' --json

Length of output: 89



Script:

#!/bin/bash
# Search for all function definitions in the QFSection.tsx file.
fd 'QFSection.tsx' -x ast-grep --lang typescript --pattern 'function $_($$$_) { $$$ }' --json

Length of output: 96



Script:

#!/bin/bash
# Search for arrow functions and traditional function definitions in the QFSection.tsx file.
fd 'QFSection.tsx' -x ast-grep --lang typescript --pattern 'const $_ = ($$$_) => { $$$ }' --json

Length of output: 2072

};

const EstimatedMatchingSection = () =>
totalEstimatedMatching !== 0 ? (
<Flex $flexDirection='column' gap='4px'>
<EstimatedMatchingPrice>
{'+ ' +
formatDonation(
totalEstimatedMatching,
allocatedFundUSDPreferred ? '$' : '',
locale,
true,
)}{' '}
{allocatedFundUSDPreferred ? '' : allocatedTokenSymbol}
{getEstimatedMatchingRange(totalEstimatedMatching)}
</EstimatedMatchingPrice>
<Flex $alignItems='center' gap='4px'>
<LightCaption>
Expand All @@ -109,6 +124,29 @@ const QFSection: FC<IQFSectionProps> = ({ projectData }) => {
</Flex>
) : null;

const DonationMatch = ({ amount }: { amount: number }) => (
<FlexSameSize $justifyContent='space-between'>
<Subline>
{allocatedFundUSDPreferred && '$'}
{amount} {!allocatedFundUSDPreferred && allocatedTokenSymbol}
</Subline>
<IconArrowRight16 color={brandColors.cyan[500]} />
<EndAlignedSubline>
{getEstimatedMatchingRange(
calculateEstimatedMatchingWithDonationAmount(
amount,
projectDonationsSqrtRootSum,
allProjectsSum,
allocatedFundUSDPreferred
? allocatedFundUSD
: matchingPool,
activeStartedRound?.maximumReward,
),
)}
</EndAlignedSubline>
</FlexSameSize>
);
Comment on lines +127 to +148
Copy link
Contributor

Choose a reason for hiding this comment

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

Tip

Codebase Verification

The DonationMatch component effectively uses the getEstimatedMatchingRange and calculateEstimatedMatchingWithDonationAmount functions. However, the current implementation does not explicitly handle edge cases such as negative donation amounts or unusual currency formats.

  • The getEstimatedMatchingRange function formats values greater than or equal to 1 with a currency but does not handle negative values.
  • The calculateEstimatedMatchingWithDonationAmount function returns 0 if any of the critical parameters are missing but does not explicitly handle negative donation amounts.

To ensure robustness, consider adding explicit checks for negative values and unusual currency formats within these functions.

  • Add validation for negative donation amounts in calculateEstimatedMatchingWithDonationAmount.
  • Ensure getEstimatedMatchingRange handles edge cases such as negative values and unusual currency formats.
Analysis chain

Review the DonationMatch component for consistency and error handling.

The DonationMatch component effectively uses the new getEstimatedMatchingRange function. Ensure that the calculations within this component handle all edge cases, such as negative donation amounts or unusual currency formats.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify handling of edge cases in `DonationMatch`.

# Test: Search for any additional calls to `DonationMatch`. Expect: Proper handling of edge cases.
ast-grep --lang typescript --pattern $'DonationMatch($_)'

Length of output: 58



Script:

#!/bin/bash
# Description: Search for the usage of `DonationMatch` in the codebase to verify edge cases handling.

# Find all files containing `DonationMatch` to locate its usage.
rg 'DonationMatch' --type tsx --type ts

Length of output: 67



Script:

#!/bin/bash
# Description: Search for the usage of `DonationMatch` in the codebase to verify edge cases handling.

# Find all files containing `DonationMatch` to locate its usage.
rg 'DonationMatch' --type ts --type tsx

Length of output: 67



Script:

#!/bin/bash
# Description: Search for the usage of `DonationMatch` in the codebase to verify edge cases handling.

# Find all files containing `DonationMatch` to locate its usage.
rg 'DonationMatch' --type ts

Length of output: 444



Script:

#!/bin/bash
# Description: Review the implementations of `getEstimatedMatchingRange` and `calculateEstimatedMatchingWithDonationAmount` for edge case handling.

# Find the implementation of `getEstimatedMatchingRange`.
rg 'function getEstimatedMatchingRange' --type ts

# Find the implementation of `calculateEstimatedMatchingWithDonationAmount`.
rg 'function calculateEstimatedMatchingWithDonationAmount' --type ts

Length of output: 122



Script:

#!/bin/bash
# Description: Review the implementations of `getEstimatedMatchingRange` and `calculateEstimatedMatchingWithDonationAmount` for edge case handling.

# Find the implementation of `getEstimatedMatchingRange`.
ast-grep --lang typescript --pattern 'function getEstimatedMatchingRange($_) { $$$ }'

# Find the implementation of `calculateEstimatedMatchingWithDonationAmount`.
ast-grep --lang typescript --pattern 'function calculateEstimatedMatchingWithDonationAmount($_) { $$$ }'

Length of output: 194



Script:

#!/bin/bash
# Description: Verify if `getEstimatedMatchingRange` and `calculateEstimatedMatchingWithDonationAmount` are defined or imported in the codebase.

# Search for `getEstimatedMatchingRange` function definition or import.
rg 'getEstimatedMatchingRange' --type ts

# Search for `calculateEstimatedMatchingWithDonationAmount` function definition or import.
rg 'calculateEstimatedMatchingWithDonationAmount' --type ts

Length of output: 1169



Script:

#!/bin/bash
# Description: Extract the definition of `getEstimatedMatchingRange` from `QFSection.tsx`.

# Extract the definition of `getEstimatedMatchingRange`.
sed -n '/const getEstimatedMatchingRange =/,/};/p' src/components/views/project/projectActionCard/QFSection.tsx

Length of output: 496



Script:

#!/bin/bash
# Description: Extract the definition of `calculateEstimatedMatchingWithDonationAmount` from `qf.ts`.

# Extract the definition of `calculateEstimatedMatchingWithDonationAmount`.
sed -n '/export const calculateEstimatedMatchingWithDonationAmount =/,/^};/p' src/helpers/qf.ts

Length of output: 1087


return (
<DonationSectionWrapper gap={isOnDonatePage ? '8px' : '24px'}>
{isOnDonatePage && (
Expand Down Expand Up @@ -225,93 +263,9 @@ const QFSection: FC<IQFSectionProps> = ({ projectData }) => {
</Flex>
<ContributionsContainer>
<Flex $flexDirection='column' gap='4px'>
<FlexSameSize $justifyContent='space-between'>
<Subline>
{allocatedFundUSDPreferred && '$'}1{' '}
{!allocatedFundUSDPreferred &&
allocatedTokenSymbol}
</Subline>
<IconArrowRight16
color={brandColors.cyan[500]}
/>
<EndAlignedSubline>
+{' '}
{formatDonation(
calculateEstimatedMatchingWithDonationAmount(
1,
projectDonationsSqrtRootSum,
allProjectsSum,
allocatedFundUSDPreferred
? allocatedFundUSD
: matchingPool,
activeStartedRound?.maximumReward,
),
allocatedFundUSDPreferred ? '$' : '',
locale,
true,
)}{' '}
{!allocatedFundUSDPreferred &&
allocatedTokenSymbol}
</EndAlignedSubline>
</FlexSameSize>
<FlexSameSize $justifyContent='space-between'>
<Subline>
{allocatedFundUSDPreferred && '$'}10{' '}
{!allocatedFundUSDPreferred &&
allocatedTokenSymbol}
</Subline>
<IconArrowRight16
color={brandColors.cyan[500]}
/>
<EndAlignedSubline>
+{' '}
{formatDonation(
calculateEstimatedMatchingWithDonationAmount(
10,
projectDonationsSqrtRootSum,
allProjectsSum,
allocatedFundUSDPreferred
? allocatedFundUSD
: matchingPool,
activeStartedRound?.maximumReward,
),
allocatedFundUSDPreferred ? '$' : '',
locale,
true,
)}{' '}
{!allocatedFundUSDPreferred &&
allocatedTokenSymbol}
</EndAlignedSubline>
</FlexSameSize>
<FlexSameSize $justifyContent='space-between'>
<Subline>
{allocatedFundUSDPreferred && '$'}100{' '}
{!allocatedFundUSDPreferred &&
allocatedTokenSymbol}
</Subline>
<IconArrowRight16
color={brandColors.cyan[500]}
/>
<EndAlignedSubline>
+{' '}
{formatDonation(
calculateEstimatedMatchingWithDonationAmount(
100,
projectDonationsSqrtRootSum,
allProjectsSum,
allocatedFundUSDPreferred
? allocatedFundUSD
: matchingPool,
activeStartedRound?.maximumReward,
),
allocatedFundUSDPreferred ? '$' : '',
locale,
true,
)}{' '}
{!allocatedFundUSDPreferred &&
allocatedTokenSymbol}
</EndAlignedSubline>
</FlexSameSize>
<DonationMatch amount={1} />
<DonationMatch amount={10} />
<DonationMatch amount={100} />
{/* <Flex $justifyContent='space-between'>
<LightSubline>Last updated: 3h ago</LightSubline>
<LightSubline>|</LightSubline>
Expand Down
Loading