네트워크에 쓰기

이전 섹션에서는 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}`);
const senderBalance = await connection.getBalance(sender.publicKey);
const receiverBalance = await connection.getBalance(receiver.publicKey);
console.log("Sender Balance:", `${senderBalance}`);
console.log("Receiver Balance:", `${receiverBalance}`);
Console
Click to execute the code.

트랜잭션 전송 및 계정 데이터 가져오기를 처리하기 위한 Connection를 생성합니다.

이 예제에서는 localhost:8899에서 실행되는 로컬 테스트 validator에 연결합니다.

Connection
const connection = new Connection("http://localhost:8899", "confirmed");

발신자와 수신자 계정으로 사용할 새 keypair를 생성합니다.

Keypair에는 다음이 포함됩니다:

  • 계정 주소 역할을 하는 공개 키
  • 트랜잭션 서명에 사용되는 개인 키
Generate Keypairs
const sender = new Keypair();
const receiver = new Keypair();

SOL을 전송하기 전에 발신자 계정에 SOL 잔액이 있어야 합니다.

메인넷 이외의 네트워크에서는 테스트용 SOL을 얻기 위해 requestAirdrop 메서드를 사용할 수 있습니다.

Airdrop
const signature = await connection.requestAirdrop(
sender.publicKey,
LAMPORTS_PER_SOL
);
await connection.confirmTransaction(signature, "confirmed");

SystemProgram.transfer() 메서드는 fromPubkey 계정에서 toPubkey 계정으로 지정된 lamports 금액만큼 SOL을 전송하는 명령어를 생성합니다.

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

트랜잭션을 생성하고 명령어를 트랜잭션에 추가합니다.

이 예제에서는 단일 명령어가 포함된 트랜잭션을 생성합니다. 그러나 하나의 트랜잭션에 여러 명령어를 추가할 수 있습니다.

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

트랜잭션에 서명하고 네트워크로 전송합니다.

발신자 keypair는 자신의 계정에서 SOL 전송을 승인하기 위해 서명자 배열에 필요합니다.

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

트랜잭션 서명은 Solana 익스플로러에서 트랜잭션을 조회하는 데 사용할 수 있는 고유 식별자입니다.

트랜잭션 전송 및 계정 데이터 가져오기를 처리하기 위한 Connection를 생성합니다.

이 예제에서는 localhost:8899에서 실행되는 로컬 테스트 validator에 연결합니다.

Connection
const connection = new Connection("http://localhost:8899", "confirmed");

발신자와 수신자 계정으로 사용할 새 keypair를 생성합니다.

Keypair에는 다음이 포함됩니다:

  • 계정 주소 역할을 하는 공개 키
  • 트랜잭션 서명에 사용되는 개인 키
Generate Keypairs
const sender = new Keypair();
const receiver = new Keypair();

SOL을 전송하기 전에 발신자 계정에 SOL 잔액이 있어야 합니다.

메인넷 이외의 네트워크에서는 테스트용 SOL을 얻기 위해 requestAirdrop 메서드를 사용할 수 있습니다.

Airdrop
const signature = await connection.requestAirdrop(
sender.publicKey,
LAMPORTS_PER_SOL
);
await connection.confirmTransaction(signature, "confirmed");

SystemProgram.transfer() 메서드는 fromPubkey 계정에서 toPubkey 계정으로 지정된 lamports 금액만큼 SOL을 전송하는 명령어를 생성합니다.

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

트랜잭션을 생성하고 명령어를 트랜잭션에 추가합니다.

이 예제에서는 단일 명령어가 포함된 트랜잭션을 생성합니다. 그러나 하나의 트랜잭션에 여러 명령어를 추가할 수 있습니다.

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

트랜잭션에 서명하고 네트워크로 전송합니다.

발신자 keypair는 자신의 계정에서 SOL 전송을 승인하기 위해 서명자 배열에 필요합니다.

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

트랜잭션 서명은 Solana 익스플로러에서 트랜잭션을 조회하는 데 사용할 수 있는 고유 식별자입니다.

Transfer SOL
import {
LAMPORTS_PER_SOL,
SystemProgram,
Transaction,
sendAndConfirmTransaction,
Keypair,
Connection
} from "@solana/web3.js";
const connection = new Connection("http://localhost:8899", "confirmed");

토큰 생성하기

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

  1. System Program을 호출하여 새 계정을 생성합니다.
  2. Token Extensions Program을 호출하여 해당 계정을 Mint로 초기화합니다.
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,
getMint
} 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("Transaction Signature:", `${transactionSignature}`);
const mintData = await getMint(
connection,
mint.publicKey,
"confirmed",
TOKEN_2022_PROGRAM_ID
);
);
Console
Click to execute the code.

Solana에서 토큰을 생성하려면 @solana/web3.js@solana/spl-token 라이브러리를 모두 사용해야 합니다.

  • 연결 생성하기
  • 트랜잭션 비용을 지불할 keypair 생성하기
  • keypair에 자금을 지원하기 위한 에어드롭 요청하기
Connection & Wallet Setup
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 account를 위한 keypair를 생성합니다.

이 keypair의 공개 키는 mint account의 주소로 사용됩니다.

Mint Keypair
const mint = new Keypair();

mint account에 필요한 최소 lamport를 계산합니다.

getMinimumBalanceForRentExemptMint 함수는 mint account의 데이터에 할당해야 하는 정확한 SOL(lamport 단위) 양을 계산합니다.

Rent Exemption
const rentExemptionLamports =
await getMinimumBalanceForRentExemptMint(connection);

첫 번째 명령어는 System Program의 createAccount 명령어를 호출하여 다음을 수행합니다:

  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
});

두 번째 명령어는 Token Extensions ProgramcreateInitializeMint2Instruction 명령어를 호출하여 다음 데이터로 mint account를 초기화합니다:

  • 소수점 2자리
  • 지갑을 mint 권한과 동결 권한 모두에 설정
Initialize Mint Instruction
const initializeMintInstruction = createInitializeMint2Instruction(
mint.publicKey,
2,
wallet.publicKey,
wallet.publicKey,
TOKEN_2022_PROGRAM_ID
);

두 명령어를 하나의 트랜잭션에 추가하세요.

두 명령어를 하나의 트랜잭션으로 결합함으로써, 계정 생성과 초기화가 원자적으로 발생하도록 보장합니다. 두 명령어가 모두 성공하거나, 아니면 둘 다 실패합니다.

이 접근 방식은 더 복잡한 Solana 트랜잭션을 구축할 때 일반적으로 사용되며, 모든 명령어가 함께 실행되도록 보장합니다.

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

트랜잭션에 서명하고 전송하세요. 두 개의 서명이 필요합니다:

  • 지갑은 트랜잭션 수수료와 계정 생성의 지불자로 서명합니다
  • 민트는 새 계정에 대한 주소 사용을 승인하기 위해 서명합니다
Send Transaction
const transactionSignature = await sendAndConfirmTransaction(
connection,
transaction,
[
wallet,
mint
]
);

반환된 트랜잭션 서명은 Solana 익스플로러에서 트랜잭션을 검사하는 데 사용할 수 있습니다.

Solana에서 토큰을 생성하려면 @solana/web3.js@solana/spl-token 라이브러리를 모두 사용해야 합니다.

  • 연결 생성하기
  • 트랜잭션 비용을 지불할 keypair 생성하기
  • keypair에 자금을 지원하기 위한 에어드롭 요청하기
Connection & Wallet Setup
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 account를 위한 keypair를 생성합니다.

이 keypair의 공개 키는 mint account의 주소로 사용됩니다.

Mint Keypair
const mint = new Keypair();

mint account에 필요한 최소 lamport를 계산합니다.

getMinimumBalanceForRentExemptMint 함수는 mint account의 데이터에 할당해야 하는 정확한 SOL(lamport 단위) 양을 계산합니다.

Rent Exemption
const rentExemptionLamports =
await getMinimumBalanceForRentExemptMint(connection);

첫 번째 명령어는 System Program의 createAccount 명령어를 호출하여 다음을 수행합니다:

  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
});

두 번째 명령어는 Token Extensions ProgramcreateInitializeMint2Instruction 명령어를 호출하여 다음 데이터로 mint account를 초기화합니다:

  • 소수점 2자리
  • 지갑을 mint 권한과 동결 권한 모두에 설정
Initialize Mint Instruction
const initializeMintInstruction = createInitializeMint2Instruction(
mint.publicKey,
2,
wallet.publicKey,
wallet.publicKey,
TOKEN_2022_PROGRAM_ID
);

두 명령어를 하나의 트랜잭션에 추가하세요.

두 명령어를 하나의 트랜잭션으로 결합함으로써, 계정 생성과 초기화가 원자적으로 발생하도록 보장합니다. 두 명령어가 모두 성공하거나, 아니면 둘 다 실패합니다.

이 접근 방식은 더 복잡한 Solana 트랜잭션을 구축할 때 일반적으로 사용되며, 모든 명령어가 함께 실행되도록 보장합니다.

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

트랜잭션에 서명하고 전송하세요. 두 개의 서명이 필요합니다:

  • 지갑은 트랜잭션 수수료와 계정 생성의 지불자로 서명합니다
  • 민트는 새 계정에 대한 주소 사용을 승인하기 위해 서명합니다
Send Transaction
const transactionSignature = await sendAndConfirmTransaction(
connection,
transaction,
[
wallet,
mint
]
);

반환된 트랜잭션 서명은 Solana 익스플로러에서 트랜잭션을 검사하는 데 사용할 수 있습니다.

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,
getMint
} from "@solana/spl-token";
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");

Is this page helpful?

목차

페이지 편집