donsmith
    • 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
      • Invitee
    • 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
    • Engagement control
    • 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 Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Versions and GitHub Sync Engagement control 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
Invitee
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
1
Subscribed
  • Any changes
    Be notified of any changes
  • Mention me
    Be notified of mention me
  • Unsubscribe
Subscribe
# A Holochain Developer Tutorial - Part 1 [![hackmd-github-sync-badge](https://hackmd.io/rNCiNe_zQ7aT3oKEl8UCqQ/badge)](https://hackmd.io/rNCiNe_zQ7aT3oKEl8UCqQ) > <span style="font-size:3em; font-weight:bold">DRAFT</span> ## Where we're going We will be building a complete Holochain app that includes testing and a user interface. We'll start with a simple zome, add the smallest test we can write, and call the zome from a simple web client. Once we have something simple that operates across the full stack, we'll add more complexity in future parts of this tutorial by adding more features to the app. This will allow us to learn different aspects of Holochain as we need the functionality. As far as _what we're building_ ... I haven't decided yet. We're just going to start. Perhaps we'll identify the path we're on once we start walking. ## Setting things up 1. Install the Nix package manager - Follow the installation instructions for your operating system using these links: [MacOS](https://developer.holochain.org/docs/install/#macos), [Windows](https://developer.holochain.org/docs/install/#windows) and [Linux](https://developer.holochain.org/docs/install/#linux). - **DO NOT** follow the instructions for _Installing the Holochain dev tools_, which is the section just after installation in the links above. This tutorial will follow a more recent approach to this part of the setup. 1. Create a folder to build this tutorial in. Optionally make it a git repo. 1. Ensure you have Node.js and npm installed correctly by running: `node -v; npm -v` 1. Create additional folders. Make them look like this: ``` . # tutorial └── service    ├── tests    │   └── src    ├── workdir    └── zomes    └── greeter    └── src ``` If it's easier, feel free to use this: `mkdir -p service/tests/src service/workdir service/zomes/greeter/src` 1. And just for completeness, let's drop a `.gitignore` file in the `service` folder with these contents: ``` .hc # holochain temp folder? .cargo # by-product of using Rust from a Nix shell? debug # Rust build artifact target # Rust build artifact **/*.rs.bk # rustfmt backup files ``` Now that we have our files and folders in place, let's finish setting up our development environment. ## Our dev environment In order to ensure a consistent environment, the Holochain dev environment uses Nix/NixOS. At the moment, we're using project-specific environment configurations and they exist in the form of a `default.nix` file. Create a `default.nix` file with these contents in your tutorial folder. ```nix= let holonixPath = builtins.fetchTarball { url = "https://github.com/holochain/holonix/archive/90a19d5771c069dbcc9b27938009486b54b12fb7.tar.gz"; sha256 = "11wv7mwliqj38jh1gda3gd0ad0vqz1d42hxnhjmqdp037gcd2cjg"; }; holonix = import (holonixPath) { includeHolochainBinaries = true; holochainVersionId = "custom"; holochainVersion = { rev = "d3a61446acaa64b1732bc0ead5880fbc5f8e3f31"; sha256 = "0k1fsxg60spx65hhxqa99nkiz34w3qw2q4wspzik1vwpkhk4pwqv"; cargoSha256 = "0fz7ymyk7g3jk4lv1zh6gbn00ad7wsyma5r7csa88myl5xd14y68"; bins = { holochain = "holochain"; hc = "hc"; }; }; }; in holonix.main ``` Alternatively, you can [download this one](https://raw.githubusercontent.com/holochain/holochain-dna-build-tutorial/develop/default.nix) (they're the same). In your terminal, navigate to your tutorial folder and open the Nix shell. ```shell nix-shell . ``` This might take a while, so let's continue to prepare while we wait. It's fine to open another terminal window in the same folder, open your code editor, create files, etc. while we wait. ## Building our first zome We're going to take real small baby steps to start off. Our first zome will contain a single function, named `hello`, that has no input parameters and returns a static string. 1. Create `service/zomes/greeter/src/lib.rs` with these contents: ```rust= use hdk::prelude::*; #[hdk_extern] pub fn hello(_: ()) -> ExternResult<String> { Ok(String::from("Hello Holo Dev")) } ``` The `use` statement on line #1 brings in the HDK. The `hdk_extern` attribute marks the function as available to be called by the Holochain conductor. The `ExternResult` type ensures we're returning a type that can be serialized back to the user interface. 1. Create `service/zomes/greeter/Cargo.toml` with these contents: ```toml= [package] name = "greeter" version = "0.0.1" authors = [ "[your name]", "[your email address]" ] edition = "2018" [lib] name = "greeter" crate-type = [ "cdylib", "rlib" ] [dependencies] hdk = "0.0.100" serde = "1" ``` This file defines the metadata for our `greeter` zome. 1. Create another `Cargo.toml` file with these contents: ```toml= [workspace] members = [ "zomes/greeter", ] [profile.dev] opt-level = "z" [profile.release] opt-level = "z" ``` This file defines all of the zomes in our project. 1. Hopefully our Nix shell has finished building. If not, you'll have to wait before completing this step. Let's build the zome into Web Assembly (WASM). From the `service` folder, inside your nix-shell, run this: ```sh CARGO_TARGET_DIR=target cargo build --release --target wasm32-unknown-unknown ``` If this succeeded, you won't see any errors, but you will have an `service/target/wasm32-unknown-unknown/release/greeter.wasm` file. 1. Now let's build the DNA file ```sh hc dna init workdir/dna ``` When prompted, enter `greeter` as the _name_ and leave the _uuid_ with its default value by just hitting enter. 1. Add the zome to the `zomes` array in the newly created DNA file `service/workdir/dna/dna.yaml` so it looks like this: ```yaml --- manifest_version: "1" name: greeter uuid: 00000000-0000-0000-0000-000000000000 properties: ~ zomes: - name: greeter bundled: ../../target/wasm32-unknown-unknown/release/greeter.wasm ``` 1. Package the WASM into a DNA file. ```sh hc dna pack workdir/dna ``` This will create `service/workdir/dna/greeter.dna`. Now we're ready to do zome testing :wink: (sorry, I couldn't resist). ## Testing our first zome We have the option of writing 2 different types of tests: unit tests written in Rust, and integration tests written in TypeScript. Writing a unit test doesn't have anything to do with Holochain - we just write them as we would any Rust code. However, our integration tests use the [Tryorama](https://github.com/holochain/tryorama) tool to create a mock environment. We'll forego writing unit tests for the time being and setup our integration testing environment instead. 1. Inside your `service/tests` folder, let's create some new files. **`package.json`** ```json= { "name": "hello-integration-tests", "version": "0.0.1", "description": "An integration test runner using Tryorama", "main": "index.js", "scripts": { "test": "TRYORAMA_LOG_LEVEL=info RUST_LOG=error RUST_BACKTRACE=1 TRYORAMA_HOLOCHAIN_PATH=\"holochain\" ts-node src/index.ts" }, "author": "Keen Holo Dev", "license": "ISC", "dependencies": { "@holochain/tryorama": "0.4.1", "@msgpack/msgpack": "^2.5.1", "@types/lodash": "^4.14.168", "@types/node": "^14.14.37", "lodash": "^4.17.21", "tape": "^5.2.2", "ts-node": "^9.1.1", "typescript": "^4.2.3" } } ``` **`tsconfig.json`** ```json= { "compilerOptions": { "target": "es5", "module": "commonjs", "resolveJsonModule": true, "strict": true, "noImplicitAny": false, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true } } ``` **`.gitignore`** ``` node_modules/ *.log ``` 1. In preparation for our test run, from the `service/tests` folder, install our dependencies. `npm install` 1. For our test file, let's create this `index.ts` file in our `src` folder. ```ts= import path from "path"; import { Orchestrator, Config, InstallAgentsHapps } from "@holochain/tryorama"; // Create a configuration for our conductor const conductorConfig = Config.gen(); // Construct proper paths for your DNAs const dnaPath = path.join(__dirname, "../../workdir/dna/greeter.dna"); // create an InstallAgentsHapps array with your DNAs to tell tryorama what // to install into the conductor. const installation: InstallAgentsHapps = [ // agent 0 [ // happ 0 [dnaPath], ], ]; const orchestrator = new Orchestrator(); orchestrator.registerScenario("holo says hello", async (s, t) => { const [alice] = await s.players([conductorConfig]); // install your happs into the coductors and destructuring the returned happ data using the same // array structure as you created in your installation array. const [[alice_common]] = await alice.installAgentsHapps(installation); let result = await alice_common.cells[0].call("greeter", "hello", null); t.equal(result, "Hello Holo Dev"); }); orchestrator.run(); ``` 1. Now, from inside our `service/tests` folder, we can run our test with: `npm test`. Everything is passing/working if the end of our output is ```sh # tests 1 # pass 1 # ok ``` 1. Now is a good time to make sure you can break the test in an expected way. For example, on line #30, change `"Hello Holo Dev"` to something else and re-run the test to watch it fail. ## Building some web UI Holochain doesn't force you to use specific technologies for the user interface. You only need to use something that can send [msgpack](https://msgpack.org) messages to the Websocket endpoint the conductor is listening to. To make this easier, we'll use JavaScript so we can use the [conductor-api](https://www.npmjs.com/package/@holochain/conductor-api) package. The user interface technology, and how to use it, is not the focus of this tutorial. So we're going to do the most basic thing we can that keeps the focus on how to interact with the Holochain conductor. To that end, we're going to use [Svelte](https://svelte.dev) and [Snowpack](https://www.snowpack.dev). > Note: this is my first time using Svelte and Snowpack. So if you see something egregious, please let me know. 1. Let's start in our tutorial folder (not `service`) and get a basic web app in place by running this in your terminal: ``` npx create-snowpack-app ui --template @snowpack/app-template-minimal ``` 1. We don't need Git submodules, so delete the new repo and install some necessary dependencies. ``` cd ui rm -rf .git npm install svelte @snowpack/plugin-svelte @holochain/conductor-api ``` Note: we'll stay in the `ui` folder for the remainder of the UI part of the tutorial. 1. Tell Snowpack about Svelte by adding its plugin to the config. Make this change to line 6 of `snowpack.config.js`: ```js= module.exports = { mount: { /* ... */ }, plugins: [ '@snowpack/plugin-svelte' ], ``` 1. Add an `App.svelte` file: ```svelte= <script> let greeting = '' function handleClick () { greeting = 'Hello from Svelte' } </script> <div> <button on:click={handleClick}>Say hello</button> <p>Greeting: {greeting}</p> </div> ``` 1. Fix up our `index.js` file so it looks like this: ```js= import App from "./App.svelte" const app = new App({ target: document.body }) export default app ``` 1. Ensure we're working up to this point. ``` npm start ``` This should open your browser on [http://localhost:8080](http://localhost:8080). You should be able to see the message display when you click this button without any errors in your console. ## Calling the `hello` zome Before we can call the zome, we need to build the hApp bundle and deploy it to the local Holochain. 1. Create the hApp bundle by running this in your nix-shell from the `service` folder: ``` hc app init workdir/happ ``` When prompted, enter `tutorial` for the _name_ and `Tutorial hApp` for the _description_. 1. Update our `service/workdir/happ/happ.yaml` to fix the bundle path of our DNA by making its `dna` section look like this: ``` --- manifest_version: "1" name: tutorial description: Tutorial hApp slots: - id: sample-slot provisioning: strategy: create deferred: false dna: bundled: "../dna/greeter.dna" properties: ~ uuid: ~ version: ~ clone_limit: 0 ``` 1. Package our DNA into a hApp bundle by running this in your nix-shell. ``` hc app pack workdir/happ ``` This will create `service/workdir/happ/greeter.happ` 1. Deploy the hApp to a local sandbox Holochain by running this in your nix-shell: ``` hc sandbox generate workdir/happ/ --run=8888 --app-id=greeter-app ``` 1. Invoke the zome function from the web UI. ```js= <script> import Buffer from 'buffer' import { AppWebsocket } from '@holochain/conductor-api' // A temporary hack for @holochain/conductor-api window.Buffer = Buffer.Buffer let greeting = '' function handleClick () { getGreeting() } async function getGreeting () { const appConnection = await AppWebsocket.connect('ws://localhost:8888') const appInfo = await appConnection.appInfo({ installed_app_id: 'greeter-app' }) const cellId = appInfo.cell_data[0].cell_id const message = await appConnection.callZome({ cap: null, cell_id: cellId, zome_name: 'greeter', fn_name: 'hello', provenance: cellId[1], payload: null, }) greeting = message } </script> ```

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