Notice
Recent Posts
Recent Comments
Link
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

개발공부일지

BlockChain - RPC 통신, ganache, web3, Solidity 본문

BlockChain

BlockChain - RPC 통신, ganache, web3, Solidity

보람- 2024. 1. 25. 14:00

목차

1. RPC 통신

2. 이더리움 개발 테스트 툴

3. ganache 

4. Web3 라이브러리

5. 솔리디티 코드 구조


 

 

 

 

1. RPC 통신


-  요청응답은 같지만 실행하는것이 목적이라 별도의 원격제어를 위한 코딩X
- 다른 주소의 공간에 프로시저를 실행 할 수 있게 하는 프로세스 간의 통신
- 일반적으로 코드작성하고 실행하면 자신의 메모리공간에서 기능하는데
- 다른 주소에 있는 함수를 실행시키고 싶을때 사용함!
- 비즈니스 로직 개발에 집중할수있음!!

 

 

 

 

 

2. 이더리움 개발 테스트 툴

 

geth : POA, go언어로 작성되어있는 이더리움 클라이언트, chainID를 확인할 수 있는 클라이언트
    - chainID : 블록체인 네트워크의 고유 식별자, 메인넷/테스트 구분 가능함

ganache : 로컬 개발 및 테스트 네트워크 환경을 제공 (이더리움 네트워크)

메타마스크 : 브라우저의 확장 프로그램, 웹 어플리케이션에서 네트워크와 상호작용, 지갑 확장 프로그램
     - 개인키 관리, 트랜잭션 생성하면 서명을 만들고, 네트워크에 요청을 보낼수 있음

truffle, hardhat : 스마트 컨트랙트 개발, 테스트 배포를 쉽게 할 수 있도록 도와주는 프레임워크

 

 

 

 

 

3. ganache 

 

- 설치하기

npm i -g ganache-cli
npx ganache-cli
Ganache CLI v6.12.2 (ganache-core: 2.13.2)

Available Accounts // 지갑(계정) 10개 제공
==================
(0) 0xb02B6A393e64E50239B7B729e51d870453e9994F (100 ETH)
(1) 0x4D6168F6788814b0447880d6c0018D2e6d9F5531 (100 ETH)
(2) 0x09127D97666c2d46FF6b19247Ae259Fa199a3F89 (100 ETH)
(3) 0x055F58AD0EF373ac1a0104334CedD4EaBA8EB5f8 (100 ETH)
(4) 0xBA87c5F33D4ac3C29Cc5C05613293a9143d8Bb9E (100 ETH)
(5) 0xfAb1498bEc7C3Ce98970B7221dD16cc6251f9597 (100 ETH)
(6) 0x0cc0fEa8fB6508B78F3C38B1C7B45bE9576d679c (100 ETH)
(7) 0xCC79B6F9285074E470A448B239Db0c2242B10516 (100 ETH)
(8) 0x72a466d6ddcb8aaf56e513cae78e1Ef651EEB846 (100 ETH)
(9) 0xAbE913c15bd6161651de1708D1A4C1d7089DA873 (100 ETH)

Private Keys // 지갑에 맞는 개인키
==================
(0) 0x9015bd4b0d02c5c4dad7044f66c4e3abef22323cd1a5e15ad4d803c897874914
(1) 0xb3da2c33310b16193d0de3b7be66600a9f378fb3b687910224c289730eaa4fba
(2) 0xca7194c59a28249741c321a8d5fea93f98182f52b908e2d820f3078fa4b2c4fc
(3) 0x3a6a7ef8b963bf09236eecbca7299a7ff1c69342c9db5a879ecf4c28abc3989b
(4) 0x81a52c7a47097c2e0a888e038c85b218ebb55c84655f0a35b61f1399f6c9f99d
(5) 0x469ca59ee8a32485cd83c78b7926100022fc5f1d7be12ba379c8128cf84807ad
(6) 0xe7f68226c5ebd9de4db297e935628e2a5715d5ad072210a79f45bbfaf9dab749
(7) 0x8af1d245d18ac6fc60d338e61e52a060ca3a9ab6a72bb3364815e018fc69c1c8
(8) 0x355a7fa95d512ee64ea367eac79d4ed45b6320f8af7fd370a5faa952e03780a7
(9) 0x48f55278b00f186081120fb9ed25318540e453062f304dd8f6e8451a9f12635b

HD Wallet
==================
Mnemonic:      crystal intact depth blush wish april master donkey keen harvest tree have
Base HD Path:  m/44'/60'/0'/0/{account_index}

Gas Price
==================
20000000000

Gas Limit
==================
6721975

Call Gas Limit
==================
9007199254740991

Listening on 127.0.0.1:8545
>

 

- 기본 포트 : 8545 (127.0.0.1:8545)

- chainID : 1337

 

 

 

 

 

4. Web3 라이브러리

 

- 이더리움 네트워크와 상호작용하기 위해 사용
- rpc 통신을 네트워크에 요청보내는것을 도와줌!
- 이더리움 재단에서 제공함!


- web3.eth.getAccounts() : 가지고 있는 지갑 전체 조회하는 요청
- web3.eth.getBalance() : 해당 지갑의 잔액 조회
   - 100000000000000000000 나오는데 wei단위를 사용
   - 10 ** 18 으로 측정된 wei (가스비연산에 사용되기위해)
- web3.utils.fromWei(data)
   - wei -> ETH로 변환 : 100 ETH

 

- 트랙잭션을 발생시킬때 사용하는 메서드 send()
- 조회할때는 call()

 

더보기
// web3
const web3 = new Web3('http://127.0.0.1:8545');
web3.eth.getAccounts().then(console.log);
console.log(web3.eth);
web3.eth.getBalance('0xAbE913c15bd6161651de1708D1A4C1d7089DA873')
  .then((data) => {
    console.log(data);
    const value = web3.utils.fromWei(data);
    console.log(`${value}ETH`);
  });

const abi = [
  {
    inputs: [],
    name: 'getValue',
    outputs: [{ internalType: 'uint256', name: '', type: 'uint256' }],
    stateMutability: 'view',
    type: 'function',
  },
  {
    inputs: [{ internalType: 'uint256', name: '_value', type: 'uint256' }],
    name: 'setValue',
    outputs: [],
    stateMutability: 'nonpayable',
    type: 'function',
  },
];

 web3.eth.sendTransaction({
     from: '0xb02B6A393e64E50239B7B729e51d870453e9994F',
     gas: '300000',
     data: '60806040523480156100115760006000fd5b50610017565b61016b806100266000396000f3fe60806040523480156100115760006000fd5b506004361061003b5760003560e01c80632096525514610041578063552410771461005f5761003b565b60006000fd5b61004961007b565b60405161005691906100f2565b60405180910390f35b610079600480360381019061007491906100b7565b61008d565b005b6000600060005054905061008a565b90565b8060006000508190909055505b5056610134565b6000813590506100b081610119565b5b92915050565b6000602082840312156100ca5760006000fd5b60006100d8848285016100a1565b9150505b92915050565b6100eb8161010e565b82525b5050565b600060208201905061010760008301846100e2565b5b92915050565b60008190505b919050565b6101228161010e565b811415156101305760006000fd5b5b50565bfea2646970667358221220cffd7a87b50c07b6273c73c174f88a0c4bb102a167bd79d7947a6a86379878a164736f6c63430008000033',
   })
   .then(console.log);

const getValue = async () => {
  // 인스턴스 생성하지 않고 abi로 직접 요청보내서 처리해보기
  const getCodeHash = await web3.eth.abi.encodeFunctionCall(abi[0], []);
  // 첫번째 매개변수는 abi, 두번째는 abi에 전달할 내용(없으면 빈배열이라도넣어야함)
  console.log(getCodeHash);
  // encodeFunctionCall(abi[0], []) : 0x20965255
  // encodeFunctionCall(abi[1], [7]) : 0x552410770000000000000000000000000000000000000000000000000000000000000007

  const data = await web3.eth.call({
    to: '0x0Af32aecDDeA070c7a03D91493273AF28f8B908B',
    data: getCodeHash,
  });
  console.log(data);
  // 0x0000000000000000000000000000000000000000000000000000000000000000
  console.log(parseInt(data));
  // 0

  return parseInt(data);
};
getValue();

// 상태변수 변환
const setValue = async () => {
  const _getValue = await getValue();
  const setCodeHash = await web3.eth.abi.encodeFunctionCall(abi[1], [
    _getValue + 1,
  ]);
  const tx = {
    from: '0xb02B6A393e64E50239B7B729e51d870453e9994F',
    to: '0x0Af32aecDDeA070c7a03D91493273AF28f8B908B',
    data: setCodeHash,
    gas: 5000000,
    gasPrice: 21000,
  };
  const data = await web3.eth.sendTransaction(tx);
  console.log('setvalue : ', data);
  console.log('++++', await getValue());
};
setValue();

 




5. 솔리디티 코드 구조

 

① 라이센스 식별자
② 솔리디티 버전
③ 배포할 내용의 컨트랙트

 

- 코드 컴파일 : solc 라이브러리 사용

- 설치하기

npm i solc@0.8.0
npx solc --bin --abi "파일경로"
npx solc --bin --abi contracts/test.sol

 

 

pragma solidity ^0.8.0;

contract Counter{
  uint256 private value; // 탈중앙화 데이터, 상태변수

  function setValue(uint256 _value) public {
    // 상태변수 전환
    value = _value;
  }

  function getValue() public view returns (uint256) {
    return value;
  }
}

 

 

 

 


※ 컨트랙트 주소, 컨트랙트 배포

※ abi, bin

※ payable