트러플을 활용한 개발을 실습한다.
개인적인 연습과정을 기록하므로 상세한 설명은 추후 추가하도록 할 예정이다.
0. 사전준비
- Truffle
- Node
- NPM
- Metamask
1. 원하는 폴더에 이동하여 아래 명령어를 통해 트러플로 init한다.
truffle init
2. 기본 구조가 생성된다. contracts 폴더 내에 myContract를 하나 생성하고 테스트를 진행해보자. MyContract 파일에 아래 코드를 입력한다.
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.9.0;
contract MyContract {
struct Student {
string name;
uint age;
}
mapping(uint256 => Student) studentInfo;
function setStudentInfo(uint _studentId, string memory name, uint age) public {
Student storage student = studentInfo[_studentId];
student.name = name;
student.age = age;
}
function getStudentInfo(uint256 _studentId) public view returns (string memory, uint) {
return (studentInfo[_studentId].name, studentInfo[_studentId].age);
}
}
3. migrations 폴더에 "2_deploy_contracts.js"파일을 생성하고, 아래 코드를 붙여넣어주자.
const MyContract = artifacts.require("MyContract");
module.exports = function (deployer) {
deployer.deploy(MyContract);
};
4. 아래 명령어를 통해 develop 모드로 진입하고 가상의 서버를 트러플이 열어준다. (10개의 Ledgers 를 생성해준다.)
truffle develop
5. 이제 Develop모드에 진입했으니 새로운 터미널을 하나 더 열고, 개발하는 폴더로 이동하여 아래 명령어를 입력해 로그창을 띄워놓자.
truffle develop --log
6. 자, 다시 truffle develop console로 돌아와, 아래 명령어를 입력한다.
migrate
7. [참고]develop console에 다음 명령어를 입력해 존재 원장 목록을 확인할 수 있다.
web3.eth.getAccounts()
8. [참고]첫번째 계정의 잔고를 확인해보자. 주소는 위 명령어로 인해 도출된 10개의 레저(원장) 중 첫번째 주소다. (wei단위로 출력된다.)
web3.eth.getBalance('0x8aC78DCeFB5989E6C190235f84B0b6A9AA60a8Ea')
9. [참고]다음 명령을 통해 출력된 숫자를 ether 단위로 변경해서 볼 수 있다.
web3.utils.fromWei("99998967970000000000", "ether")
10. 배포된 MyContract를 이제 호출해보자.
//배포한 MyContract를 app 전역변수에 담아준다.
MyContract.deployed().then(function(instance) { app = instance })
//setStudentInfo 함수를 사용해 student를 추가해주자. 매개변수값 + 어떤 레저로 불러와서 쓰는 것인지 명시
app.setStudentInfo(1, "monkey", 29, {from : '0x8aC78DCeFB5989E6C190235f84B0b6A9AA60a8Ea'})
//getStudentInfo 함수를 통해 방금 생성한 id 값이 1인 학생 정보를 확인해보자.
app.getStudentInfo(1)
-----
11. 기타 참고 명령어
//배포 후 재 배포할 때 사용 재 컴파일 -> development 서버에 재 배포함.
truffle migrate --compile-all --reset --network development
//truffle console 사용해서 컨트렉트 호출하기
//1. 변수에 할당함. 매개변수 = deployed contract Address
let hello = await HelloWorld.at("0x4Bc83f4dB815EE98479b8245B2f5078aCdba4Dd4")
//2. 호출
hello.say()
'BlockChain Developer > Public Blockchain' 카테고리의 다른 글
[Ethereum] GSN (0) | 2022.03.15 |
---|---|
[Web3- 셋팅 문제해결] 최신 React에 Web3 설치하기 (0) | 2022.02.19 |
[Hyperledger Besu] EC2에 Hyperledger IBFT 2.0 (POA) Network 구성하기 (1) | 2021.12.15 |
[IPFS] Nodejs에서 사용하기 (2) | 2021.10.04 |
[Ethereum] Geth Dapp (with Node.js & React.js) 구축하기 (1) | 2021.09.25 |