본문 바로가기
블록체인 기술사업 교육/Node.js

블록체인 기술사업 교육 14일차

by Mecodata 2023. 4. 20.

Node.js

- Chrome V8 JavaScript 엔진으로 빌드된 JavaScript 런타임 환경

- 서버 사이드 애플리케이션 개발에 주로 사용되는 소프트웨어 플랫폼

- 브라우저 외부 환경에서 자바스크립트 애플리케이션 개발에 사용

특징

- 모든 API가 비동기로 동작

- HTTP 서버 모듈 내장 => 별도의 웹서버 설치 필요 X

- 이벤트 기반 => 이벤트가 발생할 때 미리 지정해둔 작업 수행

- 논 블로킹 I/O = 오래 걸리는 함수를 백그라운드로 보내서 다음 코드가 먼저 실행되게 하고, 나중에 오래 걸리는 함수를 실행

- 노드 프로세스는 멀티 스레드이지만, 직접 다룰 수 있는 스레드는 하나(싱글 스레드)

- npm을 기반으로 다양한 모듈 제공 => 효율성이 좋음

- Javascript 언어로 backend 개발 가능하게 해줌

 

npm(Node Package Manager)

- JavaScript 패키지 매니저로 Node.js에서 사용할 수 있는 모듈들을 패키지화하여 모아둔 저장소 역할 + 패키지 설치 및 관리를 위한 CLI(Command line interface) 제공

- package.json = 프로젝트 정보와 패키지의 의존성 관리 => Java maven의 pom.xml과 같은 역할

package.json 구성요소에서 유의할 점

devDependencies = 개발할 때만 사용되는 모듈 관리 (install 시 -D 옵션 추가)
dependencies = 서비스를 배포할때 사용되는 모듈 관리

기본 명령어

- npm init = package.json 생성 (기본값으로 생성할 경우 뒤에 -y 추가 입력)

- npm install = package.json에 명시된 모든 패키지 일괄 설치 

- npm install 패키지명 = 해당 패키지 설치 (전역 설치를 실행하려면 install 뒤에 -g 추가 입력)

- npm uninstall 패키지명 = 해당 패키지 삭제

- npm update 패키지명 = 해당 패키지 업데이트

- npm ls = 패키지 목록 출력

 

require

- require("모듈 파일 경로") = 외부 모듈 불러오기

- require()는 불러오는 모듈에서 module.exports로 지정한 값들만 리턴함 => module.exports로 미지정시 해당 모듈에 있는 값을 못 가져옴

- require("dotenv").config() 실행 후 process.env를 통해 .env에 저장된 환경 변수들을 불러와 사용 가능 (npm install dotenv)

 

경로 호출

- __dirname = 현재 실행하는 파일의 절대 경로

- __filename = 현재 실행하는 파일의 절대 경로(파일명 포함)

- process.cwd() = node 명령을 호출한 작업 디렉터리의 절대경로

※ process = node.js에서 프로세스 관리를 위해 기본적으로 제공되는 객체

 

Web3.js

- 이더리움 네트워크와 상호작용할 수 있는 다양한 메서드를 제공하는 JavaScript 라이브러리 (npm install web3)

- require("web3")로 import

- web3.eth.Contract(ABI, 주소) = 해당 ABI와 주소에 해당하는 컨트랙트 import 

- web3.provider.HttpProvider(웹 주소) = http에서 동작하는 노드에 연결

- web3.eth.getAccounts() = 주소 목록 출력

- web3.utils.toWei(1, "ether") = 1 ether를 Wei로 변환

※ Promise { <pending> } => 비동기 처리 오류

Web3.js 활용 클라이언트 예시

require("dotenv").config();
const abiJson = require("./VendingMachine.json");
const a = require("./vendingMachine");
// const abi = process.env.ABI; // stirng 타입
const abi = abiJson.abi; // object 타입
const address = abiJson.address;
// console.log(abi);

const Web3 = require("web3");
const web3 = new Web3(new Web3.providers.HttpProvider("http://127.0.0.1:7545"));
// console.log(web3);
const smartContract = new web3.eth.Contract(abi, address);
let donutNumbers = smartContract.methods.getVendingMachineBalance().call();

// 토큰 조회 ver1
async function getDonuts() {
  let donutNumbers = await smartContract.methods
    .getVendingMachineBalance()
    .call();
  console.log(donutNumbers);
}

// 토큰 조회 ver2
smartContract.methods
   .getVendingMachineBalance()
   .call()
   .then((result) => console.log(result));

// 토큰 구입
const donutPurchase = async (amount) => {
  accounts = await web3.eth.getAccounts();
  balance = await web3.utils.toWei("0.02", "ether");
  receipt = await smartContract.methods.purchase(amount).send({
    from: accounts[0],
    gas: 2000000,
  });
  console.log(receipt);
};

// 토큰 충전
const donutRestock = async (amount) => {
  accounts = await web3.eth.getAccounts();
  balance = await web3.utils.toWei("0.02", "ether");
  receipt = await smartContract.methods.restock(amount).send({
    from: accounts[0],
    gas: 200000,
  });
  console.log(receipt);
};

// donutPurchase(20);
// donutRestock(100);
getDonuts();

// 토큰 구입 후 바로 잔고 확인 
donutPurchase(20).then((receipt) => {
  getDonuts();
  console.log(receipt);
});

Klaytn 거래 클라이언트 예시

const contractInfo = require("./VendingMachine_klaytn.json");
const Caver = require("caver-js"); // caver-js = Klaytn 관련 라이브러리
require("dotenv").config();

const cav = new Caver("https://api.baobab.klaytn.net:8651");

const abi = contractInfo.abi;
const address = contractInfo.address;

const smartContract = new cav.klay.Contract(abi, address);
// console.log(smartContract);

const account = cav.klay.accounts.createWithAccountKey(
  process.env.KAIKAS_ADDRESS,
  process.env.KAIKAS_PRIVATE_KEY
);
// console.log(account);

const wallet = cav.klay.accounts.wallet.add(account);
// console.log(wallet);

// smartContract.methods
//   .getVendingMachineBalance()
//   .call()
//   .then((result) => {
//     console.log(result);
//   });

// 토큰 조회
async function getDonuts() {
  let donutNumbers = await smartContract.methods
    .getVendingMachineBalance()
    .call();
  console.log(donutNumbers);
}

getDonuts();

// 토큰 구매
const donutPurchase = async (amount) => {
  receipt = await smartContract.methods.purchase(amount).send({
    from: account.address,
    gas: 2000000,
  });
  console.log(receipt);
};

// donutPurchase(20);

// 토큰 충전
const donutRestock = async (amount) => {
  receipt = await smartContract.methods.restock(amount).send({
    from: account.address,
    gas: 200000,
  });
  console.log(receipt);
};

// donutRestock(200000);

댓글