워드프레스

메타마스크 토큰 추가하기 스크립트 (워드프레스)

파이트인포2023 2024. 8. 20. 15:56
반응형

1.워드프레스 버튼id에 : addToken를 입력한다.

2.워드프레스 플러그인을 설치한다. " Insert Headers and Footers"

3.푸터에 아래의 코드를 붙여 넣고, 알맞게 수정한다.

4.체인에 맞게 수정 필요.

<script>
document.addEventListener('DOMContentLoaded', function() {
    const addTokenBtn = document.getElementById('addToken');
    if (addTokenBtn) {
        addTokenBtn.addEventListener('click', function(event) {
            event.preventDefault();
            switchToEthereumChain();
        });
    }
});

async function switchToEthereumChain() {
    const chainId = '0x1'; // Ethereum Mainnet의 Chain ID (16진수)
    try {
        await ethereum.request({
            method: 'wallet_switchEthereumChain',
            params: [{ chainId: chainId }],
        });
        addToken();
    } catch (error) {
        if (error.code === 4902) {
            try {
                // 체인이 MetaMask에 없을 경우 체인을 추가하는 로직
                await ethereum.request({
                    method: 'wallet_addEthereumChain',
                    params: [{
                        chainId: chainId,
                        chainName: 'Ethereum Mainnet',
                        rpcUrls: ['https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID'],
                        blockExplorerUrls: ['https://etherscan.io'],
                        nativeCurrency: {
                            name: 'Ether',
                            symbol: 'ETH',
                            decimals: 18
                        }
                    }],
                });
                addToken();
            } catch (addError) {
                console.error('Failed to add the Ethereum network:', addError);
                alert('Failed to add the Ethereum network. Please add it manually.');
            }
        } else {
            console.error('Failed to switch the network:', error);
            alert('Please switch to the Ethereum network manually.');
        }
    }
}

async function addToken() {
    const tokenAddress = '0x00000000'; // 토큰의 주소
    const tokenSymbol = '약어'; // 토큰 심볼
    const tokenDecimals = 18; // 소수점 이하 자릿수
    const tokenImage = '여기에 로고 주소'; // 토큰 이미지 URL

    try {
        const wasAdded = await ethereum.request({
            method: 'wallet_watchAsset',
            params: {
                type: 'ERC20',
                options: {
                    address: tokenAddress,
                    symbol: tokenSymbol,
                    decimals: tokenDecimals,
                    image: tokenImage
                },
            },
        });

        if (wasAdded) {
            console.log('Token was successfully added!');
        } else {
            console.log('Token addition was cancelled.');
        }
    } catch (error) {
        console.error('Failed to add the token:', error);
    }
}
</script>
반응형
사업자 정보 표시
주식회사 엠크릿 | 황정우 | 경남 양산시 양산역로 75, 6층 | 사업자 등록번호 : 621-86-10667 | TEL : 055-364-3363 | Mail : min02299@naver.com | 통신판매신고번호 : 제2017-경남양산-00167호 | 사이버몰의 이용약관 바로가기