Program derived addresses
Ref - https://solana.com/docs/core/pda
Video - https://www.youtube.com/watch?v=p0eD29d8JCM
Program Derived Addresses (PDAs) provide developers on Solana with two main use cases:
- Deterministic Account Addresses: PDAs provide a mechanism to deterministically derive an address using a combination of optional “seeds” (predefined inputs) and a specific program ID.
- Enable Program Signing: The Solana runtime enables programs to “sign” for PDAs which are derived from its program ID.
Properties
- PDAs are addresses derived deterministically using
- a combination of user-defined seeds
- a bump seed
- and a program’s ID.
- PDAs are addresses that fall off the Ed25519 curve and have no corresponding private key.
- Solana programs can programmatically “sign” for PDAs that are derived using its program ID.
- Deriving a PDA does not automatically create an on-chain account.
- An account using a PDA as its address must be explicitly created through a dedicated instruction within a Solana program.
Find the associated token account for a user and a mint
const { PublicKey } = require('@solana/web3.js');const { ASSOCIATED_TOKEN_PROGRAM_ID, TOKEN_PROGRAM_ID } = require('@solana/spl-token');
// Replace these with your actual valuesconst userAddress = new PublicKey('5gjLjKtBhDxWL4nwGKprThQwyzzNZ7XNAVFcEtw3rD4i');const tokenMintAddress = new PublicKey('6NeR2StEEb6CP75Gsd7ydbiAkabdriMdixPmC2U9hcJs');
// Derive the associated token addressconst getAssociatedTokenAddress = (mintAddress, ownerAddress) => { return PublicKey.findProgramAddressSync( [ ownerAddress.toBuffer(), TOKEN_PROGRAM_ID.toBuffer(), mintAddress.toBuffer(), ], ASSOCIATED_TOKEN_PROGRAM_ID );};
const [associatedTokenAddress, bump] = getAssociatedTokenAddress(tokenMintAddress, userAddress);console.log(`Associated Token Address: ${associatedTokenAddress.toBase58()}, bump: ${bump}`);
createProgramAddress
vs findProgramAddress
const { PublicKey } = require('@solana/web3.js');const { ASSOCIATED_TOKEN_PROGRAM_ID, TOKEN_PROGRAM_ID } = require('@solana/spl-token');
const PDA = PublicKey.createProgramAddressSync( [userAddress.toBuffer(), TOKEN_PROGRAM_ID.toBuffer(), tokenMintAddress.toBuffer(), Buffer.from([255])], ASSOCIATED_TOKEN_PROGRAM_ID,);
console.log(`PDA: ${PDA}`);