August 18, 2022

How to call solidity functions with Web3, metamask library

Public view/pure functions can be simply called. However, in other cases, you need to log in because of gas fee. It can be done with metamask.


public view/pure 함수는 간단히 호출할 수 있다. 그러나 그 외의 경우는 가스비를 제출해야하므로 로그인이 필요하다. 이를 위해 여기서는 메타마스크를 활용하는 방법을 알아본다.



1. public view/pure function

<script src="https://cdn.jsdelivr.net/npm/web3@1.7.3/dist/web3.min.js"></script>

<script>
const rpcPolygon = "https://polygon-rpc.com";
let web3 = "";
let contract1 = "";
async function main(){
    web3 = await new Web3(rpcPolygon);
    contract1 = await new web3.eth.Contract( [ABI], [Contract Address] );
} main();

async function callTmp(){
    contract1.methods.[function name]().call({from: [wallet address]})
    .then(function(result){
        console.log(result);
    })
    .catch(async function(e){
        console.log(e);
    });
}
</script>


Write the JavaScript code as above. It is used by calling the callTmp() function when necessary.


위와 같이 자바스크립트 코드를 작성한다. 필요할 때 callTmp() 함수를 호출하여 사용한다.

 

 

2. public function

<script src="https://cdn.jsdelivr.net/npm/web3@1.7.3/dist/web3.min.js"></script>

<script>
let web3 = "";
let contract1 = "";
async function main(){
    web3 = await new Web3(window.ethereum);
    contract1 = await new web3.eth.Contract( [ABI], [Contract Address] );
} main();

async function callTmp(){
    let param = {
        from: [my address],
        to: [contract1 address],
        value: [send coins if you want],
        data: contract1.methods.[function name]().encodeABI()
    };

    ethereum.request(
    {
        method: 'eth_sendTransaction',
        params: [param]
    })
    .then(async function(txHash){
        let receipt = null;
        while(receipt == null){
            receipt = await web3.eth.getTransactionReceipt(txHash);
            await sleep(3000);
        }
        console.log("Txhash:", receipt.transactionHash);
    })
    .catch(async function(error){
        console.log(error);
    });
}

async function sleep(milliseconds) {
    return new Promise(resolve => setTimeout(resolve, milliseconds))
}
</script>


Metamask uses the ethereum.request() function to generate a transaction. As before, proper use of the callTmp() function can help.


메타마스크에서는 트랜잭션 발생을 위해 ethereum.request() 함수를 사용한다. 이전과 마찬가지로 callTmp() 함수를 적절히 사용하면 도움이 될 수 있다.