출처 : 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

,