3

I have the following use case. Users can enter a lottery by bidding a certain amount. The program keeps track of the users and their bid amounts in its own data account (just an array of pub keys and an array of u64 amounts).

When a user submits a bid I want to check whether or not they have already bid, and if so find the entry in that array so that I can increment their bid amount by the new amount (so that users can bid more in order to increase their chances of winning and it accumulates).

Looping through the array to find the right user is too expensive, so I was looking at other options.

Does it make sense to try and create a data account for each user which just stores their current index into that array? I tried doing this using create_account_with_seed, and then using their public_key.to_string() as the seed, but the function complained that the seed was too long... so i'm not sure how to approach the problem from that angle.

Is there a better way to do this? I could imagine creating a map from public key to index, but is there a way to cap the size of that, and is searching through that map going to be cheap computationally?

The code that gives the error is just:

let bidder_data_key = Pubkey::create_with_seed(
    &wallet.pubkey(),
    &wallet.pubkey().to_string(),
    &program,
).unwrap();

thread 'main' panicked at 'called Result::unwrap() on an Err value: MaxSeedLengthExceeded', src/main.rs:243:7

For some reason though I can create a PDA address using the public_key.to_bytes() as the seed... maybe that is the way?

Thanks for any help!

1 Answer 1

4

What you're looking for is Program Derived Account (PDA)

Create a PDA for each User using their address as a seed. This will ensure that you're passing the correct data to the program each time a user calls.

You can add an id field to the User that increments.

Create a Game account (PDA preferably) which contains total_users field

An id is picked randomly, from 1 to total_users (Lottery Winner)

Only the user with that id can withdraw the funds.

3
  • Thanks! The PDA approach does seem to be the way to go
    – daoplays
    Aug 3, 2022 at 10:24
  • Would you mind to share the code for this approach. coz when I try to transfer SOL from PDA to user, it says only accounts without data are supported. I have exact scenario where I need to store all user IDs and funds to allow specific user to withdraw.
    – NaveeN .G
    Aug 4, 2022 at 5:28
  • this might help solana.stackexchange.com/questions/1376/…
    – vicyyn
    Aug 4, 2022 at 11:47

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.