SlideShare a Scribd company logo
SCORE (Smart Contract for ICON)
Oct. 2018
2
What is a Smart Contract?
● A smart contract is a computer protocol intended to digitally
facilitate, verify, or enforce the negotiation or performance of
a contract. - from Wikipedia
● SCORE (Smart Contract on Reliable Environment)
○ A collection of code (functions) and data (states) that
resides at a specific address on the blockchain.
○ Written in Python - easy learning curve
○ Can use state DB abstractions
■ VarDB, DictDB, ArrayDB
○ SCORE must follow sandbox policy.
3
SCORE Model
● State transition machine
● State transition by transaction
● Sandbox policy
○ Should be deterministic
○ No random operation
○ No network call
○ No system call
○ No long-running operation
● Address starts with ‘cx’
SCORE
def __init__(self, db)
super().__init__(db)
...
def on_install(self)
...
def transfer(self, _from, _to,
_value)
...
VarDB / DictDB / ArrayDB
State DB (leveldb)
4
T-Bears (SCORE Development Suite)
● Provide a SCORE project template to help you start right
away
● Can test your SCORE on a locally emulated SCORE
execution environment
● When ready, can deploy SCORE onto the ICON network
through CLI (command-line interface) command
● Provide additional CLI commands to interact with the ICON
network (implements JSON-RPC v3 APIs)
● https://github.com/icon-project/t-bears
5
T-Bears (SCORE Development Suite)
6
T-Bears (SCORE Development Suite)
● Install on local file system
● Using Docker
$ virtualenv -p python3.6 .venv
$ source .venv/bin/activate
(.venv) $ pip install tbears
(.venv) $ tbears start
$ docker run -it -p 9000:9000 iconloop/tbears
7
T-Bears (SCORE Development Suite)
● T-Bears CLIs
init - Initialize a SCORE project
keystore - Create a keystore file
deploy - Deploy the SCORE
scoreapi - Query the list of APIs that SCORE exposes
call - Request icx_call
sendtx - Request icx_sendTransaction
txresult - Get transaction result by transaction hash
txbyhash - Get transaction info by transaction hash
transfer - Transfer ICX coins
balance - Get the balance of given address in loop*
totalsupply - Query the total supply of ICX in loop*
lastblock - Get last block info
...
(* 1 ICX == 10 ^ 18 loop)
8
SCORE Syntax
● IconScoreBase
○ The main entry class must inherit IconScoreBase
● __init__
○ a Python init function (constructor)
● on_install
○ Called when the SCORE is deployed
● @external
○ Can be called from outside the SCORE
● @payable
○ Permitted to receive incoming ICX coins
● @eventlog
○ Include logs in its TxResult as 'eventlogs'
9
SCORE Syntax
● fallback
○ Reserved function executed whenever the SCORE
receives plain ICX coins without data
● VarDB, DictDB, ArrayDB
○ State DB abstractions
○ VarDB - simple key-value state
○ DictDB - dictionary-base store like Python dict
○ ArrayDB - one dimensional array
● Score call (InterfaceScore)
○ Used to invoke other SCORE's function
● https://icon-project.github.io/score-guide/
10
SCORE Sample - Token standard (IRC2)
● Project initialization
➔ sample_token: a project folder
➔ SampleToken: main entry class name
● https://github.com/icon-project/IIPs/blob/master/IIPS/iip-2.md
● https://github.com/sink772/IRC2-token-standard
$ tbears init sample_token SampleToken
(.venv) $ tbears init sample_token SampleToken
Initialized tbears successfully
(.venv) $ ls sample_token/
__init__.py package.json sample_token.py
11
SCORE Sample - Token standard (IRC2)
from iconservice import *
class SampleToken(IconScoreBase):
_TOTAL_SUPPLY = 'total_supply'
_DECIMALS = 'decimals'
_BALANCES = 'balances'
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, initialSupply: int, decimals: int) -> None:
super().on_install()
total_supply = initialSupply * 10 ** decimals
self._total_supply.set(total_supply)
self._decimals.set(decimals)
self._balances[self.msg.sender] = total_supply
sample_token.py
12
SCORE Sample - Token standard (IRC2)
@external(readonly=True)
def name(self) -> str:
return "SampleToken"
@external(readonly=True)
def symbol(self) -> str:
return "MST"
@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]
sample_token.py
13
SCORE Sample - Token standard (IRC2)
class TokenFallbackInterface(InterfaceScore):
@interface
def tokenFallback(self, _from: Address, _value: int, _data: bytes):
pass
...
@eventlog(indexed=3)
def Transfer(self, _from: Address, _to: Address, _value: int, _data: bytes):
pass
@external
def transfer(self, _to: Address, _value: int, _data: bytes=None):
_from = self.msg.sender
if self._balances[_from] < _value:
revert("Out of balance")
self._balances[_from] = self._balances[_from] - _value
self._balances[_to] = self._balances[_to] + _value
if _to.is_contract:
recipient_score = self.create_interface_score(_to, TokenFallbackInterface)
recipient_score.tokenFallback(_from, _value, _data)
self.Transfer(_from, _to, _value, _data)
sample_token.py
14
Deploying SCORE
● Using T-Bears
(.venv) $ cat deploy.json
{
"uri": "http://127.0.0.1:9000/api/v3",
"nid": "0x3",
"to": "cx0000000000000000000000000000000000000000",
"stepLimit": "0x60000000",
"deploy": {
"contentType": "zip",
"mode": "install",
"scoreParams": {
"initialSupply": "0x3e8",
"decimals": "0x12"
}
}
}
(.venv) $ tbears deploy -k keystore_test1 -c deploy.json sample_token
Input your keystore password:
Send transaction request successfully.
transaction hash: 0x57307d3dda1bbb9ca3edf8825d8ee439cc88831b112f46d7a78232b1fb594e63
15
Interacting with SCORE
● JSON-RPC API v3
○ https://github.com/icon-project/icon-rpc-
server/blob/master/docs/icon-json-rpc-v3.md
● icx_call
○ Call a read-only external function of SCORE
○ Does not make state transition
● icx_sendTransaction
○ Transfer designated amount of ICX coins from 'from'
address to 'to' address
○ Install a new SCORE
○ Invoke a external function of SCORE
○ Transfer a message
○ Cause state transition
16
Interacting with SCORE
● Using raw JSON-RPC API
$ curl -H "Content-Type: application/json" -d '{ "jsonrpc": "2.0",
"method": "icx_call", "id": 100, "params": { "to":
"cx08894fade41db496eae5d62fbb04010cdf41babd", "dataType": "call",
"data": { "method": "balanceOf", "params": { "_owner":
"hxca1b18d749e4339e9661061af7e1e6cabcef8a19" }}}}'
http://localhost:9000/api/v3
<-- {"jsonrpc": "2.0", "result": "0x3635c9adc5dea00000", "id": 100}
● Using Java / Python SDKs
○ https://github.com/icon-project/icon-sdk-java
○ https://github.com/icon-project/icon-sdk-python
○ JavaScript SDK is coming soon.
17
Interacting with SCORE
● Using T-Bears
(.venv) $ cat balanceof.json
{
"jsonrpc": "2.0",
"id": 100,
"method": "icx_call",
"params": {
"to": "cx08894fade41db496eae5d62fbb04010cdf41babd",
"dataType": "call",
"data": {
"method": "balanceOf",
"params": {
"_owner": "hxca1b18d749e4339e9661061af7e1e6cabcef8a19"
}
}
}
}
(.venv) $ tbears call balanceof.json -u http://localhost:9000/api/v3
response : { "jsonrpc": "2.0", "result": "0x3635c9adc5dea00000", "id": 100 }
18
Transaction Fee
● Fee = usedStep * stepPrice
○ stepPrice = ICX exchange rate (1 ICX == 10 ^ 8 Step)
○ usedStep will be increased whenever some operations
are performed (DB access, function call, input params
size, log write, …)
● stepLimit = maximum Step allowance that can be used by
the transaction
● If (usedStep > stepLimit), then tx fails and fee (stepLimit *
stepPrice) is deducted.
● If (your balance < stepLimit * stepPrice), then tx fails
immediately.
● ICON Transaction Fee and SCORE Operation Policy
19
We are Hiring!
● All levels of engineers are welcome.
● If you are interested in a career at ICON SF Office, please
send your resume to sf@icon.foundation
Thank you!

More Related Content

What's hot

Java8 stream
Java8 streamJava8 stream
Java8 stream
koji lin
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
Dmitry Soshnikov
 

What's hot (19)

Java8 stream
Java8 streamJava8 stream
Java8 stream
 
Tips and tricks for building high performance android apps using native code
Tips and tricks for building high performance android apps using native codeTips and tricks for building high performance android apps using native code
Tips and tricks for building high performance android apps using native code
 
Creating sub zero dashboard plugin for apex with google
Creating sub zero dashboard plugin for apex with googleCreating sub zero dashboard plugin for apex with google
Creating sub zero dashboard plugin for apex with google
 
Cocoaheads Meetup / Kateryna Trofimenko / Feature development
Cocoaheads Meetup / Kateryna Trofimenko / Feature developmentCocoaheads Meetup / Kateryna Trofimenko / Feature development
Cocoaheads Meetup / Kateryna Trofimenko / Feature development
 
Building fast interpreters in Rust
Building fast interpreters in RustBuilding fast interpreters in Rust
Building fast interpreters in Rust
 
Letswift19-clean-architecture
Letswift19-clean-architectureLetswift19-clean-architecture
Letswift19-clean-architecture
 
Lecture 5, c++(complete reference,herbet sheidt)chapter-15
Lecture 5, c++(complete reference,herbet sheidt)chapter-15Lecture 5, c++(complete reference,herbet sheidt)chapter-15
Lecture 5, c++(complete reference,herbet sheidt)chapter-15
 
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash course
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash courseCodepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash course
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash course
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
 
Planet-HTML5-Game-Engine Javascript Performance Enhancement
Planet-HTML5-Game-Engine Javascript Performance EnhancementPlanet-HTML5-Game-Engine Javascript Performance Enhancement
Planet-HTML5-Game-Engine Javascript Performance Enhancement
 
Explaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to ComeExplaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to Come
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation Javascript
 
Why I love Python!
Why I love Python!Why I love Python!
Why I love Python!
 
Mozilla とブラウザゲーム
Mozilla とブラウザゲームMozilla とブラウザゲーム
Mozilla とブラウザゲーム
 
Compose Async with RxJS
Compose Async with RxJSCompose Async with RxJS
Compose Async with RxJS
 
Finch + Finagle OAuth2
Finch + Finagle OAuth2Finch + Finagle OAuth2
Finch + Finagle OAuth2
 
ES6 in Real Life
ES6 in Real LifeES6 in Real Life
ES6 in Real Life
 
ITT 2015 - Saul Mora - Object Oriented Function Programming
ITT 2015 - Saul Mora - Object Oriented Function ProgrammingITT 2015 - Saul Mora - Object Oriented Function Programming
ITT 2015 - Saul Mora - Object Oriented Function Programming
 
Implementing a many-to-many Relationship with Slick
Implementing a many-to-many Relationship with SlickImplementing a many-to-many Relationship with Slick
Implementing a many-to-many Relationship with Slick
 

Similar to Score (smart contract for icon)

Intravert Server side processing for Cassandra
Intravert Server side processing for CassandraIntravert Server side processing for Cassandra
Intravert Server side processing for Cassandra
Edward Capriolo
 
In Class AssignmetzCST280W13a-1.pdfCST 280 In-Class Pract.docx
In Class AssignmetzCST280W13a-1.pdfCST 280 In-Class Pract.docxIn Class AssignmetzCST280W13a-1.pdfCST 280 In-Class Pract.docx
In Class AssignmetzCST280W13a-1.pdfCST 280 In-Class Pract.docx
bradburgess22840
 

Similar to Score (smart contract for icon) (20)

Vitalii Bondarenko HDinsight: spark. advanced in memory big-data analytics wi...
Vitalii Bondarenko HDinsight: spark. advanced in memory big-data analytics wi...Vitalii Bondarenko HDinsight: spark. advanced in memory big-data analytics wi...
Vitalii Bondarenko HDinsight: spark. advanced in memory big-data analytics wi...
 
SE2016 BigData Vitalii Bondarenko "HD insight spark. Advanced in-memory Big D...
SE2016 BigData Vitalii Bondarenko "HD insight spark. Advanced in-memory Big D...SE2016 BigData Vitalii Bondarenko "HD insight spark. Advanced in-memory Big D...
SE2016 BigData Vitalii Bondarenko "HD insight spark. Advanced in-memory Big D...
 
Exploiting GPU's for Columnar DataFrrames by Kiran Lonikar
Exploiting GPU's for Columnar DataFrrames by Kiran LonikarExploiting GPU's for Columnar DataFrrames by Kiran Lonikar
Exploiting GPU's for Columnar DataFrrames by Kiran Lonikar
 
Apache Spark, the Next Generation Cluster Computing
Apache Spark, the Next Generation Cluster ComputingApache Spark, the Next Generation Cluster Computing
Apache Spark, the Next Generation Cluster Computing
 
JVM code reading -- C2
JVM code reading -- C2JVM code reading -- C2
JVM code reading -- C2
 
Deep Learning for Computer Vision: Software Frameworks (UPC 2016)
Deep Learning for Computer Vision: Software Frameworks (UPC 2016)Deep Learning for Computer Vision: Software Frameworks (UPC 2016)
Deep Learning for Computer Vision: Software Frameworks (UPC 2016)
 
R and cpp
R and cppR and cpp
R and cpp
 
Build Your Own WebAssembly Compiler
Build Your Own WebAssembly CompilerBuild Your Own WebAssembly Compiler
Build Your Own WebAssembly Compiler
 
Relational Database Access with Python ‘sans’ ORM
Relational Database Access with Python ‘sans’ ORM  Relational Database Access with Python ‘sans’ ORM
Relational Database Access with Python ‘sans’ ORM
 
NYC* 2013 - "Advanced Data Processing: Beyond Queries and Slices"
NYC* 2013 - "Advanced Data Processing: Beyond Queries and Slices"NYC* 2013 - "Advanced Data Processing: Beyond Queries and Slices"
NYC* 2013 - "Advanced Data Processing: Beyond Queries and Slices"
 
Intravert Server side processing for Cassandra
Intravert Server side processing for CassandraIntravert Server side processing for Cassandra
Intravert Server side processing for Cassandra
 
CGI.ppt
CGI.pptCGI.ppt
CGI.ppt
 
How do you create a programming language for the JVM?
How do you create a programming language for the JVM?How do you create a programming language for the JVM?
How do you create a programming language for the JVM?
 
In Class AssignmetzCST280W13a-1.pdfCST 280 In-Class Pract.docx
In Class AssignmetzCST280W13a-1.pdfCST 280 In-Class Pract.docxIn Class AssignmetzCST280W13a-1.pdfCST 280 In-Class Pract.docx
In Class AssignmetzCST280W13a-1.pdfCST 280 In-Class Pract.docx
 
JCConf 2020 - New Java Features Released in 2020
JCConf 2020 - New Java Features Released in 2020JCConf 2020 - New Java Features Released in 2020
JCConf 2020 - New Java Features Released in 2020
 
Meetup spark structured streaming
Meetup spark structured streamingMeetup spark structured streaming
Meetup spark structured streaming
 
Day 1
Day 1Day 1
Day 1
 
Introduction to-mongo db-execution-plan-optimizer-final
Introduction to-mongo db-execution-plan-optimizer-finalIntroduction to-mongo db-execution-plan-optimizer-final
Introduction to-mongo db-execution-plan-optimizer-final
 
Introduction to Mongodb execution plan and optimizer
Introduction to Mongodb execution plan and optimizerIntroduction to Mongodb execution plan and optimizer
Introduction to Mongodb execution plan and optimizer
 
OpenStack API's and WSGI
OpenStack API's and WSGIOpenStack API's and WSGI
OpenStack API's and WSGI
 

Recently uploaded

Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Peter Udo Diehl
 

Recently uploaded (20)

IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024
 
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
 
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi IbrahimzadeFree and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
Introduction to Open Source RAG and RAG Evaluation
Introduction to Open Source RAG and RAG EvaluationIntroduction to Open Source RAG and RAG Evaluation
Introduction to Open Source RAG and RAG Evaluation
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
Agentic RAG What it is its types applications and implementation.pdf
Agentic RAG What it is its types applications and implementation.pdfAgentic RAG What it is its types applications and implementation.pdf
Agentic RAG What it is its types applications and implementation.pdf
 
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptxUnpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
 
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya HalderCustom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2
 
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
 
PLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. StartupsPLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. Startups
 
The architecture of Generative AI for enterprises.pdf
The architecture of Generative AI for enterprises.pdfThe architecture of Generative AI for enterprises.pdf
The architecture of Generative AI for enterprises.pdf
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
Powerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara LaskowskaPowerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara Laskowska
 
Demystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyDemystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John Staveley
 
Optimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through ObservabilityOptimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through Observability
 

Score (smart contract for icon)

  • 1. SCORE (Smart Contract for ICON) Oct. 2018
  • 2. 2 What is a Smart Contract? ● A smart contract is a computer protocol intended to digitally facilitate, verify, or enforce the negotiation or performance of a contract. - from Wikipedia ● SCORE (Smart Contract on Reliable Environment) ○ A collection of code (functions) and data (states) that resides at a specific address on the blockchain. ○ Written in Python - easy learning curve ○ Can use state DB abstractions ■ VarDB, DictDB, ArrayDB ○ SCORE must follow sandbox policy.
  • 3. 3 SCORE Model ● State transition machine ● State transition by transaction ● Sandbox policy ○ Should be deterministic ○ No random operation ○ No network call ○ No system call ○ No long-running operation ● Address starts with ‘cx’ SCORE def __init__(self, db) super().__init__(db) ... def on_install(self) ... def transfer(self, _from, _to, _value) ... VarDB / DictDB / ArrayDB State DB (leveldb)
  • 4. 4 T-Bears (SCORE Development Suite) ● Provide a SCORE project template to help you start right away ● Can test your SCORE on a locally emulated SCORE execution environment ● When ready, can deploy SCORE onto the ICON network through CLI (command-line interface) command ● Provide additional CLI commands to interact with the ICON network (implements JSON-RPC v3 APIs) ● https://github.com/icon-project/t-bears
  • 6. 6 T-Bears (SCORE Development Suite) ● Install on local file system ● Using Docker $ virtualenv -p python3.6 .venv $ source .venv/bin/activate (.venv) $ pip install tbears (.venv) $ tbears start $ docker run -it -p 9000:9000 iconloop/tbears
  • 7. 7 T-Bears (SCORE Development Suite) ● T-Bears CLIs init - Initialize a SCORE project keystore - Create a keystore file deploy - Deploy the SCORE scoreapi - Query the list of APIs that SCORE exposes call - Request icx_call sendtx - Request icx_sendTransaction txresult - Get transaction result by transaction hash txbyhash - Get transaction info by transaction hash transfer - Transfer ICX coins balance - Get the balance of given address in loop* totalsupply - Query the total supply of ICX in loop* lastblock - Get last block info ... (* 1 ICX == 10 ^ 18 loop)
  • 8. 8 SCORE Syntax ● IconScoreBase ○ The main entry class must inherit IconScoreBase ● __init__ ○ a Python init function (constructor) ● on_install ○ Called when the SCORE is deployed ● @external ○ Can be called from outside the SCORE ● @payable ○ Permitted to receive incoming ICX coins ● @eventlog ○ Include logs in its TxResult as 'eventlogs'
  • 9. 9 SCORE Syntax ● fallback ○ Reserved function executed whenever the SCORE receives plain ICX coins without data ● VarDB, DictDB, ArrayDB ○ State DB abstractions ○ VarDB - simple key-value state ○ DictDB - dictionary-base store like Python dict ○ ArrayDB - one dimensional array ● Score call (InterfaceScore) ○ Used to invoke other SCORE's function ● https://icon-project.github.io/score-guide/
  • 10. 10 SCORE Sample - Token standard (IRC2) ● Project initialization ➔ sample_token: a project folder ➔ SampleToken: main entry class name ● https://github.com/icon-project/IIPs/blob/master/IIPS/iip-2.md ● https://github.com/sink772/IRC2-token-standard $ tbears init sample_token SampleToken (.venv) $ tbears init sample_token SampleToken Initialized tbears successfully (.venv) $ ls sample_token/ __init__.py package.json sample_token.py
  • 11. 11 SCORE Sample - Token standard (IRC2) from iconservice import * class SampleToken(IconScoreBase): _TOTAL_SUPPLY = 'total_supply' _DECIMALS = 'decimals' _BALANCES = 'balances' 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, initialSupply: int, decimals: int) -> None: super().on_install() total_supply = initialSupply * 10 ** decimals self._total_supply.set(total_supply) self._decimals.set(decimals) self._balances[self.msg.sender] = total_supply sample_token.py
  • 12. 12 SCORE Sample - Token standard (IRC2) @external(readonly=True) def name(self) -> str: return "SampleToken" @external(readonly=True) def symbol(self) -> str: return "MST" @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] sample_token.py
  • 13. 13 SCORE Sample - Token standard (IRC2) class TokenFallbackInterface(InterfaceScore): @interface def tokenFallback(self, _from: Address, _value: int, _data: bytes): pass ... @eventlog(indexed=3) def Transfer(self, _from: Address, _to: Address, _value: int, _data: bytes): pass @external def transfer(self, _to: Address, _value: int, _data: bytes=None): _from = self.msg.sender if self._balances[_from] < _value: revert("Out of balance") self._balances[_from] = self._balances[_from] - _value self._balances[_to] = self._balances[_to] + _value if _to.is_contract: recipient_score = self.create_interface_score(_to, TokenFallbackInterface) recipient_score.tokenFallback(_from, _value, _data) self.Transfer(_from, _to, _value, _data) sample_token.py
  • 14. 14 Deploying SCORE ● Using T-Bears (.venv) $ cat deploy.json { "uri": "http://127.0.0.1:9000/api/v3", "nid": "0x3", "to": "cx0000000000000000000000000000000000000000", "stepLimit": "0x60000000", "deploy": { "contentType": "zip", "mode": "install", "scoreParams": { "initialSupply": "0x3e8", "decimals": "0x12" } } } (.venv) $ tbears deploy -k keystore_test1 -c deploy.json sample_token Input your keystore password: Send transaction request successfully. transaction hash: 0x57307d3dda1bbb9ca3edf8825d8ee439cc88831b112f46d7a78232b1fb594e63
  • 15. 15 Interacting with SCORE ● JSON-RPC API v3 ○ https://github.com/icon-project/icon-rpc- server/blob/master/docs/icon-json-rpc-v3.md ● icx_call ○ Call a read-only external function of SCORE ○ Does not make state transition ● icx_sendTransaction ○ Transfer designated amount of ICX coins from 'from' address to 'to' address ○ Install a new SCORE ○ Invoke a external function of SCORE ○ Transfer a message ○ Cause state transition
  • 16. 16 Interacting with SCORE ● Using raw JSON-RPC API $ curl -H "Content-Type: application/json" -d '{ "jsonrpc": "2.0", "method": "icx_call", "id": 100, "params": { "to": "cx08894fade41db496eae5d62fbb04010cdf41babd", "dataType": "call", "data": { "method": "balanceOf", "params": { "_owner": "hxca1b18d749e4339e9661061af7e1e6cabcef8a19" }}}}' http://localhost:9000/api/v3 <-- {"jsonrpc": "2.0", "result": "0x3635c9adc5dea00000", "id": 100} ● Using Java / Python SDKs ○ https://github.com/icon-project/icon-sdk-java ○ https://github.com/icon-project/icon-sdk-python ○ JavaScript SDK is coming soon.
  • 17. 17 Interacting with SCORE ● Using T-Bears (.venv) $ cat balanceof.json { "jsonrpc": "2.0", "id": 100, "method": "icx_call", "params": { "to": "cx08894fade41db496eae5d62fbb04010cdf41babd", "dataType": "call", "data": { "method": "balanceOf", "params": { "_owner": "hxca1b18d749e4339e9661061af7e1e6cabcef8a19" } } } } (.venv) $ tbears call balanceof.json -u http://localhost:9000/api/v3 response : { "jsonrpc": "2.0", "result": "0x3635c9adc5dea00000", "id": 100 }
  • 18. 18 Transaction Fee ● Fee = usedStep * stepPrice ○ stepPrice = ICX exchange rate (1 ICX == 10 ^ 8 Step) ○ usedStep will be increased whenever some operations are performed (DB access, function call, input params size, log write, …) ● stepLimit = maximum Step allowance that can be used by the transaction ● If (usedStep > stepLimit), then tx fails and fee (stepLimit * stepPrice) is deducted. ● If (your balance < stepLimit * stepPrice), then tx fails immediately. ● ICON Transaction Fee and SCORE Operation Policy
  • 19. 19 We are Hiring! ● All levels of engineers are welcome. ● If you are interested in a career at ICON SF Office, please send your resume to sf@icon.foundation Thank you!