Web3.js 실습 (2)

유지민·2022년 12월 9일
0

web3.js

목록 보기
2/2

실습 시작

node 

node 환경으로 이동

const Web3 = require("web3");
Web3
const web3 = new Web3("https://cloudflare-eth.com");	//cloudflare-eth 이용
web3.currentProvider

// getBlockNumber를 받아오는 다양한 방법
/*1*/web3.eth.getBlockNumber().then(console.log)
/*2*/web3.eth.getBlockNumber(function (error, result) {console.log(result)})

//3
async function getBlockNumber() {
  const latestBlockNumber = await web3.eth.getBlockNumber()
  console.log(latestBlockNumber)
  return latestBlockNumber
} // 여기 까지는 설정
getBlockNumber() // 여기는 함수 실행으로 결과값 호출



web3.eth.getBlock(CERTAIN BLOCK NUMBER).then(console.log)
web3.eth.getBlock(CERTAIN BLOCK NUMBER, function (error, result) {console.log(result)})

async function getBalance() {
  const getBalance= await web3.eth.getBalance('CERTAIN WALLET ADDRESS');
  console.log(getBalance)
  return getBalance
}

web3.eth.getBalance('CERTAIN WALLET ADDRESS', (call, wei) => { balance = web3.utils.fromWei(wei, 'ether')}).then(console.log)

async function SomeBalance(a) {
	const getBalance = await web3.eth.getBalance(a); 
	const eth_Balance = web3.utils.fromWei(getBalance); 
	console.log(eth_Balance)
}

web3.js이기 때문에 javascript문법이다.
터미널에서 쓰려니까 조금 어색함
함수를 지정해서 쓸수있음
getBalance()는 web3.eth.getBalance함수(잔액 조회 함수)를 더 간편하게 쓰려고 내가 지정한 함수.
web3.utils.fromWei는 Wei단위를 이더 단위로 변경

web3.eth.getBlockNumber() 안나오는이유 peding이 있어서 시간이 걸려서 .then을 붙여주면 나옴

web3.eth.accounts.create()
/*
{
  address: '0x4B52870A56cdFD3653A483cb5b041136648Cff67',
  privateKey: '0x55b165591a9b6fdf468b6111dab1ea9cb4b611792cf2b1cdd92257c6e1ad442c',
  signTransaction: [Function: signTransaction],
  sign: [Function: sign],
  encrypt: [Function: encrypt]
}
*/
// 위의 privateKey 넣어보기
// 메타마스크에서 개인키 추출하여 넣어보기
web3.eth.accounts.privateKeyToAccount('PRIVATE KEY')

// 32bytes 길이의 개인키는 다 됨
web3.eth.accounts.privateKeyToAccount('0x1111111111111111111111111111111111111111111111111111111111111111')
// 아래 결과 반환
/*{
  address: '0x19E7E376E7C213B7E7e7e46cc70A5dD086DAff2A',
  privateKey: '0x1111111111111111111111111111111111111111111111111111111111111111',
  signTransaction: [Function: signTransaction],
  sign: [Function: sign],
  encrypt: [Function: encrypt]
}*/

web3.eth.accounts.create() : 지갑생성 함수
web3.eth.accounts.privateKeyToAccount('PRIVATE KEY') : 개인키로 지갑정보 조회

이제 평소 리믹스에서 자주 쓰던 Goerli testnet에 연결. infura를 이용했다.
https://www.infura.io/

ctrl + c, ctrl + c로 나갔다 다시 시작

const Web3 = require("web3");
Web3
const web3 = new Web3("https://goerli.infura.io/v3/YOUR KEY");
web3.currentProvider

web3.eth.getBlockNumber().then(console.log) // goerli 테스트넷의 블록 최신번호 반환
web3.eth.getTransaction('TRANSACTION HASH').then.(console.log)

// 'BLOCK NUMBER'번째 블록에 포함된 거래 개수 
web3.eth.getBlockTransactionCount('BLOCK NUMBER').then(console.log)
// 'BLOCK NUMBER'번째 블록에 'INDEX'번째 거래
web3.eth.getTransactionFromBlock('BLOCK NUMBER', 'INDEX').then(console.log)

다른 체인이나 메인넷에 연결하고 싶으면 인퓨라에서 변경한 주소를 가져와 new Web3에 안에 넣어줘서 다시 web3를 생성

web3.eth.getChainId().then(console.log)

체인 아이디 가져오기


특정 주소의 ERC-20 잔액(usdc) 받아오기

let wallet_address = 'WALLET ADDRESS' // 임의의 지갑
let token_address = '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48' // usdc 입니다.

//wallet_address가 usdc를 얼마나 갖고 있는지를 확인하고 싶습니다.
const minABI = [  
  // balanceOf
  {    
    constant: true,
    inputs: [{ name: "_owner", type: "address" }],
    name: "balanceOf",
    outputs: [{ name: "balance", type: "uint256" }],
    type: "function",
  },
];
const contract = new web3.eth.Contract(minABI, token_address);
await contract.methods.balanceOf(wallet_address).call();
profile
개발 취준생

0개의 댓글