계정
솔라나 네트워크의 모든 데이터는 계정에 저장됩니다. 솔라나 네트워크를 단일 계정 테이블이 있는 공개 데이터베이스로 생각할 수 있습니다. 계정과 그 주소 간의 관계는 키-값 쌍과 유사하며, 키는 주소이고 값은 계정입니다.
각 계정은 동일한 기본 구조를 가지며 주소를 사용하여 찾을 수 있습니다.
3개의 계정과 그 주소를 보여주는 다이어그램. 계정 구조 정의 포함.
계정 주소
계정 주소는 솔라나 블록체인에서 계정을 찾는 데 사용되는 32바이트 고유 ID입니다. 계정 주소는 종종 base58로 인코딩된 문자열로 표시됩니다. 대부분의 계정은 Ed25519 공개 키를 주소로 사용하지만, 솔라나는 Program Derived Address도 지원하므로 이는 필수가 아닙니다.
base58로 인코딩된 공개 키 주소를 가진 계정
공개 키
아래 예제는 Solana SDK를 사용하여 keypair를 생성하는 방법을 보여줍니다.
Keypair에는 다음이 포함됩니다:
- 계정 주소 역할을 하는 공개 키
- 트랜잭션 서명에 사용되는 개인 키
import { generateKeyPairSigner } from "@solana/kit";// Kit does not enable extractable private keysconst keypairSigner = await generateKeyPairSigner();console.log(keypairSigner);
Program Derived Address
Program Derived Address(PDA)는 프로그램 ID와 하나 이상의 선택적 입력(시드)을 사용하여 결정론적으로 도출된 주소입니다. 아래 예제는 Solana SDK를 사용하여 Program Derived Address를 생성하는 방법을 보여줍니다.
import { Address, getProgramDerivedAddress } from "@solana/kit";const programAddress = "11111111111111111111111111111111" as Address;const seeds = ["helloWorld"];const [pda, bump] = await getProgramDerivedAddress({programAddress,seeds});console.log(`PDA: ${pda}`);console.log(`Bump: ${bump}`);
계정 구조
모든
Account는
최대 크기가
10MiB이며
다음 정보를 포함합니다:
lamports: 계정의 lamport 수data: 계정의 데이터owner: 계정을 소유한 프로그램의 IDexecutable: 계정이 실행 가능한 바이너리를 포함하는지 여부를 나타냄rent_epoch: 더 이상 사용되지 않는 rent epoch 필드
pub struct Account {/// lamports in the accountpub lamports: u64,/// data held in this account#[cfg_attr(feature = "serde", serde(with = "serde_bytes"))]pub data: Vec<u8>,/// the program that owns this account. If executable, the program that loads this account.pub owner: Pubkey,/// this account's data contains a loaded program (and is now read-only)pub executable: bool,/// the epoch at which this account will next owe rentpub rent_epoch: Epoch,}
Lamports
데이터
이 필드는 일반적으로 "계정 데이터"라고 불립니다. 이 필드의 data는 임의의
바이트 시퀀스를 포함할 수 있기 때문에 임의적인 것으로 간주됩니다. 각 프로그램은
이 필드에 저장된 데이터의 구조를 정의합니다.
- Program accounts: 이 필드는 실행 가능한 프로그램 코드 또는 실행 가능한 프로그램 코드를 저장하는 program data account의 주소를 포함합니다.
- Data accounts: 이 필드는 일반적으로 읽기 위한 상태 데이터를 저장합니다.
솔라나 계정에서 데이터를 읽는 것은 두 단계로 이루어집니다:
- 주소를 사용하여 계정 가져오기
- 계정의
data필드를 원시 바이트에서 계정을 소유한 프로그램이 정의한 적절한 데이터 구조로 역직렬화하기
소유자
실행 가능
이 필드는 계정이 program account인지 data account인지를 나타냅니다.
true인 경우: 계정은 program account입니다false인 경우: 계정은 data account입니다
Rent epoch
rent_epoch 필드는 더 이상 사용되지 않습니다.
과거에는 이 필드가 계정이 rent를 지불해야 하는 시기를 추적했습니다. 그러나 이 rent 수금 메커니즘은 이후 폐지되었습니다.
계정 유형
계정은 두 가지 기본 카테고리로 나뉩니다:
- Program account: 실행 가능한 코드를 포함하는 계정
- 데이터 계정: 실행 가능한 코드를 포함하지 않는 계정
프로그램의 코드와 상태를 분리하는 것은 솔라나 계정 모델의 핵심 기능입니다. (일반적으로 프로그램과 해당 데이터에 대해 별도의 파일을 가진 운영 체제와 유사합니다.)
Program accounts
모든 프로그램은 로더 프로그램이 소유하며, 이는 계정을 배포하고 관리하는 데 사용됩니다. 새로운 프로그램이 배포될 때, 실행 가능한 코드를 저장하기 위한 계정이 생성됩니다. 이를 program account라고 합니다. (간단히 말해서, program account를 프로그램 자체로 간주할 수 있습니다.)
아래 다이어그램에서 로더 프로그램이 program account를 배포하는 데 사용되는 것을
볼 수 있습니다. program account의 data에는 실행 가능한 프로그램 코드가
포함되어 있습니다.
프로그램 계정, 그 4가지 구성 요소 및 로더 프로그램의 다이어그램.
Program data accounts
loader-v3를 사용하여 배포된 프로그램은 data 필드에 프로그램 코드를 포함하지
않습니다. 대신, 그들의 data는 프로그램 코드를 포함하는 별도의 program data
account를 가리킵니다. (아래 다이어그램 참조.)
데이터가 있는 프로그램 계정. 데이터는 별도의 프로그램 데이터 계정을 가리킵니다
프로그램 배포나 업그레이드 중에는 버퍼 계정이 업로드를 임시로 준비하는 데 사용됩니다.
아래 예제는 Token Program 계정을 가져옵니다. executable 필드가 true로
설정되어 있어 이 계정이 프로그램임을 나타냅니다.
import { Address, createSolanaRpc } from "@solana/kit";const rpc = createSolanaRpc("https://api.mainnet-beta.solana.com");const programId = "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA" as Address;const accountInfo = await rpc.getAccountInfo(programId, { encoding: "base64" }).send();console.log(accountInfo);
데이터 계정
데이터 계정은 실행 가능한 코드를 포함하지 않습니다. 대신, 정보를 저장합니다.
프로그램 상태 계정
프로그램은 데이터 계정을 사용하여 상태를 유지합니다. 이를 위해 먼저 새 데이터 계정을 생성해야 합니다. 프로그램 상태 계정을 생성하는 과정은 종종 추상화되지만, 기본 프로세스를 이해하는 것이 도움이 됩니다.
상태를 관리하기 위해 새 프로그램은 다음을 수행해야 합니다:
- System Program을 호출하여 계정을 생성합니다. (System Program은 그 후 소유권을 새 프로그램에 이전합니다.)
- 명령어에 정의된 대로 계정 데이터를 초기화합니다.
프로그램 계정이 소유한 데이터 계정 다이어그램
아래 예제는 Token 2022 프로그램이 소유한 Token Mint 계정을 생성하고 가져옵니다.
import {airdropFactory,appendTransactionMessageInstructions,createSolanaRpc,createSolanaRpcSubscriptions,createTransactionMessage,generateKeyPairSigner,getSignatureFromTransaction,lamports,pipe,sendAndConfirmTransactionFactory,setTransactionMessageFeePayerSigner,setTransactionMessageLifetimeUsingBlockhash,signTransactionMessageWithSigners} from "@solana/kit";import { getCreateAccountInstruction } from "@solana-program/system";import {getInitializeMintInstruction,getMintSize,TOKEN_2022_PROGRAM_ADDRESS,fetchMint} from "@solana-program/token-2022";// Create Connection, local validator in this exampleconst rpc = createSolanaRpc("http://localhost:8899");const rpcSubscriptions = createSolanaRpcSubscriptions("ws://localhost:8900");// Generate keypairs for fee payerconst feePayer = await generateKeyPairSigner();// Fund fee payerawait airdropFactory({ rpc, rpcSubscriptions })({recipientAddress: feePayer.address,lamports: lamports(1_000_000_000n),commitment: "confirmed"});// Generate keypair to use as address of mintconst mint = await generateKeyPairSigner();// Get default mint account size (in bytes), no extensions enabledconst space = BigInt(getMintSize());// Get minimum balance for rent exemptionconst rent = await rpc.getMinimumBalanceForRentExemption(space).send();// Instruction to create new account for mint (token 2022 program)// Invokes the system programconst createAccountInstruction = getCreateAccountInstruction({payer: feePayer,newAccount: mint,lamports: rent,space,programAddress: TOKEN_2022_PROGRAM_ADDRESS});// Instruction to initialize mint account data// Invokes the token 2022 programconst initializeMintInstruction = getInitializeMintInstruction({mint: mint.address,decimals: 9,mintAuthority: feePayer.address});const instructions = [createAccountInstruction, initializeMintInstruction];// Get latest blockhash to include in transactionconst { value: latestBlockhash } = await rpc.getLatestBlockhash().send();// Create transaction messageconst transactionMessage = pipe(createTransactionMessage({ version: 0 }), // Create transaction message(tx) => setTransactionMessageFeePayerSigner(feePayer, tx), // Set fee payer(tx) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx), // Set transaction blockhash(tx) => appendTransactionMessageInstructions(instructions, tx) // Append instructions);// Sign transaction message with required signers (fee payer and mint keypair)const signedTransaction =await signTransactionMessageWithSigners(transactionMessage);// Send and confirm transactionawait sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction,{ commitment: "confirmed" });// Get transaction signatureconst transactionSignature = getSignatureFromTransaction(signedTransaction);console.log("Mint Address:", mint.address);console.log("Transaction Signature:", transactionSignature);const accountInfo = await rpc.getAccountInfo(mint.address).send();console.log(accountInfo);const mintAccount = await fetchMint(rpc, mint.address);console.log(mintAccount);
시스템 계정
System Program에 의해 생성된 후 모든 계정이 새 소유자에게 할당되는 것은 아닙니다. System Program이 소유한 계정을 시스템 계정이라고 합니다. 모든 지갑 계정은 시스템 계정이며, 이를 통해 트랜잭션 수수료를 지불할 수 있습니다.
System Program이 소유한 1,000,000 lamports를 포함하는 지갑
SOL이 처음으로 새 주소로 전송될 때, System Program이 소유한 계정이 해당 주소에 생성됩니다.
아래 예제에서는 새 keypair가 생성되고 SOL로 자금이 지원됩니다. 코드를 실행한 후,
계정의 owner가 11111111111111111111111111111111(즉,
System Program)임을 확인할 수
있습니다.
import {airdropFactory,createSolanaRpc,createSolanaRpcSubscriptions,generateKeyPairSigner,lamports} from "@solana/kit";// Create a connection to Solana clusterconst rpc = createSolanaRpc("http://localhost:8899");const rpcSubscriptions = createSolanaRpcSubscriptions("ws://localhost:8900");// Generate a new keypairconst keypair = await generateKeyPairSigner();console.log(`Public Key: ${keypair.address}`);// Funding an address with SOL automatically creates an accountconst signature = await airdropFactory({ rpc, rpcSubscriptions })({recipientAddress: keypair.address,lamports: lamports(1_000_000_000n),commitment: "confirmed"});const accountInfo = await rpc.getAccountInfo(keypair.address).send();console.log(accountInfo);
Sysvar 계정
Sysvar 계정은 미리 정의된 주소에 존재하며 클러스터 상태 데이터에 대한 접근을 제공합니다. 이들은 네트워크 클러스터에 관한 데이터로 동적으로 업데이트됩니다. Sysvar 계정의 전체 목록을 참조하세요.
아래 예제는 Sysvar Clock 계정에서 데이터를 가져와 역직렬화합니다.
import { createSolanaRpc } from "@solana/kit";import { fetchSysvarClock, SYSVAR_CLOCK_ADDRESS } from "@solana/sysvars";const rpc = createSolanaRpc("https://api.mainnet-beta.solana.com");const accountInfo = await rpc.getAccountInfo(SYSVAR_CLOCK_ADDRESS, { encoding: "base64" }).send();console.log(accountInfo);// Automatically fetch and deserialize the account dataconst clock = await fetchSysvarClock(rpc);console.log(clock);
Is this page helpful?