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

Faucet Referral Codes #30

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
20 changes: 15 additions & 5 deletions apps/staking/app/faucet/AuthModule.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -57,12 +57,13 @@ export const getFaucetFormSchema = () => {
}),
discordId: z.string().optional(),
telegramId: z.string().optional(),
referralCode: z.string().optional(),
});
};

export type FaucetFormSchema = z.infer<ReturnType<typeof getFaucetFormSchema>>;

export const AuthModule = () => {
export const AuthModule = ({ referralCode }: { referralCode?: string }) => {
const dictionary = useTranslations('faucet.form');
const generalDictionary = useTranslations('general');
const [submitAttemptCounter, setSubmitAttemptCounter] = useState<number>(0);
Expand All @@ -88,6 +89,7 @@ export const AuthModule = () => {
walletAddress: '',
discordId: '',
telegramId: '',
referralCode,
},
reValidateMode: 'onChange',
});
Expand Down Expand Up @@ -196,6 +198,12 @@ export const AuthModule = () => {
}
}, [address, ethAmount, form]); */

useEffect(() => {
if (referralCode) {
toast.info(dictionary('referralCodeAdded'));
}
}, [referralCode]);

useEffect(() => {
if (walletStatus === WALLET_STATUS.CONNECTED && address) {
form.clearErrors();
Expand Down Expand Up @@ -345,10 +353,12 @@ export const AuthModule = () => {
<>
<span className="text-center">- {generalDictionary('or')} -</span>
<WalletModalButtonWithLocales rounded="md" size="lg" className="uppercase" hideBalance />
<span className="inline-flex w-full flex-col gap-2 uppercase xl:flex-row [&>*]:flex-grow">
{!isConnected || (isConnected && discordId) ? <DiscordAuthButton /> : null}
{!isConnected || (isConnected && telegramId) ? <TelegramAuthButton /> : null}
</span>
{!referralCode ? (
<span className="inline-flex w-full flex-col gap-2 uppercase xl:flex-row [&>*]:flex-grow">
{!isConnected || (isConnected && discordId) ? <DiscordAuthButton /> : null}
{!isConnected || (isConnected && telegramId) ? <TelegramAuthButton /> : null}
</span>
) : null}
</>
) : null}

Expand Down
12 changes: 12 additions & 0 deletions apps/staking/app/faucet/[referralCode]/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { Faucet } from '@/app/faucet/page';

interface FaucetCodePageParams {
params: {
referralCode: string;
};
}

export default function FaucetCodePage({ params }: FaucetCodePageParams) {
const { referralCode } = params;
return <Faucet referralCode={referralCode} />;
}
115 changes: 91 additions & 24 deletions apps/staking/app/faucet/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ import { getLocale, getTranslations } from 'next-intl/server';
import { type Address, formatEther, isAddress as isAddressViem } from 'viem';
import { FaucetFormSchema } from './AuthModule';
import {
codeExists,
getCodeUseTransactionHistory,
getReferralCodeDetails,
getTransactionHistory,
hasRecentTransaction,
idIsInTable,
Expand Down Expand Up @@ -76,7 +79,6 @@ class FaucetResult {

const faucetTokenWarning = BigInt(20000 * Math.pow(10, SENT_DECIMALS));
const faucetGasWarning = BigInt(0.01 * Math.pow(10, ETH_DECIMALS));
const faucetTokenDrip = BigInt(FAUCET.DRIP * Math.pow(10, SENT_DECIMALS));

const minTargetEthBalance = BigInt(FAUCET.MIN_ETH_BALANCE * Math.pow(10, ETH_DECIMALS));

Expand Down Expand Up @@ -138,18 +140,20 @@ export async function transferTestTokens({
walletAddress: targetAddress,
discordId,
telegramId,
referralCode: code,
}: FaucetFormSchema) {
const dictionary = await getTranslations('faucet.form.error');
const locale = await getLocale();

let result: FaucetResult = new FaucetResult({});
let db: BetterSql3.Database | undefined;
let faucetTokenDrip = BigInt(FAUCET.DRIP * Math.pow(10, SENT_DECIMALS));

try {
if (!isAddress(targetAddress)) {
throw new FaucetError(
FAUCET_ERROR.INVALID_ADDRESS,
dictionary('invalidAddress', { example: '0x...' })
dictionary(FAUCET_ERROR.INVALID_ADDRESS, { example: '0x...' })
);
}

Expand All @@ -158,7 +162,7 @@ export async function transferTestTokens({
*/
const chain = process.env.FAUCET_CHAIN;
if (!chain || !isChain(chain) || chain !== CHAIN.TESTNET) {
throw new FaucetError(FAUCET_ERROR.INCORRECT_CHAIN, dictionary('incorrectChain'));
throw new FaucetError(FAUCET_ERROR.INCORRECT_CHAIN, dictionary(FAUCET_ERROR.INCORRECT_CHAIN));
}

const { faucetAddress, faucetWallet } = await connectFaucetWallet();
Expand Down Expand Up @@ -200,21 +204,73 @@ export async function transferTestTokens({
db = openDatabase();

let usedOperatorAddress = false;
let usedWalletListAddress = false;
let usedCode = false;

/**
* If the user has not provided a Discord or Telegram ID, they must be an operator.
* If the user provided a referral code, check only the referral code to determine eligibility
*/
if (!discordId && !telegramId) {
if (code) {
if (!codeExists({ db, code })) {
throw new FaucetError(
FAUCET_ERROR.INVALID_REFERRAL_CODE,
dictionary(FAUCET_ERROR.INVALID_REFERRAL_CODE)
);
}

const { wallet, maxuses, drip: codeDrip } = getReferralCodeDetails({ db, code });
Copy link
Collaborator

Choose a reason for hiding this comment

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

maxUses?


if (wallet === targetAddress) {
throw new FaucetError(
FAUCET_ERROR.REFERRAL_CODE_CANT_BE_USED_BY_CREATOR,
dictionary(FAUCET_ERROR.REFERRAL_CODE_CANT_BE_USED_BY_CREATOR)
);
}

const codeTransactionHistory = getCodeUseTransactionHistory({ db, code });

if (codeTransactionHistory.length >= (maxuses ?? 1)) {
throw new FaucetError(
FAUCET_ERROR.REFERRAL_CODE_OUT_OF_USES,
dictionary(FAUCET_ERROR.REFERRAL_CODE_OUT_OF_USES)
);
}

if (
!idIsInTable({
db,
source: TABLE.OPERATOR,
id: targetAddress,
})
codeTransactionHistory.filter((transaction) => transaction.target === targetAddress)
.length >= 1
Comment on lines +240 to +241
Copy link
Collaborator

Choose a reason for hiding this comment

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

Suggested change
codeTransactionHistory.filter((transaction) => transaction.target === targetAddress)
.length >= 1
codeTransactionHistory.some((transaction) => transaction.target === targetAddress)

) {
throw new FaucetError(
FAUCET_ERROR.REFERRAL_CODE_ALREADY_USED,
dictionary(FAUCET_ERROR.REFERRAL_CODE_ALREADY_USED)
);
}

if (codeDrip) {
faucetTokenDrip = BigInt(parseInt(codeDrip) * Math.pow(10, SENT_DECIMALS));
}

usedCode = true;
} else if (!discordId && !telegramId) {
/**
* If the user has not provided a Discord or Telegram ID, they must be an operator.
*/
const idIsOxenOperator = idIsInTable({
db,
source: TABLE.OPERATOR,
id: targetAddress,
});

const idIsInWalletList = idIsInTable({
db,
source: TABLE.WALLET,
id: targetAddress,
});

if (!idIsOxenOperator && !idIsInWalletList) {
throw new FaucetError(
FAUCET_ERROR.INVALID_OXEN_ADDRESS,
dictionary('invalidOxenAddress', {
dictionary(FAUCET_ERROR.INVALID_OXEN_ADDRESS, {
oxenRegistrationDate: new Intl.DateTimeFormat(locale, {
dateStyle: 'long',
}).format(new Date(COMMUNITY_DATE.OXEN_SERVICE_NODE_BONUS_PROGRAM)),
Expand All @@ -223,22 +279,31 @@ export async function transferTestTokens({
}

if (
hasRecentTransaction({
db,
source: TABLE.OPERATOR,
id: targetAddress,
hoursBetweenTransactions,
})
(idIsOxenOperator &&
hasRecentTransaction({
db,
source: TABLE.OPERATOR,
id: targetAddress,
hoursBetweenTransactions,
})) ||
(idIsInWalletList &&
hasRecentTransaction({
db,
source: TABLE.WALLET,
id: targetAddress,
hoursBetweenTransactions,
}))
) {
const transactionHistory = getTransactionHistory({ db, address: targetAddress });
throw new FaucetError(
FAUCET_ERROR.ALREADY_USED,
dictionary('alreadyUsed'),
dictionary(FAUCET_ERROR.ALREADY_USED),
transactionHistory
);
}

usedOperatorAddress = true;
if (idIsOxenOperator) usedOperatorAddress = true;
else if (idIsInWalletList) usedWalletListAddress = true;

/**
* If the user has provided a Discord ID they must be in the approved list of Discord IDs and not have used the faucet recently.
Expand All @@ -253,7 +318,7 @@ export async function transferTestTokens({
) {
throw new FaucetError(
FAUCET_ERROR.INVALID_SERVICE,
dictionary('invalidService', {
dictionary(FAUCET_ERROR.INVALID_SERVICE, {
service: 'Discord',
snapshotDate: new Intl.DateTimeFormat(locale, {
dateStyle: 'long',
Expand All @@ -267,7 +332,7 @@ export async function transferTestTokens({
) {
throw new FaucetError(
FAUCET_ERROR.ALREADY_USED_SERVICE,
dictionary('alreadyUsedService', {
dictionary(FAUCET_ERROR.ALREADY_USED_SERVICE, {
service: 'Discord',
})
);
Expand All @@ -286,7 +351,7 @@ export async function transferTestTokens({
) {
throw new FaucetError(
FAUCET_ERROR.INVALID_SERVICE,
dictionary('invalidService', {
dictionary(FAUCET_ERROR.INVALID_SERVICE, {
service: 'Telegram',
snapshotDate: new Intl.DateTimeFormat(locale, {
dateStyle: 'long',
Expand All @@ -305,7 +370,7 @@ export async function transferTestTokens({
) {
throw new FaucetError(
FAUCET_ERROR.ALREADY_USED_SERVICE,
dictionary('alreadyUsedService', {
dictionary(FAUCET_ERROR.ALREADY_USED_SERVICE, {
service: 'Telegram',
})
);
Expand Down Expand Up @@ -338,7 +403,7 @@ export async function transferTestTokens({
const timestamp = Date.now();
const writeTransactionResult = db
.prepare(
`INSERT INTO ${TABLE.TRANSACTIONS} (hash, target, amount, timestamp, discord, telegram, operator, ethhash, ethamount) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`
`INSERT INTO ${TABLE.TRANSACTIONS} (hash, target, amount, timestamp, discord, telegram, operator, wallet, code, ethhash, ethamount) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
)
.run(
sessionTokenTxHash,
Expand All @@ -348,6 +413,8 @@ export async function transferTestTokens({
discordId,
telegramId,
usedOperatorAddress ? targetAddress : undefined,
usedWalletListAddress ? targetAddress : undefined,
usedCode ? code : undefined,
ethTxHash ?? null,
ethTopupValue.toString()
);
Expand Down
6 changes: 5 additions & 1 deletion apps/staking/app/faucet/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ import { useTranslations } from 'next-intl';
import { AuthModule } from './AuthModule';

export default function FaucetPage() {
return <Faucet />;
}

export function Faucet({ referralCode }: { referralCode?: string }) {
const dictionary = useTranslations('faucet.information');
return (
<NextAuthProvider>
Expand Down Expand Up @@ -38,7 +42,7 @@ export default function FaucetPage() {
<p>{dictionary.rich('walletRequirementDescription')}</p>
</div>
<div className="h-max min-h-[400px]">
<AuthModule />
<AuthModule referralCode={referralCode} />
</div>
</div>
</NextAuthProvider>
Expand Down
Loading