네트워크에 쓰기

이전 섹션에서는 Solana 네트워크에서 데이터를 읽는 방법을 배웠습니다. 이제 네트워크에 데이터를 쓰는 방법을 알아보겠습니다. Solana 네트워크에 쓰기는 하나 이상의 명령어를 포함하는 트랜잭션을 보내는 것을 의미합니다.

프로그램(스마트 컨트랙트)은 각 명령어에 대한 비즈니스 로직에 따라 이러한 명령어를 처리합니다. 트랜잭션을 제출하면 Solana 런타임은 각 명령어를 순차적으로 그리고 원자적으로 실행합니다(모든 명령어가 성공하거나 전체 트랜잭션이 실패함을 의미).

이 섹션에서는 두 가지 기본 예제를 살펴보겠습니다:

  1. 계정 간 SOL 전송하기
  2. 새 토큰 생성하기

이 예제들은 Solana 프로그램을 호출하기 위해 트랜잭션을 구축하고 보내는 방법을 보여줍니다. 자세한 내용은 트랜잭션 및 명령어Solana의 수수료 페이지를 참조하세요.

SOL 전송하기

이 예제에서는 두 계정 간에 SOL을 전송하는 방법을 배웁니다.

Solana에서 각 계정은 특정 프로그램을 소유자로 가집니다. 프로그램 소유자만이 계정의 SOL(lamport) 잔액을 차감할 수 있습니다.

System Program은 모든 "지갑" 계정의 소유자입니다. SOL을 전송하려면 System Program의 transfer 명령어를 호출해야 합니다.

Transfer SOL
import {
LAMPORTS_PER_SOL,
SystemProgram,
Transaction,
sendAndConfirmTransaction,
Keypair,
Connection
} from "@solana/web3.js";
const connection = new Connection("http://localhost:8899", "confirmed");
const sender = new Keypair();
const receiver = new Keypair();
const signature = await connection.requestAirdrop(
sender.publicKey,
LAMPORTS_PER_SOL
);
await connection.confirmTransaction(signature, "confirmed");
const transferInstruction = SystemProgram.transfer({
fromPubkey: sender.publicKey,
toPubkey: receiver.publicKey,
lamports: 0.01 * LAMPORTS_PER_SOL
});
const transaction = new Transaction().add(transferInstruction);
const transactionSignature = await sendAndConfirmTransaction(
connection,
transaction,
[sender]
);
console.log("Transaction Signature:", `${transactionSignature}`);
Click to execute the code.

이것은 Solana의 모든 프로그램과 상호작용하기 위한 트랜잭션을 구축하는 단계입니다.

호출하려는 명령을 생성하세요.

Instruction
const transferInstruction = SystemProgram.transfer({
fromPubkey: sender.publicKey,
toPubkey: receiver.publicKey,
lamports: 0.01 * LAMPORTS_PER_SOL
});

트랜잭션에 명령을 추가하세요:

Transaction
const transaction = new Transaction().add(transferInstruction);

트랜잭션에 서명하고 전송하세요:

Send Transaction
const transactionSignature = await sendAndConfirmTransaction(
connection,
transaction,
[sender] // signer keypair
);

토큰 생성하기

이 예제에서는 Token Extensions Program을 사용하여 Solana에서 새 토큰을 생성하는 방법을 배우게 됩니다. 이를 위해서는 두 가지 명령이 필요합니다:

  1. 새 계정을 생성하기 위해 System Program을 호출합니다.
  2. 해당 계정을 Mint로 초기화하기 위해 Token Extensions Program을 호출합니다.
Create Mint Account
import {
Connection,
Keypair,
SystemProgram,
Transaction,
sendAndConfirmTransaction,
LAMPORTS_PER_SOL
} from "@solana/web3.js";
import {
MINT_SIZE,
TOKEN_2022_PROGRAM_ID,
createInitializeMint2Instruction,
getMinimumBalanceForRentExemptMint
} from "@solana/spl-token";
const connection = new Connection("http://localhost:8899", "confirmed");
const wallet = new Keypair();
// Fund the wallet with SOL
const signature = await connection.requestAirdrop(
wallet.publicKey,
LAMPORTS_PER_SOL
);
await connection.confirmTransaction(signature, "confirmed");
// Generate keypair to use as address of mint account
const mint = new Keypair();
// Calculate lamports required for rent exemption
const rentExemptionLamports =
await getMinimumBalanceForRentExemptMint(connection);
// Instruction to create new account with space for new mint account
const createAccountInstruction = SystemProgram.createAccount({
fromPubkey: wallet.publicKey,
newAccountPubkey: mint.publicKey,
space: MINT_SIZE,
lamports: rentExemptionLamports,
programId: TOKEN_2022_PROGRAM_ID
});
// Instruction to initialize mint account
const initializeMintInstruction = createInitializeMint2Instruction(
mint.publicKey,
2, // decimals
wallet.publicKey, // mint authority
wallet.publicKey, // freeze authority
TOKEN_2022_PROGRAM_ID
);
// Build transaction with instructions to create new account and initialize mint account
const transaction = new Transaction().add(
createAccountInstruction,
initializeMintInstruction
);
const transactionSignature = await sendAndConfirmTransaction(
connection,
transaction,
[
wallet, // payer
mint // mint address keypair
]
);
console.log("Mint Account:", `${mint.publicKey}`);
console.log("Transaction Signature:", `${transactionSignature}`);
Click to execute the code.

다음은 예제가 수행하는 작업에 대한 단계별 분석입니다:

연결을 생성하고 지갑에 자금을 충전합니다

Connection and Wallet
const connection = new Connection("http://localhost:8899", "confirmed");
const wallet = new Keypair();
const signature = await connection.requestAirdrop(
wallet.publicKey,
LAMPORTS_PER_SOL
);
await connection.confirmTransaction(signature, "confirmed");

Mint 계정을 위한 keypair 생성하기

Mint Keypair
const mint = new Keypair();

rent 면제를 위한 최소 lamport 계산하기

Rent Exemption
const rentExemptionLamports =
await getMinimumBalanceForRentExemptMint(connection);

새 계정 생성을 위한 명령어 만들기

  1. mint 데이터 저장을 위한 필요한 공간 할당
  2. 새 계정에 자금을 제공하기 위해 지갑에서 lamport 전송
  3. 계정의 소유권 할당을 Token Extensions 프로그램(TOKEN_2022_PROGRAM_ID)에게 부여
Create Account Instruction
const createAccountInstruction = SystemProgram.createAccount({
fromPubkey: wallet.publicKey,
newAccountPubkey: mint.publicKey,
space: MINT_SIZE,
lamports: rentExemptionLamports,
programId: TOKEN_2022_PROGRAM_ID
});

Mint 계정 초기화를 위한 명령어 만들기

Initialize Mint Instruction
const initializeMintInstruction = createInitializeMint2Instruction(
mint.publicKey,
2, // decimals
wallet.publicKey, // mint authority
wallet.publicKey, // freeze authority
TOKEN_2022_PROGRAM_ID
);

두 명령어를 트랜잭션에 추가하기

Build Transaction
const transaction = new Transaction().add(
createAccountInstruction,
initializeMintInstruction
);

필요한 서명자들과 함께 트랜잭션 전송 및 확인하기

Send Transaction
const transactionSignature = await sendAndConfirmTransaction(
connection,
transaction,
[wallet, mint]
);

Mint 계정과 트랜잭션 서명 출력하기

Output
console.log("Mint Account:", `${mint.publicKey}`);
console.log("Transaction Signature:", `${transactionSignature}`);

두 명령어를 하나의 트랜잭션으로 결합함으로써 계정 생성과 초기화가 원자적으로 이루어지도록 보장합니다. 두 명령어가 모두 성공하거나 둘 다 실패합니다. 이 접근 방식은 더 복잡한 Solana 트랜잭션을 구축할 때 일반적으로 사용되며, 모든 명령어가 함께 실행되도록 보장합니다.

Is this page helpful?

목차

페이지 편집