WEB3.0

Yona·2022년 1월 26일
1

블록체인

목록 보기
18/22
post-thumbnail

📔 Web3.0

Web3.0 ...?
= Read + Wrtie + Own

📔 Web3.js

블록체인과 상호작용하는 클라이언트를 개발하기 위해서 사용되는 라이브러리.
이더리움 블록체인과 JSON RPC를 사용하여 소통한다.

$ npm install web3

npm install 명령어를 통해 간단하게 설치가 가능하며,

web3.js 에는 다음과 같은 모듈이 있다.

$ Web3.modules
> {
    Eth: Eth(provider), // 이더리움 네트워크와 상호작용하기 위한 모듈
    Net: Net(provider), // 네트워크 속성과 상호작용하기 위한 모듈
    Personal: Personal(provider), // 이더리움 계정과 상호작용하기 위한 모듈 
    Shh: Shh(provider), // 귓속말 프로토콜(?)과 상호작용하기 위한 모듈
    Bzz: Bzz(provider), // Swarm 네트워크와 상호작용하기 위한 모듈
}

📔 Infura(인퓨라)

원격 이더리움 노드를 통해 이더리움 네트워크에 접근할 수 있게 해주는 서비스.

https://infura.io/ 회원 가입 이후,

Dashboard 에서 CREATE NEW PROJECT 로 하나의 프로젝트를 만들어준다.

위에 적힌 KEYS 부분에서 "PROJECT ID" 가 API Key와 같은 역할이다.

⚙️ 예시 코드

⚙️ getBalance() - 잔액 조회

const Web3 = require('web3');
const rpcURL ="https://ropsten.infura.io/v3/{infura에서 발급받은 개인 key}"

const web3 = new Web3(rpcURL);

const account = "{개인 지갑 주소}";

web3.eth.getBalance(account).then((bal) => {
    console.log(`지갑 ${account}의 잔액은... ${bal} 입니다.`);
})
// 실행 결과
$ 지갑 0xd9Eba49d7A8073A779633a838e18589f4edBFe22의 잔액은... 5693033873293706590 입니다.

지갑에 들어있는 Eth의 개수와는 달리 이상한 숫자가 나온다.

화폐의 단위가 이더(Eth)가 아닌 wei이기 때문이다.

web3.utils.fromwei()는 wei 단위를 화폐 단위로 변환을 해준다.

//...
web3.eth.getBalance(account).then((bal) => {
    console.log(`지갑 ${account}의 잔액은... ${bal} 입니다.`);
	return web3.utils.fromWei(bal, "ether"); // web3.utils.fromWei 추가
})
.then((eth)=> {
    console.log(`이더 단위로는 ${eth} 입니다.`)
})
// 실행 결과
지갑 0xd9Eba49d7A8073A779633a838e18589f4edBFe22의 잔액은... 5693033873293706590 입니다.
이더 단위로는 5.69303387329370659 입니다.

⚙️ getTransaction, getTransactionReceipt- 트랜잭션 조회

const Web3 = require('web3');
const rpcURL ="https://ropsten.infura.io/v3/{infura에서 발급받은 개인 key}"

const web3 = new Web3(rpcURL);

const txId = "{트랜잭션 해시 값}";

web3.eth.getTransaction(txId)
    .then((obj)=> {
        console.log(obj);
});
// 실행결과 
{
  accessList: [],
  blockHash: '0xb531433ffe59bd933a0ab4f9e979566cca81dc9149941f526362934010aa701f',
  blockNumber: 11855222,
 	...

⚙️ getBlock - 블록 조회

const Web3 = require('web3');
const rpcURL ="https://ropsten.infura.io/v3/{infura에서 발급받은 개인 key}"

const web3 = new Web3(rpcURL);

const blockNum = "{block 번호}";

web3.eth.getBlock(blockNum)
	.then((obj)=> {
    	console.log(obj)
})
// 실행 결과 - block이 갖고 있는 정보를 볼 수 있다.
{
  baseFeePerGas: 16,
  difficulty: '2227247239',
  extraData: '0xd883010a0f846765746888676f312e31372e35856c696e7578',
  gasLimit: 8000000,

🔨 getTransactionByAccount - 특정 주소의 거래 내역 조회

// 블록 범위에 있는 블록에 기록된 트랙잭션 중 해당 계정이 참여한 트랜잭션만 추출
// 인자로 주소값 account 와 블록 숫자로 이루어진 블록 범위값 startBlcok, endBlock을 인자로 갖는다.
// 해당 블록 범위 내에 송신 또는 수신자로 참여한 트랜잭션들로 구성된 배열 반환

const Web3 = require('web3');
const rpcURL ="https://ropsten.infura.io/v3/{infura에서 발급받은 개인 key}"

const web3 = new Web3(rpcURL);

function Solution(startBlock, endBlock, account) {

    transaction_box = []

    web3.eth.getBlock(startBlock, function(err, res) {
        if(!err) {
            for(let i=0; i<res.transactions.length; i++) {
                transaction_box.push(res.transactions[i])
            }
        }
        
        for(let j=0; j<transaction_box.length; j++) {
            //console.log(transaction_box[j])
            web3.eth.getTransaction(transaction_box[j], function(err1, res1) {
                if(!err1) {
                    if(res1.from === account) {
                        console.log(`${res1.from} 에서 ${res1.to} 로 보내줬다.`)
                    }
                    else if(res1.to === account) {
                        console.log(`${res1.to} 에서 ${res1.from} 로 받았다.`)
                    }
                }
            })
        }

    })
}

console.log(Solution(11855222, 11855225, "0xd9Eba49d7A8073A779633a838e18589f4edBFe22"))

대충 재귀로 돌려가지고 저런식으로 하면 될것같은데... 자바스크립트 잘 했으면 좋겠다... ㅠㅠㅠㅠㅠ


💡 참고 링크

1) http://channy.creation.net/blog/1509
2) https://www.npmjs.com/package/web3
3) https://web3js.readthedocs.io/en/v1.2.11/web3.html#web3-modules
4) https://web3js.readthedocs.io/en/v1.2.11/web3-utils.html?highlight=fromWei#fromwei

0개의 댓글