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

Feat: Registration Discount codes #1084

Merged
merged 22 commits into from
Oct 21, 2024
Merged
Show file tree
Hide file tree
Changes from 14 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
8 changes: 4 additions & 4 deletions apps/web/app/(basenames)/names/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,16 +31,16 @@ export const metadata: Metadata = {
export default async function Page() {
return (
<ErrorsProvider context="registration">
<RegistrationProviders>
<Suspense>
<Suspense>
<RegistrationProviders>
<main>
<RegistrationFlow />
<RegistrationValueProp />
<PoweredByEns />
<RegistrationFAQ />
</main>
</Suspense>
</RegistrationProviders>
</RegistrationProviders>
</Suspense>
</ErrorsProvider>
);
}
37 changes: 37 additions & 0 deletions apps/web/pages/api/proofs/discountCode/consume/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import type { NextApiRequest, NextApiResponse } from 'next';
import { logger } from 'apps/web/src/utils/logger';
import { withTimeout } from 'apps/web/pages/api/decorators';
import { incrementDiscountCodeUsage } from 'apps/web/src/utils/proofs/discount_code_storage';

/*
this endpoint will increment the discount code usage to prevent abuse
*/

type DiscountCodeRequest = {
code: string;
};

async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method !== 'POST') {
return res.status(405).json({ error: 'Method not allowed' });
}

try {
const { code } = req.body as DiscountCodeRequest;

if (!code || typeof code !== 'string') {
return res.status(500).json({ error: 'Invalid request' });
}

// 1. get the database model
kirkas marked this conversation as resolved.
Show resolved Hide resolved
await incrementDiscountCodeUsage(code);

return res.status(200).json({ success: true });
} catch (error: unknown) {
logger.error('error incrementing the discount code', error);
}
// If error is not an instance of Error, return a generic error message
return res.status(500).json({ error: 'An unexpected error occurred' });
}

export default withTimeout(handler);
80 changes: 80 additions & 0 deletions apps/web/pages/api/proofs/discountCode/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import type { NextApiRequest, NextApiResponse } from 'next';
import { proofValidation, signDiscountMessageWithTrustedSigner } from 'apps/web/src/utils/proofs';
import { logger } from 'apps/web/src/utils/logger';
import { withTimeout } from 'apps/web/pages/api/decorators';
import { Address, Hash, stringToHex } from 'viem';
import { USERNAME_DISCOUNT_CODE_VALIDATORS } from 'apps/web/src/addresses/usernames';
import { baseSepolia } from 'viem/chains';
import { getDiscountCode } from 'apps/web/src/utils/proofs/discount_code_storage';

export type DiscountCodeResponse = {
discountValidatorAddress: Address;
address: Address;
signedMessage: Hash;
};

/*
this endpoint returns whether or a discount code is valid
*/
async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method !== 'GET') {
return res.status(405).json({ error: 'method not allowed' });
}
const { address, chain, code } = req.query;
const validationErr = proofValidation(address, chain);
if (validationErr) {
return res.status(validationErr.status).json({ error: validationErr.error });
}

if (!code || typeof code !== 'string') {
return res.status(500).json({ error: 'Discount code invalid' });
}

try {
// 1. get the database model
const discountCodes = await getDiscountCode(code);

// 2. Validation: Coupon exists
if (!discountCodes || discountCodes.length === 0) {
return res.status(500).json({ error: 'Discount code invalid' });
}

const discountCode = discountCodes[0];

// 2.1 Validation: Coupon is expired
if (new Date(discountCode.expires_at) < new Date()) {
return res.status(500).json({ error: 'Discount code invalid' });
}

// 2.2 Validation: Coupon can be redeemed
if (Number(discountCode.usage_count) >= Number(discountCode.usage_limit)) {
return res.status(500).json({ error: 'Discount code invalid' });
}

// 3. Sign the validationData
const couponCodeUuid = stringToHex(discountCode.code, { size: 32 });
const expirationTimeUnix = Math.floor(discountCode.expires_at.getTime() / 1000);

const signature = await signDiscountMessageWithTrustedSigner(
address as Address,
couponCodeUuid,
USERNAME_DISCOUNT_CODE_VALIDATORS[baseSepolia.id],
expirationTimeUnix,
);

// 4. Return the discount data
const result: DiscountCodeResponse = {
discountValidatorAddress: USERNAME_DISCOUNT_CODE_VALIDATORS[baseSepolia.id],
address: address as Address,
signedMessage: signature,
};

return res.status(200).json(result);
} catch (error: unknown) {
logger.error('error getting proofs for discount code', error);
}
// If error is not an instance of Error, return a generic error message
return res.status(500).json({ error: 'An unexpected error occurred' });
}

export default withTimeout(handler);
5 changes: 5 additions & 0 deletions apps/web/src/addresses/usernames.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,3 +86,8 @@ export const EXPONENTIAL_PREMIUM_PRICE_ORACLE: AddressMap = {
[baseSepolia.id]: '0x2B73408052825e17e0Fe464f92De85e8c7723231',
[base.id]: '0xd53B558e1F07289acedf028d226974AbBa258312',
};

export const USERNAME_DISCOUNT_CODE_VALIDATORS: AddressMap = {
[baseSepolia.id]: '0x52acEeB464F600437a3681bEC087fb53F3f75638',
// [base.id]: '0x6E89d99643DB1223697C77A9F8B2Cb07E898e743',
kirkas marked this conversation as resolved.
Show resolved Hide resolved
};
43 changes: 41 additions & 2 deletions apps/web/src/components/Basenames/RegistrationContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import useBaseEnsName from 'apps/web/src/hooks/useBaseEnsName';
import useBasenameChain from 'apps/web/src/hooks/useBasenameChain';
import { Discount, formatBaseEthDomain, isValidDiscount } from 'apps/web/src/utils/usernames';
import { ActionType } from 'libs/base-ui/utils/logEvent';
import { useRouter } from 'next/navigation';
import { useRouter, useSearchParams } from 'next/navigation';
import {
Dispatch,
ReactNode,
Expand All @@ -20,6 +20,7 @@ import {
useContext,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import { useInterval } from 'usehooks-ts';
Expand Down Expand Up @@ -119,8 +120,12 @@ export default function RegistrationProvider({ children }: RegistrationProviderP
address,
});

// Discount code from URL
const searchParams = useSearchParams();
const code = searchParams?.get('code');

// Username discount states
const { data: discounts, loading: loadingDiscounts } = useAggregatedDiscountValidators();
const { data: discounts, loading: loadingDiscounts } = useAggregatedDiscountValidators(code);
const discount = findFirstValidDiscount(discounts);

const allActiveDiscounts = useMemo(
Expand Down Expand Up @@ -210,12 +215,46 @@ export default function RegistrationProvider({ children }: RegistrationProviderP
transactionIsSuccess,
]);

// Move from search to claim
useEffect(() => {
if (selectedName.length) {
setRegistrationStep(RegistrationSteps.Claim);
}
}, [selectedName.length]);

// On registration success with discount code: mark as consumed
const hasRun = useRef(false);

useEffect(() => {
const consumeDiscountCode = async () => {
if (
!hasRun.current &&
registrationStep === RegistrationSteps.Success &&
code &&
discount &&
discount.discount === Discount.DISCOUNT_CODE
) {
hasRun.current = true;
kirkas marked this conversation as resolved.
Show resolved Hide resolved
const response = await fetch('/api/proofs/discountCode/consume', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ code }),
});

if (!response.ok) {
throw new Error('Failed to record discount code consumption');
}
}
};

consumeDiscountCode().catch((error) => {
logError(error, 'Error recording discount code consumption');
hasRun.current = false;
});
}, [discount, code, registrationStep, logError]);

// Log user moving through the flow
useEffect(() => {
logEventWithContext(`step_${registrationStep}`, ActionType.change);
Expand Down
19 changes: 17 additions & 2 deletions apps/web/src/hooks/useAggregatedDiscountValidators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
useCheckCBIDAttestations,
useCheckCoinbaseAttestations,
useCheckEAAttestations,
useDiscountCodeAttestations,
useSummerPassAttestations,
} from 'apps/web/src/hooks/useAttestations';
import { useActiveDiscountValidators } from 'apps/web/src/hooks/useReadActiveDiscountValidators';
Expand Down Expand Up @@ -37,7 +38,7 @@ export function findFirstValidDiscount(
return sortedDiscounts.find((data) => data?.discountKey) ?? undefined;
}

export function useAggregatedDiscountValidators() {
export function useAggregatedDiscountValidators(code: string | null | undefined) {
const { data: activeDiscountValidators, isLoading: loadingActiveDiscounts } =
useActiveDiscountValidators();
const { data: CBIDData, loading: loadingCBIDAttestations } = useCheckCBIDAttestations();
Expand All @@ -49,6 +50,8 @@ export function useAggregatedDiscountValidators() {
const { data: BuildathonData, loading: loadingBuildathon } = useBuildathonAttestations();
const { data: BaseDotEthData, loading: loadingBaseDotEth } = useBaseDotEthAttestations();
const { data: BNSData, loading: loadingBNS } = useBNSAttestations();
const { data: DiscountCodeData, loading: loadingDiscountCode } =
useDiscountCodeAttestations(code);

const loadingDiscounts =
loadingCoinbaseAttestations ||
Expand All @@ -59,7 +62,8 @@ export function useAggregatedDiscountValidators() {
loadingBuildathon ||
loadingSummerPass ||
loadingBaseDotEth ||
loadingBNS;
loadingBNS ||
loadingDiscountCode;

const discountsToAttestationData = useMemo<MappedDiscountData>(() => {
const discountMapping: MappedDiscountData = {};
Expand Down Expand Up @@ -114,6 +118,16 @@ export function useAggregatedDiscountValidators() {
if (BNSData && validator.discountValidator === BNSData.discountValidatorAddress) {
discountMapping[Discount.BNS_NAME] = { ...BNSData, discountKey: validator.key };
}

if (
DiscountCodeData &&
validator.discountValidator === DiscountCodeData.discountValidatorAddress
) {
discountMapping[Discount.DISCOUNT_CODE] = {
...DiscountCodeData,
discountKey: validator.key,
};
}
});

return discountMapping;
Expand All @@ -127,6 +141,7 @@ export function useAggregatedDiscountValidators() {
SummerPassData,
BaseDotEthData,
BNSData,
DiscountCodeData,
]);

return {
Expand Down
69 changes: 69 additions & 0 deletions apps/web/src/hooks/useAttestations.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { useErrors } from 'apps/web/contexts/Errors';
import { CoinbaseProofResponse } from 'apps/web/pages/api/proofs/coinbase';
import { DiscountCodeResponse } from 'apps/web/pages/api/proofs/discountCode';
import AttestationValidatorABI from 'apps/web/src/abis/AttestationValidator';
import CBIDValidatorABI from 'apps/web/src/abis/CBIdDiscountValidator';
import EarlyAccessValidatorABI from 'apps/web/src/abis/EarlyAccessValidator';
Expand Down Expand Up @@ -487,3 +488,71 @@ export function useBNSAttestations() {
}
return { data: null, loading: isLoading, error };
}

// returns info about Discount Codes attestations
export function useDiscountCodeAttestations(code: string | null | undefined) {
const { logError } = useErrors();
const { address } = useAccount();
const [loading, setLoading] = useState(false);
const [discountCodeResponse, setDiscountCodeResponse] = useState<DiscountCodeResponse | null>(
null,
);

const { basenameChain } = useBasenameChain();

useEffect(() => {
async function checkDiscountCode(a: string, c: string) {
try {
setLoading(true);
const params = new URLSearchParams();
params.append('address', a);
params.append('chain', basenameChain.id.toString());
params.append('code', c.toString());
const response = await fetch(`/api/proofs/discountCode?${params}`);
const result = (await response.json()) as DiscountCodeResponse;
if (response.ok) {
setDiscountCodeResponse(result);
}
} catch (error) {
logError(error, 'Error checking Discount code');
} finally {
setLoading(false);
}
}

if (address && !IS_EARLY_ACCESS && !!code) {
checkDiscountCode(address, code).catch((error) => {
logError(error, 'Error checking Discount code');
});
}
}, [address, basenameChain.id, code, logError]);

const signature = discountCodeResponse?.signedMessage;
const readContractArgs = useMemo(() => {
if (!address || !signature || !code) {
return {};
}

return {
address: discountCodeResponse?.discountValidatorAddress,
abi: AttestationValidatorABI,
functionName: 'isValidDiscountRegistration',
args: [address, signature],
};
}, [address, code, discountCodeResponse?.discountValidatorAddress, signature]);

const { data: isValid, isLoading, error } = useReadContract(readContractArgs);

if (isValid && discountCodeResponse && address && signature) {
return {
data: {
discountValidatorAddress: discountCodeResponse.discountValidatorAddress,
discount: Discount.DISCOUNT_CODE,
validationData: signature,
},
loading: false,
error: null,
};
}
return { data: null, loading: loading || isLoading, error };
}
Loading
Loading