아이콘 DB

아이콘(ICON) 2019. 5. 30. 10:10

 

처음보는 문법들이 많다.

환경 설정은 이제 100% 이해 한거 같고 참 어려운곳에 시간을 너무 많이

허비한 느낌이 들지만..

화살표 함수나 이런 문법도 기존의 python 문법이 아닌 3.5부터

생긴 문법이다.

 

python으로 강의하고 python을 가장 자신 있는 언어라 생각 했는데

공부 새로 다시 해야겠다는 생각만 든다.

출처 :  https://docs.python.org/3/library/typing.html#module-typing

https://medium.com/b-ock-chain/how-to-score-3-cc73dc2e7fba

 

 

 

def greeting(name: str) -> str:
    return 'Hello ' + name

print(greeting("tkpark"))

def func1(arg1: int, arg2: str) -> int:
    return 100
print(func1(1,"tkpark"))

 

결과

root@1deaf713a0c1:/tbears/icon-dice-roll# python3 ex3.py
Hello tkpark
100
root@1deaf713a0c1:/tbears/icon-dice-roll#

 

 

출처

https://medium.com/b-ock-chain/how-to-score-2-104b687edd56

이제 구글의 leve db에 대해서 공부할 차례다.

 

 

 self._total_supply = VarDB(self._TOTAL_SUPPLY, db, value_type=int)
self._decimals = VarDB(self._DECIMALS, db, value_type=int)
self._balances = DictDB(self._BALANCES, db, value_type=int)
 

#############################################################

package.json

{
    "version": "0.0.1",
    "main_file": "appointment_payment",
    "main_score": "AppointmentPayment"
}

 

 

 

 

root@ee255e9c17ba:/tbears/appointment_payment# ls -al
total 16
drwxr-xr-x 2 root root 4096 Jun  7 08:08 .
drwxr-xr-x 1 root root 4096 Jun  7 07:38 ..
-rw-r--r-- 1 root root 1090 Jun  7 08:05 appointment_payment.py
-rw-r--r-- 1 root root    0 Jun  7 07:30 __init__.py
-rw-r--r-- 1 root root  107 Jun  7 07:36 package.json
root@ee255e9c17ba:/tbears/appointment_payment#

from iconservice import *

TAG = 'AppointmentPayment'

class AppointmentPayment(IconScoreBase):

    _BALANCES = 'balances'
    _TOTAL_SUPPLY = 'total_supply'
    _DECIMALS = 'decimals'

    def __init__(self, db: IconScoreDatabase) -> None:
        super().__init__(db)
        self._total_supply = VarDB(self._TOTAL_SUPPLY, db, value_type=int)
        self._decimals = VarDB(self._DECIMALS, db, value_type=int)
        self._balances = DictDB(self._BALANCES, db, value_type=int)

    def on_install(self) -> None:
        super().on_install()

    def on_update(self) -> None:
        super().on_update()

    @external(readonly=True)
    def name(self) -> str:
        return "SampleToken"

    @external(readonly=True)
    def symbol(self) -> str:
        return "ST"

    @external(readonly=True)
    def decimals(self) -> int:
        return self._decimals.get()

    @external(readonly=True)
    def totalSupply(self) -> int:
        return self._total_supply.get()

    @external(readonly=True)
    def balanceOf(self, _owner: Address) -> int:
        return self._balances[_owner]

 

 

 

 

클라우드 소스 가지고와서 실행해 보았다.

샘플  소스 구동은 되는데 이것 저것 신경써야 될게 많은듯 하다.

from iconservice import *
TAG = 'SampleOne'
class SampleOne(IconScoreBase):
    _OWNER_NAME = "owner_name"
    _ARRAY_DB_SAMPLE = "array_db_sample"
    _DICT_DB_SAMPLE = "dict_db_sample"
    def __init__(self, db: IconScoreDatabase) -> None:
        super().__init__(db)
        self._owner_name = VarDB(self._OWNER_NAME, db, str)
        self._dict_db = DictDB(self._DICT_DB_SAMPLE, db, str)
    def on_install(self) -> None:
        super().on_install()
        self._owner_name.set("Life4honor")
        self._dict_db["Jin"] = "Developer"
        self._array_db.put("Jin")
        self._dict_db["nanaones"] = "Developer"
        self._array_db.put("nanaones")
        self._dict_db["ICON"] = "Blockchain"
        self._array_db.put("ICON")
        self._dict_db["SCORE"] = "Smart Contract"
        self._array_db.put("SCORE")
    def on_update(self) -> None:
        super().on_update()
    @property
    def _array_db(self):
        return ArrayDB(self._ARRAY_DB_SAMPLE, self.db, str)
    @payable
    @external
    def deposit(self):
        amount = self.msg.value
        if amount >= 10000000000000000000:
            revert("ICX amount must be lower than 10")           
        self.icx.transfer(self.msg.sender, amount)
        Logger.info(f'Sent winner ({self.msg.sender}) {amount}.', TAG) 

소스코드 다 짰으면 python3로 컴파일 한번 해보고 deploy 하는게

시간을 좀 줄일수 있다.

 

 

 

윗부분은 레벨DB과 아랫부분은  deposit은 송금이 된다.

 

 

 

블로그 이미지

iesay

,

개발 환경 : Docker for Windows Installer.exe ,  Visual Studio Code - Insiders

 

 

도커 설치 후  명령어 실행

docker run -it -p 127.0.0.1:9000:9000 -p 127.0.0.1:5000:5000 --rm ibriz/icon-workshop:latest 

만약 도커가 실행되지 않는다면 컨테너를 swich 시켜라

 

마켓플레이스에서 remote 검색하여

remote development 설치

 

 

왼쪽 아래 녹색 ><버튼 클릭 

 

attack를 시키면 사용이 가능하다.

그 뒤 도커의 세션을 바로 load하면 된다.

 

해당 기능은 파이참에서 유료로 제공해주는 기능이라고 한다.

nodejs든 python이든 아주 좋은 환경에서 개발이 가능해 보인다.

 

 

 

 

'아이콘(ICON)' 카테고리의 다른 글

Python(파이썬) 웹프레임워크 - Django(장고)  (0) 2019.06.26
아이콘 DB  (0) 2019.05.30
아이콘 스마트컨트렉 분석(dice_roll)  (0) 2019.05.27
클라우드 세일  (0) 2019.05.23
아이콘 스마트컨트렉 도커 설치  (0) 2019.05.20
블로그 이미지

iesay

,

출처 : https://medium.com/@2infiniti/icon-dapp-from-a-z-part-3-icon-dice-roll-dapp-7f0ca72057f5

 

준비물 : 지갑2개(키스토어),  x윈도우 웹브라우저

 

아이콘 도커 접속

docker run -it -p 127.0.0.1:9000:9000 -p 127.0.0.1:5000:5000 --rm ibriz/icon-workshop:latest 

 

icon-dice-roll소스를 다운로드 받아 준다.

git clone https://gitlab.com/ibriz/icon-dice-roll.git

 

중요

tbears의 -k 키스토어 옵션과 -c 컨피그옵션은 deploy할 디렉토리와 동일하게 둔다.

tbears_cli_config.json

{
    "uri": "https://bicon.net.solidwallet.io/api/v3",
    "nid": "0x3",
    "keyStore": null,
    "from": "hx040fe47c7a7827684aa4c0bfcfdbbbdbb3ec3b6a",
    "to": "cx0000000000000000000000000000000000000000",
    "deploy": {
        "stepLimit": "0x59682f00",
        "mode": "install",
        "scoreParams": {}
    },
    "txresult": {},
    "transfer": {
        "stepLimit": "0xf4240"
    }
}
 

uri : 테스트넷 서버주소

from : A지갑주소 (도박을 만든 포주)

stepLimit : ICX 스마트컨트렉 수수료

            ( 16진수로 되어 있는데 약 11 ICX정도 지출된다)

 

 

ICONex 에서 생성한 키스토어를 넣어 준다.  도박장 주인

keystore_test1

 

 

 

icon-dice-roll에 tbears_cli_config.json , keystore_test1  복사 한다.

root@e3c558b878a6:/tbears# cp tbears_cli_config.json icon-dice-roll/
root@e3c558b878a6:/tbears# cp keystore_test1 icon-dice-roll/
root@e3c558b878a6:/tbears# cd icon-dice-roll/
root@e3c558b878a6:/tbears/icon-dice-roll# pwd
/tbears/icon-dice-roll
root@e3c558b878a6:/tbears/icon-dice-roll# ls
 config                     keystores        tbears_cli_config.json
 dice-roll                  keystore_test1   testcmdline
'ICON Workshop Guide.pdf'   README.md        webapp
root@e3c558b878a6:/tbears/icon-dice-roll#
 

 

해당 디렉토리로 이동 후

tbears deploy dice-roll -k keystore_test1 -p 키스토어패스워드

 

Send deploy request successfully.
If you want to check SCORE deployed successfully, execute txresult command
transaction hash: 0x8c46c029a137bc676cc06a3b938a20112981043b086f665151befc3191ee0c11

root@e3c558b878a6:/tbears/icon-dice-roll# tbears txresult 0x8c46c029a137bc676cc06a3b938a20112981043b086f665151befc3191ee0c11
Transaction result: {
    "jsonrpc": "2.0",
    "result": {
        "txHash": "0x8c46c029a137bc676cc06a3b938a20112981043b086f665151befc3191ee0c11",
        "blockHeight": "0x740a3",
        "blockHash": "0xf2bd7fdfec266534e668fcd00c6a46342ee04bf6fcb2a6cf412655df5528d643",
        "txIndex": "0x0",
        "to": "cx0000000000000000000000000000000000000000",
        "scoreAddress": "cxeb428634534e073101b6124815175ffe16f82fa8",
        "stepUsed": "0x3e4c5bb0",
        "stepPrice": "0x2540be400",
        "cumulativeStepUsed": "0x3e4c5bb0",
        "eventLogs": [],
        "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
        "status": "0x1"
    },
    "id": 1
}
root@e3c558b878a6:/tbears/icon-dice-roll#

 

저 부분이 컨트렉 주소다.

유저가 입금하고 송금 받는곳이다.

자동으로 해준다.

 

 

/tbears/icon-dice-roll/testcmdline

vi send_set_treasury.json

{
  "jsonrpc": "2.0",
  "method": "icx_sendTransaction",
  "params": {
    "version": "0x3",
    "from": "hx040fe47c7a7827684aa4c0bfcfdbbbdbb3ec3b6a",
    "value": "0x6f05b59d3b200000",
    "stepLimit": "0x59682f00",
    "nid": "0x3",
    "nonce": "0x2",
    "to": "cxeb428634534e073101b6124815175ffe16f82fa8",
    "dataType": "call",
    "data": {
      "method": "set_treasury"
      }
  },
  "id": 1
}
 

지갑주소, 수수료, to에 스마트컨트렉 주소를 넣는다.

# pwd
/tbears/icon-dice-roll


root@e3c558b878a6:/tbears/icon-dice-roll# tbears sendtx -k keystore_test1 testcmdline/send_set_treasury.json -p 키스토어패스워드


Send transaction request successfully.
transaction hash: 0x38ba401e1592060b80d2d777033381e1821de92da1c73892dcde7bfadcd41258

root@e3c558b878a6:/tbears/icon-dice-roll#
 

 

cd webapp

main.py

import ast
import json
import threading
import time

from flask import Flask, render_template, jsonify
from iconsdk.builder.call_builder import CallBuilder
from iconsdk.icon_service import IconService
from iconsdk.providers.http_provider import HTTPProvider
from iconsdk.wallet.wallet import KeyWallet
import urllib.request

from repeater import retry

app = Flask(__name__)

default_score = "cxeb428634534e073101b6124815175ffe16f82fa8"
icon_service = IconService(HTTPProvider("https://bicon.net.solidwallet.io/api/v3"))

wallets = {
    'wallet1': KeyWallet.load("../keystore_test1", "키스토어패스워드"),
}


@app.route('/getLatestTx', methods=['GET', 'POST'])
def latest_transactions():
    params = {}
    call = CallBuilder().from_(wallets['wallet1'].get_address()) \
        .to(default_score) \
        .method("get_results") \
        .params(params) \
        .build()
    result = icon_service.call(call)

    transaction_list = []
    for resultVal in result['result']:
        transaction_list.append(ast.literal_eval(resultVal))

    score_balance = icon_service.get_balance(default_score)
    account_balance = icon_service.get_balance(wallets['wallet1'].get_address())

    decending_ordered_transaction = sorted(transaction_list, key=lambda val: int(val['timestamp']), reverse=True)
    latest_transaction = decending_ordered_transaction[0] if len(decending_ordered_transaction) > 0 else []
    response = {
        'transaction_list': decending_ordered_transaction,
        'score_balance': score_balance,
        'account_balance': account_balance,
        'latest_transaction': latest_transaction
    }
    return jsonify(response)


@app.route('/getTransaction', methods=['GET', 'POST'])
def testnet_transactions():
    tx_list = urllib.request.urlopen(
        "https://bicon.tracker.solidwallet.io/v3/contract/txList?addr=cx9d10d63edc8225b7fbbecb335a099d97d0ee19d8&page=1&count=10").read()
    jsonTransaction = json.loads(tx_list)
    return render_template('flip.html', context=jsonTransaction['data'])


def occasional_update(first_time=False):
    app.config['updated'] = not first_time
    threading.Timer(10, occasional_update).start()


@app.route("/updated")
def updated():
    while not app.config['updated']:
        time.sleep(0.5)
    app.config['updated'] = False
    return "Updated"


@app.route("/")
def main():
    return render_template("index.html")


if __name__ == '__main__':
    occasional_update(first_time=True)
    app.run(debug=True, host='0.0.0.0', port=5000)

 

 

root@e3c558b878a6:/tbears/icon-dice-roll/testcmdline# pwd
/tbears/icon-dice-roll/testcmdline

vi send_bet.json

{
  "jsonrpc": "2.0",
  "method": "icx_sendTransaction",
  "params": {
    "version": "0x3",
    "from": "hxe7af5fcfd8dfc67530a01a0e403882687528dfcb",
    "value": "0xde0b6b3a7640000",
    "stepLimit": "0x59682f00",
    "nid": "0x3",
    "nonce": "0x1",
    "to": "cxeb428634534e073101b6124815175ffe16f82fa8",
    "dataType": "call"
  },
  "id": 1
}
 

수수료부분만과 to만 컨트렉주소로 바꾸어 준다.

from 키스토어를 로드 할때 그 주소가 들어 가는거 같다.

 


 

 

 root@e3c558b878a6:/tbears/icon-dice-roll/webapp# python3 main.py &
  * Serving Flask app "main" (lazy loading)
 * Environment: production
   WARNING: Do not use the development server in a production environment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 280-257-458

백그라운드로 & 실행 시킨다. 해당 커멘드로 베팅도 해야 되기 때문이다.

 

cd..

 

1.json 유저 키스토어를 넣는다.

 

tbears sendtx -k 1.json testcmdline/send_bet.json -p 패스워드 

 

 

 

 

 

 

asdas

 

 

'아이콘(ICON)' 카테고리의 다른 글

Python(파이썬) 웹프레임워크 - Django(장고)  (0) 2019.06.26
아이콘 DB  (0) 2019.05.30
아이콘 개발환경(윈도우)  (0) 2019.05.29
클라우드 세일  (0) 2019.05.23
아이콘 스마트컨트렉 도커 설치  (0) 2019.05.20
블로그 이미지

iesay

,