2

I created a spl-token and I want to let users claim airdrops from my website.

My current implementation in short:

  1. Calculate associated token account
  2. Check if the token account exist
  3. If not, create the associated token account by sending tx (user pays gas fee)
  4. If exist, show claim airdrop button

Does creating the associated token account on the frontend side considered bad practice? Or is it possible to simplify the process and create the token account during claim airdrop?


Also, I would like to know if airdrops can only be done through programs(smart contracts) if I want to make sure an address only claimed once.

What if I want to add conditions to check the eligibility of the user, such as if the user holds more than 10 SOL, or the address holds 10 SOL for more than 2 years?


Thank you for the kind help!

1 Answer 1

3

You can use the function

getOrCreateAssociatedTokenAccount

from web3js to get the TokenAccount and create it if it does not exist.

If you already have a claim transaction you can also add another createTokenAccount instruction to it like this to save one step:

const transaction = new Transaction().add(
                    createAssociatedTokenAccountInstruction(
                        payer.publicKey,
                        associatedToken,
                        owner,
                        mint,
                        programId,
                        associatedTokenProgramId
                    )
                );

You can also create the token account in the program using init_if_needed like to:

https://beta.solpg.io/631a439777ea7f12846aee89

#[derive(Accounts)]
pub struct Initialize<'info> {
    #[account(
        init_if_needed,
        payer = payer, 
        associated_token::mint = mint, 
        associated_token::authority = payer
    )]
    pub token_account: Account<'info, TokenAccount>,
    pub mint: Account<'info, Mint>,
     #[account(mut)]
    pub payer: Signer<'info>,
    pub system_program: Program<'info, System>,
    pub token_program: Program<'info, Token>,
    pub associated_token_program: Program<'info, AssociatedToken>,
    pub rent: Sysvar<'info, Rent>,
}

Instead of doing it in a program you can also use an api, like nextJS and deploy it to vercel and save who claimed in some database. You can do your checks either in the program or in the api. If you use an API make sure the people sign a message first so you can be sure that its actually their wallet.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.