Willem Olding
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # First steps writing Holochain hApps with Rust **Now updated for Holochain v0.0.2!** If you have been following the development of Holochain you may be aware that a developer preview of the next iteration has been released. This release does away with JavaScript as the main language for developing hApps, instead switching to WebAssembly. This means that [any language that can compile to WebAssembly](https://github.com/appcypher/awesome-wasm-langs) can one day be used for Holochain. Writing WebAssembly that complies with the Holochain runtime can be tricky. To make development as streamlined as possible the core team has been developing a Holochain-dev-kit (HDK) for the first supported language, Rust! In the near future there are also plans to release an HDK for [AssemblyScript](https://github.com/AssemblyScript/assemblyscript), a strictly-typed subset of TypeScript, and the community is encouraged to develop an HDK for their language of choice. In this article we will walk through the steps of creating a simple hApp using Rust and highlight some of the differences from the previous version. ## Requirements First step is to download the appropriate [dev preview release](https://github.com/holochain/holochain-rust/releases/tag/holochain-cmd-v0.0.2) for your OS. If you decide to build the latest version from source, be warned that the API is undergoing rapid change, so some of the steps in this article may not work. The release contains the binary for the holochain developer command line tool, `hc`, which is used to generate a skeleton app, run tests and build the app package. Ensure that `hc` is available on your path. If you instead decide to [build from source](https://github.com/holochain/holochain-rust/tree/holochain-cmd-v0.0.2/cmd) cargo will ensure the binaries are on your path automatically. If you want to jump ahead to see what the completed project will look like, the [full source code is available on GitHub](https://github.com/willemolding/holochain-rust-todo). ## First steps We will be making a classic to-do list hApp. A user can create new lists and add items to a list. They should also be able to retrieve a list by its address and all of the items on each list. Let's begin by generating an empty hApp skeleton by running: ``` hc init todo-list ``` This will generate the following directory structure: ``` todo-list/ ├── app.json ├── test │   └── ... └── zomes ``` Notice the `zomes` directory. All Holochain hApps are comprised of one or more zomes. They can be thought of as similar to modules in JavaScript, each one should provide some self-contained functionality. Every zome has its own build system so it is possible to combine zomes written in different languages to produce a single hApp. We will create a single zome called `lists` that uses a Rust build system: ``` cd todo-list hc generate zomes/lists rust ``` The project structure should now be as follows: ``` ├── app.json ├── test │   └── ... └── zomes └── lists ├── code │   ├── .build │   ├── Cargo.toml │   └── src │   └── lib.rs └── zome.json ``` ## Writing the lists zome The Rust HDK makes use of Rust macros to reduce the need for boilerplate code. The most important of which is the [`define_zome!`](https://developer.holochain.org/api/0.0.2/hdk/macro.define_zome.html) macro. Every zome must use this to define the structure of the zome, what entries it contains, which functions it exposes and what to do on first start-up (genesis). Open up `lib.rs` and replace its contents with the following: ``` #[macro_use] extern crate hdk; define_zome! { entries: [ ] genesis: || { Ok(()) } functions: { } } ``` This is the simplest possible zome with no entries and no exposed functions. ### Adding some Entries Unlike in holochain-proto, where you needed to define a JSON schema to validate entries, holochain entries in Rust map to a native struct type. We can define our list and listItem structs as follows: ``` #[derive(Serialize, Deserialize, Debug, DefaultJson)] struct List { name: String } #[derive(Serialize, Deserialize, Debug, DefaultJson)] struct ListItem { text: String, completed: bool } ``` You might notice that the `List` struct does not contain a field that holds a collection of `ListItem`s. This will be implemented using links, which we will discuss later. Also be sure to add the following to the list of imports: ``` #![feature(try_from)] use std::convert::TryFrom; #[macro_use] extern crate hdk; #[macro_use] extern crate serde_derive; #[macro_use] extern crate holochain_core_types_derive; #[macro_use] extern crate serde_json; use hdk::holochain_core_types::{ hash::HashString, error::HolochainError, entry::Entry, dna::zome::entry_types::Sharing, entry::entry_type::EntryType, json::JsonString, cas::content::Address }; ``` The `Serialize` and `Deserialize` derived traits allow the structs to be converted to and from JSON, which is how entries are managed internally in Holochain. The DefaultJson derived trait comes from the holochain hDK itself and allows for seamless converting between data stored in the DHT and rust structs. These structs on their own are not yet valid Holochain entries. To create these we must include them in the `define_zome!` macro by using the `entry!` macro: ``` ... define_zome! { entries: [ entry!( name: "list", description: "", sharing: Sharing::Public, native_type: List, validation_package: || hdk::ValidationPackageDefinition::Entry, validation: |list: List, _ctx: hdk::ValidationData| { Ok(()) }, links: [ to!( "listItem", tag: "items", validation_package: || hdk::ValidationPackageDefinition::Entry, validation: |base: Address, target: Address, _ctx: hdk::ValidationData| { Ok(()) } ) ] ), entry!( name: "listItem", description: "", sharing: Sharing::Public, native_type: ListItem, validation_package: || hdk::ValidationPackageDefinition::Entry, validation: |list_item: ListItem, _ctx: hdk::ValidationData| { Ok(()) } ) ] ... ``` Take note of the `native_type` field of the macro which gives which Rust struct represents the entry type. The `validation_package` field is a function that defines what data should be passed to the validation function through the `ctx` argument. In this case we use a predefined function to only include the entry itself, but it is also possible to pass chain headers, chain entries or the full local chain. The validation field is a function that performs custom validation for the entry. In both our cases we are just returning `Ok(())`. New in Holochain v0.0.2 is validation for link entries. As we will see later links are the main way to encode relational data in holochain. The `links` section of the entry macro defines what other types of entries are allowed to link to and from this type. This also includes a validation function for fine grain control over linking. See [the entry macro documentation](https://developer.holochain.org/api/0.0.2/hdk/macro.entry.html) for more info. ### Adding Functions Finally we need a way to interact with the hApp. We will define the following functions: `create_list`, `add_item` and `get_list`. `get_list` will retrieve a list and all the items linked to each list. For each of these functions we must define a handler, which is a Rust function that will be executed when the container calls the function. (For more on containers, read [Nico's recent post](https://medium.com/holochain/holochain-developer-preview-release-56d0ede52da#23a8).) It is best practice for functions to always return a JSON string (`serde_json::Value`). At the moment the handler function names cannot be the same as the function itself so we will prefix them with `handle_`. This will be fixed in an upcoming release. The handler for `create_list` could be written as: ``` fn handle_create_list(list: List) -> JsonString { let list_entry = Entry::new(EntryType::App("list".into()), list); match hdk::commit_entry(&list_entry) { Ok(address) => json!({"success": true, "address": address}).into(), Err(hdk_err) => hdk_err.into() } } ``` The `hdk::commit_entry` function is how a zome can interact with holochain core to add entries to the DHT or local chain. This will trigger the validation function for the entry and if successful will store the entry and return its hash/address. The `add_item` function requires the use of holochain links to associate two entries. In holochain-proto this required the use of a commit with a special Links entry but it can now be done using the HDK function `link_entries(address1, address2, tag)`. The add item handler accepts a `ListItem` and an address of a list, commits the `ListItem`, then links it to the list address: ``` fn handle_add_item(list_item: ListItem, list_addr: HashString) -> JsonString { let list_item_entry = Entry::new(EntryType::App("listItem".into()), list_item); match hdk::commit_entry(&list_item_entry) // commit the list item .and_then(|item_addr| { hdk::link_entries(&list_addr, &item_addr, "items") // if successful, link to list }) { Ok(_) => { json!({"success": true}).into() }, Err(hdk_err) => hdk_err.into() } } ``` At the moment there is no validation done on the link entries. This will be added soon with an additional validation callback. Finally, `get_list` requires us to use the HDK function `get_links(base_address, tag)`. As you may have guessed, this will return the addresses of all the entries that are linked to the `base_address` with a given tag. As this only returns the addresses, we must then map over each of then and load the required entry. ``` fn handle_get_list(list_addr: HashString) -> JsonString { // try and get the list entry and ensure it is the data type we expect let maybe_list = hdk::get_entry(list_addr.clone()) .map(|entry| List::try_from(entry.unwrap().value())); match maybe_list { Ok(Ok(list)) => { // try and load the list items and convert them to the correct struct // please forgive the unwraps. They greatly simplify the example code let list_items = hdk::get_links(&list_addr, "items").unwrap().addresses() .iter() .map(|item_address| { let entry = hdk::get_entry(item_address.to_owned()).unwrap().unwrap(); ListItem::try_from(entry.value().clone()).unwrap() }).collect::<Vec<ListItem>>(); // if this was successful for all list items then return them json!({"name": list.name, "items": list_items}).into() }, _ => json!({"successs": false, "message": "No list at this address"}).into() } } ``` Phew! That is all the handlers set up. Finally the function definitions must be added to the `define_zome!` macro. Before doing that, it is worth briefly discussing a new concept in Holochain, *function groups*. Zome function groups have a name and access setting which must be one of `Public`, `Agent`, `ApiKey` or `Zome`. Using this it is possible to limit access to certain functions. This feature is currently undergoing some changes and will likely be renamed in future versions. The function field of our zome definition should be updated to: ``` define_zome! { ... functions: { // "main" is the name of the capability // "Public" is the access setting of the capability main (Public) { create_list: { inputs: |list: List|, outputs: |result: JsonString|, handler: handle_create_list } add_item: { inputs: |list_item: ListItem, list_addr: HashString|, outputs: |result: JsonString|, handler: handle_add_item } get_list: { inputs: |list_addr: HashString|, outputs: |result: JsonString|, handler: handle_get_list } } } } ``` and there we have it! The zome we created should now build if we run: ``` hc package ``` from the root directory. This will compile the Rust to WebAssembly and produce a `bundle.json` file which contains the compiled WASM code and the required metadata. This is the file that we can load and run using `hc`. ## Writing tests Developers who have worked previously with holochain-proto will be pleased to hear there is an entirely new testing framework built on JavaScript. We recommend using [tape.js](https://github.com/substack/tape) but likely any JavaScript testing framework will be usable in the future. Opening up the `test/index.js` file you will see a skeleton test file already created: ``` const test = require('tape'); const Container = require('@holochain/holochain-nodejs') // instantiate an app from the DNA JSON bundle const app = Container.loadAndInstantiate("dist/bundle.json") app.start() test('description of example test', (t) => { // indicates the number of assertions that follow t.plan(1) // Make a call to a Zome function // indicating the group and function, and passing it an input const result = app.call("zome-name", "group-name", "function-name", "input-data") t.equal(result, "Error calling zome function: InternalFailure(Dna(ZomeNotFound(\"Zome \\\'zome-name\\\' not found\")))") }) ``` This illustrates the `app.call` function that is exposed by the container for each app and that can be used to call our functions. Take note that the input-data should be a JSON object that matches the function signature. `call` will also return a JSON object. Lets add some tests for our todo list: ``` test('Can create a list', (t) => { const create_result = app.call("lists", "main", "create_list", {list: {name: "test list"}}) console.log(create_result) t.equal(create_result.success, true) t.end() }) test('Can add some items', (t) => { const create_result = app.call("lists", "main", "create_list", {list: {name: "test list"}}) const list_addr = create_result.address const result1 = app.call("lists", "main", "add_item", {list_item: {text: "Learn Rust", completed: true}, list_addr: list_addr}) const result2 = app.call("lists", "main", "add_item", {list_item: {text: "Master Holochain", completed: false}, list_addr: list_addr}) console.log(result1) console.log(result2) t.equal(result1.success, true) t.equal(result2.success, true) t.end() }) test('Can get a list with items', (t) => { const create_result = app.call("lists", "main", "create_list", {list: {name: "test list"}}) const list_addr = create_result.address app.call("lists", "main", "add_item", {list_item: {text: "Learn Rust", completed: true}, list_addr: list_addr}) app.call("lists", "main", "add_item", {list_item: {text: "Master Holochain", completed: false}, list_addr: list_addr}) const get_result = app.call("lists", "main", "get_list", {list_addr: list_addr}) console.log(get_result) t.equal(get_result.items.length, 2, "there should be 2 items in the list") t.end() }) ``` Running `hc test` will build the test file and run it using `node` which is able to load and execute holochain hApps via the holochain node container. If everything has worked correctly you should see some test output with everything passing. Pro tip: [Pipe the output to tap-spec](https://github.com/scottcorgan/tap-spec) (which must be installed via npm first) to get beautifully formatted test output. ## Conclusion And there we have it! A simple zome created in holochain using the Rust HDK. Those with previous experience developing for holochain-proto will appreciate the reduced boilerplate, strong typing and vastly improved testing framework. The [complete working version of this project is available on github](https://github.com/willemolding/holochain-rust-todo). This builds under the 0.0.2 release but as the API and HDK are changing it will likely fail under newer releases.

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully