SlideShare a Scribd company logo
Rust Smart Contracts
Maksym Zavershynskyi, Near Protocol
Smart Contracts & AWS Lambda
• Event-driven — executes code
only when needed. Pay per
execution;

• Serverless — no need to provision
servers;
Request
Response
Regular server is active all time
Zzzzz..
Lambda is only active when called
Smart Contracts & AWS Lambda
• Event-driven — executes code
only when needed. Pay per
execution;

• Serverless — no need to provision
servers;
Regular server is active all time
Lambda is only active when called
Request
Response
Request
Response
A Smart Contract
• Event-driven — executes code only when needed. Pay per execution;

• Serverless — no need to provision servers; 

• Decentralized — it is not run by a single entity.
Immutable History of Events
Users running nodes collectively build the blockchain
Fat Fingers and Bugs in Closed Code
Inside a Node
Blockchain Layer
• P2P Network
• Consensus
• Blocks Storage
• RPC API
Runtime Layer
Virtual Machine
State Storage
Code
WASM 

+ Rust/TypeScript
Pros:

• Existing tooling and community;

• General purpose & Turing complete;



Cons:

• Was not designed for the
blockchain;

• No formal verification.
Specialized

VM + Language
Pros:

• Designed for the blockchain;

• Allows formal verification (?)



Cons:

• Niche language;

• Not Turing complete (?)
Requirements for VM
• Platform-independent		 	 	 	 	 	 	 WASM ✓

• Determinism		 	 	 	 	 	 	 	 	 	 WASM ✓ w/o floats

• Sand-boxed execution/compilation	 	 	 WASM ✓ certain executors

• Small size of compiled code	 	 	 	 	 WASM ✓

• Close to machine code	 	 	 	 	 	 	 WASM ✓
WASM + Rust Bonus Points
• Existing tooling and community;

• Code transfer;

• Memory safety;

• Zero-cost abstractions.
Rust Zero-Cost Abstractions
Zero cost abstractions. What you don’t use, you don’t pay for.
And further: What you do use, you couldn’t hand code any better.
- Bjarne Stroustrup
Rust APIs
near_bindgen 		 — Rust API for NEAR blockchain

smart_contract 	 — Rust API for Wavelet blockchain by Perlin

EWASM 	 	 	 — a subset of WASM for Ethereum-like blockchains

Ink! 	 	 	 	 — Rust API for Substrate/Polkadot blockchain

Mantle 	 	 	 — Rust API for Oasis blockchain

Deprecated:

PWASM + Fleetwood — Rust API for Parity's Kovan blockchain
Contract Interface and Blockchain Interface
Blockchain Layer
WASM Executor
Rust Contract
Contract Interface
Methods defined by the contract 

that the blockchain can call
State Storage
Blockchain Interface

Methods defined by the blockchain 

that the contract can call
eDSL-based Rust API
#![cfg_attr(not(any(test, feature = "test-env")), no_std)]
use ink_core::{memory::format, storage};
use ink_lang::contract;
contract!{
struct Incrementer {
value: storage::Value<u32>,
}
impl Deploy for Incrementer {
fn deploy(&mut self, init_value: u32) {
self.value.set(init_value)
}
}
impl Incrementer {
pub(external) fn inc(&mut self, by: u32) {
env.println(&format!("Incrementer::inc by = {:?}", by));
self.value += by;
}
}
}
Ink! (eDSL)
• Contract Interface:

• Implement Deploy::deploy

• Wrap code into contract!{}

• Blockchain Interface:

• Interactions through env::*

• Blockchain Interface (State):

• Use storage::* wrappers;
use mantle::{Context, Service};
#[derive(Service)]
struct Incrementer {
value: u32,
}
impl Incrementer {
pub fn new(_ctx: &Context) -> Result<Self> {
Ok(Self { value: 0 })
}
pub fn inc(&mut self, _ctx: &Context, by: u32) {
self.value += by;
}
}
fn main() {
mantle::service!(Incrementer);
}
Mantle (eDSL)
• Contract Interface:

• Additional argument: &Context

• Decorate with with #[derive(Service)]
• Special main function.

• Blockchain Interface:

• Through &Context

• Blockchain Interface (State):

• Decorate fields with #[indexed];

• Compiler plugin.
Non-invasive Rust API
#[derive(Default, Serialize, Deserialize)]
struct Incrementer {
value: u32,
}
#[near_bindgen]
impl Incrementer {
pub fn inc(&mut self, by: u32) {
self.value += by;
}
}
near_bindgen (non-invasive)
• Contract Interface:

• Derived from your code.

• Blockchain Interface:

• Interactions through Blockchain<>

• Blockchain Interface (State):

• Derived from your code.
So insignificant that we did not give it a name
How Does near_bindgen Work
M.A.G.I.C.
How Does near_bindgen Work
Macros

Automatically

Generated

Injected

Code
How Does It Work
#[derive(Default, Serialize, Deserialize)]
struct Incrementer {
value: u32,
}
#[near_bindgen]
impl Incrementer {
pub fn inc(&mut self, by: u32) {
self.value += by;
}
}
Injected code uses Default to initialize new
contract.

&self and &mut self tell macro whether
the state needs to be saved.

Arguments and return values are injected with
JSON-serialization/deserialization allowing
cross-contract calls written in other languages,
like TypeScript.

Any Rust struct can be a contract with zero
modifications.
Expanded
#[derive(Default, Serialize, Deserialize)]
struct Incrementer {
value: u32,
}
impl Incrementer {
pub fn inc(&mut self, by: u32) {
self.value += by;
}
}
#[no_mangle]
pub extern "C" fn inc() {
let args: serde_json::Value = serde_json::from_slice(&input_read()).unwrap();
let by = serde_json::from_value(args["by"].clone()).unwrap();
let mut contract: Incrementer = read_state().unwrap_or_default();
let result = contract.inc(by);
write_state(&contract);
}
Generating eDSL style API
#[derive(Service)]
struct Incrementer {
value: u32,
}
#[mantle_bindgen]
impl Incrementer {
pub fn inc(&mut self, by: u32) {
self.value += by;
}
}
#[derive(Service)]
struct Incrementer {
value: u32,
}
impl Incrementer {
pub fn new(_ctx: &Context) -> Result<Self> {
Ok(Self { value: Default::default() })
}
pub fn inc(&mut self, _ctx: &Context, by: u32) {
self.value += by;
}
}
fn main() {
mantle::service!(Incrementer);
}
struct Incrementer {
value: u32,
}
#[smart_contract]
impl Incrementer {
pub fn init(_params: &mut Parameters) -> Self {
Self { value: 0 }
}
pub fn inc(&mut self, params: &mut Parameters)
-> Result<(), Box<dyn Error>> {
let by: u64 = params.read();
self.value += by;
Ok(())
}
}
Wavelet's smart_contract (non-invasive)
• Contract Interface:

• Derived from your code.
• init function.

• Blockchain Interface:

• Interactions through Parameters

• Blockchain Interface (State):

• Derived from your code.
WASI — Path to Unification
WASI is a modular system interface for WebAssembly.
WASI
SensorsProcesses
Smart contracts
3D Graphics
Core Crypto
WASI — Path to Unification
• Contract Interface — generated by #[near_bindgen]

• Blockchain Interface — available through WASI
Nice to Have Features
• Asynchronous cross-contract calls

• Unit tests and integration tests

• Type-safe

• Model checking (?)
Asynchronous Calls
Rust Contract A
Rust Contract B
TypeScript Contract C
Combinator All
Callback
Promise
Promise
Unit Tests and Integration Tests
Contract A Contract B
Blockchain
Dependency Inversion and Dependency Injection
Impl Contract A Impl Contract B
Impl Blockchain
Trait Contract A Trait Contract B
Trait Blockchain
Unit Testing Contract A
Impl Contract A Impl Contract B
Impl Blockchain
Trait Contract A Trait Contract B
Trait Blockchain
Injected Mock
Injected Mock
Integration Testing Contracts A and B
Impl Contract A Impl Contract B
Impl Blockchain
Trait Contract A Trait Contract B
Trait Blockchain
Injected Mock
Async Cross-Contract Calls
#[derive(Serialize, Deserialize)]
struct Incrementer {
value: u32,
blockchain: Blockchain<dyn Generic>,
decrementer: Contract<dyn Decrementer>,
}
#[near_bindgen]
impl Incrementer {
pub fn inc(&mut self, by: u32) {
self.value += by;
let promise = promise!(self.decrementer.dec, by);
callback!(promise, self.dec_result, by);
}
pub fn dec_result(&mut self, result: bool, by: u32) {
if !result {
self.value -= by;
self.blockchain.log("Rolling back the increment.");
}
}
}
impl Default for Incrementer {
fn default() -> Self {
Self {decrementer: Contract::address("8fd6dac32dd220396f2285700c951cd1befb92b0"), ..Default::default()}
}
}
trait Decrementer {
fn dec(&mut self, value: u32) -> bool;
About Near Protocol
Team of 14 people:

• 3 ex-MemSQL, 5 ex-Google, 1 ex-Facebook

• 4 TopCoder/ICPC Champions/Medalists/Finalists
nearprotocol.com

https://medium.com/nearprotocol

https://twitter.com/NEARProtocol

More Related Content

What's hot

Orion Context Broker NGSI-v2 Overview for Developers That Already Know NGSI-v...
Orion Context Broker NGSI-v2 Overview for Developers That Already Know NGSI-v...Orion Context Broker NGSI-v2 Overview for Developers That Already Know NGSI-v...
Orion Context Broker NGSI-v2 Overview for Developers That Already Know NGSI-v...Fermin Galan
 
Orion Context Broker NGSI-v2 Overview for Developers That Already Know NGSI-v...
Orion Context Broker NGSI-v2 Overview for Developers That Already Know NGSI-v...Orion Context Broker NGSI-v2 Overview for Developers That Already Know NGSI-v...
Orion Context Broker NGSI-v2 Overview for Developers That Already Know NGSI-v...Fermin Galan
 
Libbitcoin slides
Libbitcoin slidesLibbitcoin slides
Libbitcoin slidesswansontec
 
Orion Context Broker NGSI-v2 Overview for Developers That Already Know NGSI-v...
Orion Context Broker NGSI-v2 Overview for Developers That Already Know NGSI-v...Orion Context Broker NGSI-v2 Overview for Developers That Already Know NGSI-v...
Orion Context Broker NGSI-v2 Overview for Developers That Already Know NGSI-v...Fermin Galan
 
Meteor and Bitcoin (Lightning Talk)
Meteor and Bitcoin (Lightning Talk)Meteor and Bitcoin (Lightning Talk)
Meteor and Bitcoin (Lightning Talk)Ryan Casey
 
Envoy, Wasm and Rust - the Mighty Trio
Envoy, Wasm and Rust -  the Mighty TrioEnvoy, Wasm and Rust -  the Mighty Trio
Envoy, Wasm and Rust - the Mighty TrioAnton Weiss
 
Introducing envoy-based service mesh at Booking.com
Introducing envoy-based service mesh at Booking.comIntroducing envoy-based service mesh at Booking.com
Introducing envoy-based service mesh at Booking.comIvan Kruglov
 
Greyhound - Powerful Pure Functional Kafka Library
Greyhound - Powerful Pure Functional Kafka LibraryGreyhound - Powerful Pure Functional Kafka Library
Greyhound - Powerful Pure Functional Kafka LibraryNatan Silnitsky
 
Cosmos SDK Workshop: How to Build a Blockchain from Scratch
Cosmos SDK Workshop: How to Build a Blockchain from ScratchCosmos SDK Workshop: How to Build a Blockchain from Scratch
Cosmos SDK Workshop: How to Build a Blockchain from ScratchTendermint Inc
 
Asynchronous Services – A promising future for OSGi - T Ward
Asynchronous Services – A promising future for OSGi - T WardAsynchronous Services – A promising future for OSGi - T Ward
Asynchronous Services – A promising future for OSGi - T Wardmfrancis
 
Building a blockchain on tendermint
Building a blockchain on tendermintBuilding a blockchain on tendermint
Building a blockchain on tendermintLviv Startup Club
 
Serverless architecture: introduction & first steps
Serverless architecture: introduction & first stepsServerless architecture: introduction & first steps
Serverless architecture: introduction & first stepsThe Software House
 
Cloud Native Identity with SPIFFE
Cloud Native Identity with SPIFFECloud Native Identity with SPIFFE
Cloud Native Identity with SPIFFEPrabath Siriwardena
 
Kerberos, NTLM and LM-Hash
Kerberos, NTLM and LM-HashKerberos, NTLM and LM-Hash
Kerberos, NTLM and LM-HashAnkit Mehta
 
Real time websites and mobile apps with SignalR
Real time websites and mobile apps with SignalRReal time websites and mobile apps with SignalR
Real time websites and mobile apps with SignalRRoy Cornelissen
 
Many Chains, Many Tokens, One Ecosystem
Many Chains, Many Tokens, One EcosystemMany Chains, Many Tokens, One Ecosystem
Many Chains, Many Tokens, One EcosystemTendermint Inc
 

What's hot (19)

Orion Context Broker NGSI-v2 Overview for Developers That Already Know NGSI-v...
Orion Context Broker NGSI-v2 Overview for Developers That Already Know NGSI-v...Orion Context Broker NGSI-v2 Overview for Developers That Already Know NGSI-v...
Orion Context Broker NGSI-v2 Overview for Developers That Already Know NGSI-v...
 
Orion Context Broker NGSI-v2 Overview for Developers That Already Know NGSI-v...
Orion Context Broker NGSI-v2 Overview for Developers That Already Know NGSI-v...Orion Context Broker NGSI-v2 Overview for Developers That Already Know NGSI-v...
Orion Context Broker NGSI-v2 Overview for Developers That Already Know NGSI-v...
 
Libbitcoin slides
Libbitcoin slidesLibbitcoin slides
Libbitcoin slides
 
Orion Context Broker NGSI-v2 Overview for Developers That Already Know NGSI-v...
Orion Context Broker NGSI-v2 Overview for Developers That Already Know NGSI-v...Orion Context Broker NGSI-v2 Overview for Developers That Already Know NGSI-v...
Orion Context Broker NGSI-v2 Overview for Developers That Already Know NGSI-v...
 
Bletchley
BletchleyBletchley
Bletchley
 
Meteor and Bitcoin (Lightning Talk)
Meteor and Bitcoin (Lightning Talk)Meteor and Bitcoin (Lightning Talk)
Meteor and Bitcoin (Lightning Talk)
 
Envoy, Wasm and Rust - the Mighty Trio
Envoy, Wasm and Rust -  the Mighty TrioEnvoy, Wasm and Rust -  the Mighty Trio
Envoy, Wasm and Rust - the Mighty Trio
 
Node.js Chapter1
Node.js Chapter1Node.js Chapter1
Node.js Chapter1
 
Introducing envoy-based service mesh at Booking.com
Introducing envoy-based service mesh at Booking.comIntroducing envoy-based service mesh at Booking.com
Introducing envoy-based service mesh at Booking.com
 
Greyhound - Powerful Pure Functional Kafka Library
Greyhound - Powerful Pure Functional Kafka LibraryGreyhound - Powerful Pure Functional Kafka Library
Greyhound - Powerful Pure Functional Kafka Library
 
Kerberos
KerberosKerberos
Kerberos
 
Cosmos SDK Workshop: How to Build a Blockchain from Scratch
Cosmos SDK Workshop: How to Build a Blockchain from ScratchCosmos SDK Workshop: How to Build a Blockchain from Scratch
Cosmos SDK Workshop: How to Build a Blockchain from Scratch
 
Asynchronous Services – A promising future for OSGi - T Ward
Asynchronous Services – A promising future for OSGi - T WardAsynchronous Services – A promising future for OSGi - T Ward
Asynchronous Services – A promising future for OSGi - T Ward
 
Building a blockchain on tendermint
Building a blockchain on tendermintBuilding a blockchain on tendermint
Building a blockchain on tendermint
 
Serverless architecture: introduction & first steps
Serverless architecture: introduction & first stepsServerless architecture: introduction & first steps
Serverless architecture: introduction & first steps
 
Cloud Native Identity with SPIFFE
Cloud Native Identity with SPIFFECloud Native Identity with SPIFFE
Cloud Native Identity with SPIFFE
 
Kerberos, NTLM and LM-Hash
Kerberos, NTLM and LM-HashKerberos, NTLM and LM-Hash
Kerberos, NTLM and LM-Hash
 
Real time websites and mobile apps with SignalR
Real time websites and mobile apps with SignalRReal time websites and mobile apps with SignalR
Real time websites and mobile apps with SignalR
 
Many Chains, Many Tokens, One Ecosystem
Many Chains, Many Tokens, One EcosystemMany Chains, Many Tokens, One Ecosystem
Many Chains, Many Tokens, One Ecosystem
 

Similar to Rust Smart Contracts

Realtime web experience with signalR
Realtime web experience with signalRRealtime web experience with signalR
Realtime web experience with signalRRan Wahle
 
(Don't) Go Tracing Server Calls
(Don't) Go Tracing Server Calls(Don't) Go Tracing Server Calls
(Don't) Go Tracing Server CallsBrandon Hunter
 
«Real Time» Web Applications with SignalR in ASP.NET
«Real Time» Web Applications with SignalR in ASP.NET«Real Time» Web Applications with SignalR in ASP.NET
«Real Time» Web Applications with SignalR in ASP.NETAlessandro Giorgetti
 
Token platform based on sidechain
Token platform based on sidechainToken platform based on sidechain
Token platform based on sidechainLuniverse Dunamu
 
Algorand Technical Workshop 2021
Algorand Technical Workshop 2021Algorand Technical Workshop 2021
Algorand Technical Workshop 2021DanielBohnemann
 
Deploying large-scale, serverless and asynchronous systems - without integrat...
Deploying large-scale, serverless and asynchronous systems - without integrat...Deploying large-scale, serverless and asynchronous systems - without integrat...
Deploying large-scale, serverless and asynchronous systems - without integrat...DiUS
 
Introduction to Ethereum Smart Contracts
Introduction to Ethereum Smart Contracts Introduction to Ethereum Smart Contracts
Introduction to Ethereum Smart Contracts ArcBlock
 
The consortium 基于状态的数据中心自动化管理工具
The consortium  基于状态的数据中心自动化管理工具The consortium  基于状态的数据中心自动化管理工具
The consortium 基于状态的数据中心自动化管理工具Leo Zhou
 
Hyperleger Composer Architecure Deep Dive
Hyperleger Composer Architecure Deep DiveHyperleger Composer Architecure Deep Dive
Hyperleger Composer Architecure Deep DiveDan Selman
 
Typhoon Managed Execution Toolkit
Typhoon Managed Execution ToolkitTyphoon Managed Execution Toolkit
Typhoon Managed Execution ToolkitDimitry Snezhkov
 
Smart Contracts: From Zero to Dapp Hero | Hedera18
Smart Contracts: From Zero to Dapp Hero | Hedera18Smart Contracts: From Zero to Dapp Hero | Hedera18
Smart Contracts: From Zero to Dapp Hero | Hedera18Hedera Hashgraph
 
Contract-based Testing Approach as a Tool for Shift Lef
Contract-based Testing Approach as a Tool for Shift LefContract-based Testing Approach as a Tool for Shift Lef
Contract-based Testing Approach as a Tool for Shift LefKatherine Golovinova
 
사물 인터넷을 위한 AWS FreeRTOS 소개
사물 인터넷을 위한 AWS FreeRTOS 소개사물 인터넷을 위한 AWS FreeRTOS 소개
사물 인터넷을 위한 AWS FreeRTOS 소개Harry Oh
 
[Call for code] IBM 블록체인을 활용하여 투명하게 구호기금 관리하기 - Hyperledger Fabric v1.1 by 맹개발
[Call for code] IBM 블록체인을 활용하여 투명하게 구호기금 관리하기 - Hyperledger Fabric v1.1 by 맹개발 [Call for code] IBM 블록체인을 활용하여 투명하게 구호기금 관리하기 - Hyperledger Fabric v1.1 by 맹개발
[Call for code] IBM 블록체인을 활용하여 투명하게 구호기금 관리하기 - Hyperledger Fabric v1.1 by 맹개발 Yunho Maeng
 
.NET Conf 2019 高雄場 - .NET Core 3.0
.NET Conf 2019 高雄場 - .NET Core 3.0.NET Conf 2019 高雄場 - .NET Core 3.0
.NET Conf 2019 高雄場 - .NET Core 3.0Jeff Chu
 
Design patterns for microservice architecture
Design patterns for microservice architectureDesign patterns for microservice architecture
Design patterns for microservice architectureThe Software House
 
Blockchain technology-in-fin tech - Anton Sitnikov
Blockchain technology-in-fin tech - Anton SitnikovBlockchain technology-in-fin tech - Anton Sitnikov
Blockchain technology-in-fin tech - Anton SitnikovDataFest Tbilisi
 
بالعربي التطور في البرمجة باستخدام ال .Net
بالعربي التطور في البرمجة باستخدام ال .Netبالعربي التطور في البرمجة باستخدام ال .Net
بالعربي التطور في البرمجة باستخدام ال .NetMohamed Galal
 
Deploying Cloud Native Red Team Infrastructure with Kubernetes, Istio and Envoy
Deploying Cloud Native Red Team Infrastructure with Kubernetes, Istio and Envoy Deploying Cloud Native Red Team Infrastructure with Kubernetes, Istio and Envoy
Deploying Cloud Native Red Team Infrastructure with Kubernetes, Istio and Envoy Jeffrey Holden
 

Similar to Rust Smart Contracts (20)

Realtime web experience with signalR
Realtime web experience with signalRRealtime web experience with signalR
Realtime web experience with signalR
 
(Don't) Go Tracing Server Calls
(Don't) Go Tracing Server Calls(Don't) Go Tracing Server Calls
(Don't) Go Tracing Server Calls
 
«Real Time» Web Applications with SignalR in ASP.NET
«Real Time» Web Applications with SignalR in ASP.NET«Real Time» Web Applications with SignalR in ASP.NET
«Real Time» Web Applications with SignalR in ASP.NET
 
Token platform based on sidechain
Token platform based on sidechainToken platform based on sidechain
Token platform based on sidechain
 
Algorand Technical Workshop 2021
Algorand Technical Workshop 2021Algorand Technical Workshop 2021
Algorand Technical Workshop 2021
 
Deploying large-scale, serverless and asynchronous systems - without integrat...
Deploying large-scale, serverless and asynchronous systems - without integrat...Deploying large-scale, serverless and asynchronous systems - without integrat...
Deploying large-scale, serverless and asynchronous systems - without integrat...
 
Introduction to Ethereum Smart Contracts
Introduction to Ethereum Smart Contracts Introduction to Ethereum Smart Contracts
Introduction to Ethereum Smart Contracts
 
The consortium 基于状态的数据中心自动化管理工具
The consortium  基于状态的数据中心自动化管理工具The consortium  基于状态的数据中心自动化管理工具
The consortium 基于状态的数据中心自动化管理工具
 
Hyperleger Composer Architecure Deep Dive
Hyperleger Composer Architecure Deep DiveHyperleger Composer Architecure Deep Dive
Hyperleger Composer Architecure Deep Dive
 
Typhoon Managed Execution Toolkit
Typhoon Managed Execution ToolkitTyphoon Managed Execution Toolkit
Typhoon Managed Execution Toolkit
 
Smart Contracts: From Zero to Dapp Hero | Hedera18
Smart Contracts: From Zero to Dapp Hero | Hedera18Smart Contracts: From Zero to Dapp Hero | Hedera18
Smart Contracts: From Zero to Dapp Hero | Hedera18
 
Contract-based Testing Approach as a Tool for Shift Lef
Contract-based Testing Approach as a Tool for Shift LefContract-based Testing Approach as a Tool for Shift Lef
Contract-based Testing Approach as a Tool for Shift Lef
 
사물 인터넷을 위한 AWS FreeRTOS 소개
사물 인터넷을 위한 AWS FreeRTOS 소개사물 인터넷을 위한 AWS FreeRTOS 소개
사물 인터넷을 위한 AWS FreeRTOS 소개
 
[Call for code] IBM 블록체인을 활용하여 투명하게 구호기금 관리하기 - Hyperledger Fabric v1.1 by 맹개발
[Call for code] IBM 블록체인을 활용하여 투명하게 구호기금 관리하기 - Hyperledger Fabric v1.1 by 맹개발 [Call for code] IBM 블록체인을 활용하여 투명하게 구호기금 관리하기 - Hyperledger Fabric v1.1 by 맹개발
[Call for code] IBM 블록체인을 활용하여 투명하게 구호기금 관리하기 - Hyperledger Fabric v1.1 by 맹개발
 
.NET Conf 2019 高雄場 - .NET Core 3.0
.NET Conf 2019 高雄場 - .NET Core 3.0.NET Conf 2019 高雄場 - .NET Core 3.0
.NET Conf 2019 高雄場 - .NET Core 3.0
 
Design patterns for microservice architecture
Design patterns for microservice architectureDesign patterns for microservice architecture
Design patterns for microservice architecture
 
Deno Crate Organization
Deno Crate OrganizationDeno Crate Organization
Deno Crate Organization
 
Blockchain technology-in-fin tech - Anton Sitnikov
Blockchain technology-in-fin tech - Anton SitnikovBlockchain technology-in-fin tech - Anton Sitnikov
Blockchain technology-in-fin tech - Anton Sitnikov
 
بالعربي التطور في البرمجة باستخدام ال .Net
بالعربي التطور في البرمجة باستخدام ال .Netبالعربي التطور في البرمجة باستخدام ال .Net
بالعربي التطور في البرمجة باستخدام ال .Net
 
Deploying Cloud Native Red Team Infrastructure with Kubernetes, Istio and Envoy
Deploying Cloud Native Red Team Infrastructure with Kubernetes, Istio and Envoy Deploying Cloud Native Red Team Infrastructure with Kubernetes, Istio and Envoy
Deploying Cloud Native Red Team Infrastructure with Kubernetes, Istio and Envoy
 

Recently uploaded

一比一原版UTS毕业证悉尼科技大学毕业证成绩单如何办理
一比一原版UTS毕业证悉尼科技大学毕业证成绩单如何办理一比一原版UTS毕业证悉尼科技大学毕业证成绩单如何办理
一比一原版UTS毕业证悉尼科技大学毕业证成绩单如何办理aagad
 
The Use of AI in Indonesia Election 2024: A Case Study
The Use of AI in Indonesia Election 2024: A Case StudyThe Use of AI in Indonesia Election 2024: A Case Study
The Use of AI in Indonesia Election 2024: A Case StudyDamar Juniarto
 
How to Use Contact Form 7 Like a Pro.pptx
How to Use Contact Form 7 Like a Pro.pptxHow to Use Contact Form 7 Like a Pro.pptx
How to Use Contact Form 7 Like a Pro.pptxGal Baras
 
The+Prospects+of+E-Commerce+in+China.pptx
The+Prospects+of+E-Commerce+in+China.pptxThe+Prospects+of+E-Commerce+in+China.pptx
The+Prospects+of+E-Commerce+in+China.pptxlaozhuseo02
 
1.Wireless Communication System_Wireless communication is a broad term that i...
1.Wireless Communication System_Wireless communication is a broad term that i...1.Wireless Communication System_Wireless communication is a broad term that i...
1.Wireless Communication System_Wireless communication is a broad term that i...JeyaPerumal1
 
Article writing on excessive use of internet.pptx
Article writing on excessive use of internet.pptxArticle writing on excessive use of internet.pptx
Article writing on excessive use of internet.pptxabhinandnam9997
 
History+of+E-commerce+Development+in+China-www.cfye-commerce.shop
History+of+E-commerce+Development+in+China-www.cfye-commerce.shopHistory+of+E-commerce+Development+in+China-www.cfye-commerce.shop
History+of+E-commerce+Development+in+China-www.cfye-commerce.shoplaozhuseo02
 
The AI Powered Organization-Intro to AI-LAN.pdf
The AI Powered Organization-Intro to AI-LAN.pdfThe AI Powered Organization-Intro to AI-LAN.pdf
The AI Powered Organization-Intro to AI-LAN.pdfSiskaFitrianingrum
 
ER(Entity Relationship) Diagram for online shopping - TAE
ER(Entity Relationship) Diagram for online shopping - TAEER(Entity Relationship) Diagram for online shopping - TAE
ER(Entity Relationship) Diagram for online shopping - TAEHimani415946
 
Multi-cluster Kubernetes Networking- Patterns, Projects and Guidelines
Multi-cluster Kubernetes Networking- Patterns, Projects and GuidelinesMulti-cluster Kubernetes Networking- Patterns, Projects and Guidelines
Multi-cluster Kubernetes Networking- Patterns, Projects and GuidelinesSanjeev Rampal
 

Recently uploaded (12)

一比一原版UTS毕业证悉尼科技大学毕业证成绩单如何办理
一比一原版UTS毕业证悉尼科技大学毕业证成绩单如何办理一比一原版UTS毕业证悉尼科技大学毕业证成绩单如何办理
一比一原版UTS毕业证悉尼科技大学毕业证成绩单如何办理
 
The Use of AI in Indonesia Election 2024: A Case Study
The Use of AI in Indonesia Election 2024: A Case StudyThe Use of AI in Indonesia Election 2024: A Case Study
The Use of AI in Indonesia Election 2024: A Case Study
 
How to Use Contact Form 7 Like a Pro.pptx
How to Use Contact Form 7 Like a Pro.pptxHow to Use Contact Form 7 Like a Pro.pptx
How to Use Contact Form 7 Like a Pro.pptx
 
The+Prospects+of+E-Commerce+in+China.pptx
The+Prospects+of+E-Commerce+in+China.pptxThe+Prospects+of+E-Commerce+in+China.pptx
The+Prospects+of+E-Commerce+in+China.pptx
 
1.Wireless Communication System_Wireless communication is a broad term that i...
1.Wireless Communication System_Wireless communication is a broad term that i...1.Wireless Communication System_Wireless communication is a broad term that i...
1.Wireless Communication System_Wireless communication is a broad term that i...
 
Article writing on excessive use of internet.pptx
Article writing on excessive use of internet.pptxArticle writing on excessive use of internet.pptx
Article writing on excessive use of internet.pptx
 
History+of+E-commerce+Development+in+China-www.cfye-commerce.shop
History+of+E-commerce+Development+in+China-www.cfye-commerce.shopHistory+of+E-commerce+Development+in+China-www.cfye-commerce.shop
History+of+E-commerce+Development+in+China-www.cfye-commerce.shop
 
The AI Powered Organization-Intro to AI-LAN.pdf
The AI Powered Organization-Intro to AI-LAN.pdfThe AI Powered Organization-Intro to AI-LAN.pdf
The AI Powered Organization-Intro to AI-LAN.pdf
 
Stay Ahead with 2024's Top Web Design Trends
Stay Ahead with 2024's Top Web Design TrendsStay Ahead with 2024's Top Web Design Trends
Stay Ahead with 2024's Top Web Design Trends
 
The Best AI Powered Software - Intellivid AI Studio
The Best AI Powered Software - Intellivid AI StudioThe Best AI Powered Software - Intellivid AI Studio
The Best AI Powered Software - Intellivid AI Studio
 
ER(Entity Relationship) Diagram for online shopping - TAE
ER(Entity Relationship) Diagram for online shopping - TAEER(Entity Relationship) Diagram for online shopping - TAE
ER(Entity Relationship) Diagram for online shopping - TAE
 
Multi-cluster Kubernetes Networking- Patterns, Projects and Guidelines
Multi-cluster Kubernetes Networking- Patterns, Projects and GuidelinesMulti-cluster Kubernetes Networking- Patterns, Projects and Guidelines
Multi-cluster Kubernetes Networking- Patterns, Projects and Guidelines
 

Rust Smart Contracts

  • 1. Rust Smart Contracts Maksym Zavershynskyi, Near Protocol
  • 2. Smart Contracts & AWS Lambda • Event-driven — executes code only when needed. Pay per execution; • Serverless — no need to provision servers; Request Response Regular server is active all time Zzzzz.. Lambda is only active when called
  • 3. Smart Contracts & AWS Lambda • Event-driven — executes code only when needed. Pay per execution; • Serverless — no need to provision servers; Regular server is active all time Lambda is only active when called Request Response Request Response
  • 4. A Smart Contract • Event-driven — executes code only when needed. Pay per execution; • Serverless — no need to provision servers; • Decentralized — it is not run by a single entity.
  • 5. Immutable History of Events Users running nodes collectively build the blockchain
  • 6. Fat Fingers and Bugs in Closed Code
  • 7. Inside a Node Blockchain Layer • P2P Network • Consensus • Blocks Storage • RPC API Runtime Layer Virtual Machine State Storage Code
  • 8. WASM 
 + Rust/TypeScript Pros: • Existing tooling and community; • General purpose & Turing complete; 
 Cons: • Was not designed for the blockchain; • No formal verification. Specialized
 VM + Language Pros: • Designed for the blockchain; • Allows formal verification (?) 
 Cons: • Niche language; • Not Turing complete (?)
  • 9. Requirements for VM • Platform-independent WASM ✓ • Determinism WASM ✓ w/o floats • Sand-boxed execution/compilation WASM ✓ certain executors • Small size of compiled code WASM ✓ • Close to machine code WASM ✓
  • 10. WASM + Rust Bonus Points • Existing tooling and community; • Code transfer; • Memory safety; • Zero-cost abstractions.
  • 11. Rust Zero-Cost Abstractions Zero cost abstractions. What you don’t use, you don’t pay for. And further: What you do use, you couldn’t hand code any better. - Bjarne Stroustrup
  • 12. Rust APIs near_bindgen — Rust API for NEAR blockchain smart_contract — Rust API for Wavelet blockchain by Perlin EWASM — a subset of WASM for Ethereum-like blockchains Ink! — Rust API for Substrate/Polkadot blockchain Mantle — Rust API for Oasis blockchain Deprecated: PWASM + Fleetwood — Rust API for Parity's Kovan blockchain
  • 13. Contract Interface and Blockchain Interface Blockchain Layer WASM Executor Rust Contract Contract Interface Methods defined by the contract 
 that the blockchain can call State Storage Blockchain Interface
 Methods defined by the blockchain 
 that the contract can call
  • 15. #![cfg_attr(not(any(test, feature = "test-env")), no_std)] use ink_core::{memory::format, storage}; use ink_lang::contract; contract!{ struct Incrementer { value: storage::Value<u32>, } impl Deploy for Incrementer { fn deploy(&mut self, init_value: u32) { self.value.set(init_value) } } impl Incrementer { pub(external) fn inc(&mut self, by: u32) { env.println(&format!("Incrementer::inc by = {:?}", by)); self.value += by; } } } Ink! (eDSL) • Contract Interface: • Implement Deploy::deploy • Wrap code into contract!{}
 • Blockchain Interface: • Interactions through env::*
 • Blockchain Interface (State): • Use storage::* wrappers;
  • 16. use mantle::{Context, Service}; #[derive(Service)] struct Incrementer { value: u32, } impl Incrementer { pub fn new(_ctx: &Context) -> Result<Self> { Ok(Self { value: 0 }) } pub fn inc(&mut self, _ctx: &Context, by: u32) { self.value += by; } } fn main() { mantle::service!(Incrementer); } Mantle (eDSL) • Contract Interface: • Additional argument: &Context • Decorate with with #[derive(Service)] • Special main function.
 • Blockchain Interface: • Through &Context
 • Blockchain Interface (State): • Decorate fields with #[indexed]; • Compiler plugin.
  • 18. #[derive(Default, Serialize, Deserialize)] struct Incrementer { value: u32, } #[near_bindgen] impl Incrementer { pub fn inc(&mut self, by: u32) { self.value += by; } } near_bindgen (non-invasive) • Contract Interface: • Derived from your code.
 • Blockchain Interface: • Interactions through Blockchain<>
 • Blockchain Interface (State): • Derived from your code. So insignificant that we did not give it a name
  • 19. How Does near_bindgen Work M.A.G.I.C.
  • 20. How Does near_bindgen Work Macros
 Automatically
 Generated
 Injected
 Code
  • 21. How Does It Work #[derive(Default, Serialize, Deserialize)] struct Incrementer { value: u32, } #[near_bindgen] impl Incrementer { pub fn inc(&mut self, by: u32) { self.value += by; } } Injected code uses Default to initialize new contract. &self and &mut self tell macro whether the state needs to be saved. Arguments and return values are injected with JSON-serialization/deserialization allowing cross-contract calls written in other languages, like TypeScript. Any Rust struct can be a contract with zero modifications.
  • 22. Expanded #[derive(Default, Serialize, Deserialize)] struct Incrementer { value: u32, } impl Incrementer { pub fn inc(&mut self, by: u32) { self.value += by; } } #[no_mangle] pub extern "C" fn inc() { let args: serde_json::Value = serde_json::from_slice(&input_read()).unwrap(); let by = serde_json::from_value(args["by"].clone()).unwrap(); let mut contract: Incrementer = read_state().unwrap_or_default(); let result = contract.inc(by); write_state(&contract); }
  • 23. Generating eDSL style API #[derive(Service)] struct Incrementer { value: u32, } #[mantle_bindgen] impl Incrementer { pub fn inc(&mut self, by: u32) { self.value += by; } } #[derive(Service)] struct Incrementer { value: u32, } impl Incrementer { pub fn new(_ctx: &Context) -> Result<Self> { Ok(Self { value: Default::default() }) } pub fn inc(&mut self, _ctx: &Context, by: u32) { self.value += by; } } fn main() { mantle::service!(Incrementer); }
  • 24. struct Incrementer { value: u32, } #[smart_contract] impl Incrementer { pub fn init(_params: &mut Parameters) -> Self { Self { value: 0 } } pub fn inc(&mut self, params: &mut Parameters) -> Result<(), Box<dyn Error>> { let by: u64 = params.read(); self.value += by; Ok(()) } } Wavelet's smart_contract (non-invasive) • Contract Interface: • Derived from your code. • init function. • Blockchain Interface: • Interactions through Parameters • Blockchain Interface (State): • Derived from your code.
  • 25. WASI — Path to Unification WASI is a modular system interface for WebAssembly. WASI SensorsProcesses Smart contracts 3D Graphics Core Crypto
  • 26. WASI — Path to Unification • Contract Interface — generated by #[near_bindgen] • Blockchain Interface — available through WASI
  • 27. Nice to Have Features • Asynchronous cross-contract calls • Unit tests and integration tests • Type-safe • Model checking (?)
  • 28. Asynchronous Calls Rust Contract A Rust Contract B TypeScript Contract C Combinator All Callback Promise Promise
  • 29. Unit Tests and Integration Tests Contract A Contract B Blockchain
  • 30. Dependency Inversion and Dependency Injection Impl Contract A Impl Contract B Impl Blockchain Trait Contract A Trait Contract B Trait Blockchain
  • 31. Unit Testing Contract A Impl Contract A Impl Contract B Impl Blockchain Trait Contract A Trait Contract B Trait Blockchain Injected Mock Injected Mock
  • 32. Integration Testing Contracts A and B Impl Contract A Impl Contract B Impl Blockchain Trait Contract A Trait Contract B Trait Blockchain Injected Mock
  • 33. Async Cross-Contract Calls #[derive(Serialize, Deserialize)] struct Incrementer { value: u32, blockchain: Blockchain<dyn Generic>, decrementer: Contract<dyn Decrementer>, } #[near_bindgen] impl Incrementer { pub fn inc(&mut self, by: u32) { self.value += by; let promise = promise!(self.decrementer.dec, by); callback!(promise, self.dec_result, by); } pub fn dec_result(&mut self, result: bool, by: u32) { if !result { self.value -= by; self.blockchain.log("Rolling back the increment."); } } } impl Default for Incrementer { fn default() -> Self { Self {decrementer: Contract::address("8fd6dac32dd220396f2285700c951cd1befb92b0"), ..Default::default()} } } trait Decrementer { fn dec(&mut self, value: u32) -> bool;
  • 34. About Near Protocol Team of 14 people: • 3 ex-MemSQL, 5 ex-Google, 1 ex-Facebook • 4 TopCoder/ICPC Champions/Medalists/Finalists