💡ABI (Application Binary Interface)
ABI는 Application Binary Interface의 약자로, 런타임 시 바이너리 코드와 상호작용하기 위한 인터페이스이다. ABI는 바이너리 형태로 되어있는 스마트 컨트랙트가 어떤 인터페이스를 가지고 있는지 알려주는 역할을 한다.
✓ ABI를 사용해 Contract ABI Call 하기
아래와 같이 Hello World 코드를 작성해보자.
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
contract HelloWorld{
function renderHelloWorld () public pure returns (string memory greeting){
greeting = "Hewllo World";
}
}
그리고 해당 파일을 컴파일 후, "Compilation Details"를 눌러 컨트랙트 세부 정보를 확인해보자.
Compilation Details 화면에서는 컴파일된 컨트랙트에 대한 세부적인 정보를 확인할 수 있다. 이 중에서 ABI 정보를 확인해보자.
ABI를 통해 컨트랙트 내 함수를 어떻게 사용하는지 확인할 수 있다. Web3.js 에서는 web3.eth.Contract() 에 ABI를 인자로 넣어 컨트랙트를 구현한다. WEB3DEPLOY에서는 ABI와 Web3.js 를 이용해 컨트랙트를 바로 배포할 수 있는 자바스크립트 코드도 확인할 수 있다.
다시 ABI로 돌아와, ABI를 복사하여 해당 컨트랙트를 사용해보자. Compilation Details의 ABI 메뉴 옆에 있는 복사버튼 또는 Compilation Deatils 아래에 있는 복사버튼을 통해 ABI를 복사할 수 있다.
ABI는 다음과 같은 형태이다.
[
{
"inputs": [],
"name": "renderHelloWorld",
"outputs": [
{
"internalType": "string",
"name": "greeting",
"type": "string"
}
],
"stateMutability": "pure",
"type": "function"
}
]
이를 Ganache에 배포 후 다음과 같은 코드를 작성해보자.
const express = require("express");
const app = express();
const port = 8080;
const Contract = require("web3-eth-contract");
async function helloWorld() {
try {
const abi = [
{
inputs: [],
name: "renderHelloWorld",
outputs: [
{
internalType: "string",
name: "greeting",
type: "string",
},
],
stateMutability: "pure",
type: "function",
},
];
const address = "{컨트랙트 주소}";
Contract.setProvider("http://127.0.0.1:7545");
const contract = new Contract(abi, address);
const result = await contract.methods.renderHelloWorld().call();
console.log(result);
return result;
} catch (e) {
console.log(e);
return e;
}
}
app.get("/helloWorld", (req, res) => {
helloWorld().then((result) => {
res.send(result);
});
});
app.listen(port, () => {
console.log("Listening...");
});
브라우저에서 http://localhost:8080/helloworld 를 호출하면 다음과 같이 화면에 출력되는 것을 확인할 수 있다.
web3.eth.Contract() 는 ABI와 계정 주소를 입력 받고, 컨트랙트 객체를 반환한다. 이 컨트랙트 객체는 자바스크립트 객체처럼 사용할 수 있으며, 컨트랙트 내의 상태변수와 함수를 속성과 메서드처럼 사용할 수 있다.
const contract = new Contract(abi, address);
이렇게 만들어진 컨트랙트 객체에 있는 함수를 사용하기 위해서는 contract.methods.함수명().call()와 같이 사용할 수 있다. contract.methods.함수명()은 컨트랙트에 있는 함수를 실행하는 트랜잭션 객체를 생성한다. 또한, contract.methods.함수명().call 와 같이 사용할 수 있다. contract.methods.함수명()은 컨트랙트에 있는 함수를 실행하는 트랜잭션 객체를 생성한다. 또한 contract.methods.함수명().call()은 트랜잭션을 실행한 결과를 Promise 형태로 반환한다. 아래의 코드는 컨트랙트의 renderHelloWorld() 함수를 실행하는 트랜잭션 객체를 call 하여 함수를 실행한 결과를 result 변수에 담아 콘솔창에 출력한다. Contract ABI를 이용해 함수를 호출했기 때문에 Contract ABI Call이라고 한다.
const result = awiat contract.methods.renderHelloWorld().call();
console.log(result);
'블록체인 > WEB3 개발' 카테고리의 다른 글
req.body가 undefined라면 express 미들웨어 body-parser 모듈을 확인하세요! (0) | 2022.08.30 |
---|---|
NFT 거래소를 위한 스마트 컨트랙트 개발 (0) | 2022.08.10 |
이더스캔 API(Etherscan API) 이용해보기 (0) | 2022.08.03 |
노드 RPC Call을 Infura를 통해 제어해보기 (0) | 2022.08.03 |
서버에서 Web3.js 라이브러리 사용하기 (0) | 2022.08.02 |
댓글