본문 바로가기

카테고리 없음

Web3j 스터디 (6) 네이티브 코인 전송

1. 지갑 주소 생성 (Private Key, Public Key)
1.1 Private Key로 Public Key 추출
1.2 생성된 주소 메타마스크에 등록해보기
1.3 Private Key로 서명 생성

2. 단위 변환 (wei, gwei, eth)
2.1 wei → eth
2.2 eth → wei

3. 네이티브 코인 전송
3.1 네이티브 코인 전송 (from, to, amount)

 

네이티브 코인이란?

네이티브 코인은 블록체인 네트워크가 기본적으로 사용하는 화폐이다.

  • Ethereum → ETH
  • BNB Chain → BNB
  • Bitcoin → BTC
  • Avalanche → AVAX
  • Solana → SOL

네트워크의 전송 수수료(가스비) 도 이 네이티브 코인으로 지불한다.

 네이티브 코인의 특징

  • 스마트 컨트랙트를 직접 호출하지 않아도 전송 가능
  • 지갑 A → 지갑 B 로 바로 보낼 수 있음
  • 이더리움에서는 eth_sendTransaction RPC 로 처리됨
  • 컨트랙트 로그가 없음 (TransactionReceipt.logs = 빈 배열)

 

코인 vs 토큰 차이

구분 코인 토큰
소속 자체 블록체인 보유 다른 블록체인 위에서 실행
예시 BTC, ETH, BNB ERC-20(유틸리티 토큰), ERC-721(NFT)
수수료 지불 YES (네트워크 유지 화폐) NO (코인은 필요함)
구현 방식 프로토콜 레벨 스마트 컨트랙트 레벨

 

 

 

 Java + Web3j로 네이티브 코인 보내기

1) 준비물

① Sepolia 테스트넷 ETH
https://cloud.google.com/application/web3/faucet/ethereum/sepolia

② Infura API 키
https://developer.metamask.io/

③ 전송에 사용할 개인키
→ 메타마스크 → 계정 내보내기

 


 

전체 코드

package transfer.nativecoin;

import java.math.BigDecimal;
import org.web3j.crypto.Credentials;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.methods.response.TransactionReceipt;
import org.web3j.protocol.http.HttpService;
import org.web3j.tx.Transfer;
import org.web3j.utils.Convert.Unit;

public class NativeCoinTransfer {

    public static void main(String[] args) throws Exception {

        String infuraKey = "c...";       // 본인 infura 키
        String privateKey = "0x4...";    // 전송자 개인키

        String sepoliaUrl = "https://sepolia.infura.io/v3/" + infuraKey;
        String toAddress = "0x1...";     // 받는 주소
        BigDecimal value = new BigDecimal("0.000001"); // 전송 금액

        System.out.println("받는 주소 : " + toAddress);
        System.out.println("전송 금액 : " + value + " ETH");

        Web3j web3 = Web3j.build(new HttpService(sepoliaUrl));
        Credentials credentials = Credentials.create(privateKey);

        System.out.println("보내는 주소 : " + credentials.getAddress());
        System.out.println("\n트랜잭션 전송 중...");

        TransactionReceipt transactionReceipt =
            Transfer.sendFunds(web3, credentials, toAddress, value, Unit.ETHER).send();

        System.out.println("\n=== 네이티브 코인 전송 완료 ===");
        System.out.println("트랜잭션 해시 : " + transactionReceipt.getTransactionHash());
        System.out.println("블록 번호 : " + transactionReceipt.getBlockNumber());
        System.out.println("가스 사용량 : " + transactionReceipt.getGasUsed());
        System.out.println("상태 : " + (transactionReceipt.isStatusOK() ? "성공" : "실패"));
        System.out.println("보낸 주소 : " + transactionReceipt.getFrom());
        System.out.println("받은 주소 : " + transactionReceipt.getTo());

        System.out.println("\n탐색기 확인 : https://sepolia.etherscan.io/tx/" + transactionReceipt.getTransactionHash());
    }
}

코드 설명

Web3j 연결

Web3j web3 = Web3j.build(new HttpService(sepoliaUrl));

Infura RPC 엔드포인트로 네트워크 연결

Credentials 생성

Credentials credentials = Credentials.create(privateKey);

여기서 개인키를 넣으면 자동으로 from 주소 계산됨

Transfer.sendFunds()

Transfer.sendFunds(web3, credentials, toAddress, value, Unit.ETHER)

Transfer 클래스는 다음을 자동 처리해준다:

  • 가스비 추정
  • 가스 한도 자동 설정
  • 단위 변환 (ETH → Wei)
  • 전송 트랜잭션 생성

즉, 가장 간단한 ETH 전송 API이다. 

 

(참고)

.send() : 동기 방식 (결과를 기다림)
.sendAsync() : 비동기 방식 (즉시 반환)

 

TransactionReceipt 출력

transactionReceipt.getTransactionHash();
transactionReceipt.getGasUsed();
transactionReceipt.isStatusOK();

네이티브 코인 전송은 컨트랙트 호출이 없기 때문에 Logs가 비어 있다.

 

예:

logs=[]

결과 예시 (Transaction Receipt)

=== 네이티브 코인 전송 완료 ===
트랜잭션 해시 : 0xa942c4156a199edc61fe2c411cfe1dd5584ef3af3640ab90373a1d38d357f56d
블록 번호 : 9743467
가스 사용량 : 21000
상태 : 성공
보낸 주소 : 0x658b8a1ae242d0460d4777e17c9af438daab4f77
받은 주소 : 0x192897df0b17c99fa24ecf998c22e2e83c3cd3d8

탐색기 확인 : https://sepolia.etherscan.io/tx/0xa942c4156a199edc61fe2c411cfe1dd5584ef3af3640ab90373a1d38d357f56d

=== 전체 영수증 정보 ===
TransactionReceipt{transactionHash='0xa942c4156a199edc61fe2c411cfe1dd5584ef3af3640ab90373a1d38d357f56d', transactionIndex='0x44', blockHash='0xb541bd970b414c3229a652abe68df22852c55437bbe4e069626a0b3a7fad4caa', blockNumber='0x94ac6b', cumulativeGasUsed='0xca8ef0', gasUsed='0x5208', contractAddress='null', root='null', status='0x1', from='0x658b8a1ae242d0460d4777e17c9af438daab4f77', to='0x192897df0b17c99fa24ecf998c22e2e83c3cd3d8', logs=[], logsBloom='0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', revertReason='null', type='0x0', effectiveGasPrice='0xf4248', blobGasPrice='null', blobGasused='null'}

 

핵심 정리

  • 네이티브 코인은 네트워크의 기본 화폐
  • 계약 없이 지갑 간 바로 전송 가능
  • ERC-20 / 721 등은 따로 스마트 컨트랙트 호출 필요
  • Web3j 의 Transfer.sendFunds() 로 ETH 전송이 매우 간단
  • 테스트넷 전송도 Receipt로 확인 가능