본문 바로가기
블록체인/[파공이]파이썬으로 공부하는 이더리움(Web3)

[web3]PYTHON web3를 활용하여 Smart Contract 배포하기!!(2) - 더하기 함수

by 일등박사 2022. 8. 20.

2022.08.17 - [일등박사의 생각/블록체인] - [web3]PYTHON web3를 활용하여 Smart Contract 배포하기!!(1)

 

[web3]PYTHON web3를 활용하여 Smart Contract 배포하기!!(1)

2022.08.13 - [일등박사의 생각/데이터분석] - [이더리움] Private Block Chain vs Public Block Chain [이더리움] Private Block Chain vs Public Block Chain 게임 좋아하시나요?? 저는 예~전에 디아블로2를 재..

drfirst.tistory.com


안녕하세요!!

지난 포스팅에 이어 Python Web3를 활용, 

이더리움 네티워크에 Smart Contract 배포를 진행해 보겠습니다~!

 

우선 항상 그렇듯 Ganache로 private ethereum network를 생성합니다!

2022.08.13 - [일등박사의 생각/블록체인] - [GANACHE] 가나슈 설치하기!!! (Python api 연결준비)

 

[GANACHE] 가나슈 설치하기!!! (Python api 연결준비)

2022.08.13 - [일등박사의 생각/데이터분석] - [이더리움] Private Block Chain vs Public Block Chain 지난 포스팅을 통하여 Private Ethereum Network 에 대하여 알아보았는데요!! 이번 포스팅에서는 Window환경..

drfirst.tistory.com

 

Smart Cotract에 배포1 - 더하기 함수!!

 

// plus.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;

contract ViewAndPure {
    uint public x = 1;

    // 아래 내용이 핵신@@ i와  j를 밭으면 둘을 더한 값을 return 함
    function add(uint i, uint j) public pure returns (uint) {
        return i + j;
    }
}

위의 Solidity 코드의 배포를 시작해봅시다!!

 

1. Python Web3로 import 및 세팅

## 기본 페키지 및 주소 불러오기
from web3 import Web3
from solcx import compile_standard, install_solc
import json

BLOCKCHAIN_ADR = "HTTP://127.0.0.1:8545"
chain_id = 1337

# solc 버젼이 맞게 설치
install_solc('0.8.13')

 

2. plus.sol을 solc로 complie 하기

contact_list_file3  = '''
// plus.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;

contract ViewAndPure {
    uint public x = 1;

    // 아래 내용이 핵신@@ i와  j를 밭으면 둘을 더한 값을 return 함
    function add(uint i, uint j) public pure returns (uint) {
        return i + j;
    }
}

'''
compiled_sol = compile_standard(
    {
        "language": "Solidity",
        "sources": {"plus.sol": {"content": contact_list_file3}},
        "settings": {
            "outputSelection": {
                "*": {
                    "*": ["abi", "metadata", "evm.bytecode", "evm.bytecode.sourceMap"] # output needed to interact with and deploy contract 
                }
            }
        },
    },
    solc_version="0.8.13",
)
# print(compiled_sol)
# with open("compiled_code.json", "w") as file:
#     json.dump(compiled_sol, file)

# get bytecode
bytecode = compiled_sol["contracts"]["plus.sol"]["ViewAndPure"]["evm"]["bytecode"]["object"]
# get abia
abi = json.loads(compiled_sol["contracts"]["plus.sol"]["ViewAndPure"]["metadata"])["output"]["abi"]

 

 

3. Ethereum Network에 Deploy 하기!!

# For connecting to ganache
w3 = Web3(Web3.HTTPProvider(BLOCKCHAIN_ADR))

ContactList = w3.eth.contract(abi=abi, bytecode=bytecode)# Get the number of latest transaction
nonce = w3.eth.getTransactionCount(w3.eth.accounts[0])

# build transaction
transaction = ContactList.constructor().buildTransaction(
    {
        "chainId": chain_id,
        "gasPrice": w3.eth.gas_price,
        "from": w3.eth.accounts[-1],
        "nonce": nonce,
    }
)
# Sign the transaction
## 아래의 private_key는 ganache에서 직접 복사해 와야합니다!!
sign_transaction = w3.eth.account.sign_transaction(transaction, private_key="86d33c7ee6acc4400f5e207083cbdb250660630c6e92d14a58f196c740e8bbb7")
print("Deploying Contract!")
# Send the transaction
transaction_hash = w3.eth.send_raw_transaction(sign_transaction.rawTransaction)
# Wait for the transaction to be mined, and get the transaction receipt
print("Waiting for transaction to finish...")
transaction_receipt = w3.eth.wait_for_transaction_receipt(transaction_hash)
print(f"Done! Contract deployed to {transaction_receipt.contractAddress}")

(위 과정에서는 이더리움 네트워크의 mining이 진행되어야 deploy가 완료됩니다, 아래와같이 print가 다되어야 성공!)

진행 후 ganache를 확인해보면!

아래 그림과 같이 1개의 transaction이 생성되었음을 확인할 수 있고 

그 내용은 아래와 같이 contract가 create된 것임을 알 수 있습니다!!

이제 Deploy된 함수를사용해 볼까요!?

 

4. Deploy된 함수 활용하기!!

## ethereum에서 transaction_receipt.contractAddress를 바탕으로
## 방금 전 배포하였던 smart contract의 주소를 받아온다!!
smart_contract_addSol = w3.eth.contract(address=transaction_receipt.contractAddress, abi=abi)

## smart_contract_addSol 이라는 Smart Contract내에 존재하는
## 이름이 add인 functions을 불러온다!! 그리고 3,5를 변수로 넣는다 

res = smart_contract_addSol.functions.add(3,5).call()

## res로 무슨 값이 나올까!
print(res)

 

그 결과!!! 덧샘 값이 나옴을 확인할 수 있다.

 

참 쉽죠~!!

이것이 바로 Ethereum Machine을 Back End로 활용하여 함수를 실행 시킨것입니다!!

다음포스팅에서는 함수 실행에 더하여 데이터를 Ethereum Machine에 저장하는것 까지

진행해보겠습니다!

 

감사합니다.

댓글