[Solidity] Web3

Alexandria·2024년 3월 4일

Solidity

목록 보기
10/11
post-thumbnail

1. Javascript

스마트 컨트랙트의 ABI배포된 주소를 알고 있어야 한다.

metamask가 존재하면 다음과 같이 연결을 요청한다.

그렇지 않다면 truffle console과 같이 그냥 접속한다.

그리고 버튼을 누르면 배포한 컨트랙트의 sayHello 함수를 호출한다.

<!DOCTYPE html>
<html lang="ko">
    <head>
        <script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/web3/1.8.1/web3.min.js"></script>
        <script>
            const CONTRACT_ADDRESS  = "0x4284b6b242aa02e791dda938a496e8366669fe3e";
            const CONTRACT_ABI      = [ { "inputs": [], "stateMutability": "nonpayable", "type": "constructor" }, { "inputs": [], "name": "Message", "outputs": [ { "internalType": "string", "name": "", "type": "string" } ], "stateMutability": "view", "type": "function", "constant": true }, { "inputs": [], "name": "sayHello", "outputs": [ { "internalType": "string", "name": "", "type": "string" } ], "stateMutability": "view", "type": "function", "constant": true } ];
            let web3;
            let contract;
            let accounts;

            $(window).on("load", async function () {
                if (window.ethereum) { // metamask 존재 여부 확인
                    web3 = new Web3(window.ethereum);

                    try {
                        // metamask 요청
                        accounts = await window.ethereum.request({ method: "eth_requestAccounts" });
                    } catch (error) {
                        console.log(`metamask error : ${error}`);
                    }
                } else if (window.web3) {
                    web3        = new Web3(Web3.currentProvider);
                    accounts    = await web3.eth.getAccounts();
                } else {
                    // 네트워크 접속
                    web3        = new Web3(new Web3.providers.HttpProvider("http://192.168.0.13:8545"));
                    // 계정 10개
                    accounts    = await web3.eth.getAccounts();
                }

                if (web3) {
                    const account     = accounts[0];
                    console.log(account);

                    // 배포된 컨트랙트
                    contract        = new web3.eth.Contract(CONTRACT_ABI, CONTRACT_ADDRESS);
                }
            });
        </script>
    </head>
    <body>
        <button onclick="btnClick()">sayHello</button>
        <p id="ret"></p>

        <script>
            async function btnClick() {
                // 버튼 클릭 시 sayHello 호출
                let ret         = await contract.methods.sayHello().call();
                $("#ret").text(ret);
            }
        </script>
    </body>
</html>

2. Python

스마트 컨트랙트의 ABI배포된 주소를 알고 있어야 한다.

다양한 API를 제공하고 있으며 자세한 사용법은 readthedocs

payable이 아닌 함수는 call을 이용한다.

import web3

CONTRACT_ADDRESS    = "0x551487aBE89B7D947195782D3eC484Ed5DE3B0b9"
CONTRACT_ABI        = """[ { "inputs": [], "stateMutability": "nonpayable", "type": "constructor" }, { "inputs": [], "name": "Message", "outputs": [ { "internalType": "string", "name": "", "type": "string" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "sayHello", "outputs": [ { "internalType": "string", "name": "", "type": "string" } ], "stateMutability": "view", "type": "function" } ]"""

w3          = web3.Web3(provider=web3.Web3.HTTPProvider(f"http://127.0.0.1:8545"))
accounts    = w3.eth.accounts
print(accounts)
print(f"latest block number : {w3.eth.block_number}")

contract    = w3.eth.contract(address=CONTRACT_ADDRESS, abi=CONTRACT_ABI)
result      = contract.functions.sayHello().call()
print(f"Hello World : {result}")
profile
IT 도서관

0개의 댓글