Ver3.5 라라벨(Laravel)에서 스마트 컨트랙트 호출 테스트 환경 구성하기

라라벨(Laravel)에서 스마트 컨트랙트 호출 테스트 환경 구성하기
PHP 백엔드와 이더리움 블록체인을 연결하는 실전 개발 환경 세팅 가이드
PHP 기반의 강력한 웹 프레임워크 Laravel(라라벨)과 이더리움 스마트 컨트랙트를 연동하는 건 생각보다 훨씬 실용적인 시나리오예요.
실제로 기존에 라라벨로 구축된 서비스에 블록체인 기능을 붙여야 하는 경우가 꽤 많거든요 — NFT 민팅 백엔드, 토큰 전송 API, DeFi 대시보드 등등.
이 글에서는 로컬 테스트 환경부터 실제 스마트 컨트랙트 호출까지 단계별로 완전히 파헤쳐볼 거예요.
Hardhat 또는 Ganache로 로컬 블록체인 띄우고, Web3.php로 라라벨에서 컨트랙트 함수 호출하는 것까지 — 실제 코드와 함께 쭉 따라오면 됩니다! 🚀
솔리디티 문법 자체보다는 라라벨 ↔ 스마트 컨트랙트 연동 테스트 환경 구성에 집중합니다.
본격적으로 시작하기 전에 필요한 도구들을 싹 정리해볼게요.
이거 빠지면 나중에 "왜 안 되지??" 하면서 삽질하게 됨 ㅋㅋㅋ 미리 다 깔아두세요!
새 프로젝트를 만들거나 기존 프로젝트에 붙여도 됩니다.
새로 만드는 경우:
<span class="tx-comment"># Laravel 새 프로젝트 생성</span>
composer create-project laravel/laravel laravel-web3-test
cd laravel-web3-test
<span class="tx-comment"># PHP 버전 확인</span>
php --version
<span class="tx-comment"># Node.js 버전 확인</span>
node --version
라라벨에서 이더리움과 통신하려면 web3p/web3.php 패키지가 핵심이에요.
이게 없으면 아무것도 못 함 ㅋㅋ
<span class="tx-comment"># Web3.php 설치</span>
composer require web3p/web3.php
<span class="tx-comment"># 추가로 필요한 패키지들</span>
composer require kornrunner/keccak
composer require simplito/elliptic-php
web3p/web3.php는 현재 0.1.x 버전이 가장 안정적이에요.PHP 8.x와 호환성 이슈가 있을 수 있으니
composer.json에서 버전을 명시하는 게 좋아요:"web3p/web3.php": "^0.1.4"
라라벨 프로젝트 루트에 blockchain 폴더를 만들어서 Hardhat 프로젝트를 분리해서 관리하는 게 깔끔해요!
<span class="tx-comment"># 라라벨 프로젝트 루트에서</span>
mkdir blockchain
cd blockchain
<span class="tx-comment"># npm 초기화 및 Hardhat 설치</span>
npm init -y
npm install --save-dev hardhat
<span class="tx-comment"># Hardhat 프로젝트 초기화</span>
npx hardhat init
<span class="tx-comment"># 선택 메뉴에서 "Create a JavaScript project" 선택</span>
<span class="tx-comment"># 나머지는 Enter로 기본값 사용</span>
<span class="tx-comment"># 추가 의존성 설치</span>
npm install --save-dev @nomicfoundation/hardhat-toolbox
.gitignore에 blockchain/node_modules를 꼭 추가하세요.안 그러면 git에 node_modules가 올라가는 대참사가... ㅠㅠ
테스트 환경이니까 너무 복잡한 컨트랙트 말고, 라라벨에서 호출하기 좋은 심플한 예제 컨트랙트를 만들어볼게요.
기본적인 값 저장/조회 + 이벤트 발생 기능을 포함한 컨트랙트입니다!
blockchain/contracts/SimpleStorage.sol 파일을 만들어요:
<span class="tx-comment">// SPDX-License-Identifier: MIT</span>
<span class="tx-keyword">pragma solidity</span> ^0.8.19;
<span class="tx-comment">/**
* @title SimpleStorage
* @dev 라라벨 테스트용 심플 스토리지 컨트랙트
*/</span>
<span class="tx-keyword">contract</span> <span class="tx-func">SimpleStorage</span> {
<span class="tx-comment">// 상태 변수</span>
<span class="tx-keyword">uint256 private</span> storedValue;
<span class="tx-keyword">string private</span> storedMessage;
<span class="tx-keyword">address public</span> owner;
<span class="tx-comment">// 이벤트 정의</span>
<span class="tx-keyword">event</span> <span class="tx-func">ValueChanged</span>(
<span class="tx-keyword">address indexed</span> caller,
<span class="tx-keyword">uint256</span> oldValue,
<span class="tx-keyword">uint256</span> newValue
);
<span class="tx-keyword">event</span> <span class="tx-func">MessageChanged</span>(
<span class="tx-keyword">address indexed</span> caller,
<span class="tx-keyword">string</span> newMessage
);
<span class="tx-comment">// 생성자</span>
<span class="tx-keyword">constructor</span>(<span class="tx-keyword">uint256</span> _initialValue) {
storedValue = _initialValue;
owner = msg.sender;
storedMessage = <span class="tx-string">"Hello from Blockchain!"</span>;
}
<span class="tx-comment">// 값 설정 (트랜잭션 발생)</span>
<span class="tx-keyword">function</span> <span class="tx-func">setValue</span>(<span class="tx-keyword">uint256</span> _value) <span class="tx-keyword">public</span> {
<span class="tx-keyword">uint256</span> oldValue = storedValue;
storedValue = _value;
<span class="tx-keyword">emit</span> <span class="tx-func">ValueChanged</span>(msg.sender, oldValue, _value);
}
<span class="tx-comment">// 값 조회 (view - 가스 없음)</span>
<span class="tx-keyword">function</span> <span class="tx-func">getValue</span>() <span class="tx-keyword">public view returns</span> (<span class="tx-keyword">uint256</span>) {
<span class="tx-keyword">return</span> storedValue;
}
<span class="tx-comment">// 메시지 설정</span>
<span class="tx-keyword">function</span> <span class="tx-func">setMessage</span>(<span class="tx-keyword">string memory</span> _message) <span class="tx-keyword">public</span> {
storedMessage = _message;
<span class="tx-keyword">emit</span> <span class="tx-func">MessageChanged</span>(msg.sender, _message);
}
<span class="tx-comment">// 메시지 조회</span>
<span class="tx-keyword">function</span> <span class="tx-func">getMessage</span>() <span class="tx-keyword">public view returns</span> (<span class="tx-keyword">string memory</span>) {
<span class="tx-keyword">return</span> storedMessage;
}
<span class="tx-comment">// 값 증가 (연산 예시)</span>
<span class="tx-keyword">function</span> <span class="tx-func">increment</span>(<span class="tx-keyword">uint256</span> _amount) <span class="tx-keyword">public</span> {
<span class="tx-keyword">uint256</span> oldValue = storedValue;
storedValue += _amount;
<span class="tx-keyword">emit</span> <span class="tx-func">ValueChanged</span>(msg.sender, oldValue, storedValue);
}
<span class="tx-comment">// 오너 체크 modifier</span>
<span class="tx-keyword">modifier</span> <span class="tx-func">onlyOwner</span>() {
<span class="tx-keyword">require</span>(msg.sender == owner, <span class="tx-string">"Not the owner"</span>);
_;
}
<span class="tx-comment">// 오너만 리셋 가능</span>
<span class="tx-keyword">function</span> <span class="tx-func">reset</span>() <span class="tx-keyword">public</span> <span class="tx-func">onlyOwner</span> {
<span class="tx-keyword">uint256</span> oldValue = storedValue;
storedValue = 0;
<span class="tx-keyword">emit</span> <span class="tx-func">ValueChanged</span>(msg.sender, oldValue, 0);
}
}
blockchain/scripts/deploy.js 파일을 만들어요:
<span class="tx-keyword">const</span> hre = require(<span class="tx-string">"hardhat"</span>);
<span class="tx-keyword">const</span> fs = require(<span class="tx-string">"fs"</span>);
<span class="tx-keyword">const</span> path = require(<span class="tx-string">"path"</span>);
<span class="tx-keyword">async function</span> <span class="tx-func">main</span>() {
<span class="tx-comment">// 배포자 계정 가져오기</span>
<span class="tx-keyword">const</span> [deployer] = <span class="tx-keyword">await</span> hre.ethers.<span class="tx-func">getSigners</span>();
console.<span class="tx-func">log</span>(<span class="tx-string">"배포 계정:"</span>, deployer.address);
<span class="tx-comment">// 컨트랙트 팩토리 가져오기</span>
<span class="tx-keyword">const</span> SimpleStorage = <span class="tx-keyword">await</span> hre.ethers.<span class="tx-func">getContractFactory</span>(<span class="tx-string">"SimpleStorage"</span>);
<span class="tx-comment">// 초기값 42로 배포</span>
<span class="tx-keyword">const</span> simpleStorage = <span class="tx-keyword">await</span> SimpleStorage.<span class="tx-func">deploy</span>(42);
<span class="tx-keyword">await</span> simpleStorage.<span class="tx-func">waitForDeployment</span>();
<span class="tx-keyword">const</span> contractAddress = <span class="tx-keyword">await</span> simpleStorage.<span class="tx-func">getAddress</span>();
console.<span class="tx-func">log</span>(<span class="tx-string">"컨트랙트 주소:"</span>, contractAddress);
<span class="tx-comment">// ABI 파일 경로</span>
<span class="tx-keyword">const</span> artifactPath = path.<span class="tx-func">join</span>(
__dirname,
<span class="tx-string">"../artifacts/contracts/SimpleStorage.sol/SimpleStorage.json"</span>
);
<span class="tx-comment">// 라라벨 프로젝트로 ABI + 주소 내보내기</span>
<span class="tx-keyword">const</span> artifact = JSON.<span class="tx-func">parse</span>(fs.<span class="tx-func">readFileSync</span>(artifactPath, <span class="tx-string">"utf8"</span>));
<span class="tx-keyword">const</span> deployInfo = {
address: contractAddress,
abi: artifact.abi,
deployedAt: <span class="tx-keyword">new</span> <span class="tx-func">Date</span>().<span class="tx-func">toISOString</span>(),
network: hre.network.name
};
<span class="tx-comment">// 라라벨 storage 폴더에 저장</span>
<span class="tx-keyword">const</span> outputPath = path.<span class="tx-func">join</span>(
__dirname,
<span class="tx-string">"../../storage/app/contracts/SimpleStorage.json"</span>
);
<span class="tx-comment">// 폴더 없으면 생성</span>
fs.<span class="tx-func">mkdirSync</span>(path.<span class="tx-func">dirname</span>(outputPath), { recursive: <span class="tx-keyword">true</span> });
fs.<span class="tx-func">writeFileSync</span>(outputPath, JSON.<span class="tx-func">stringify</span>(deployInfo, <span class="tx-keyword">null</span>, 2));
console.<span class="tx-func">log</span>(<span class="tx-string">"✅ 배포 정보 저장 완료:"</span>, outputPath);
}
main().<span class="tx-func">catch</span>((error) => {
console.<span class="tx-func">error</span>(error);
process.<span class="tx-func">exit</span>(1);
});
배포 스크립트에서 자동으로 라라벨
storage 폴더에 저장하면, 라라벨에서 항상 최신 정보를 읽어올 수 있어요! 🎯
blockchain/hardhat.config.js를 이렇게 설정해요:
require(<span class="tx-string">"@nomicfoundation/hardhat-toolbox"</span>);
<span class="tx-comment">/** @type import('hardhat/config').HardhatUserConfig */</span>
module.exports = {
solidity: {
version: <span class="tx-string">"0.8.19"</span>,
settings: {
optimizer: {
enabled: <span class="tx-keyword">true</span>,
runs: 200
}
}
},
networks: {
<span class="tx-comment">// 로컬 Hardhat 네트워크 (기본값)</span>
hardhat: {
chainId: 31337
},
<span class="tx-comment">// Hardhat Node 실행 시 연결용</span>
localhost: {
url: <span class="tx-string">"http://127.0.0.1:8545"</span>,
chainId: 31337
},
<span class="tx-comment">// Ganache 사용 시</span>
ganache: {
url: <span class="tx-string">"http://127.0.0.1:7545"</span>,
chainId: 1337
}
}
};
이제 실제로 로컬 블록체인을 띄우고 컨트랙트를 배포해볼 시간이에요!
Hardhat Node를 사용하는 방법과 Ganache를 사용하는 방법 두 가지를 모두 알려드릴게요 😎
cd blockchain
<span class="tx-comment"># Hardhat 로컬 노드 실행</span>
npx hardhat node
<span class="tx-comment"># 실행되면 이런 출력이 나와요:</span>
<span class="tx-comment"># Started HTTP and WebSocket JSON-RPC server at http://127.0.0.1:8545/</span>
<span class="tx-comment"># </span>
<span class="tx-comment"># Accounts</span>
<span class="tx-comment"># ========</span>
<span class="tx-comment"># Account #0: 0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266 (10000 ETH)</span>
<span class="tx-comment"># Private Key: 0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80</span>
<span class="tx-comment"># ... (총 20개 계정)</span>
cd blockchain
<span class="tx-comment"># 컴파일</span>
npx hardhat compile
<span class="tx-comment"># localhost 네트워크에 배포</span>
npx hardhat run scripts/deploy.js --network localhost
<span class="tx-comment"># 성공 시 출력:</span>
<span class="tx-comment"># 배포 계정: 0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266</span>
<span class="tx-comment"># 컨트랙트 주소: 0x5FbDB2315678afecb367f032d93F642f64180aa3</span>
<span class="tx-comment"># ✅ 배포 정보 저장 완료: .../storage/app/contracts/SimpleStorage.json</span>
노드를 재시작할 때마다 컨트랙트를 다시 배포해야 하고, 컨트랙트 주소도 바뀌어요.
이게 테스트 환경에서는 오히려 장점이 될 수 있어요 — 깨끗한 상태에서 테스트 가능! 🧹
GUI가 있어서 시각적으로 확인하기 좋은 Ganache도 많이 써요.
특히 처음 배우는 분들한테 추천!
<span class="tx-comment"># Ganache CLI 설치 (전역)</span>
npm install -g ganache
<span class="tx-comment"># Ganache 실행 (포트 7545, chainId 1337)</span>
ganache --port 7545 --chainId 1337 --deterministic
<span class="tx-comment"># --deterministic 옵션: 항상 같은 계정/키 생성 (테스트에 유용!)</span>
<span class="tx-comment"># 컨트랙트 배포 (ganache 네트워크로)</span>
npx hardhat run scripts/deploy.js --network ganache
개발 초기에 디버깅할 때 엄청 편해요 ㅋㅋㅋ 강추!
배포 후 storage/app/contracts/SimpleStorage.json이 생성됐는지 확인해요:
{
<span class="tx-string">"address"</span>: <span class="tx-string">"0x5FbDB2315678afecb367f032d93F642f64180aa3"</span>,
<span class="tx-string">"abi"</span>: [
{
<span class="tx-string">"inputs"</span>: [{ <span class="tx-string">"name"</span>: <span class="tx-string">"_initialValue"</span>, <span class="tx-string">"type"</span>: <span class="tx-string">"uint256"</span> }],
<span class="tx-string">"stateMutability"</span>: <span class="tx-string">"nonpayable"</span>,
<span class="tx-string">"type"</span>: <span class="tx-string">"constructor"</span>
},
{
<span class="tx-string">"name"</span>: <span class="tx-string">"getValue"</span>,
<span class="tx-string">"outputs"</span>: [{ <span class="tx-string">"type"</span>: <span class="tx-string">"uint256"</span> }],
<span class="tx-string">"stateMutability"</span>: <span class="tx-string">"view"</span>,
<span class="tx-string">"type"</span>: <span class="tx-string">"function"</span>
},
<span class="tx-comment">// ... 나머지 ABI</span>
],
<span class="tx-string">"deployedAt"</span>: <span class="tx-string">"2024-01-15T10:30:00.000Z"</span>,
<span class="tx-string">"network"</span>: <span class="tx-string">"localhost"</span>
}
이제 진짜 핵심이에요! 라라벨에서 스마트 컨트랙트를 호출하는 서비스 클래스를 만들어볼게요.
깔끔하게 Service 패턴으로 구성해서 재사용성을 높일 거예요 💪
라라벨 .env 파일에 블록체인 관련 설정을 추가해요:
<span class="tx-comment"># 블록체인 설정</span>
<span class="tx-var">WEB3_RPC_URL</span>=http://127.0.0.1:8545
<span class="tx-var">WEB3_CHAIN_ID</span>=31337
<span class="tx-var">WEB3_DEFAULT_GAS</span>=3000000
<span class="tx-var">WEB3_GAS_PRICE</span>=20000000000
<span class="tx-comment"># 테스트 계정 (Hardhat 기본 계정 - 절대 실제 환경에 쓰지 마세요!)</span>
<span class="tx-var">WEB3_DEPLOYER_ADDRESS</span>=0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266
<span class="tx-var">WEB3_DEPLOYER_PRIVATE_KEY</span>=0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80
<span class="tx-comment"># 컨트랙트 정보 (배포 후 자동 업데이트됨)</span>
<span class="tx-var">CONTRACT_SIMPLE_STORAGE</span>=storage/app/contracts/SimpleStorage.json
<span class="tx-tag"><?php</span>
<span class="tx-keyword">return</span> [
<span class="tx-comment">/*
|--------------------------------------------------------------------------
| Web3 / Blockchain 설정
|--------------------------------------------------------------------------
*/</span>
<span class="tx-string">'rpc_url'</span> => env(<span class="tx-string">'WEB3_RPC_URL'</span>, <span class="tx-string">'http://127.0.0.1:8545'</span>),
<span class="tx-string">'chain_id'</span> => (int) env(<span class="tx-string">'WEB3_CHAIN_ID'</span>, 31337),
<span class="tx-string">'default_gas'</span> => (int) env(<span class="tx-string">'WEB3_DEFAULT_GAS'</span>, 3000000),
<span class="tx-string">'gas_price'</span> => env(<span class="tx-string">'WEB3_GAS_PRICE'</span>, <span class="tx-string">'20000000000'</span>),
<span class="tx-string">'accounts'</span> => [
<span class="tx-string">'deployer'</span> => [
<span class="tx-string">'address'</span> => env(<span class="tx-string">'WEB3_DEPLOYER_ADDRESS'</span>),
<span class="tx-string">'private_key'</span> => env(<span class="tx-string">'WEB3_DEPLOYER_PRIVATE_KEY'</span>),
],
],
<span class="tx-string">'contracts'</span> => [
<span class="tx-string">'simple_storage'</span> => env(
<span class="tx-string">'CONTRACT_SIMPLE_STORAGE'</span>,
<span class="tx-string">'storage/app/contracts/SimpleStorage.json'</span>
),
],
];
app/Services/Web3Service.php를 만들어요. 이게 핵심 서비스 클래스예요!
<span class="tx-tag"><?php</span>
<span class="tx-keyword">namespace</span> App\Services;
<span class="tx-keyword">use</span> Web3\Web3;
<span class="tx-keyword">use</span> Web3\Contract;
<span class="tx-keyword">use</span> Web3\Providers\HttpProvider;
<span class="tx-keyword">use</span> Web3\RequestManagers\HttpRequestManager;
<span class="tx-keyword">use</span> Web3\Utils;
<span class="tx-keyword">use</span> Illuminate\Support\Facades\Log;
<span class="tx-keyword">use</span> Exception;
<span class="tx-keyword">class</span> <span class="tx-func">Web3Service</span>
{
<span class="tx-keyword">protected</span> Web3 $web3;
<span class="tx-keyword">protected</span> <span class="tx-keyword">string</span> $rpcUrl;
<span class="tx-keyword">protected int</span> $chainId;
<span class="tx-keyword">public function</span> <span class="tx-func">__construct</span>()
{
$this->rpcUrl = config(<span class="tx-string">'web3.rpc_url'</span>);
$this->chainId = config(<span class="tx-string">'web3.chain_id'</span>);
<span class="tx-comment">// Web3 인스턴스 생성</span>
$provider = <span class="tx-keyword">new</span> <span class="tx-func">HttpProvider</span>(
<span class="tx-keyword">new</span> <span class="tx-func">HttpRequestManager</span>($this->rpcUrl, 30)
);
$this->web3 = <span class="tx-keyword">new</span> <span class="tx-func">Web3</span>($provider);
}
<span class="tx-comment">/**
* 현재 블록 번호 조회
*/</span>
<span class="tx-keyword">public function</span> <span class="tx-func">getBlockNumber</span>(): <span class="tx-keyword">int</span>
{
$blockNumber = 0;
$this->web3->eth->blockNumber(<span class="tx-keyword">function</span> ($err, $result) <span class="tx-keyword">use</span> (&$blockNumber) {
<span class="tx-keyword">if</span> ($err !== <span class="tx-keyword">null</span>) {
<span class="tx-keyword">throw new</span> <span class="tx-func">Exception</span>(<span class="tx-string">'블록 번호 조회 실패: '</span> . $err->getMessage());
}
$blockNumber = hexdec($result->toString());
});
<span class="tx-keyword">return</span> $blockNumber;
}
<span class="tx-comment">/**
* 계정 잔액 조회 (Wei → ETH 변환)
*/</span>
<span class="tx-keyword">public function</span> <span class="tx-func">getBalance</span>(<span class="tx-keyword">string</span> $address): <span class="tx-keyword">string</span>
{
$balance = <span class="tx-string">'0'</span>;
$this->web3->eth->getBalance($address, <span class="tx-string">'latest'</span>,
<span class="tx-keyword">function</span> ($err, $result) <span class="tx-keyword">use</span> (&$balance) {
<span class="tx-keyword">if</span> ($err !== <span class="tx-keyword">null</span>) {
<span class="tx-keyword">throw new</span> <span class="tx-func">Exception</span>(<span class="tx-string">'잔액 조회 실패: '</span> . $err->getMessage());
}
<span class="tx-comment">// Wei를 ETH로 변환 (1 ETH = 10^18 Wei)</span>
$weiValue = $result->toString();
$balance = bcdiv($weiValue, bcpow(<span class="tx-string">'10'</span>, <span class="tx-string">'18'</span>), 18);
}
);
<span class="tx-keyword">return</span> $balance;
}
<span class="tx-comment">/**
* 컨트랙트 인스턴스 생성
*/</span>
<span class="tx-keyword">public function</span> <span class="tx-func">getContract</span>(<span class="tx-keyword">string</span> $contractName): Contract
{
$contractPath = base_path(config(<span class="tx-string">"web3.contracts.{$contractName}"</span>));
<span class="tx-keyword">if</span> (!file_exists($contractPath)) {
<span class="tx-keyword">throw new</span> <span class="tx-func">Exception</span>(<span class="tx-string">"컨트랙트 파일을 찾을 수 없습니다: {$contractPath}"</span>);
}
$contractData = json_decode(file_get_contents($contractPath), <span class="tx-keyword">true</span>);
$abi = json_encode($contractData[<span class="tx-string">'abi'</span>]);
$contract = <span class="tx-keyword">new</span> <span class="tx-func">Contract</span>($this->web3->provider, $abi);
$contract->at($contractData[<span class="tx-string">'address'</span>]);
<span class="tx-keyword">return</span> $contract;
}
<span class="tx-comment">/**
* 컨트랙트 주소 조회
*/</span>
<span class="tx-keyword">public function</span> <span class="tx-func">getContractAddress</span>(<span class="tx-keyword">string</span> $contractName): <span class="tx-keyword">string</span>
{
$contractPath = base_path(config(<span class="tx-string">"web3.contracts.{$contractName}"</span>));
$contractData = json_decode(file_get_contents($contractPath), <span class="tx-keyword">true</span>);
<span class="tx-keyword">return</span> $contractData[<span class="tx-string">'address'</span>];
}
<span class="tx-comment">/**
* Web3 인스턴스 반환
*/</span>
<span class="tx-keyword">public function</span> <span class="tx-func">getWeb3</span>(): Web3
{
<span class="tx-keyword">return</span> $this->web3;
}
}
컨트랙트별로 전용 서비스 클래스를 만드는 게 깔끔해요!
app/Services/SimpleStorageService.php:
<span class="tx-tag"><?php</span>
<span class="tx-keyword">namespace</span> App\Services;
<span class="tx-keyword">use</span> Web3\Contract;
<span class="tx-keyword">use</span> Exception;
<span class="tx-keyword">class</span> <span class="tx-func">SimpleStorageService</span>
{
<span class="tx-keyword">protected</span> Web3Service $web3Service;
<span class="tx-keyword">protected</span> Contract $contract;
<span class="tx-keyword">protected string</span> $contractAddress;
<span class="tx-keyword">protected string</span> $defaultAccount;
<span class="tx-keyword">protected string</span> $privateKey;
<span class="tx-keyword">public function</span> <span class="tx-func">__construct</span>(Web3Service $web3Service)
{
$this->web3Service = $web3Service;
$this->contract = $web3Service->getContract(<span class="tx-string">'simple_storage'</span>);
$this->contractAddress = $web3Service->getContractAddress(<span class="tx-string">'simple_storage'</span>);
$this->defaultAccount = config(<span class="tx-string">'web3.accounts.deployer.address'</span>);
$this->privateKey = config(<span class="tx-string">'web3.accounts.deployer.private_key'</span>);
}
<span class="tx-comment">/**
* getValue() 호출 - view 함수 (가스 없음)
*/</span>
<span class="tx-keyword">public function</span> <span class="tx-func">getValue</span>(): <span class="tx-keyword">int</span>
{
$result = <span class="tx-keyword">null</span>;
$error = <span class="tx-keyword">null</span>;
$this->contract->call(<span class="tx-string">'getValue'</span>, [],
<span class="tx-keyword">function</span> ($err, $res) <span class="tx-keyword">use</span> (&$result, &$error) {
<span class="tx-keyword">if</span> ($err !== <span class="tx-keyword">null</span>) {
$error = $err->getMessage();
<span class="tx-keyword">return</span>;
}
<span class="tx-comment">// 결과는 배열로 반환됨</span>
$result = isset($res[0]) ? (int) $res[0]->toString() : 0;
}
);
<span class="tx-keyword">if</span> ($error) {
<span class="tx-keyword">throw new</span> <span class="tx-func">Exception</span>(<span class="tx-string">'getValue 호출 실패: '</span> . $error);
}
<span class="tx-keyword">return</span> $result ?? 0;
}
<span class="tx-comment">/**
* getMessage() 호출
*/</span>
<span class="tx-keyword">public function</span> <span class="tx-func">getMessage</span>(): <span class="tx-keyword">string</span>
{
$result = <span class="tx-keyword">null</span>;
$error = <span class="tx-keyword">null</span>;
$this->contract->call(<span class="tx-string">'getMessage'</span>, [],
<span class="tx-keyword">function</span> ($err, $res) <span class="tx-keyword">use</span> (&$result, &$error) {
<span class="tx-keyword">if</span> ($err !== <span class="tx-keyword">null</span>) {
$error = $err->getMessage();
<span class="tx-keyword">return</span>;
}
$result = $res[0] ?? <span class="tx-string">''</span>;
}
);
<span class="tx-keyword">if</span> ($error) {
<span class="tx-keyword">throw new</span> <span class="tx-func">Exception</span>(<span class="tx-string">'getMessage 호출 실패: '</span> . $error);
}
<span class="tx-keyword">return</span> $result ?? <span class="tx-string">''</span>;
}
<span class="tx-comment">/**
* setValue() 호출 - 트랜잭션 발생 (가스 필요)
*/</span>
<span class="tx-keyword">public function</span> <span class="tx-func">setValue</span>(<span class="tx-keyword">int</span> $value): <span class="tx-keyword">string</span>
{
$txHash = <span class="tx-keyword">null</span>;
$error = <span class="tx-keyword">null</span>;
$this->contract->send(
<span class="tx-string">'setValue'</span>,
$value,
[
<span class="tx-string">'from'</span> => $this->defaultAccount,
<span class="tx-string">'gas'</span> => <span class="tx-string">'0x'</span> . dechex(config(<span class="tx-string">'web3.default_gas'</span>)),
<span class="tx-string">'gasPrice'</span> => <span class="tx-string">'0x'</span> . dechex(config(<span class="tx-string">'web3.gas_price'</span>)),
],
<span class="tx-keyword">function</span> ($err, $result) <span class="tx-keyword">use</span> (&$txHash, &$error) {
<span class="tx-keyword">if</span> ($err !== <span class="tx-keyword">null</span>) {
$error = $err->getMessage();
<span class="tx-keyword">return</span>;
}
$txHash = $result;
}
);
<span class="tx-keyword">if</span> ($error) {
<span class="tx-keyword">throw new</span> <span class="tx-func">Exception</span>(<span class="tx-string">'setValue 트랜잭션 실패: '</span> . $error);
}
<span class="tx-keyword">return</span> $txHash ?? <span class="tx-string">''</span>;
}
<span class="tx-comment">/**
* increment() 호출
*/</span>
<span class="tx-keyword">public function</span> <span class="tx-func">increment</span>(<span class="tx-keyword">int</span> $amount = 1): <span class="tx-keyword">string</span>
{
$txHash = <span class="tx-keyword">null</span>;
$error = <span class="tx-keyword">null</span>;
$this->contract->send(
<span class="tx-string">'increment'</span>,
$amount,
[
<span class="tx-string">'from'</span> => $this->defaultAccount,
<span class="tx-string">'gas'</span> => <span class="tx-string">'0x'</span> . dechex(config(<span class="tx-string">'web3.default_gas'</span>)),
],
<span class="tx-keyword">function</span> ($err, $result) <span class="tx-keyword">use</span> (&$txHash, &$error) {
<span class="tx-keyword">if</span> ($err !== <span class="tx-keyword">null</span>) {
$error = $err->getMessage();
<span class="tx-keyword">return</span>;
}
$txHash = $result;
}
);
<span class="tx-keyword">if</span> ($error) {
<span class="tx-keyword">throw new</span> <span class="tx-func">Exception</span>(<span class="tx-string">'increment 트랜잭션 실패: '</span> . $error);
}
<span class="tx-keyword">return</span> $txHash ?? <span class="tx-string">''</span>;
}
}
view / pure 함수 호출. 블록체인 상태를 변경하지 않음. 가스 없음. 즉시 결과 반환.send: 상태를 변경하는 함수 호출. 트랜잭션 생성. 가스 필요. 트랜잭션 해시 반환.
이 차이를 헷갈리면 나중에 왜 값이 안 바뀌지?? 하면서 멘붕 옴 ㅋㅋㅋ
app/Providers/Web3ServiceProvider.php를 만들어요:
<span class="tx-tag"><?php</span>
<span class="tx-keyword">namespace</span> App\Providers;
<span class="tx-keyword">use</span> App\Services\Web3Service;
<span class="tx-keyword">use</span> App\Services\SimpleStorageService;
<span class="tx-keyword">use</span> Illuminate\Support\ServiceProvider;
<span class="tx-keyword">class</span> <span class="tx-func">Web3ServiceProvider</span> <span class="tx-keyword">extends</span> ServiceProvider
{
<span class="tx-keyword">public function</span> <span class="tx-func">register</span>(): <span class="tx-keyword">void</span>
{
<span class="tx-comment">// Web3Service를 싱글톤으로 등록</span>
$this->app->singleton(Web3Service::class, <span class="tx-keyword">function</span> ($app) {
<span class="tx-keyword">return new</span> <span class="tx-func">Web3Service</span>();
});
<span class="tx-comment">// SimpleStorageService 등록</span>
$this->app->singleton(SimpleStorageService::class, <span class="tx-keyword">function</span> ($app) {
<span class="tx-keyword">return new</span> <span class="tx-func">SimpleStorageService</span>(
$app->make(Web3Service::class)
);
});
}
<span class="tx-keyword">public function</span> <span class="tx-func">boot</span>(): <span class="tx-keyword">void</span>
{
<span class="tx-comment">// config 파일 퍼블리시</span>
$this->publishes([
__DIR__ . <span class="tx-string">'/../config/web3.php'</span> => config_path(<span class="tx-string">'web3.php'</span>),
], <span class="tx-string">'web3-config'</span>);
}
}
config/app.php의 providers 배열에 추가하거나, Laravel 11이라면 bootstrap/providers.php에 추가:
<span class="tx-comment">// bootstrap/providers.php (Laravel 11)</span>
<span class="tx-keyword">return</span> [
App\Providers\AppServiceProvider::class,
App\Providers\Web3ServiceProvider::class, <span class="tx-comment">// 추가!</span>
];
app/Http/Controllers/BlockchainController.php:
<span class="tx-tag"><?php</span>
<span class="tx-keyword">namespace</span> App\Http\Controllers;
<span class="tx-keyword">use</span> App\Services\Web3Service;
<span class="tx-keyword">use</span> App\Services\SimpleStorageService;
<span class="tx-keyword">use</span> Illuminate\Http\Request;
<span class="tx-keyword">use</span> Illuminate\Http\JsonResponse;
<span class="tx-keyword">use</span> Exception;
<span class="tx-keyword">class</span> <span class="tx-func">BlockchainController</span> <span class="tx-keyword">extends</span> Controller
{
<span class="tx-keyword">public function</span> <span class="tx-func">__construct</span>(
<span class="tx-keyword">private readonly</span> Web3Service $web3Service,
<span class="tx-keyword">private readonly</span> SimpleStorageService $storageService
) {}
<span class="tx-comment">/**
* 블록체인 상태 확인
*/</span>
<span class="tx-keyword">public function</span> <span class="tx-func">status</span>(): JsonResponse
{
<span class="tx-keyword">try</span> {
$blockNumber = $this->web3Service->getBlockNumber();
$deployerAddress = config(<span class="tx-string">'web3.accounts.deployer.address'</span>);
$balance = $this->web3Service->getBalance($deployerAddress);
<span class="tx-keyword">return</span> response()->json([
<span class="tx-string">'status'</span> => <span class="tx-string">'connected'</span>,
<span class="tx-string">'block_number'</span> => $blockNumber,
<span class="tx-string">'deployer_balance'</span> => $balance . <span class="tx-string">' ETH'</span>,
<span class="tx-string">'rpc_url'</span> => config(<span class="tx-string">'web3.rpc_url'</span>),
]);
} <span class="tx-keyword">catch</span> (Exception $e) {
<span class="tx-keyword">return</span> response()->json([
<span class="tx-string">'status'</span> => <span class="tx-string">'error'</span>,
<span class="tx-string">'message'</span> => $e->getMessage(),
], 500);
}
}
<span class="tx-comment">/**
* 저장된 값 조회
*/</span>
<span class="tx-keyword">public function</span> <span class="tx-func">getValue</span>(): JsonResponse
{
<span class="tx-keyword">try</span> {
$value = $this->storageService->getValue();
$message = $this->storageService->getMessage();
<span class="tx-keyword">return</span> response()->json([
<span class="tx-string">'value'</span> => $value,
<span class="tx-string">'message'</span> => $message,
]);
} <span class="tx-keyword">catch</span> (Exception $e) {
<span class="tx-keyword">return</span> response()->json([
<span class="tx-string">'error'</span> => $e->getMessage()
], 500);
}
}
<span class="tx-comment">/**
* 값 설정 (트랜잭션)
*/</span>
<span class="tx-keyword">public function</span> <span class="tx-func">setValue</span>(Request $request): JsonResponse
{
$request->validate([
<span class="tx-string">'value'</span> => <span class="tx-string">'required|integer|min:0'</span>,
]);
<span class="tx-keyword">try</span> {
$txHash = $this->storageService->setValue($request->integer(<span class="tx-string">'value'</span>));
<span class="tx-keyword">return</span> response()->json([
<span class="tx-string">'success'</span> => <span class="tx-keyword">true</span>,
<span class="tx-string">'tx_hash'</span> => $txHash,
<span class="tx-string">'message'</span> => <span class="tx-string">'트랜잭션이 성공적으로 전송되었습니다'</span>,
]);
} <span class="tx-keyword">catch</span> (Exception $e) {
<span class="tx-keyword">return</span> response()->json([
<span class="tx-string">'error'</span> => $e->getMessage()
], 500);
}
}
<span class="tx-comment">/**
* 값 증가
*/</span>
<span class="tx-keyword">public function</span> <span class="tx-func">increment</span>(Request $request): JsonResponse
{
$amount = $request->integer(<span class="tx-string">'amount'</span>, 1);
<span class="tx-keyword">try</span> {
$txHash = $this->storageService->increment($amount);
<span class="tx-keyword">return</span> response()->json([
<span class="tx-string">'success'</span> => <span class="tx-keyword">true</span>,
<span class="tx-string">'tx_hash'</span> => $txHash,
<span class="tx-string">'amount_added'</span> => $amount,
]);
} <span class="tx-keyword">catch</span> (Exception $e) {
<span class="tx-keyword">return</span> response()->json([
<span class="tx-string">'error'</span> => $e->getMessage()
], 500);
}
}
}
routes/api.php에 추가:
<span class="tx-keyword">use</span> App\Http\Controllers\BlockchainController;
Route::prefix(<span class="tx-string">'blockchain'</span>)->group(<span class="tx-keyword">function</span> () {
Route::get(<span class="tx-string">'/status'</span>, [BlockchainController::class, <span class="tx-string">'status'</span>]);
Route::get(<span class="tx-string">'/value'</span>, [BlockchainController::class, <span class="tx-string">'getValue'</span>]);
Route::post(<span class="tx-string">'/value'</span>, [BlockchainController::class, <span class="tx-string">'setValue'</span>]);
Route::post(<span class="tx-string">'/increment'</span>, [BlockchainController::class, <span class="tx-string">'increment'</span>]);
});
이제 진짜 꽃이에요! 🌸 라라벨의 PHPUnit 테스트로 스마트 컨트랙트 호출을 자동화 테스트해볼게요.
이게 되면 CI/CD 파이프라인에도 붙일 수 있어서 진짜 프로처럼 개발할 수 있어요 ㅋㅋㅋ
1️⃣ view 함수는 실제 로컬 노드에 call 해서 테스트
2️⃣ 트랜잭션 함수는 Mock 처리하거나 Hardhat의 빠른 마이닝 활용
로컬 Hardhat은 트랜잭션이 즉시 마이닝되니까 생각보다 빠름!
tests/Feature/BlockchainTest.php:
<span class="tx-tag"><?php</span>
<span class="tx-keyword">namespace</span> Tests\Feature;
<span class="tx-keyword">use</span> Tests\TestCase;
<span class="tx-keyword">use</span> App\Services\Web3Service;
<span class="tx-keyword">use</span> App\Services\SimpleStorageService;
<span class="tx-keyword">use</span> Illuminate\Foundation\Testing\WithFaker;
<span class="tx-keyword">class</span> <span class="tx-func">BlockchainTest</span> <span class="tx-keyword">extends</span> TestCase
{
<span class="tx-keyword">use</span> WithFaker;
<span class="tx-keyword">protected</span> Web3Service $web3Service;
<span class="tx-keyword">protected</span> SimpleStorageService $storageService;
<span class="tx-keyword">protected function</span> <span class="tx-func">setUp</span>(): <span class="tx-keyword">void</span>
{
<span class="tx-keyword">parent</span>::setUp();
<span class="tx-comment">// 로컬 블록체인이 실행 중인지 확인</span>
<span class="tx-keyword">if</span> (!$this->isBlockchainRunning()) {
$this->markTestSkipped(
<span class="tx-string">'로컬 블록체인이 실행되지 않았습니다. npx hardhat node를 먼저 실행하세요.'</span>
);
}
$this->web3Service = app(Web3Service::class);
$this->storageService = app(SimpleStorageService::class);
}
<span class="tx-comment">/**
* 블록체인 연결 테스트
*/</span>
<span class="tx-keyword">public function</span> <span class="tx-func">test_can_connect_to_blockchain</span>(): <span class="tx-keyword">void</span>
{
$blockNumber = $this->web3Service->getBlockNumber();
$this->assertIsInt($blockNumber);
$this->assertGreaterThanOrEqual(0, $blockNumber);
echo <span class="tx-string">"\n✅ 현재 블록 번호: {$blockNumber}"</span>;
}
<span class="tx-comment">/**
* 계정 잔액 조회 테스트
*/</span>
<span class="tx-keyword">public function</span> <span class="tx-func">test_can_get_account_balance</span>(): <span class="tx-keyword">void</span>
{
$address = config(<span class="tx-string">'web3.accounts.deployer.address'</span>);
$balance = $this->web3Service->getBalance($address);
$this->assertIsString($balance);
$this->assertGreaterThan(0, (float) $balance);
echo <span class="tx-string">"\n✅ 잔액: {$balance} ETH"</span>;
}
<span class="tx-comment">/**
* getValue() 호출 테스트
*/</span>
<span class="tx-keyword">public function</span> <span class="tx-func">test_can_get_value_from_contract</span>(): <span class="tx-keyword">void</span>
{
$value = $this->storageService->getValue();
$this->assertIsInt($value);
$this->assertGreaterThanOrEqual(0, $value);
echo <span class="tx-string">"\n✅ 현재 저장된 값: {$value}"</span>;
}
<span class="tx-comment">/**
* getMessage() 호출 테스트
*/</span>
<span class="tx-keyword">public function</span> <span class="tx-func">test_can_get_message_from_contract</span>(): <span class="tx-keyword">void</span>
{
$message = $this->storageService->getMessage();
$this->assertIsString($message);
$this->assertNotEmpty($message);
echo <span class="tx-string">"\n✅ 저장된 메시지: {$message}"</span>;
}
<span class="tx-comment">/**
* setValue() 트랜잭션 테스트
*/</span>
<span class="tx-keyword">public function</span> <span class="tx-func">test_can_set_value_via_transaction</span>(): <span class="tx-keyword">void</span>
{
$newValue = rand(100, 9999);
<span class="tx-comment">// 트랜잭션 전송</span>
$txHash = $this->storageService->setValue($newValue);
$this->assertNotEmpty($txHash);
$this->assertStringStartsWith(<span class="tx-string">'0x'</span>, $txHash);
<span class="tx-comment">// 잠깐 대기 (블록 마이닝 시간)</span>
sleep(1);
<span class="tx-comment">// 값이 실제로 변경됐는지 확인</span>
$currentValue = $this->storageService->getValue();
$this->assertEquals($newValue, $currentValue);
echo <span class="tx-string">"\n✅ 값 설정 성공: {$newValue}, TX: {$txHash}"</span>;
}
<span class="tx-comment">/**
* increment() 테스트
*/</span>
<span class="tx-keyword">public function</span> <span class="tx-func">test_can_increment_value</span>(): <span class="tx-keyword">void</span>
{
<span class="tx-comment">// 현재 값 저장</span>
$beforeValue = $this->storageService->getValue();
$incrementAmount = 10;
<span class="tx-comment">// increment 실행</span>
$txHash = $this->storageService->increment($incrementAmount);
$this->assertNotEmpty($txHash);
sleep(1);
<span class="tx-comment">// 값이 증가했는지 확인</span>
$afterValue = $this->storageService->getValue();
$this->assertEquals($beforeValue + $incrementAmount, $afterValue);
echo <span class="tx-string">"\n✅ 증가 성공: {$beforeValue} → {$afterValue}"</span>;
}
<span class="tx-comment">/**
* API 엔드포인트 테스트
*/</span>
<span class="tx-keyword">public function</span> <span class="tx-func">test_blockchain_status_api</span>(): <span class="tx-keyword">void</span>
{
$response = $this->getJson(<span class="tx-string">'/api/blockchain/status'</span>);
$response->assertStatus(200)
->assertJsonStructure([
<span class="tx-string">'status'</span>,
<span class="tx-string">'block_number'</span>,
<span class="tx-string">'deployer_balance'</span>,
])
->assertJson([<span class="tx-string">'status'</span> => <span class="tx-string">'connected'</span>]);
}
<span class="tx-comment">/**
* 로컬 블록체인 실행 여부 확인
*/</span>
<span class="tx-keyword">private function</span> <span class="tx-func">isBlockchainRunning</span>(): <span class="tx-keyword">bool</span>
{
<span class="tx-keyword">try</span> {
$rpcUrl = config(<span class="tx-string">'web3.rpc_url'</span>);
$ch = curl_init($rpcUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, <span class="tx-keyword">true</span>);
curl_setopt($ch, CURLOPT_TIMEOUT, 3);
curl_setopt($ch, CURLOPT_POST, <span class="tx-keyword">true</span>);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
<span class="tx-string">'jsonrpc'</span> => <span class="tx-string">'2.0'</span>,
<span class="tx-string">'method'</span> => <span class="tx-string">'eth_blockNumber'</span>,
<span class="tx-string">'params'</span> => [],
<span class="tx-string">'id'</span> => 1
]));
curl_setopt($ch, CURLOPT_HTTPHEADER, [<span class="tx-string">'Content-Type: application/json'</span>]);
$result = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
<span class="tx-keyword">return</span> $httpCode === 200 && $result !== <span class="tx-keyword">false</span>;
} <span class="tx-keyword">catch</span> (Exception $e) {
<span class="tx-keyword">return false</span>;
}
}
}
<span class="tx-comment"># 전체 테스트 실행</span>
php artisan test
<span class="tx-comment"># 특정 테스트 파일만 실행</span>
php artisan test tests/Feature/BlockchainTest.php
<span class="tx-comment"># 상세 출력과 함께</span>
php artisan test tests/Feature/BlockchainTest.php --verbose
<span class="tx-comment"># 성공 시 출력 예시:</span>
<span class="tx-comment"># PASS Tests\Feature\BlockchainTest</span>
<span class="tx-comment"># ✓ can connect to blockchain</span>
<span class="tx-comment"># ✓ can get account balance</span>
<span class="tx-comment"># ✓ can get value from contract</span>
<span class="tx-comment"># ✓ can get message from contract</span>
<span class="tx-comment"># ✓ can set value via transaction</span>
<span class="tx-comment"># ✓ can increment value</span>
<span class="tx-comment"># ✓ blockchain status api</span>
<span class="tx-comment">#</span>
<span class="tx-comment"># Tests: 7 passed (14 assertions)</span>
이제 GitHub Actions 같은 CI/CD에 붙이면 자동화 테스트도 가능해요 🎉
실제 블록체인 연결 없이도 테스트하고 싶을 때가 있죠?
CI/CD 환경에서 Hardhat 노드를 매번 띄우기 어려울 때 특히 유용해요!
라라벨의 Mock 기능을 활용해서 Web3 서비스를 가짜로 대체하는 방법을 알아볼게요 😎
tests/Unit/SimpleStorageServiceTest.php:
<span class="tx-tag"><?php</span>
<span class="tx-keyword">namespace</span> Tests\Unit;
<span class="tx-keyword">use</span> Tests\TestCase;
<span class="tx-keyword">use</span> App\Services\Web3Service;
<span class="tx-keyword">use</span> App\Services\SimpleStorageService;
<span class="tx-keyword">use</span> Mockery;
<span class="tx-keyword">class</span> <span class="tx-func">SimpleStorageServiceTest</span> <span class="tx-keyword">extends</span> TestCase
{
<span class="tx-comment">/**
* Mock을 사용한 getValue 테스트
*/</span>
<span class="tx-keyword">public function</span> <span class="tx-func">test_get_value_returns_correct_type</span>(): <span class="tx-keyword">void</span>
{
<span class="tx-comment">// SimpleStorageService를 Mock으로 대체</span>
$mockService = Mockery::mock(SimpleStorageService::class);
$mockService->shouldReceive(<span class="tx-string">'getValue'</span>)
->once()
->andReturn(42);
$this->app->instance(SimpleStorageService::class, $mockService);
$service = app(SimpleStorageService::class);
$value = $service->getValue();
$this->assertEquals(42, $value);
$this->assertIsInt($value);
}
<span class="tx-comment">/**
* Mock을 사용한 setValue 테스트
*/</span>
<span class="tx-keyword">public function</span> <span class="tx-func">test_set_value_returns_tx_hash</span>(): <span class="tx-keyword">void</span>
{
$fakeTxHash = <span class="tx-string">'0xabc123def456789...'</span>;
$mockService = Mockery::mock(SimpleStorageService::class);
$mockService->shouldReceive(<span class="tx-string">'setValue'</span>)
->with(100)
->once()
->andReturn($fakeTxHash);
$this->app->instance(SimpleStorageService::class, $mockService);
$service = app(SimpleStorageService::class);
$txHash = $service->setValue(100);
$this->assertEquals($fakeTxHash, $txHash);
$this->assertStringStartsWith(<span class="tx-string">'0x'</span>, $txHash);
}
<span class="tx-comment">/**
* API 엔드포인트 Mock 테스트
*/</span>
<span class="tx-keyword">public function</span> <span class="tx-func">test_get_value_api_with_mock</span>(): <span class="tx-keyword">void</span>
{
$mockService = Mockery::mock(SimpleStorageService::class);
$mockService->shouldReceive(<span class="tx-string">'getValue'</span>)->andReturn(777);
$mockService->shouldReceive(<span class="tx-string">'getMessage'</span>)->andReturn(<span class="tx-string">'Hello Mock!'</span>);
$this->app->instance(SimpleStorageService::class, $mockService);
$response = $this->getJson(<span class="tx-string">'/api/blockchain/value'</span>);
$response->assertStatus(200)
->assertJson([
<span class="tx-string">'value'</span> => 777,
<span class="tx-string">'message'</span> => <span class="tx-string">'Hello Mock!'</span>,
]);
}
<span class="tx-keyword">protected function</span> <span class="tx-func">tearDown</span>(): <span class="tx-keyword">void</span>
{
Mockery::close();
<span class="tx-keyword">parent</span>::tearDown();
}
}
Feature 테스트: 실제 로컬 블록체인 연결 → 통합 테스트. 개발 환경에서 실행.
E2E 테스트: 테스트넷(Sepolia 등) 연결 → 실제 네트워크 환경 검증.
이 부분이 진짜 꿀팁이에요 ㅋㅋㅋ 삽질을 줄여드릴게요!
실제로 개발하다 보면 이런 에러들을 엄청 많이 만나거든요 😅
<span class="tx-comment">// 에러 메시지</span>
<span class="tx-tag">cURL error 7: Failed to connect to 127.0.0.1 port 8545</span>
cd blockchain && npx hardhat node를 먼저 실행하세요.또는
.env의 WEB3_RPC_URL이 잘못 설정된 경우도 있어요.
<span class="tx-comment">// 에러 메시지</span>
<span class="tx-tag">컨트랙트 파일을 찾을 수 없습니다: .../storage/app/contracts/SimpleStorage.json</span>
배포 스크립트를 아직 실행하지 않았거나, Hardhat 노드를 재시작해서 이전 배포가 사라진 경우예요.
npx hardhat run scripts/deploy.js --network localhost를 다시 실행하세요.
<span class="tx-comment">// 에러 메시지</span>
<span class="tx-tag">TypeError: Cannot read properties of undefined (reading 'inputs')</span>
storage/app/contracts/SimpleStorage.json의 abi 배열을 직접 확인해보세요.함수명 오타도 자주 있으니 꼭 체크!
<span class="tx-comment">// 에러 메시지</span>
<span class="tx-tag">Error: Nonce too low. Expected nonce to be X but got Y</span>
Hardhat 노드를 완전히 재시작하거나, 트랜잭션 전송 시 nonce를 명시적으로 지정하세요.
<span class="tx-comment">// 에러 메시지</span>
<span class="tx-tag">Call to undefined function bcdiv()</span>
sudo apt-get install php8.x-bcmath 또는 php.ini에서 extension=bcmath 활성화하세요.
<span class="tx-comment">// JSON-RPC 직접 테스트 (curl로 확인)</span>
curl -X POST http://127.0.0.1:8545 \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}'
<span class="tx-comment">// 응답 예시:</span>
<span class="tx-comment">// {"jsonrpc":"2.0","id":1,"result":"0x5"}</span>
<span class="tx-comment">// 컨트랙트 call 직접 테스트</span>
curl -X POST http://127.0.0.1:8545 \
-H "Content-Type: application/json" \
-d '{
"jsonrpc":"2.0",
"method":"eth_call",
"params":[{
"to":"0x5FbDB2315678afecb367f032d93F642f64180aa3",
"data":"0x20965255"
},"latest"],
"id":1
}'
getValue() 함수의 함수 셀렉터예요!함수 시그니처
getValue()를 Keccak-256 해시한 후 앞 4바이트를 16진수로 표현한 값이에요.Web3.php가 내부적으로 이걸 자동으로 계산해줘요 😊
기본 호출은 됐으니 이제 좀 더 심화된 내용으로 가볼게요!
실제 프로덕션 환경에서 자주 쓰이는 패턴들이에요 💪
트랜잭션을 보낸 후 실제로 처리됐는지 확인하는 방법:
<span class="tx-comment">// Web3Service에 추가</span>
<span class="tx-keyword">public function</span> <span class="tx-func">getTransactionReceipt</span>(<span class="tx-keyword">string</span> $txHash): ?<span class="tx-keyword">array</span>
{
$receipt = <span class="tx-keyword">null</span>;
$this->web3->eth->getTransactionReceipt($txHash,
<span class="tx-keyword">function</span> ($err, $result) <span class="tx-keyword">use</span> (&$receipt) {
<span class="tx-keyword">if</span> ($err !== <span class="tx-keyword">null</span>) {
<span class="tx-keyword">throw new</span> <span class="tx-func">Exception</span>($err->getMessage());
}
<span class="tx-keyword">if</span> ($result !== <span class="tx-keyword">null</span>) {
$receipt = [
<span class="tx-string">'transactionHash'</span> => $result->transactionHash,
<span class="tx-string">'blockNumber'</span> => hexdec($result->blockNumber),
<span class="tx-string">'gasUsed'</span> => hexdec($result->gasUsed),
<span class="tx-string">'status'</span> => hexdec($result->status) === 1 ? <span class="tx-string">'success'</span> : <span class="tx-string">'failed'</span>,
<span class="tx-string">'logs'</span> => $result->logs ?? [],
];
}
}
);
<span class="tx-keyword">return</span> $receipt;
}
<span class="tx-comment">/**
* 트랜잭션 완료까지 폴링 (최대 30초)
*/</span>
<span class="tx-keyword">public function</span> <span class="tx-func">waitForTransaction</span>(<span class="tx-keyword">string</span> $txHash, <span class="tx-keyword">int</span> $timeout = 30): <span class="tx-keyword">array</span>
{
$startTime = time();
<span class="tx-keyword">while</span> (time() - $startTime < $timeout) {
$receipt = $this->getTransactionReceipt($txHash);
<span class="tx-keyword">if</span> ($receipt !== <span class="tx-keyword">null</span>) {
<span class="tx-keyword">return</span> $receipt;
}
usleep(500000); <span class="tx-comment">// 0.5초 대기</span>
}
<span class="tx-keyword">throw new</span> <span class="tx-func">Exception</span>(<span class="tx-string">"트랜잭션 타임아웃: {$txHash}"</span>);
}
<span class="tx-comment">// SimpleStorageService에 추가</span>
<span class="tx-keyword">public function</span> <span class="tx-func">getValueChangedEvents</span>(<span class="tx-keyword">int</span> $fromBlock = 0): <span class="tx-keyword">array</span>
{
$events = [];
$error = <span class="tx-keyword">null</span>;
<span class="tx-comment">// ValueChanged 이벤트 토픽 (keccak256 해시)</span>
<span class="tx-comment">// ValueChanged(address,uint256,uint256) 의 해시</span>
$eventTopic = <span class="tx-string">'0x'</span> . keccak256(<span class="tx-string">'ValueChanged(address,uint256,uint256)'</span>);
$this->web3Service->getWeb3()->eth->getLogs([
<span class="tx-string">'fromBlock'</span> => <span class="tx-string">'0x'</span> . dechex($fromBlock),
<span class="tx-string">'toBlock'</span> => <span class="tx-string">'latest'</span>,
<span class="tx-string">'address'</span> => $this->contractAddress,
<span class="tx-string">'topics'</span> => [$eventTopic],
], <span class="tx-keyword">function</span> ($err, $result) <span class="tx-keyword">use</span> (&$events, &$error) {
<span class="tx-keyword">if</span> ($err !== <span class="tx-keyword">null</span>) {
$error = $err->getMessage();
<span class="tx-keyword">return</span>;
}
<span class="tx-keyword">foreach</span> ($result <span class="tx-keyword">as</span> $log) {
$events[] = [
<span class="tx-string">'blockNumber'</span> => hexdec($log->blockNumber),
<span class="tx-string">'txHash'</span> => $log->transactionHash,
<span class="tx-comment">// topics[1]: caller 주소 (indexed)</span>
<span class="tx-string">'caller'</span> => <span class="tx-string">'0x'</span> . substr($log->topics[1], 26),
<span class="tx-comment">// data: oldValue + newValue (non-indexed)</span>
<span class="tx-string">'rawData'</span> => $log->data,
];
}
});
<span class="tx-keyword">if</span> ($error) {
<span class="tx-keyword">throw new</span> <span class="tx-func">Exception</span>(<span class="tx-string">'이벤트 조회 실패: '</span> . $error);
}
<span class="tx-keyword">return</span> $events;
}
트랜잭션은 시간이 걸리니까 라라벨 큐(Queue)와 함께 쓰면 훨씬 좋아요!
<span class="tx-tag"><?php</span>
<span class="tx-keyword">namespace</span> App\Jobs;
<span class="tx-keyword">use</span> App\Services\SimpleStorageService;
<span class="tx-keyword">use</span> Illuminate\Bus\Queueable;
<span class="tx-keyword">use</span> Illuminate\Contracts\Queue\ShouldQueue;
<span class="tx-keyword">use</span> Illuminate\Foundation\Bus\Dispatchable;
<span class="tx-keyword">use</span> Illuminate\Queue\InteractsWithQueue;
<span class="tx-keyword">use</span> Illuminate\Queue\SerializesModels;
<span class="tx-keyword">use</span> Illuminate\Support\Facades\Log;
<span class="tx-keyword">class</span> <span class="tx-func">SetContractValueJob</span> <span class="tx-keyword">implements</span> ShouldQueue
{
<span class="tx-keyword">use</span> Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
<span class="tx-keyword">public int</span> $tries = 3;
<span class="tx-keyword">public int</span> $timeout = 60;
<span class="tx-keyword">public function</span> <span class="tx-func">__construct</span>(
<span class="tx-keyword">private readonly int</span> $value,
<span class="tx-keyword">private readonly</span> ?<span class="tx-keyword">string</span> $callbackUrl = <span class="tx-keyword">null</span>
) {}
<span class="tx-keyword">public function</span> <span class="tx-func">handle</span>(SimpleStorageService $storageService): <span class="tx-keyword">void</span>
{
<span class="tx-keyword">try</span> {
$txHash = $storageService->setValue($this->value);
Log::info(<span class="tx-string">'컨트랙트 값 설정 성공'</span>, [
<span class="tx-string">'value'</span> => $this->value,
<span class="tx-string">'tx_hash'</span> => $txHash,
]);
<span class="tx-comment">// 콜백 URL이 있으면 결과 전송</span>
<span class="tx-keyword">if</span> ($this->callbackUrl) {
Http::post($this->callbackUrl, [
<span class="tx-string">'status'</span> => <span class="tx-string">'success'</span>,
<span class="tx-string">'tx_hash'</span> => $txHash,
<span class="tx-string">'value'</span> => $this->value,
]);
}
} <span class="tx-keyword">catch</span> (Exception $e) {
Log::error(<span class="tx-string">'컨트랙트 값 설정 실패'</span>, [
<span class="tx-string">'error'</span> => $e->getMessage(),
<span class="tx-string">'value'</span> => $this->value,
]);
<span class="tx-keyword">throw</span> $e;
}
}
}
<span class="tx-comment">// 컨트롤러에서 사용:</span>
<span class="tx-comment">// SetContractValueJob::dispatch(100, 'https://callback.url/webhook');</span>
재능넷 같은 플랫폼에서 블록체인 기능을 개발할 때 실제로 도움이 되는 팁들을 모아봤어요!
이거 알면 개발 속도가 확 올라가요 ㅋㅋㅋ 🚀
laravel-web3-test/
├── app/
│ ├── Http/
│ │ └── Controllers/
│ │ └── BlockchainController.php
│ ├── Jobs/
│ │ └── SetContractValueJob.php
│ ├── Providers/
│ │ └── Web3ServiceProvider.php
│ └── Services/
│ ├── Web3Service.php <span class="tx-comment"># 기본 Web3 연결</span>
│ └── SimpleStorageService.php <span class="tx-comment"># 컨트랙트별 서비스</span>
├── blockchain/ <span class="tx-comment"># Hardhat 프로젝트</span>
│ ├── contracts/
│ │ └── SimpleStorage.sol
│ ├── scripts/
│ │ └── deploy.js
│ ├── test/
│ │ └── SimpleStorage.test.js
│ └── hardhat.config.js
├── config/
│ └── web3.php
├── storage/
│ └── app/
│ └── contracts/
│ └── SimpleStorage.json <span class="tx-comment"># 배포 후 자동 생성</span>
└── tests/
├── Feature/
│ └── BlockchainTest.php
└── Unit/
└── SimpleStorageServiceTest.php
Web3Service를 싱글톤으로 등록해서 요청마다 새 연결을 만들지 않도록 해요. 이미 위에서 했죠? 😊
블록체인 상태가 자주 바뀌지 않는 데이터는 라라벨 캐시를 활용해요.
<span class="tx-keyword">public function</span> <span class="tx-func">getValueCached</span>(): <span class="tx-keyword">int</span>
{
<span class="tx-keyword">return</span> Cache::remember(<span class="tx-string">'contract.simple_storage.value'</span>, 30, <span class="tx-keyword">function</span> () {
<span class="tx-keyword">return</span> $this->getValue();
});
}
<span class="tx-comment">// 트랜잭션 후 캐시 무효화</span>
<span class="tx-keyword">public function</span> <span class="tx-func">setValueAndClearCache</span>(<span class="tx-keyword">int</span> $value): <span class="tx-keyword">string</span>
{
$txHash = $this->setValue($value);
Cache::forget(<span class="tx-string">'contract.simple_storage.value'</span>);
<span class="tx-keyword">return</span> $txHash;
}
블록체인 관련 에러를 일관되게 처리하는 미들웨어를 만들어요.
.env.testing에 테스트용 설정을 따로 관리해요.
<span class="tx-comment"># .env.testing</span>
<span class="tx-var">WEB3_RPC_URL</span>=http://127.0.0.1:8545
<span class="tx-var">WEB3_CHAIN_ID</span>=31337
<span class="tx-comment"># .env.production (예시 - 실제 테스트넷)</span>
<span class="tx-var">WEB3_RPC_URL</span>=https://sepolia.infura.io/v3/YOUR_PROJECT_ID
<span class="tx-var">WEB3_CHAIN_ID</span>=11155111
2. Hardhat 기본 계정의 프라이빗 키를 실제 환경에 사용 — 이건 공개된 키라 누구나 알아요!
3. .env 파일을 git에 커밋 — .gitignore에 반드시 포함!
4. 프론트엔드에서 프라이빗 키 노출 — 서버 사이드에서만 처리해야 해요.
package.json에 편리한 스크립트를 추가해요:
{
<span class="tx-string">"scripts"</span>: {
<span class="tx-string">"node"</span>: <span class="tx-string">"hardhat node"</span>,
<span class="tx-string">"compile"</span>: <span class="tx-string">"hardhat compile"</span>,
<span class="tx-string">"deploy:local"</span>: <span class="tx-string">"hardhat run scripts/deploy.js --network localhost"</span>,
<span class="tx-string">"deploy:ganache"</span>: <span class="tx-string">"hardhat run scripts/deploy.js --network ganache"</span>,
<span class="tx-string">"test"</span>: <span class="tx-string">"hardhat test"</span>,
<span class="tx-string">"test:coverage"</span>: <span class="tx-string">"hardhat coverage"</span>,
<span class="tx-string">"setup:local"</span>: <span class="tx-string">"npm run compile && npm run deploy:local"</span>
}
}
cd blockchain && npm run node (Hardhat 노드 실행)2. 터미널 2:
cd blockchain && npm run setup:local (컴파일 + 배포)3. 터미널 3:
php artisan serve (라라벨 서버 실행)4. 터미널 4:
php artisan test tests/Feature/BlockchainTest.php (테스트 실행)이 4개 터미널 구성이 개발할 때 제일 편해요 ㅋㅋㅋ
로컬 테스트가 완료됐으면 이제 실제 테스트넷에 배포해볼 차례예요!
Sepolia 테스트넷은 이더리움의 공식 테스트넷으로 실제 네트워크 환경과 거의 동일해요 🌍
<span class="tx-comment"># .env에 추가</span>
<span class="tx-var">INFURA_PROJECT_ID</span>=your_infura_project_id
<span class="tx-var">WEB3_SEPOLIA_RPC_URL</span>=https://sepolia.infura.io/v3/${INFURA_PROJECT_ID}
<span class="tx-var">WEB3_SEPOLIA_CHAIN_ID</span>=11155111
<span class="tx-comment">// hardhat.config.js에 Sepolia 추가</span>
networks: {
sepolia: {
url: process.env.WEB3_SEPOLIA_RPC_URL,
accounts: [process.env.WEB3_DEPLOYER_PRIVATE_KEY],
chainId: 11155111
}
}
<span class="tx-comment">// 배포 명령어</span>
<span class="tx-comment">// npx hardhat run scripts/deploy.js --network sepolia</span>
Alchemy 계정이 있으면 하루에 0.5 ETH까지 받을 수 있어요!
config/web3.php를 환경별로 자동 전환되도록 개선:
<span class="tx-tag"><?php</span>
$network = env(<span class="tx-string">'WEB3_NETWORK'</span>, <span class="tx-string">'local'</span>);
$networks = [
<span class="tx-string">'local'</span> => [
<span class="tx-string">'rpc_url'</span> => <span class="tx-string">'http://127.0.0.1:8545'</span>,
<span class="tx-string">'chain_id'</span> => 31337,
],
<span class="tx-string">'ganache'</span> => [
<span class="tx-string">'rpc_url'</span> => <span class="tx-string">'http://127.0.0.1:7545'</span>,
<span class="tx-string">'chain_id'</span> => 1337,
],
<span class="tx-string">'sepolia'</span> => [
<span class="tx-string">'rpc_url'</span> => env(<span class="tx-string">'WEB3_SEPOLIA_RPC_URL'</span>),
<span class="tx-string">'chain_id'</span> => 11155111,
],
];
<span class="tx-keyword">return</span> array_merge(
[
<span class="tx-string">'network'</span> => $network,
<span class="tx-string">'default_gas'</span> => (int) env(<span class="tx-string">'WEB3_DEFAULT_GAS'</span>, 3000000),
<span class="tx-string">'accounts'</span> => [
<span class="tx-string">'deployer'</span> => [
<span class="tx-string">'address'</span> => env(<span class="tx-string">'WEB3_DEPLOYER_ADDRESS'</span>),
<span class="tx-string">'private_key'</span> => env(<span class="tx-string">'WEB3_DEPLOYER_PRIVATE_KEY'</span>),
],
],
<span class="tx-string">'contracts'</span> => [
<span class="tx-string">'simple_storage'</span> => env(
<span class="tx-string">'CONTRACT_SIMPLE_STORAGE'</span>,
<span class="tx-string">'storage/app/contracts/SimpleStorage.json'</span>
),
],
],
$networks[$network] ?? $networks[<span class="tx-string">'local'</span>]
);
와 여기까지 따라오셨다면 진짜 대단해요! 👏
라라벨에서 스마트 컨트랙트 호출 테스트 환경을 완전히 구성한 거예요.
마지막으로 전체 흐름을 한 번 더 정리해볼게요!
| 구성 요소 | 역할 | 핵심 포인트 |
|---|---|---|
| Hardhat Node | 로컬 이더리움 시뮬레이터 | 포트 8545, 재시작 시 초기화 |
| Web3.php | PHP ↔ 블록체인 통신 | call(view) vs send(트랜잭션) 구분 |
| ABI | 컨트랙트 인터페이스 정의 | 배포 시 자동으로 storage에 저장 |
| Web3Service | 기본 Web3 연결 관리 | 싱글톤으로 등록 |
| ContractService | 컨트랙트별 비즈니스 로직 | 컨트랙트마다 전용 서비스 클래스 |
| PHPUnit 테스트 | 자동화 테스트 | Feature(실제) + Unit(Mock) 병행 |
재능넷 같은 플랫폼에서 NFT 발행이나 토큰 전송 기능을 붙일 때도 이 패턴 그대로 확장하면 돼요!
Web3.php의 한계(비동기 처리 등)가 있긴 하지만, PHP 백엔드에서 블록체인 연동하는 데는 충분히 실용적이에요 💪
✅ Web3.php로 스마트 컨트랙트 call/send 호출 가능
✅ PHPUnit으로 블록체인 연동 자동화 테스트 가능
✅ Mock을 활용한 단위 테스트 작성 가능
✅ 테스트넷으로 확장하는 방법 이해
블록체인 개발의 세계에 오신 걸 환영해요! 🚀
이 글에서 다룬 내용들을 실제 프로젝트에 적용하다 보면 더 다양한 케이스를 만나게 될 거예요.
ERC-20 토큰 컨트랙트 연동, ERC-721 NFT 민팅, 멀티시그 지갑 연동 등 — 모두 이 기본 패턴에서 확장되는 거예요.
재능넷의 지식인의 숲에서 더 많은 Web3 개발 가이드를 찾아보세요! 🌲
관련 키워드
댓글 작성
이 글에 대한 여러분의 생각을 들려주세요
로그인이 필요합니다
댓글을 작성하려면 먼저 로그인해주세요.
댓글 0
지식인의 숲 - 지적 재산권 보호 고지
지적 재산권 보호 고지
- 저작권 및 소유권: 본 컨텐츠는 재능넷의 독점 AI 기술로 생성되었으며, 대한민국 저작권법 및 국제 저작권 협약에 의해 보호됩니다.
- AI 생성 컨텐츠의 법적 지위: 본 AI 생성 컨텐츠는 재능넷의 지적 창작물로 인정되며, 관련 법규에 따라 저작권 보호를 받습니다.
- 사용 제한: 재능넷의 명시적 서면 동의 없이 본 컨텐츠를 복제, 수정, 배포, 또는 상업적으로 활용하는 행위는 엄격히 금지됩니다.
- 데이터 수집 금지: 본 컨텐츠에 대한 무단 스크래핑, 크롤링, 및 자동화된 데이터 수집은 법적 제재의 대상이 됩니다.
- AI 학습 제한: 재능넷의 AI 생성 컨텐츠를 타 AI 모델 학습에 무단 사용하는 행위는 금지되며, 이는 지적 재산권 침해로 간주됩니다.
아직 댓글이 없습니다.