Smartcity Hack Substrate Workshop

This is the cheat sheet in addition to my SmartCityHack Workshop (part1, part2, sorry, videos are in Russian only so far..)

Intro

Polkadot Substrate briefly

https://www.parity.io/a-brief-summary-of-everything-substrate-polkadot/

Runtime vs Smart Contracts

Polkadot parachains require more effort than smart contract-based Dapps and some applications don’t justify setting up a whole parachain, while others do. This depends on the scope of each application and has to be evaluated on an individual basis https://www.parity.io/a-brief-summary-of-everything-substrate-polkadot/

One could argue that parachains are optimized for interoperability (communication between separate applications/chains), while smart contracts are optimized for intraoperability (communication within a chain runtime). https://www.parity.io/a-brief-summary-of-everything-substrate-polkadot/

SRML

Substrate Runitme Modules library

  • Assets
  • Aura
  • Balances
  • Consensus
  • Contract
  • Council
  • Democracy
  • Finality Tracker
  • Grandpa
  • Indices
  • Session
  • Staking
  • Sudo
  • Timestamp
  • Treasury

Build your chain in 30mins

From scratch. Use template https://github.com/paritytech/substrate/tree/master/node-template

Follow the tutorial https://docs.substrate.dev/docs/creating-a-custom-substrate-chain

Have a look on Gav's demo from Web3 Summit 2018 https://youtu.be/0IoUZdDi5Is

Robonomics Substrate Node

Robonomics breifly https://agryaznov.com/reports/2018/08/29/robonomics-2018.html

https://github.com/airalab/substrate-node-robonomics

Launch command

$ ./target/release/robonomics --bootnodes /ip4/95.216.202.55/tcp/30333/p2p/QmbPgV4iTsWHhrZDTPU5g1YtxJ11PcGC3f9oMTaNLUvJ6m --name greez --telemetry-url  ws://telemetry.polkadot.io:1024

Make Polkadot UI understand it: put this json to Settings/Developer/Custom type definitions

https://github.com/airalab/substrate-node-robonomics/blob/master/res/custom_types.json

Let's dissect the runtime logic

https://github.com/airalab/substrate-node-robonomics/blob/v0.10.2/runtime/src/robonomics.rs

hint: promisee - тот, кто шлёт Demand (кредитор) promisor - тот, кто шлёт Offer (должник). В текущей версии именно он финализирует обязательство (что не очень правильно, см ниже как добавим Custodian-a)

model - ipfs хеш файла с идентификатором кфс; например, описание пакетов, которые установлены на дроне, их параметров и т.п objective - ipfs хеш файла-таблицы с данными для кфс; например, координата куда должен прилететь дрон, или gcode для 3д принтера result - ipfs хеш файла с протоколом работ или результатом проверки; например, третья сторона проверила конечное местоположение дрона, финализировала контракт, указав подтверждение- файл со своими координатами обнаруженного дрона.

при матчинге Offer-Demand, создаётся обязательство: fn create_liability при этом резервируется сумма контракта на счету promisee:

T::Currency::reserve(&promisee, order.cost)
   .map_err(|_| "promisee's balance too low")?;

которая затем пересылается при финализировании обязательства:

 T::Currency::repatriate_reserved(&liability.promisee, &liability.promisor, liability.order.cost)?;

Try It with UI

If you don't have your own Node yet, go to https://polkadot.js.org/apps/#/settings, Custom Tab and set this endpoint: wss://robonomics.akru.me/

Modify, re-build and launch

Let's add the Custodian role into the process. Currently, promisor finalizes liability by himself. This allows him to misbehavior and take the money without really executing the order. We need a third party here, let's call him Custodian, who verifies the order execution and finalizes the liability.

Have a look at my Pull Request: https://github.com/airalab/substrate-node-robonomics/pull/23 (yay! it is merged! :stuckouttonguewinkingeye: )

It's quite a simple (but powerful!) upgrade: just 7 strings of new code, find them by the prepending commment starting with // ACTION: add custodian here

Checkout this upgraded version, and now build it

$ ./build.sh
$ cargo build --release

Why 2 builds

purge chain (not the only possible option)

$ ./target/release/robonomics  purge-chain --dev

alternative option: don't purge, just load new wasm runtime runtime/wasm/target/wasm32-unknown-unknown/release/robonomics_runtime.compact.wasm (awesome fork-less feature of Substrate)

launch

$ ./target/release/robonomics --name greez --dev

Update custom types to Polkadot UI at Settings/Developer/Custom type definitions

{
    "Order": {
        "model": "Vec<u8>",
        "objective": "Vec<u8>",
        "cost": "Balance",
        "custodian": "AccountId"
    },
    "Demand": {
        "order": "Order",
        "sender": "AccountId"
    },
    "Offer": {
        "order": "Order",
        "sender": "AccountId"
    },
    "Liability": {
        "order": "Order",
        "promisee": "AccountId",
        "promisor": "AccountId",
        "result": "Option<Vec<u8>>"
    },
    "LiabilityIndex": "u64"
}

Some ideas for further improvements

Substrate UI

Home task

Build UI for the Robonomics Liability process Good explanation of how to accomplish this https://shawntabrizi.com/substrate-collectables-workshop/#/4/introduction