Create Program User

Initialize your onchain user account to start betting.

What You'll Do

Create an onchain Program User account that tracks your betting activity.

Prerequisites

  • SDK initialized with a wallet
  • Wallet funded with SOL for fees

Create User Account

Use the SDK to create your program user:

typescript
import { SDK } from "@solworks/poll-sdk";

const txHash = await sdk.createUser({
  signers: [wallet],
});

console.log("User created:", txHash);

Check If User Exists

Before creating, check if the user already exists:

typescript
async function userExists(walletPublicKey: PublicKey): Promise<boolean> {
  const userAddress = sdk.addresses.user.get(walletPublicKey);

  try {
    await sdk.accounts.user.single(userAddress);
    return true;
  } catch {
    return false;
  }
}

const exists = await userExists(wallet.publicKey);
if (!exists) {
  await sdk.createUser({ signers: [wallet] });
}

Get User Account Data

After creation, fetch the user account data:

typescript
const userAddress = sdk.addresses.user.get(wallet.publicKey);
const userAccount = await sdk.accounts.user.single(userAddress);

console.log("User Stats:");
console.log("- Total Wagers:", userAccount.totalWagersCount);
console.log("- Total Wagered:", userAccount.totalWageredAmount);
console.log("- In Wager Amount:", userAccount.inWagerAmount);
console.log("- Next Wager ID:", userAccount.nextWagerId);

User Account Fields

The program user account tracks:

FieldDescription
totalWagersCountNumber of wagers placed
totalWageredAmountTotal USDC wagered (lifetime)
inWagerAmountUSDC currently locked in active wagers
nextWagerIdID for the next bet this user creates

User Address Derivation

The user account address is a PDA derived from:

typescript
const [userAddress] = PublicKey.findProgramAddressSync(
  [Buffer.from("user"), wallet.publicKey.toBuffer()],
  programId
);

// Or use the SDK helper
const userAddress = sdk.addresses.user.get(wallet.publicKey);

What Happens

When you create a user:

1. A Program Derived Address (PDA) is calculated

2. A new account is created at that address

3. Account is initialized with zero stats

4. Account is owned by the betting program

Error Handling

Common errors when creating users:

typescript
try {
  await sdk.createUser({ signers: [wallet] });
} catch (error) {
  if (error.message.includes("already in use")) {
    console.log("User already exists");
  } else if (error.message.includes("insufficient funds")) {
    console.log("Need more SOL for transaction fees");
  } else {
    throw error;
  }
}

Next Steps

With your program user created, you're ready to create your first bet.