[Algorand] Transaction 작성
파이썬을 이용한 Transaction
파이썬을 이용하여 Transaction 작성 방법
테스트넷 노드 실행
지난 글에서 환경 구축을 완료했습니다.
스마트 컨트랙트를 작성하기에 앞서 샌드박스에서 알고랜드 테스트넷 노드를 실행시킵니다.
cd sandbox
./sandbox up testnet
알고랜드 테스트넷 월렛 만들기
from algosdk import account, mnemonic
def generate_algorand_keypair():
private_key, address = account.generate_account()
print("My address: {}".format(address))
print("My private key: {}".format(private_key))
print("My passphrase: {}".format(mnemonic.from_private_key(private_key)))
위를 통해 알고랜드 테스트넷에서 월렛을 생성할 수 있습니다.
generate_alogrand_keypair() 함수를 실행하면
address, private key 그리고 passphrase를 순서대로 볼 수 있습니다.
주의해야 할 것은 private key와 passphrase를 인터넷 공간에서 노출되어서는 안 됩니다.
월렛을 복구할 경우 passphrase를 입력을 요구하는데, 이 단어들이 유출되었을 경우 월렛의 자산을 통째로 빼앗길 수 있습니다.
생성된 월렛으로 작업을 계속해야 하기 때문에, 해당 내용을 코드 위에 주석 처리하여 붙여놓습니다.
테스트용 알고랜드 지급받기
블록체인에서 트랜젝션을 하기 위해서는 여분의 Algo를 보유해야 합니다.
따라서 테스트용 Algo를 얻어야 합니다.
알고랜드디스펜서를 통해 5 Algo를 받아봅시다.
Algorand Dispenser
dispenser.testnet.aws.algodev.network
해당 사이트에 접속하여 Algorand Account에 아까 생성한 알고랜드 주소를 기입합니다.
그러면 최하단에 Transaction ID 항목에 5 Algo를 전송한 Transaction 주소가 나타납니다.
이를 클릭하게 되면 AlgoExplorer 사이트에서 해당 트랜젝션 정보를 확인할 수 있습니다.
Transfer 타입의 트랜젝션 정보가 나타나며, 송금에 참여한 주소와 수량을 알 수 있습니다.
트랜젝션 프로그래밍
트랜젝션을 위한 부분은 다음과 같습니다. 해당 모듈과 코드를 사용하면 됩니다.
from algosdk.v2client import algod
from algosdk.future import transaction
from algosdk import constants
import json
import base64
def first_transaction_example(private_key, my_address):
algod_address = "http://localhost:4001"
algod_token = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
algod_client = algod.AlgodClient(algod_token, algod_address)
account_info = algod_client.account_info(my_address)
print("Account balance: {} microAlgos".format(account_info.get('amount')) + "\n")
# build transaction
params = algod_client.suggested_params()
# comment out the next two (2) lines to use suggested fees
params.flat_fee = True
params.fee = constants.MIN_TXN_FEE
receiver = "HZ57J3K46JIJXILONBBZOHX6BKPXEM2VVXNRFSUED6DKFD5ZD24PMJ3MVA"
note = "Hello World".encode()
amount = 1000000
unsigned_txn = transaction.PaymentTxn(my_address, params, receiver, amount, None, note)
# sign transaction
signed_txn = unsigned_txn.sign(private_key)
#submit transaction
txid = algod_client.send_transaction(signed_txn)
print("Successfully sent transaction with txID: {}".format(txid))
# wait for confirmation
try:
confirmed_txn = transaction.wait_for_confirmation(algod_client, txid, 4)
except Exception as err:
print(err)
return
print("Transaction information: {}".format(
json.dumps(confirmed_txn, indent=4)))
print("Decoded note: {}".format(base64.b64decode(
confirmed_txn["txn"]["txn"]["note"]).decode()))
print("Starting Account balance: {} microAlgos".format(account_info.get('amount')) )
print("Amount transfered: {} microAlgos".format(amount) )
print("Fee: {} microAlgos".format(params.fee) )
account_info = algod_client.account_info(my_address)
print("Final Account balance: {} microAlgos".format(account_info.get('amount')) + "\n")
하나씩 살펴봅니다.
클라이언트 생성
algod_address = "http://localhost:4001"
algod_token = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
algod_client = algod.AlgodClient(algod_token, algod_address)
알고랜드 테스트넷 샌드박스에서 API 엔드포인트 주소로는 "localhost:4001"을, 토큰으로는 "aaa..."를 제공합니다.
따라서 해당 토큰과 주소로 클라이언트 클래스를 생성합니다.
잔고 확인
account_info = algod_client.account_info(my_address)
print("Account balance: {} microAlgos".format(account_info.get('amount')) + "\n")
account_info 메서드로 주소의 Algo 잔고를 알 수 있습니다.
트랜젝션 생성
params = algod_client.suggested_params()
# comment out the next two (2) lines to use suggested fees
params.flat_fee = True
params.fee = constants.MIN_TXN_FEE
receiver = "HZ57J3K46JIJXILONBBZOHX6BKPXEM2VVXNRFSUED6DKFD5ZD24PMJ3MVA"
note = "Hello World".encode()
amount = 1000000
unsigned_txn = transaction.PaymentTxn(my_address, params, receiver, amount, None, note)
위 부분은 트랜젝션을 생성하는 부분입니다.
params는 트랜젝션의 파라미터를 설정합니다.
flat_fee는 고정 수수료를, MIN_TXN_FEE는 비용으로 최소 트랜젝션 수수료를 지불한다는 의미입니다.
따라서 최소 트랜젝션 수수료로 고정한다는 의미입니다.
receiver로는 해당 금액을 받게 될 주소가 들어가며,
note는 송금의 메모로 쓰일 문장을 작성합니다.
수량의 단위는 마이크로입니다. 1,000,000 MicroAlgi == 1 Algo를 송금하는 내용입니다.
PaymentTxn은 트랜잭션 타입 중 송금을 의미합니다.
트랜젝션 타입에는 송금을 포함하여 다음과 같은 타입들이 있습니다.
- Payment - 송금
- Key Registration - 컨센서스 참여를 위한 계좌 등록
- Asset Configuration - 자산 생성, 변경, 제거 등 설정 변경
- Asset Freeze - 동결자산 송수신 목적
- Asset Transfer - 자산을 opt-in 목적
- Application Call
트랜젝션 서명
signed_txn = unsigned_txn.sign(private_key)
트랜젝션이 유효한지 고려하기 전에 프라이빗 키로 서명하는 부분입니다.
트랜젝션 제출
#submit transaction
txid = algod_client.send_transaction(signed_txn)
print("Successfully sent transaction with txID: {}".format(txid))
# wait for confirmation
try:
confirmed_txn = transaction.wait_for_confirmation(algod_client, txid, 4)
except Exception as err:
print(err)
return
print("Transaction information: {}".format(
json.dumps(confirmed_txn, indent=4)))
print("Decoded note: {}".format(base64.b64decode(
confirmed_txn["txn"]["txn"]["note"]).decode()))
print("Starting Account balance: {} microAlgos".format(account_info.get('amount')) )
print("Amount transfered: {} microAlgos".format(amount) )
print("Fee: {} microAlgos".format(params.fee) )
account_info = algod_client.account_info(my_address)
print("Final Account balance: {} microAlgos".format(account_info.get('amount')) + "\n")
네트워크에 서명된 트랜젝션을 제출하는 부분입니다.
send_transaction() 함수를 통해 트렌젝션을 네트워크에 제출합니다. 이때 리턴 값으로는 송금 트랜젝션의 ID를 내어줍니다.
wait_for_confirmation() 부분에서 트랜젝션이 완료되어 네트워크에서 인정되기까지 대기합니다.
트랜젝션이 완료되면 다음과 같이 트랜젝션 정보를 표시해줍니다.
1 Algo 송금으로 수수료로는 1/1000 Algo를 사용했고 이에 계좌에는 3.999 Algo가 남아있습니다.
이 송금 트랜젝션 ID는 TDYBNIDUGOUKWIL7YFSI5IWYCK7KZ3Z6YSWKBAHC3T3MSZ4TLS2A 입니다.
이를 AlgoExplorer에 기입하면 해당 송금 트랜젝션 정보를 확인할 수 있습니다.
여기까지의 트랜젝션 내역들을 알고랜드 월렛인 myAlgoWallet 앱에서도 확인할 수 있습니다.
레퍼런스
https://developer.algorand.org/docs/sdks/python/
Your first transaction - Algorand Developer Portal
Algorand Developer Docs, SDKs, REST APIs, CLI tools, ecosystem projects, metrics dashboard and sample code, how-tos, and news from the Algorand developer community
developer.algorand.org