🔧 연동 흐름
1. front end
<button id="connect-metamask">MetaMask 연결</button>
<script>
document.getElementById('connect-metamask').addEventListener('click', async () => {
if (typeof window.ethereum !== 'undefined') {
try {
const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
const address = accounts[0];
console.log("사용자 지갑 주소:", address);
// 서버로 전송 예시 (ajax)
fetch('/metamask-connect', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({address}),
});
} catch (err) {
console.error("MetaMask 연결 실패", err);
}
} else {
alert('MetaMask가 설치되어 있지 않습니다.');
}
});
</script>
2. back end
namespace Eccube\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
class MetaMaskController extends AbstractController
{
/**
* @Route("/metamask-connect", name="metamask_connect", methods={"POST"})
*/
public function connect(Request $request)
{
$data = json_decode($request->getContent(), true);
$address = $data['address'] ?? null;
if ($address) {
// 예: DB 저장, 사용자 세션 연결 등
return new JsonResponse(['success' => true, 'address' => $address]);
}
return new JsonResponse(['success' => false], 400);
}
}
🔹 3) CSRF 예외 처리 (필요 시)
Symfony는 POST 요청에 CSRF 토큰을 요구하므로, API용 라우트는 예외 설정 필요.
src/Eccube/EventListener/CsrfValidationListener.php 또는 설정파일에 /metamask-connect 예외 처리
MetaMask: The Leading Crypto Wallet Platform, Blockchain Wallet
Set up your crypto wallet and access all of Web3 and enjoy total control over your data, assets, and digital self. The go-to web3 wallet for 100+ million users.
metamask.io
- MetaMask Wallet API 개요: 이 문서에서는 MetaMask의 Wallet API가 Ethereum provider API와 JSON-RPC API로 구성되어 있으며, window.ethereum 객체를 통해 dapp과 MetaMask 간의 상호작용을 가능하게 한다고 설명합니다. 주요 기능으로는 사용자 계정 접근, 트랜잭션 서명, 네트워크 관리 등이 포함됩니다.
- JSON-RPC API 참조: MetaMask의 Wallet API는 JSON-RPC API를 래핑하여 다양한 메서드를 제공합니다. 이 문서에서는 표준 Ethereum JSON-RPC 메서드와 MetaMask 고유의 메서드에 대한 정보를 제공합니다
https://docs.metamask.io/wallet/concepts/wallet-api/?utm_source=chatgpt.com
About the Wallet API | MetaMask developer documentation
Learn about the MetaMask Ethereum provider API and JSON-RPC API.
docs.metamask.io
- Ethereum Provider API 참조 : Ethereum Provider API는 MetaMask의 Wallet API의 핵심 구성 요소로, dApp이 사용자의 MetaMask 지갑과 상호 작용할 수 있도록 지원합니다. 이 API는 window.ethereum 객체를 통해 제공되며, 계정 요청, 트랜잭션 서명, 네트워크 상태 감지 등 다양한 기능을 제공합니다.
- 계정 요청: 사용자의 계정 정보를 요청할 수 있습니다.
- 트랜잭션 서명: 사용자에게 트랜잭션 서명을 요청할 수 있습니다.
- 네트워크 감지: 사용자가 연결된 네트워크 정보를 확인할 수 있습니다.
- 이벤트 리스닝: 계정 변경, 네트워크 변경 등의 이벤트를 감지할 수 있습니다.
EIP-1193 : Ethereum Provider JavaScript API 표준 : https://eips.ethereum.org/EIPS/eip-1193?utm_source=chatgpt.com
MetaMask Ethereum Provider API : https://docs.metamask.io/wallet/reference/provider-api/?utm_source=chatgpt.com
https://docs.senderwallet.io/api-reference/ethereum/ethereum-provider-api?utm_source=chatgpt.com
Ethereum provider API | MetaMask developer documentation
See the MetaMask Ethereum provider API reference.
docs.metamask.io
// MetaMask 설치 여부 확인
if (window.ethereum && window.ethereum.isMetaMask) {
// 계정 요청
const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
console.log('사용자 계정:', accounts[0]);
// 네트워크 ID 확인
const chainId = await window.ethereum.request({ method: 'eth_chainId' });
console.log('현재 네트워크 ID:', chainId);
// 계정 변경 이벤트 리스닝
window.ethereum.on('accountsChanged', (accounts) => {
console.log('계정 변경됨:', accounts);
});
// 네트워크 변경 이벤트 리스닝
window.ethereum.on('chainChanged', (chainId) => {
console.log('네트워크 변경됨:', chainId);
});
} else {
console.log('MetaMask가 설치되어 있지 않습니다.');
}
About the Wallet API | MetaMask developer documentation
Learn about the MetaMask Ethereum provider API and JSON-RPC API.
docs.metamask.io