Browse Source

Merge pull request #263 from moxiegirl/smart-contract-tut

Initial Smart Contract docs
feat/clarity-updates
Moxiegirl 5 years ago
committed by GitHub
parent
commit
5fa77fc09d
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
  1. 7
      _common/construction.md
  2. 4
      _config.yml
  3. 90
      _core/smart/clarityCLI.md
  4. 181
      _core/smart/clarityRef.md
  5. 137
      _core/smart/functions.md
  6. 24
      _core/smart/install-source.md
  7. 134
      _core/smart/overview.md
  8. 68
      _core/smart/principals.md
  9. 268
      _core/smart/sdk-quickstart.md
  10. 336
      _core/smart/tutorial.md
  11. 402
      _data/clarityRef.json
  12. 10
      _data/navigation_core.yml
  13. 4
      _data/navigation_home.yml
  14. 6
      _data/navigation_learn.yml
  15. 2
      _develop/zero_to_dapp_1.md
  16. 2
      _develop/zero_to_dapp_2.md
  17. 8
      _develop/zero_to_dapp_2_win.md
  18. 2
      _develop/zero_to_dapp_3.md
  19. 2
      _develop/zero_to_dapp_3_win.md
  20. 2
      _develop/zero_to_dapp_4.md
  21. 18
      _includes/head.html
  22. 2
      _includes/navbar.html
  23. 42
      _layouts/core.html
  24. 42
      _layouts/learn.html
  25. 2
      assets/js/main.js
  26. 95
      assets/navgoco/jquery.cookie.js
  27. 8
      assets/navgoco/jquery.cookie.min.js
  28. 71
      assets/navgoco/jquery.navgoco.css
  29. 314
      assets/navgoco/jquery.navgoco.js
  30. 8
      assets/navgoco/jquery.navgoco.min.js

7
_common/construction.md

@ -1,7 +0,0 @@
---
layout: evaluate
permalink: /:collection/:path.html
---
# Excuse our dust!
This section UNDER CONSTRUCTION please comeback and visit us soon. If you have questions about this area or suggestions for content, please feel free to post on the [Blockstack Forum](https://forum.blockstack.org/).

4
_config.yml

@ -102,8 +102,8 @@ kramdown:
toc:
min_level: 2 # default: 1
max_level: 3 # default: 6
list_class: "uk-nav uk-nav-default"
sublist_class: "uk-nav-sub doc-nav"
# list_class: "uk-nav uk-nav-default"
# sublist_class: "uk-nav-sub doc-nav"
plugins:
- jekyll-feed

90
_core/smart/clarityCLI.md

@ -0,0 +1,90 @@
---
layout: core
permalink: /:collection/:path.html
---
# clarity-cli command line
{:.no_toc}
You use the `clarity-cli` command to work with smart contracts within the Blockstack virtual environment. This command has the following subcommands:
* TOC
{:toc}
## initialize
```bash
clarity-cli initialize [vm-state.db]
```
Initializes a local VM state database. If the database exists, this command throws an error.
## mine_block
```bash
clarity-cli mine_block [block time] [vm-state.db]
```
Simulates mining a new block.
## get_block_height
```bash
clarity-cli get_block_height [vm-state.db]
```
Prints the simulated block height.
## check
```bash
clarity-cli check [program-file.scm] (vm-state.db)
```
Type checks a potential contract definition.
## launch
```bash
clarity-cli launch [contract-name] [contract-definition.scm] [vm-state.db]
```
Launches a new contract in the local VM state database.
## eval
```bash
clarity-cli eval [context-contract-name] (program.scm) [vm-state.db]
```
Evaluates, in read-only mode, a program in a given contract context.
## eval_raw
```bash
```
Type check and evaluate an expression for validity inside of a function’s source. It does not evaluate within a contract or database context.
## repl
```bash
clarity-cli repl
```
Type check and evaluate expressions in a stdin/stdout loop.
## execute
```bash
clarity-cli execute [vm-state.db] [contract-name] [public-function-name] [sender-address] [args...]
```
Executes a public function of a defined contract.
## generate_address
```bash
clarity-cli generate_address
```
Generates a random Stacks public address for testing purposes.

181
_core/smart/clarityRef.md

@ -0,0 +1,181 @@
---
layout: core
permalink: /:collection/:path.html
---
# Clarity language reference
This file contains the reference for the Clarity language.
* TOC
{:toc}
## Block Properties
The `get-block-info` function fetches property details for a block at a specified block height. For example:
```cl
(get-block-info time 10) ;; Returns 1557860301
```
Because the Clarity language is in pre-release, the block properties that are fetched are simulated properties from a SQLite database. The available property names are:
<table class="uk-table">
<tr>
<th>Property</th>
<th>Definition</th>
</tr>
<tr>
<td><code>header-hash</code></td>
<td>A 32-byte buffer containing the block hash.</td>
</tr>
<tr>
<td><code>burnchain-header-hash</code></td>
<td>A 32-byte buffer that contains the hash from the proof of burn.</td>
</tr>
<tr>
<td><code>vrf-seed</code></td>
<td>A 32-byte buffer containing the Verifiable Random Function (VRF) seed value used for the block.</td>
</tr>
<tr>
<td><code>time</code></td>
<td>An integer value containing that roughly corresponds to when the block was mined. This is a Unix epoch timestamp in seconds. </td>
</tr>
</table>
{% include warning.html content="The <code>time</code> does not increase monotonically with each block. Block times are accurate only to within two hours. See <a href='https://github.com/bitcoin/bips/blob/master/bip-0113.mediawiki' target='_blank'>BIP113</a> for more information." %}
## Supported types
This section lists the types available to smart contracts. The only atomic types supported by the Clarity are booleans, integers, fixed length buffers, and principals.
### Int type
The integer type in the Clarity language is a 16-byte signed integer, which allows it to specify the maximum amount of microstacks spendable in a single Stacks transfer. The special `BlockHeightInt` you can obtain with the `get-block-info` function.
### Bool type
Supports values of `'true` or `'false`.
### Buffer type
Buffer types represent fixed-length byte buffers. Currently, the only way to construct a Buffer is using string literals, for example `"alice.id"` or `hash160("bob.id")`
All of the hash functions return buffers:
`hash160`
`sha256`
`keccak256`
The block properties `header-hash`, `burnchain-header-hash`, and `vrf-seed` are all buffers.
### List type
Clarity supports lists of the atomic types. However, the only variable length lists in the language appear as function inputs; there is no support for list operations like append or join.
### Principal type
Clarity provides this primitive for checking whether or not the smart contract transaction was signed by a particular principal. Principals represent a spending entity and are roughly equivalent to a Stacks address. The principal's signature is not checked by the smart contract, but by the virtual machine. A smart contract function can use the globally defined `tx-sender` variable to obtain the current principal.
Smart contracts may also be principals (represented by the smart contract's identifier). However, there is no private key associated with the smart contract, and it cannot broadcast a signed transaction on the blockchain. A smart contract uses the special variable `contract-name` to refer to its own principal.
[//]: # You can use the `is-contract?` to determine whether a given principal corresponds to a smart contract.
### Tuple type
To support the use of named fields in keys and values, Clarity allows the construction of named tuples using a function `(tuple ...)`, for example
```cl
(define imaginary-number-a (tuple (real 1) (i 2)))
(define imaginary-number-b (tuple (real 2) (i 3)))
```
This allows for creating named tuples on the fly, which is useful for data maps where the keys and values are themselves named tuples. Values in a given mapping are set or fetched using:
<table class="uk-table uk-table-small">
<tr>
<th class="uk-width-small">Function</th>
<th>Description</th>
</tr>
<tr>
<td><code>(fetch-entry map-name key-tuple)</code></td>
<td>Fetches the value associated with a given key in the map, or returns <code>none</code> if there is no such value.</td>
</tr>
<tr>
<td><code>(set-entry! map-name key-tuple value-tuple)</code></td>
<td>Sets the value of key-tuple in the data map</td>
</tr>
<tr>
<td><code>(insert-entry! map-name key-tuple value-tuple)</code></td>
<td>Sets the value of key-tuple in the data map if and only if an entry does not already exist.</td>
</tr>
<tr>
<td><code>(delete-entry! map-name key-tuple)</code></td>
<td>Deletes key-tuple from the data map.</td>
</tr>
</table>
To access a named value of a given tuple, the `(get name tuple)` function returns that item from the tuple.
### Optional type
Represents an optional value. This is used in place of the typical usage of "null" values in other languages, and represents a type that can either be some value or `none`. Optional types are used as the return types of data-map functions.
### Response type
Response types represent the result of a public function. Use this type to indicate and return data associated with the execution of the function. Also, the response should indicate whether the function error'ed (and therefore did not materialize any data in the database) or ran `ok` (in which case data materialized in the database).
Response types contain two subtypes -- a response type in the event of `ok` (that is, a public function returns an integer code on success) and an `err` type (that is, a function returns a buffer on error).
## Native variables
The Clarity language includes native variables you can use in your contract.
### block-height
The height of a block in the Stacks blockchain. Block height is the number of blocks in the chain between any given block and the very first block in the blockchain. You can obtain a `block-height` via the `get-block-info` function.
### contract-name
Represents the current contract.
### tx-sender
Represents the current principal. This variable does not change during inter-contract calls. This means that if a transaction invokes a function in a given smart contract, that function is able to make calls into other smart contracts on your behalf. This enables a wide variety of applications, but it comes with some dangers for users of smart contracts. Static analysis of Clarity contracts guarantees the language allows clients to deduce which functions a given smart contract will ever call. Good clients should always warn users about any potential side effects of a given transaction.
## Clarity function reference
{% capture function_list %}
{% for entry in site.data.clarityRef %}
{{ entry.name }}||{{ entry.signature }}||{{ entry.input_type }}||{{ entry.output_type }}||{{ entry.description }}||{{ entry.example }}
{% if forloop.last == false %}::{% endif%}
{% endfor %}
{% endcapture %}
{% assign function_array = function_list | split: '::' | sort %}
{% for function in function_array %}
{% assign function_vals = function | split: '||' %}
### {{function_vals[0] | lstrip | rstrip}}
**Syntax**
```{{function_vals[1] | lstrip | rstrip }} ```
<table class="uk-table uk-table-small">
<tr>
<th class="uk-width-small">Input type:</th>
<td><code>{{function_vals[2] | lstrip | rstrip }}</code></td>
</tr>
<tr>
<th>Output type:</th>
<td><code>{{function_vals[3] | rstrip }}</code></td>
</tr>
</table>
{{function_vals[4]}}
<h4>Example</h4>
```cl
{{function_vals[5] | lstrip | rstrip }}
```
<hr class="uk-divider-icon">
{% endfor %}

137
_core/smart/functions.md

@ -0,0 +1,137 @@
---
layout: core
permalink: /:collection/:path.html
---
# Define functions and data maps
{:.no_toc}
Clarity includes _defines_ and native functions for creating user-defined functions.
* TOC
{:toc}
## define and define-public functions
Functions specified via `define-public` statements are public functions. Functions without these designations, simple `define` statements, are private functions. You can run a contract's public functions directly via the `clarity-cli execute` command line directly or from other contracts. You can use the `clarity eval` or `clarity eval_raw` commands to evaluate private functions via the command line.
Public functions return a Response type result. If the function returns an `ok` type, then the function call is considered valid, and any changes made to the blockchain state will be materialized. If the function returns an `err` type, it is considered invalid, and has no effect on the smart contract's state.
For example, consider two functions, `foo.A` and `bar.B` where the `foo.A` function calls `bar.B`, the table below shows the data materialization that results from the possible combination of return values:
<table class="uk-table">
<tr>
<th></th>
<th>foo.A =&gt;</th>
<th>bar.B</th>
<th>Data impact that results</th>
</tr>
<tr>
<th rowspan="2">Function returns</th>
<td><code>err</code></td>
<td><code>ok</code></td>
<td>No changes result from either function.</td>
</tr>
<tr>
<td><code>ok</code></td>
<td><code>err</code></td>
<td>Change from <code>foo.A</code> is possible; no changes from <code>foo.B</code> materialize.</td>
</tr>
</table>
Defining of constants and functions are allowed for simplifying code using a define statement. However, these are purely syntactic. If a definition cannot be inlined, the contract is rejected as illegal. These definitions are also private, in that functions defined this way may only be called by other functions defined in the given smart contract.
## define-read-only functions
Functions specified via `define-read-only` statements are public. Unlike functions created by `define-public`, functions created with `define-read-only` may return any type. However, `define-read-only` statements cannot perform state mutations. Any attempts to modify contract state by these functions or functions called by these functions result in an error.
## define-map functions for data
Data within a smart contract's data-space is stored within maps. These stores relate a typed-tuple to another typed-tuple (almost like a typed key-value store). As opposed to a table data structure, a map only associates a given key with exactly one value. A smart contract defines the data schema of a data map with the `define-map` function.
```cl
(define-map map-name ((key-name-0 key-type-0) ...) ((val-name-0 val-type-0) ...))
```
Clarity contracts can only call the `define-map` function in the top-level of the smart-contract (similar to `define`. This function accepts a name for the map, and a definition of the structure of the key and value types. Each of these is a list of `(name, type)` pairs. Types are either the values `'principal`, `'integer`, `'bool` or the output of one of the hash calls which is an n-byte fixed-length buffer.
To support the use of named fields in keys and values, Clarity allows the construction of tuples using a function `(tuple ((key0 expr0) (key1 expr1) ...))`, for example:
```cl
(tuple (name "blockstack") (id 1337))
```
This allows for creating named tuples on the fly, which is useful for data maps where the keys and values are themselves named tuples. To access a named value of a given tuple, the function (get #name tuple) will return that item from the tuple.
The `define-map` interface, as described, disallows range-queries and queries-by-prefix on data maps. Within a smart contract function, you cannot iterate over an entire map. Values in a given mapping are set or fetched using the following functions:
<table class="uk-table">
<tr>
<th>Function</th>
<th>Description</th>
</tr>
<tr>
<td><code>(fetch-entry map-name key-tuple)</code></td>
<td>Fetches the value associated with a given key in the map, or returns <code>'null</code> if there is none.</td>
</tr>
<tr>
<td><code>(set-entry! map-name key-tuple value-tuple)</code></td>
<td>Sets the value of key-tuple in the data map.</td>
</tr>
<tr>
<td><code>(insert-entry! map-name key-tuple value-tuple)</code></td>
<td>Sets the value of <code>key-tuple</code> in the data map if and only if an entry does not already exist.</td>
</tr>
<tr>
<td><code>(delete-entry! map-name key-tuple)</code></td>
<td>Removes the value associated with the input key for the given map.</td>
</tr>
</table>
Data maps make reasoning about functions easier. By inspecting a given function definition, it is clear which maps will be modified and, even within those maps, which keys are affected by a given invocation. Also, the interface of data maps ensures that the return types of map operations are fixed length; Fixed length returns is a requirement for static analysis of a contract's runtime, costs, and other properties.
## List operations and functions
Lists may be multi-dimensional. However, note that runtime admission checks on typed function-parameters and data-map functions like `set-entry!` are charged based on the _maximal_ size of the multi-dimensional list.
You can call `filter` `map` and `fold` functions with user-defined functions (that is, functions defined with `(define ...)`, `(define-read-only ...)`, or `(define-public ...)`) or simple, native functions (for example, `+`, `-`, `not`).
## Intra-contract calls
A smart contract may call functions from other smart contracts using a `(contract-call!)` function:
```cl
(contract-call! contract-name function-name arg0 arg1 ...)
```
This function accepts a function name and the smart contract's name as input. For example, to call the function `token-transfer` in the smart contract, you would use:
`(contract-call! tokens token-transfer burn-address name-price))`
For intra-contract calls dynamic dispatch is not supported. When a contract is launched, any contracts it depends on (calls) must exist. Additionally, no cycles may exist in the call graph of a smart contract. This prevents recursion (and re-entrancy bugs. A static analysis of the call graph detects such structures and they are rejected by the network.
A smart contract may not modify other smart contracts' data directly; it can read data stored in those smart contracts' maps. This read ability does not alter any confidentiality guarantees of Clarity. All data in a smart contract is inherently public, andis readable through querying the underlying database in any case.
### Reading from other smart contracts
To read another contract's data, use `(fetch-contract-entry)` function. This behaves identically to `(fetch-entry)`, though it accepts a contract principal as an argument in addition to the map name:
```cl
(fetch-contract-entry
'contract-name
'map-name
'key-tuple) ;; value tuple or none
```
For example, you could do this:
```cl
(fetch-contract-entry
names
name-map
1) ;;returns owner principal of name
```
Just as with the `(contract-call)` function, the map name and contract principal arguments must be constants, specified at the time of publishing.
Finally, and importantly, the `tx-sender` variable does not change during inter-contract calls. This means that if a transaction invokes a function in a given smart contract, that function is able to make calls into other smart contracts on your behalf. This enables a wide variety of applications, but it comes with some dangers for users of smart contracts. However, the static analysis guarantees of Clarity allow clients to know a priori which functions a given smart contract will ever call. Good clients should always warn users about any potential side effects of a given transaction.

24
_core/smart/install-source.md

@ -0,0 +1,24 @@
---
layout: core
permalink: /:collection/:path.html
---
# Install Clarity from Source
Build using `rust` and `cargo`:
```bash
$ cargo build --release
```
Install globally (you may have to run as sudoer):
```bash
$ cargo install --path .
```
You should now be able to run the command:
```bash
$ blockstack-core
```

134
_core/smart/overview.md

@ -0,0 +1,134 @@
---
layout: core
permalink: /:collection/:path.html
---
# Welcome to Clarity
{:.no_toc}
Clarity is Blockstack's smart contracting language for use with the Stacks blockchain. Clarity supports programmatic control over digital assets within the Stacks blockchain (for example, BNS names, Stacks tokens, and so forth). This section discusses the following topics:
* TOC
{:toc}
<div class="uk-card uk-card-default uk-card-body">
<h5>Clarity is in pre-release</h5>
<p>Clarity, its accompanying toolset, and the SDK are in pre-release. If you encounter issues with or have feature requests regarding Clarity, please create an issue on the <a href='https://github.com/blockstack/blockstack-core/issues' target='_blank'>blockstack/blockstack-core</a> repository. To read previous or join ongoing discussions about smart contracts in general and Clarity in particular, visit the <strong><a href='https://forum.blockstack.org/c/clarity' target='_blank'>Smart Contracts</a></strong> topic in the Blockstack Forum.
</p>
</div>
## Who should use smart contracts?
You can use Clarity to write standalone contracts or to write contracts that are part of decentralized applications (DApps) you write with the blockstack.js library. Smart contracts allow two parties to exchange anything of value (money, property, shares), in an automated, auditable, and secure way _without the services of a middleman_. Nick Szabo introduced the canonical metaphor for smart contracts, a vending machine.
In Nick Szabo's metaphor, the vending machine is the smart contract. The buyer and machine owner are the two parties. A vending machine executes a set of hard-coded actions when the buyer engages with it. The machine displays the items and their prices. A buyer enters money into the machine which determines if the amount fails to mee, meets, or exceeds an item's price. Based on the amount, the machine asks for more money, dispenses an item, or dispenses and item and change.
Not every application requires smart contracts. If you are not sure or are new to smart contracts concepts, you should read <a href="https://blockgeeks.com/guides/smart-contracts/" target="_blank">a good general explanation of smart contracts</a> before working with Clarity.
## Language and program design
Clarity differs from most other smart contract languages in two essential ways:
* The language is not intended to be compiled.
* The language is not Turing complete.
These differences allow for static analysis of programs to determine properties like runtime cost and data usage.
A Clarity smart contract is composed of two parts &mdash; a data-space and a set of functions. Only the associated smart contract may modify its corresponding data-space on the blockchain. Functions are private unless they are defined as public functions. Users call smart contracts' public functions by broadcasting a transaction on the blockchain which invokes the public function.
Contracts can also call public functions from other smart contracts. The ability to do a static analysis of a smart contract allows a user to determine dependency between contracts.
## The coding environment
Clarity is a list processing (LISP) language, as such it is not compiled. Omitting compilation prevents the possibility of error or bugs introduced at the compiler level. You can write Clarity smart contract programs on any operating system with a text editor. You can use any editor you are comfortable with such as Atom, Vim, or even Notepad. The Clarity files you create with an editor have a `.clar` extension.
Clarity is in pre-release and does not yet directly interact with the live Stacks blockchain. For the pre-release period you need a test environment to run Clarity contracts. Blockstack provides a Docker image called `clarity-developer-preview` that you can use or you can build a test environment locally from code. Either the Docker image or a local environment is sufficient for testing Clarity programming for standalone contracts.
You use the `clarity-cli` command line to check, launch, and execute standalone Clarity contracts. You can use this same command line to create simulate mining Stacks and inspecting a blockchain.
Blockstack expects that some decentralized applications (DApp) will want to make use of Clarity contracts as part of their applications. For this purpose, you should use the Clarity SDK, also in pre-release. The SDK is a development environment, testing framework, and deployment tool. It provides a library for safe interactions with Clarity contracts from a DApp written with the blockstack.js library.
## Basic building blocks of Clarity contracts
The basic building blocks of Clarity are _atoms_ and _lists_. An atom is a number or string of contiguous characters. Some examples of atoms:
* `token-sender`
* `10000`
* `SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR`
Atoms can be native functions, user-defined functions, variables, and values that appear in a program. Functions that mutate data by convention terminate with an `!` exclamation point, for example the `insert-entry!` function.
A list is a sequences of atoms enclosed with `()` parentheses. Lists can contain other lists. Some examples of lists are:
* `(get-block-info time 10)`
* `(and 'true 'false)`
* `(is-none? (get id (fetch-entry names-map (tuple (name \"blockstack\")))))`
You can add comments to your Clarity contracts using `;;` (double semi-colons). Both standalone and inline comments are supported.
```cl
;; Transfers tokens to a specified principal
(define-public (transfer (recipient principal) (amount int))
(transfer! tx-sender recipient amount)) ;; returns: boolean
```
You use the `clarity-cli` command to check and launch a Clarity (`.clar`) program.
## hello-world example
The easiest program to run in any language is a hello world program. In Clarity, you can write this `hello-world.clar` program.
```cl
(begin
(print "hello world"))
```
This program defines a single `hello-world` user function. The `begin` is a native Clarity function that evaluates the expressions input to it and returns the value of the last expression. Here there is a single `print` expression. Both the `begin` and the `print` are enclosed in `()` parentheses.
For the pre-release, the Blockstack test environment includes the `clarity-cli` command for interacting with the contract and SQLite to support the data space. You create a SQLLite database to hold data related to Clarity contracts. This database simulates the blockchain by recording the contract activity.
You can't run even an a hello-world program without first initializing a Clarity contract's data space within the database. You can use the `clarity-cli initialize` command to set up the database.
```clarity-cli initialize /data/db```
This command initializes the `db` database which resides in the `/data` directory of the container. You can name the database anything you like, the name `db` is not required. You can use SQLite to query this database:
```sql
sqlite> .open db
sqlite> .tables
contracts maps_table type_analysis_table
data_table simmed_block_table
sqlite>
```
After you initialize the contract's data space, you can `check` a Clarity program for problems.
```clarity-cli check ./hello.clar /data/db```
As the name implies, the `check` ensures the contract definition passes a type check; passing programs will returns an exit code of `0` (zero). Once a contract passes a check, you `launch` it.
```bash
root@4224dd95b5f5:/data# clarity-cli launch hello ./hello.clar /data/db
Buffer(BuffData { data: [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100] })
Contract initialized!
```
Because Clarity does not support simple strings, it stores the `hello world` string in a buffer. Printing out that string displays the ASCII representation for each character. You can see the record of this contract's launch in the corresponding database:
```sql
sqlite> select * from contracts;
1|hello|{"contract_context":{"name":"hello","variables":{},"functions":{}}}
sqlite> select * from type_analysis_table;
1|hello|{"private_function_types":{},"variable_types":{},"public_function_types":{},"read_only_function_types":{},"map_types":{}}
sqlite>
```
## Language rules and limitations
The Clarity smart contract has the following limitations:
* The only atomic types are booleans, integers, fixed length buffers, and principals
* Recursion is illegal and there is no lambda function.
* Looping may only be performed via `map`, `filter`, or `fold`
* There is support for lists of the atomic types, however, the only variable length lists in the language appear as function inputs; There is no support for list operations like append or join.
* Variables are created via `let` binding and there is no support for mutating functions like `set`.

68
_core/smart/principals.md

@ -0,0 +1,68 @@
---
layout: core
permalink: /:collection/:path.html
---
# Principals
{:.no_toc}
_Principals_ are a Clarity native type that represents a spending entity. This section discusses principals and how they are used in the Clarity.
* TOC
{:toc}
## Principals and tx-sender
A principal is represented by a public-key hash or multi-signature Stacks address. Assets in Clarity and the Stacks blockchain are "owned" by objects of the principal type; put another way, principal object types may own an asset.
A given principal operates on its assets by issuing a signed transaction on the Stacks blockchain. A Clarity contract can use a globally defined `tx-sender` variable to obtain the current principal.
The following user-defined function transfers an asset, in this case, tokens, between two principals:
```
(define (transfer! (sender principal) (recipient principal) (amount int))
(if (and
(not (eq? sender recipient))
(debit-balance! sender amount)
(credit-balance! recipient amount))
'true
'false))
```
The principal's signature is not checked by the smart contract, but by the virtual machine.
## Smart contracts as principals
Smart contracts themselves are principals and are represented by the smart contract's identifier. You create the identifier when you launch the contract, for example, the contract identifier here is `hanomine`.
```bash
clarity-cli launch hanomine /data/hano.clar /data/db
```
A smart contract may use the special variable `contract-name` to refer to its own principal.
To allow smart contracts to operate on assets it owns, smart contracts may use the special `(as-contract expr)` function. This function executes the expression (passed as an argument) with the `tx-sender` set to the contract's principal, rather than the current sender. The `as-contract` function returns the value of the provided expression.
For example, a smart contract that implements something like a "token faucet" could be implemented as so:
```cl
(define-public (claim-from-faucet)
(if (is-none? (fetch-entry claimed-before (tuple (sender tx-sender))))
(let ((requester tx-sender)) ;; set a local variable requester = tx-sender
(begin
(insert-entry! claimed-before (tuple (sender requester)) (tuple (claimed 'true)))
(as-contract (stacks-transfer! requester 1)))))
(err 1))
```
In this example, the public function `claim-from-faucet`:
* Checks if the sender has claimed from the faucet before.
* Assigns the tx sender to a `requester` variable.
* Adds an entry to the tracking map.
* Uses `as-contract` to send 1 microstack
Contract writers can use the primitive function `is-contract?` to determine whether a given principal corresponds to a smart contract.
Unlike other principals, there is no private key associated with a smart contract. As it lacks a private key, a Clarity smart contract cannot broadcast a signed transaction on the blockchain.

268
_core/smart/sdk-quickstart.md

@ -0,0 +1,268 @@
---
layout: core
permalink: /:collection/:path.html
---
# Quickstart for the SDK
{:.no_toc}
You can use the software developer kit (SDK) to develop, test, and deploy Clarity smart contracts. The SDK goes beyond the basic test environment to allow for development of Javascript or TypeScript clients that call upon Clarity contracts.
* TOC
{:toc}
<div class="uk-card uk-card-default uk-card-body">
<h5>Clarity is in pre-release</h5>
<p>Clarity, its accompanying toolset, and the SDK are in pre-release. If you encounter issues with or have feature requests regarding Clarity, please create an issue on the <a href='https://github.com/blockstack/blockstack-core/issues' target='_blank'>blockstack/blockstack-core</a> repository. To read previous or join ongoing discussions about smart contracts in general and Clarity in particular, visit the <strong><a href='https://forum.blockstack.org/c/clarity' target='_blank'>Smart Contracts</a></strong> topic in the Blockstack Forum.
</p>
</div>
## About this tutorial and the prerequisites you need
{% include note.html content="This tutorial was written on macOS High Sierra 10.13.4. If you use a Windows or Linux system, you can still follow along. However, you will need to \"translate\" appropriately for your operating system." %}
For this tutorial, you will use `npm` to manage dependencies and scripts. The tutorial relies on the `npm` dependency manager. Before you begin, verify you have installed `npm` using the `which` command to verify.
```bash
$ which npm
/usr/local/bin/npm
```
If you don't find `npm` in your system, [install
it](https://www.npmjs.com/get-npm).
You use `npm` to install Yeoman. Yeoman is a generic scaffolding system that
helps users rapidly start new projects and streamline the maintenance of
existing projects. Verify you have installed `yo` using the `which` command.
```
$ which yo
/usr/local/bin/yo
```
If you don't have Yeoman, you can install it with the `npm install -g yo` command.
## Task 1: Generate an initial Clarity project
The SDK uses Yeoman to generate a project scaffold &mdash; an initial set of directories and files.
1. Create a new directory for your project.
```sh
mkdir hello-clarity-sdk
```
2. Change into your new project directory.
```sh
cd hello-clarity-sdk
```
3. Use the `npm` command to initialize a Clarity project.
```sh
npm init yo clarity-dev
npx: installed 15 in 1.892s
create package.json
create .vscode/extensions.json
...
Project created at /private/tmp/hello-clarity-sdk
✔ create-yo ok!
```
Depending on your connection speed, it may take time to construct the scaffolding.
## Task 2: Investigate the generated project
Your project should contain three directories:
| Directory |Description |
|---|---|
| `contracts` | Contains `.clar` files (Clarity contract files) here. |
| `test` | Contains files for testing your application. |
| `node_modules` | Contains packages the project depends on. Added by `npm`. |
The `contracts` directory contains a single file in `sample/hello-world.clar` file.
```cl
(define (hello-world)
"hello world")
(define (echo-number (val int))
val)
```
The contract exposes 2 rudimentary functions. The **say-hi** returns a `hello world` string. The **increment-number**: echos `val`.
The project also includes `tests/hello-world.ts` file. The test is written in Typescript. You can also write tests in Javascript.
{% highlight cl linenos %}
import { Client, Provider, ProviderRegistry, Result } from "@blockstack/clarity";
import { assert } from "chai";
describe("hello world contract test suite", () => {
let helloWorldClient: Client;
let provider: Provider;
before(async () => {
provider = await ProviderRegistry.createProvider();
helloWorldClient = new Client("hello-world", "sample/hello-world", provider);
});
it("should have a valid syntax", async () => {
await helloWorldClient.checkContract();
});
describe("deploying an instance of the contract", () => {
before(async () => {
await helloWorldClient.deployContract();
});
it("should print hello world message", async () => {
const query = helloWorldClient.createQuery({ method: { name: "hello-world", args: [] } });
const receipt = await helloWorldClient.submitQuery(query);
const result = Result.unwrap(receipt);
const parsedResult = Buffer.from(result.replace("0x", ""), "hex").toString();
assert.equal(parsedResult, "hello world");
});
it("should echo number", async () => {
const query = helloWorldClient.createQuery({
method: { name: "echo-number", args: ["123"] }
});
const receipt = await helloWorldClient.submitQuery(query);
const result = Result.unwrap(receipt);
assert.equal(result, "123");
});
});
after(async () => {
await provider.close();
});
});
{% endhighlight %}
The `hello-world.ts` test file is a client that runs the `hello-world.clar` contract. Tests are critical for smart contracts as they are intended to manipulate assets and their ownership. These manipulations are irreversible within a blockchain. As you create a contracts, you should not be surprise if you end up spending more time and having more code in your `tests` than in your `contracts` directory. The `tests/hello-world.ts` file in the scaffold has the following content:
The first part of the test (lines 1 -10) sets up the test environment. It defines a Clarity `provider` and launches it (line 9). The Client instance contains a contract name and the path to the sample code. This test also checks the client (line 14) and then launches it (line 19), this is equivalent to running `clarity-cli check` with the command line. The remaining test code exercises the contract. Try running this test.
```sh
npm run test
> hello-clarity-sdk@0.0.0 test /private/tmp/hello-clarity-sdk
> mocha
hello world contract test suite
✓ should have a valid syntax
deploying an instance of the contract
✓ should print hello world message
✓ should echo number
3 passing (182ms)
```
In the next section, try your hand at expanding the `hello-world.clar` program.
## Task 3: Try to expand the contract
In this task, you are challenged to expand the contents of the `contracts/hello-world.clar` file. Use your favorite editor and open the `contracts/hello-world.clar` file. If you use Visual Studio Code, you can install the Blockstack Clarity extension. The extension provides `syntax coloration` and some `autocompletion`.
Edit the `hello-world.clar` file.
```cl
;; Functions
(define (hello-world)
"hello world")
(define (echo-number (val int))
val)
```
Use the `+` function to create a `increment-number-by-10` function.
<div class="uk-inline">
<button class="uk-button uk-button-primary" enter="button">ANSWER</button>
<div uk-dropdown>
<pre>
;; Functions
(define (say-hi)
"hello world")
(define (increment-number (number int))
(+ 1 number))
(define (increment-number-by-10 (number int))
(+ 10 number))
</pre>
</div>
</div>
Use the `+` and `-` function to create a `decrement-number` user-defined method.
<div class="uk-inline">
<button class="uk-button uk-button-primary" enter="button">ANSWER</button>
<div uk-dropdown>
<pre>
;; Functions
(define (say-hi)
"hello world")
(define (increment-number (number int))
(+ 1 number))
(define (increment-number-by-10 (number int))
(+ 10 number))
(define (decrement-number (number int))
(- number 1))
</pre>
</div>
</div>
Finally, try adding a `counter` variable and be sure to store it. Increment `counter` in your code` and add a `get-counter` funtion to return the result. Here is a hint, you can add a `var` to a contract by adding the following line (before the function):
```cl
;; Storage
(define-data-var internal-value int 0)
``
<div class="uk-inline">
<button class="uk-button uk-button-primary" enter="button">ANSWER</button>
<div uk-dropdown>
<pre>
;; Storage
(define-data-var counter int 0)
;; Functions
(define (say-hi)
"hello world")
(define (increment-number (number int))
(+ 1 number))
(define (increment-number-by-10 (number int))
(+ 10 number))
(define (decrement-number (number int))
(- number 1))
(define (increment-counter)
(set-var! counter (+ 1 counter)))
(define (get-counter)
(counter))
</pre>
</div>
</div>
To review other, longer sample programs visit the <a href="https://github.com/blockstack/clarity-js-sdk/tree/master/packages/clarity-tutorials" target="_blank">clarity-js-sdk</a> repository.

336
_core/smart/tutorial.md

@ -0,0 +1,336 @@
---
layout: core
permalink: /:collection/:path.html
---
# Hello Clarity tutorial
In this tutorial, you learn how to use Clarity, Blockstack's smart contracting language. Use this tutorial to get a quick introduction to Clarity and the default Blockstack test environment.
* TOC
{:toc}
<div class="uk-card uk-card-default uk-card-body">
<h5>Clarity is in pre-release</h5>
<p>Clarity and its accompanying toolset are in pre-release. If you encounter issues with or have feature requests regarding Clarity, please create an issue on the <a href='https://github.com/blockstack/blockstack-core/issues' target='_blank'>blockstack/blockstack-core</a> repository. To read previous or join ongoing discussions about smart contracts in general and Clarity in particular, visit the <strong><a href='https://forum.blockstack.org/c/clarity' target='_blank'>Smart Contracts</a></strong> topic in the Blockstack Forum.
</p>
</div>
## Before you begin (pre-requisites)
The Clarity language goes live in the next Stacks blockchain fork. Until the fork, you can run Clarity in a test environment. You run this test environment in a Docker container. Before you begin this tutorial, make sure you have <a href="https://docs.docker.com" target="_blank">Docker installed on your workstation</a>.
If for some reason you don't want to run the test environment with Docker, you can build and maintain a local environment. Instructions for downloading and building the environment are available in the `blockstack/blockstack-core` repository's <a href='https://github.com/blockstack/blockstack-core' target='_blank'>README</a> file.
## Task 1: Set up the test environment
Blockstack publishes the `clarity-developer-preview` image on Docker hub. A container built from this image contains sample programs, the Blockstack Core, and tools for working with them. In this task, you use Docker to pull and and run the image on your local workstation.
1. Pull the Blockstack core `clarity-developer-preview` image from Docker Hub.
```bash
$ docker pull blockstack/blockstack-core:clarity-developer-preview
```
2. Start the Blockstack Core test environment with a Bash shell.
```bash
$ docker run -it -v $HOME/blockstack-dev-data:/data/ blockstack/blockstack-core:clarity-developer-preview bash
```
The launches a container with the Clarity test environment and opens a bash shell into the container. The `-v` flag creates a local `$HOME/blockstack-dev-data` directory in your workstation and mounts it at the `/data` directory inside the container. The shell opens into the `src/blockstack-core` directory. This directory contains the source for a core and includes Clarity contract samples you can run.
3. List the contents of the `sample-programs` directory.
```bash
root@f88368ba07b2:/src/blockstack-core# ls sample-programs/
names.clar tokens.clar
```
The sample programs directory contains two simple Clarity programs. Clarity code files have a `.clar` suffix.
4. Go ahead and display the contents of the `tokens.clar` program with the `cat` command.
```bash
root@c28600552694:/src/blockstack-core# cat sample-programs/tokens.clar
```
The next section gives you an introduction to the Clarity language by way of examining this program's code.
## Task 2: Review a simple Clarity program
If you haven't already done so, use the `cat` or `more` command to display the `tokens.clar` file's code. Clarity is designed for static analysis; it is not a compiled language and is not Turing complete. It language is a LISP-like language. LISP is an acronym for list processing.
The first line of the `tokens.clar` program contains a user-defined `get-balance` function.
```cl
(define (get-balance (account principal))
(default-to 0 (get balance (fetch-entry tokens (tuple (account account))))))
```
`get-balance` is a private function because it is constructed with the `define` call. To create public functions, you would use the `define-public` function. Public functions can be called from other contracts or even from the command line with the `clarity-cli`.
Notice the program is enclosed in `()` (parentheses) and each statement as well. The `get-balance` function takes an `account` argument of the special type `principal`. Principals represent a spending entity and are roughly equivalent to a Stacks address.
Along with the `principal` types, Clarity supports booleans, integers, and fixed length buffers. Variables are created via `let` binding but there is no support for mutating functions like `set`.
The next sequence of lines shows an `if` statement that allows you to set conditions for execution in the language..
```cl
(define (token-credit! (account principal) (tokens int))
(if (<= tokens 0)
(err "must move positive balance")
(let ((current-amount (get-balance account)))
(begin
(set-entry! tokens (tuple (account account))
(tuple (balance (+ tokens current-amount))))
(ok tokens)))))
```
Every smart contract has both a data space and code. The data space of a contract may only interact with that contract. This particular function is interacting with a map named `tokens`. The `set-entry!` function is a native function that sets the value associated with the input key to the inputted value in the `tokens` data map. Because `set-entry!` mutates data so it has an `!` exclamation point; this is by convention in Clarity.
In the first `token-transfer` public function, you see that it calls the private `get-balance` function and passes it `tx-sender`. The `tx-sender` isa a globally defined variable that represents the the current principal.
```cl
(define-public (token-transfer (to principal) (amount int))
(let ((balance (get-balance tx-sender)))
(if (or (> amount balance) (<= amount 0))
(err "must transfer positive balance and possess funds")
(begin
(set-entry! tokens (tuple (account tx-sender))
(tuple (balance (- balance amount))))
(token-credit! to amount)))))
(define-public (mint! (amount int))
(let ((balance (get-balance tx-sender)))
(token-credit! tx-sender amount)))
(token-credit! 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 10000)
(token-credit! 'SM2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQVX8X0G 300)
```
The final two lines of the program pass a principal, represented by a Stacks address, and an amount to the private user-defined `token-credit` function.
Smart contracts may call other smart contracts using a `contract-call!` function. This means that if a transaction invokes a function in a given smart contract, that function is able to make calls into other smart contracts on your behalf. The ability to read and do a static analysis of Clarity code allows clients to learn which functions a given smart contract will ever call. Good clients should always warn users about any potential side effects of a given transaction.
Take a moment to `cat` the contents of the `names.clar` file.
```bash
cat names.clar
````
Which `tokens.clar` function is being called?
## Task 3: Initialize data-space and launch contracts
In this task, you interact with the the contracts using the `clarity-cli` command line.
1. Initialize a new `db` database in the `/data/` directory
```bash
# clarity-cli initialize /data/db
Database created
```
You should see a message saying `Database created`. The command creates an SQLlite database. The database is available in the container and also in your workstation. In this tutorial, your workstation mount should at this point contain the `$HOME/blockstack-dev-data/db` directory.
2. Type check the `names.clar` contract.
```bash
# clarity-cli check sample-programs/names.clar /data/db
```
You should get an error:
```
Type check error.
NoSuchContract("tokens")
```
This happens because the `names.clar` contract _calls_ the `tokens.clar` contract, and that contract has not been created on the blockchain.
3. Type check the `tokens.clar` contract, it should pass a check as it does not use the `contract-call` function:
```bash
# clarity-cli check sample-programs/tokens.clar /data/db
Checks passed.
```
When the `check` command executes successfully and exits with the stand UNIX `0` exit code.
4. Launch the `tokens.clar` contract.
You use the `launch` command to instantiate a contract on the Stacks blockchain. If you have dependencies between contracts, for example names.clar is dependent on tokens.clar, you must launch the dependency first.
```bash
# clarity-cli launch tokens sample-programs/tokens.clar /data/db
Contract initialized!
```
Once launched, you can execute the contract or a public method on the contract. Your development database has an instantiated `tokens` contract. If you were to close the container and restart it later with the same mount point and you wouldn't need to relaunch that database; it persists until you remove it from your local drive.
5. Recheck the `names.clar` contract.
```bash
# clarity-cli check sample-programs/names.clar /data/db
```
The program should pass validation because its dependency on `tokens.clar` is fulfilled.
6. Instantiate the `names.clar` contract as well.
```bash
# clarity-cli launch names sample-programs/names.clar /data/db
```
## Task 4. Examine the SQLite database
The test environment uses a SQLite database to represent the blockchain. You initialized this database when you ran this earlier:
```bash
clarity-cli initialize /data/db
```
As you work the contracts, data is added to the `db` database because you pass this database as a parameter, for example:
```bash
clarity-cli launch tokens sample-programs/tokens.clar /data/db
```
The database exists on your local workstation and persists through restarts of the container. You can use this database to examine the effects of your Clarity programs. The tables in the SQLite database are the following:
<table class="uk-table">
<tr>
<th>Name</th>
<th>Purpose</th>
</tr>
<tr>
<td><code>contracts</code></td>
<td>Lists contracts and stores a JSON description of it.</td>
</tr>
<tr>
<td><code>data_table</code></td>
<td>Lists the data associated with a contract.</td>
</tr>
<tr>
<td><code>maps_table</code></td>
<td>Lists maps types associated with a contract and stores JSON description of it.</td>
</tr>
<tr>
<td><code>simmed_block_table</code></td>
<td>Supports the test environment by simulating responses to blockchain information queries.</td>
</tr>
<tr>
<td><code>type_analysis_table</code></td>
<td>Provides a JSON describing contract data.</td>
</tr>
</table>
While not required, you can install SQLite in your local environment and use it to examine the data associated with and impacted by your contract. For example, this what the `maps_table` contains after you initialize the `tokens` contract.
```
sqlite> select * from maps_table;
1|tokens|tokens|{"Atom":{"TupleType":{"type_map":{"account":{"Atom":"PrincipalType"}}}}}|{"Atom":{"TupleType":{"type_map":{"balance":{"Atom":"IntType"}}}}}
sqlite>
````
## Task 5: Execute a public function
In this section, you use the public `mint!` function in the `tokens` contract to mint some new tokens.
1. Use the `clarity_cli` command to create a demo address.
```
# clarity-cli generate_address
SP26CHZZ26Q25WDD1CFJYSED169PS9HTNX445XKDG
```
2. Add the address to your environment.
```bash
# DEMO_ADDRESS=SP26CHZZ26Q25WDD1CFJYSED169PS9HTNX445XKDG
```
3. Get the current balance of your new address.
```bash
# echo "(get-balance '$DEMO_ADDRESS)" | clarity-cli eval tokens /data/db
Program executed successfully! Output:
0
```
This command uses the private `get-balance` function in the `tokens` contract and pipes the result to the `eval` subcommand. The `eval` subcommand lets you evaluate both public and _private_ functions of a contract in read-only mode.
4. Try minting some tokens and sending them to an address we'll use for our demo.
```bash
# clarity-cli execute /data/db tokens mint! $DEMO_ADDRESS 100000
```
This executes the public `mint!` function defined in the tokens contract, sending 100000 tokens to you `$DEMO_ADDRESS`.
5. Use the `clarity-cli eval` command to check the result of this call.
```bash
# echo "(get-balance '$DEMO_ADDRESS)" | clarity-cli eval tokens /data/db
Program executed successfully! Output:
100000
```
## Task 6: Spend tokens by registering a name
Now, let's register a name using the `names.clar` contract. Names are just integers in this sample contract, so you'll register the name 10.
1. Compute the hash of the name we want to register.
You'll _salt_ the hash with the salt `8888`:
```bash
# echo "(hash160 (xor 10 8888))" | clarity-cli eval names /data/db
Program executed successfully! Output:
0xb572fb1ce2e9665f1efd0994fe077b50c3a48fde
```
The value of the name hash is:
```
0xb572fb1ce2e9665f1efd0994fe077b50c3a48fde
```
2. Preorder the name using the _execute_ command:
```bash
# clarity-cli execute /data/db names preorder $DEMO_ADDRESS 0xb572fb1ce2e9665f1efd0994fe077b50c3a48fde 1000
Transaction executed and committed. Returned: 0
```
This executes the public `preorder` function defined in the `names.clar` contract. The function reserves a name by paying the name fee (in this case, 1000 tokens).
3. Check the demo address' new balance:
```bash
# echo "(get-balance '$DEMO_ADDRESS)" | clarity-cli eval tokens /data/db
Program executed successfully! Output:
99000
```
4. Register the name by executing the _register_ function:
```bash
# clarity-cli execute /data/db names register $DEMO_ADDRESS \'$DEMO_ADDRESS 10 8888
Transaction executed and committed. Returned: 0clarity-cli execute /data/db names register $DEMO_ADDRESS \'$DEMO_ADDRESS 10 8888
```
5. Lookup the "owner address" for the name:
```bash
# echo "(get owner (fetch-entry name-map (tuple (name 10))))" | clarity-cli eval names /data/db
Program executed successfully! Output:
(some 'SP26CHZZ26Q25WDD1CFJYSED169PS9HTNX445XKDG)
```
## Where to go next
{:.no_toc}
* <a href="clarityRef.html">Clarity Language Reference</a>
* <a href="clarityRef.html">clarity-cli command line</a>

402
_data/clarityRef.json

@ -0,0 +1,402 @@
[
{
"name": "+ (add)",
"input_type": "int, ...",
"output_type": "int",
"signature": "(+ i1 i2...)",
"description": "Adds a variable number of integer inputs and returns the result. In the event of an _overflow_, throws a runtime error.",
"example": "(+ 1 2 3) ;; Returns 6"
},
{
"name": "- (subtract)",
"input_type": "int, ...",
"output_type": "int",
"signature": "(- i1 i2...)",
"description": "Subtracts a variable number of integer inputs and returns the result. In the event of an _underflow_, throws a runtime error.",
"example": "(- 2 1 1) ;; Returns 0\n(- 0 3) ;; Returns -3\n"
},
{
"name": "* (multiply)",
"input_type": "int, ...",
"output_type": "int",
"signature": "(* i1 i2...)",
"description": "Multiplies a variable number of integer inputs and returns the result. In the event of an _overflow_, throws a runtime error.",
"example": "(* 2 3) ;; Returns 6\n(* 5 2) ;; Returns 10\n(* 2 2 2) ;; Returns 8\n"
},
{
"name": "/ (divide)",
"input_type": "int, ...",
"output_type": "int",
"signature": "(/ i1 i2...)",
"description": "Integer divides a variable number of integer inputs and returns the result. In the event of division by zero, throws a runtime error.",
"example": "(/ 2 3) ;; Returns 0\n(/ 5 2) ;; Returns 2\n(/ 4 2 2) ;; Returns 1\n"
},
{
"name": ">= (greater than or equal)",
"input_type": "int, int",
"output_type": "bool",
"signature": "(>= i1 i2)",
"description": "Compares two integers, returning `true` if `i1` is greater than or equal to `i2` and `false` otherwise.",
"example": "(>= 1 1) ;; Returns 'true\n(>= 5 2) ;; Returns 'true\n"
},
{
"name": "<= (less than or equal)",
"input_type": "int, int",
"output_type": "bool",
"signature": "(> i1 i2)",
"description": "Compares two integers, returning true if `i1` is less than or equal to `i2` and `false` otherwise.",
"example": "(<= 1 1) ;; Returns 'true\n(<= 5 2) ;; Returns 'false\n"
},
{
"name": "< (less than)",
"input_type": "int, int",
"output_type": "bool",
"signature": "(< i1 i2)",
"description": "Compares two integers, returning `true` if `i1` is less than `i2` and `false` otherwise.",
"example": "(< 1 2) ;; Returns 'true\n(< 5 2) ;; Returns 'false\n"
},
{
"name": "> (greater than)",
"input_type": "int, int",
"output_type": "bool",
"signature": "(> i1 i2)",
"description": "Compares two integers, returning `true` if `i1` is greater than `i2` and false otherwise.",
"example": "(> 1 2) ;; Returns 'false\n(> 5 2) ;; Returns 'true\n"
},
{
"name": "mod",
"input_type": "int, int",
"output_type": "int",
"signature": "(mod i1 i2)",
"description": "Returns the integer remainder from integer dividing `i1` by `i2`. In the event of a division by zero, throws a runtime error.",
"example": "(mod 2 3) ;; Returns 0\n(mod 5 2) ;; Returns 1\n(mod 7 1) ;; Returns 0\n"
},
{
"name": "pow",
"input_type": "int, int",
"output_type": "int",
"signature": "(pow i1 i2)",
"description": "Returns the result of raising `i1` to the power of `i2`. In the event of an _overflow_, throws a runtime error.",
"example": "(pow 2 3) ;; Returns 8\n(pow 2 2) ;; Returns 4\n(pow 7 1) ;; Returns 7\n"
},
{
"name": "xor",
"input_type": "int, int",
"output_type": "int",
"signature": "(xor i1 i2)",
"description": "Returns the result of bitwise exclusive or'ing `i1` with `i2`.",
"example": "(xor 1 2) ;; Returns 3\n(xor 120 280) ;; Returns 352\n"
},
{
"name": "and",
"input_type": "bool, ...",
"output_type": "bool",
"signature": "(and b1 b2 ...)",
"description": "Returns `true` if all boolean inputs are `true`. Importantly, the supplied arguments are evaluated in-order and lazily. Lazy evaluation means that if one of the arguments returns `false`, the function short-circuits, and no subsequent arguments are evaluated.",
"example": "(and 'true 'false) ;; Returns 'false\n(and (eq? (+ 1 2) 1) (eq? 4 4)) ;; Returns 'false\n(and (eq? (+ 1 2) 3) (eq? 4 4)) ;; Returns 'true\n"
},
{
"name": "or",
"input_type": "bool, ...",
"output_type": "bool",
"signature": "(or b1 b2 ...)",
"description": "Returns `true` if any boolean inputs are `true`. Importantly, the supplied arguments are evaluated in-order and lazily. Lazy evaluation means that if one of the arguments returns `false`, the function short-circuits, and no subsequent arguments are evaluated.",
"example": "(or 'true 'false) ;; Returns 'true\n(or (eq? (+ 1 2) 1) (eq? 4 4)) ;; Returns 'true\n(or (eq? (+ 1 2) 1) (eq? 3 4)) ;; Returns 'false\n(or (eq? (+ 1 2) 3) (eq? 4 4)) ;; Returns 'true\n"
},
{
"name": "not",
"input_type": "bool",
"output_type": "bool",
"signature": "(not b1)",
"description": "Returns the inverse of the boolean input.",
"example": "(not 'true) ;; Returns 'false\n(not (eq? 1 2)) ;; Returns 'true\n"
},
{
"name": "eq?",
"input_type": "A, A, ...",
"output_type": "bool",
"signature": "(eq? v1 v2...)",
"description": "Compares the inputted values, returning `true` if they are all equal. Note that _unlike_ the `(and ...)` function, `(eq? ...)` will _not_ short-circuit.",
"example": "(eq? 1 1) ;; Returns 'true\n(eq? 1 'false) ;; Returns 'false\n(eq? \"abc\" 234 234) ;; Returns 'false\n"
},
{
"name": "if",
"input_type": "bool, A, A",
"output_type": "A",
"signature": "(if bool1 expr1 expr2)",
"description": "The `if` function admits a boolean argument and two expressions \nwhich must return the same type. In the case that the boolean input is `true`, the\n`if` function evaluates and returns `expr1`. If the boolean input is `false`, the\n`if` function evaluates and returns `expr2`.",
"example": "(if true 1 2) ;; Returns 1\n(if (> 1 2) 1 2) ;; Returns 2"
},
{
"name": "let",
"input_type": "((name2 AnyType) (name2 AnyType) ...), A",
"output_type": "A",
"signature": "(let ((name1 expr1) (name2 expr2) ...) expr-body)",
"description": "The `let` function accepts a list of `variable name` and `expression` pairs,\nevaluating each expression and _binding_ it to the corresponding variable name. The _context_\ncreated by this set of bindings is used for evaluating and return the value of `expr-body`.",
"example": "(let ((a 2) (b (+ 5 6 7))) (+ a b)) ;; Returns 20"
},
{
"name": "fetch-var",
"input_type": "VarName",
"output_type": "A",
"signature": "(fetch-var var-name)",
"description": "The `fetch-var` function looks up and returns an entry from a contract's data map.\nThe value is looked up using `var-name`.",
"example": "(fetch-var cursor) ;; Returns cursor"
},
{
"name": "set-var!",
"input_type": "VarName, AnyType",
"output_type": "bool",
"signature": "(set-var! var-name expr1)",
"description": "The `set-var!` function sets the value associated with the input variable to the \ninputted value.",
"example": "(set-var! cursor (+ cursor 1)) ;; Returns 'true"
},
{
"name": "map",
"input_type": "Function(A) -> B, (list A)",
"output_type": "(list B)",
"signature": "(map func list)",
"description": "The `map` function applies the input function `func` to each element of the\ninput list, and outputs a list containing the _outputs_ from those function applications.",
"example": "(map not (list true false true false)) ;; Returns 'false true false true"
},
{
"name": "fold",
"input_type": "Function(A, B) -> B, (list A)",
"output_type": "B",
"signature": "(fold func list initial-value)",
"description": "The `fold` function applies the input function `func` to each element of the\ninput list _and_ the output of the previous application of the `fold` function. When invoked on\nthe first list element, it uses the `initial-value` as the second input. `fold` returns the last\nvalue return by the successive applications.",
"example": "(fold * (list 2 2 2) 1) ;; Returns 8\n(fold * (list 2 2 2) 0) ;; Returns 0"
},
{
"name": "list",
"input_type": "A, ...",
"output_type": "(list A)",
"signature": "(list expr1 expr2 expr3 ...)",
"description": "The `list` function constructs a list composed of the inputted values. Each\nsupplied value must be of the same type.",
"example": "(list (+ 1 2) 4 5) ;; Returns [3 4 5]"
},
{
"name": "fetch-entry",
"input_type": "MapName, Tuple",
"output_type": "Optional(Tuple)",
"signature": "(fetch-entry map-name key-tuple)",
"description": "The `fetch-entry` function looks up and returns an entry from a contract's data map.\nThe value is looked up using `key-tuple`.\nIf there is no value associated with that key in the data map, the function returns a (none) option. Otherwise,\nit returns (some value)",
"example": "(expects! (fetch-entry names-map (tuple (name \"blockstack\"))) (err 1)) ;; Returns (tuple (id 1337))\n(expects! (fetch-entry names-map ((name \"blockstack\"))) (err 1)) ;; Same command, using a shorthand for constructing the tuple\n"
},
{
"name": "fetch-contract-entry",
"input_type": "ContractName, MapName, Tuple",
"output_type": "Optional(Tuple)",
"signature": "(fetch-contract-entry contract-name map-name key-tuple)",
"description": "The `fetch-contract-entry` function looks up and returns an entry from a\ncontract other than the current contract's data map. The value is looked up using `key-tuple`.\nIf there is no value associated with that key in the data map, the function returns a (none) option. Otherwise,\nit returns (some value).",
"example": "(expects! (fetch-contract-entry names-contract names-map (tuple (name \"blockstack\")) (err 1))) ;; Returns (tuple (id 1337))\n(expects! (fetch-contract-entry names-contract names-map ((name \"blockstack\")) (err 1)));; Same command, using a shorthand for constructing the tuple\n"
},
{
"name": "set-entry!",
"input_type": "MapName, TupleA, TupleB",
"output_type": "bool",
"signature": "(set-entry! map-name key-tuple value-tuple)",
"description": "The `set-entry!` function sets the value associated with the input key to the \ninputted value. This function performs a _blind_ update; whether or not a value is already associated\nwith the key, the function overwrites that existing association.",
"example": "(set-entry! names-map (tuple (name \"blockstack\")) (tuple (id 1337))) ;; Returns 'true\n(set-entry! names-map ((name \"blockstack\")) ((id 1337))) ;; Same command, using a shorthand for constructing the tuple\n"
},
{
"name": "insert-entry!",
"input_type": "MapName, TupleA, TupleB",
"output_type": "bool",
"signature": "(insert-entry! map-name key-tuple value-tuple)",
"description": "The `insert-entry!` function sets the value associated with the input key to the \ninputted value if and only if there is not already a value associated with the key in the map.\nIf an insert occurs, the function returns `true`. If a value already existed for\nthis key in the data map, the function returns `false`.",
"example": "(insert-entry! names-map (tuple (name \"blockstack\")) (tuple (id 1337))) ;; Returns 'true\n(insert-entry! names-map (tuple (name \"blockstack\")) (tuple (id 1337))) ;; Returns 'false\n(insert-entry! names-map ((name \"blockstack\")) ((id 1337))) ;; Same command, using a shorthand for constructing the tuple\n"
},
{
"name": "delete-entry!",
"input_type": "MapName, Tuple",
"output_type": "bool",
"signature": "(delete-entry! map-name key-tuple)",
"description": "The `delete-entry!` function removes the value associated with the input key for\nthe given map. If an item exists and is removed, the function returns `true`.\nIf a value did not exist for this key in the data map, the function returns `false`.",
"example": "(delete-entry! names-map (tuple (name \"blockstack\"))) ;; Returns 'true\n(delete-entry! names-map (tuple (name \"blockstack\"))) ;; Returns 'false\n(delete-entry! names-map ((name \"blockstack\"))) ;; Same command, using a shorthand for constructing the tuple\n"
},
{
"name": "tuple",
"input_type": "(list (KeyName AnyType))",
"output_type": "Tuple",
"signature": "(tuple ((key0 expr0) (key1 expr1) ...))",
"description": "The `tuple` function constructs a typed tuple from the supplied key and expression pairs.\nA `get` function can use typed tuples as input to select specific values from a given tuple.\nKey names may not appear multiple times in the same tuple definition. Supplied expressions are evaluated and\nassociated with the expressions' paired key name.",
"example": "(tuple (name \"blockstack\") (id 1337))"
},
{
"name": "get",
"input_type": "KeyName and Tuple | Optional(Tuple)",
"output_type": "AnyType",
"signature": "(get key-name tuple)",
"description": "The `get` function fetches the value associated with a given key from the supplied typed tuple.\nIf an `Optional` value is supplied as the inputted tuple, `get` returns an `Optional` type of the specified key in\nthe tuple. If the supplied option is a `(none)` option, get returns `(none)`.",
"example": "(get id (tuple (name \"blockstack\") (id 1337))) ;; Returns 1337\n(get id (fetch-entry names-map (tuple (name \"blockstack\")))) ;; Returns (some 1337)\n(get id (fetch-entry names-map (tuple (name \"non-existent\")))) ;; Returns (none)\n"
},
{
"name": "begin",
"input_type": "AnyType, ... A",
"output_type": "A",
"signature": "(begin expr1 expr2 expr3 ... expr-last)",
"description": "The `begin` function evaluates each of its input expressions, returning the\nreturn value of the last such expression.",
"example": "(begin (+ 1 2) 4 5) ;; Returns 5"
},
{
"name": "hash160",
"input_type": "buff|int",
"output_type": "(buff 20)",
"signature": "(hash160 value)",
"description": "The `hash160` function computes `RIPEMD160(SHA256(x))` of the inputted value.\nIf an integer (128 bit) is supplied the hash is computed over the little-endian representation of the\ninteger.",
"example": "(hash160 0) ;; Returns 0xe4352f72356db555721651aa612e00379167b30f"
},
{
"name": "sha256",
"input_type": "buff|int",
"output_type": "(buff 32)",
"signature": "(sha256 value)",
"description": "The `sha256` function computes `SHA256(x)` of the inputted value.\nIf an integer (128 bit) is supplied the hash is computed over the little-endian representation of the\ninteger.",
"example": "(sha256 0) ;; Returns 0x374708fff7719dd5979ec875d56cd2286f6d3cf7ec317a3b25632aab28ec37bb"
},
{
"name": "keccak256",
"input_type": "buff|int",
"output_type": "(buff 32)",
"signature": "(keccak256 value)",
"description": "The `keccak256` function computes `KECCAK256(value)` of the inputted value.\nNote that this differs from the `NIST SHA-3` (that is, FIPS 202) standard. If an integer (128 bit) \nis supplied the hash is computed over the little-endian representation of the integer.",
"example": "(keccak256 0) ;; Returns 0xf490de2920c8a35fabeb13208852aa28c76f9be9b03a4dd2b3c075f7a26923b4"
},
{
"name": "print",
"input_type": "A",
"output_type": "A",
"signature": "(print expr)",
"description": "The `print` function evaluates and returns its input expression. On Blockstack Core\nnodes configured for development (as opposed to production mining nodes), this function prints the resulting value to `STDOUT` (standard output).",
"example": "(print (+ 1 2 3)) ;; Returns 6"
},
{
"name": "contract-call!",
"input_type": "ContractName, PublicFunctionName, Arg0, ...",
"output_type": "Response(A,B)",
"signature": "(contract-call! contract-name function-name arg0 arg1 ...)",
"description": "The `contract-call!` function executes the given public function of the given contract.\nYou _may not_ this function to call a public function defined in the current contract. If the public\nfunction returns _err_, any database changes resulting from calling `contract-call!` are aborted.\nIf the function returns _ok_, database changes occurred.",
"example": "(contract-call! tokens transfer 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 19) ;; Returns (ok 1)"
},
{
"name": "as-contract",
"input_type": "A",
"output_type": "A",
"signature": "(as-contract expr)",
"description": "The `as-contract` function switches the current context's `tx-sender` value to the _contract's_ \nprincipal and executes `expr` with that context. It returns the resulting value of `expr`.",
"example": "(as-contract (print tx-sender)) ;; Returns 'CTcontract.name"
},
{
"name": "get-block-info",
"input_type": "BlockInfoPropertyName, BlockHeightInt",
"output_type": "buff | int",
"signature": "(get-block-info prop-name block-height-expr)",
"description": "The `get-block-info` function fetches data for a block of the given block height. The \nvalue and type returned are determined by the specified `BlockInfoPropertyName`. If the provided `BlockHeightInt` does\nnot correspond to an existing block, the function is aborted. The currently available property names \nare `time`, `header-hash`, `burnchain-header-hash`, and `vrf-seed`. \n\nThe `time` property returns an integer value of the block header time field. This is a Unix epoch timestamp in seconds \nwhich roughly corresponds to when the block was mined. **Warning**: this does not increase monotonically with each block\nand block times are accurate only to within two hours. See [BIP113](https://github.com/bitcoin/bips/blob/master/bip-0113.mediawiki) for more information. \n\nThe `header-hash`, `burnchain-header-hash`, and `vrf-seed` properties return a 32-byte buffer. \n",
"example": "(get-block-info time 10) ;; Returns 1557860301\n(get-block-info header-hash 2) ;; Returns 0x374708fff7719dd5979ec875d56cd2286f6d3cf7ec317a3b25632aab28ec37bb\n(get-block-info vrf-seed 6) ;; Returns 0xf490de2920c8a35fabeb13208852aa28c76f9be9b03a4dd2b3c075f7a26923b4\n"
},
{
"name": "ok",
"input_type": "A",
"output_type": "Response(A,B)",
"signature": "(ok value)",
"description": "The `ok` function constructs a response type from the input value. Use `ok` for\ncreating return values in public functions. An _ok_ value indicates that any database changes during\nthe processing of the function should materialize.",
"example": "(ok 1) ;; Returns (ok 1)"
},
{
"name": "err",
"input_type": "A",
"output_type": "Response(A,B)",
"signature": "(err value)",
"description": "The `err` function constructs a response type from the input value. Use `err` for\ncreating return values in public functions. An _err_ value indicates that any database changes during\nthe processing of the function should be rolled back.",
"example": "(err 'true) ;; Returns (err 'true)"
},
{
"name": "default-to",
"input_type": "A, Optional(A)",
"output_type": "A",
"signature": "(default-to default-value option-value)",
"description": "The `default-to` function attempts to 'unpack' the second argument: if the argument is\na `(some ...)` option, it returns the inner value of the option. If the second argument is a `(none)` value,\n`default-to` it returns the value of `default-value`.",
"example": "(default-to 0 (get id (fetch-entry names-map (tuple (name \"blockstack\"))))) ;; Returns 1337\n(default-to 0 (get id (fetch-entry names-map (tuple (name \"non-existant\"))))) ;; Returns 0\n"
},
{
"name": "expects!",
"input_type": "Optional(A) | Response(A,B), C",
"output_type": "A",
"signature": "(expects! option-input thrown-value)",
"description": "The `expects!` function attempts to 'unpack' the first argument: if the argument is\nan option type, and the argument is a `(some ...)` option, `expects!` returns the inner value of the\noption. If the argument is a response type, and the argument is an `(ok ...)` response, `expects!` returns\n the inner value of the `ok`. If the supplied argument is either an `(err ...)` or a `(none)` value,\n`expects!` _returns_ `thrown-value` from the current function and exits the current control-flow.",
"example": "(expects! (fetch-entry names-map (tuple (name \"blockstack\"))) (err 1)) ;; Returns (tuple (id 1337))"
},
{
"name": "expects-err!",
"input_type": "Response(A,B), C",
"output_type": "B",
"signature": "(expects-err! response-input thrown-value)",
"description": "The `expects-err!` function attempts to 'unpack' the first argument: if the argument\nis an `(err ...)` response, `expects-err!` returns the inner value of the `err`.\nIf the supplied argument is an `(ok ...)` value,\n`expects-err!` _returns_ `thrown-value` from the current function and exits the current control-flow.",
"example": "(expects-err! (err 1) 'false) ;; Returns 1"
},
{
"name": "is-ok?",
"input_type": "Response(A,B)",
"output_type": "bool",
"signature": "(is-ok? value)",
"description": "`is-ok?` tests a supplied response value, returning `true` if the response was `ok`,\nand `false` if it was an `err`.",
"example": "(is-ok? (ok 1)) ;; Returns 'true\n(is-ok? (err 1)) ;; Returns 'false"
},
{
"name": "is-none?",
"input_type": "Optional(A)",
"output_type": "bool",
"signature": "(is-none? value)",
"description": "`is-none?` tests a supplied option value, returning `true` if the option value is `(none)`,\nand `false` if it is a `(some ...)`.",
"example": "(is-none? (get id (fetch-entry names-map (tuple (name \"blockstack\"))))) ;; Returns 'false\n(is-none? (get id (fetch-entry names-map (tuple (name \"non-existant\"))))) ;; Returns 'true"
},
{
"name": "filter",
"input_type": "Function(A) -> bool, (list A)",
"output_type": "(list A)",
"signature": "(filter func list)",
"description": "The `filter` function applies the input function `func` to each element of the\ninput list, and returns the same list with any elements removed for which the `func` returned `false`.",
"example": "(filter not (list true false true false)) ;; Returns (list false false)"
},
{
"name": "define-map",
"input_type": "MapName, KeyTupleDefinition, MapTupleDefinition",
"output_type": "Not Applicable",
"signature": "(define-map map-name ((key-name-0 key-type-0) ...) ((val-name-0 val-type-0) ...))",
"description": "`define-map` is used to define a new datamap for use in a smart contract. Such\nmaps are only modifiable by the current smart contract.\n\nMaps are defined with a key tuple type and value tuple type. These are defined using a list\nof name and type pairs, e.g., a key type might be `((id int))`, which is a tuple with a single \"id\"\nfield of type `int`.\n\nLike other kinds of definition statements, `define-map` may only be used at the top level of a smart contract\ndefinition (i.e., you cannot put a define statement in the middle of a function body).",
"example": "\n(define-map squares ((x int)) ((square int)))\n(define (add-entry (x int))\n (insert-entry! squares ((x 2)) ((square (* x x)))))\n(add-entry 1)\n(add-entry 2)\n(add-entry 3)\n(add-entry 4)\n(add-entry 5)\n"
},
{
"name": "define-data-var",
"input_type": "VarName, TypeDefinition, Value",
"output_type": "Not Applicable",
"signature": "(define-data-var var-name type value)",
"description": "`define-data-var` is used to define a new persisted variable for use in a smart contract. Such\nvariable are only modifiable by the current smart contract.\n\nPersisted variable are defined with a type and a value.\n\nLike other kinds of definition statements, `define-data-var` may only be used at the top level of a smart contract\ndefinition (i.e., you cannot put a define statement in the middle of a function body).",
"example": "\n(define-data-var size int 0)\n(define (set-size (value int))\n (set-var! size value))\n(set-size 1)\n(set-size 2)\n"
},
{
"name": "define-public",
"input_type": "MethodSignature, MethodBody",
"output_type": "Not Applicable",
"signature": "(define-public (function-name (arg-name-0 arg-type-0) (arg-name-1 arg-type-1) ...) function-body)",
"description": "`define-public` is used to define a _public_ function and transaction for a smart contract. Public\nfunctions are callable from other smart contracts and may be invoked directly by users by submitting a transaction\nto the Stacks blockchain.\n\nLike other kinds of definition statements, `define-public` may only be used at the top level of a smart contract\ndefinition (i.e., you cannot put a define statement in the middle of a function body).\n\nPublic functions _must_ return a ResponseType (using either `ok` or `err`). Any datamap modifications performed by\na public function is aborted if the function returns an `err` type. Public functions may be invoked by other\ncontracts via `contract-call!`.",
"example": "\n(define-public (hello-world (input int))\n (begin (print (+ 2 input))\n (ok input)))\n"
},
{
"name": "define",
"input_type": "MethodSignature, MethodBody",
"output_type": "Not Applicable",
"signature": "(define (function-name (arg-name-0 arg-type-0) (arg-name-1 arg-type-1) ...) function-body)",
"description": "`define` is used to define _private_ functions for a smart contract. Private\nfunctions may not be called from other smart contracts, nor may they be invoked directly by users.\nInstead, these functions may only be invoked by other functions defined in the same smart contract.\n\nLike other kinds of definition statements, `define` may only be used at the top level of a smart contract\ndefinition (i.e., you cannot put a define statement in the middle of a function body).\n\nPrivate functions may return any type.",
"example": "\n(define (max-of (i1 int) (i2 int))\n (if (> i1 i2)\n i1\n i2))\n(max-of 4 6) ;; returns 6\n"
},
{
"name": "define-read-only",
"input_type": "MethodSignature, MethodBody",
"output_type": "Not Applicable",
"signature": "(define-read-only (function-name (arg-name-0 arg-type-0) (arg-name-1 arg-type-1) ...) function-body)",
"description": "`define-read-only` is used to define a _public read-only_ function for a smart contract. Such\nfunctions are callable from other smart contracts.\n\nLike other kinds of definition statements, `define-read-only` may only be used at the top level of a smart contract\ndefinition (i.e., you cannot put a define statement in the middle of a function body).\n\nRead-only functions may return any type. However, read-only functions\nmay not perform any datamap modifications, or call any functions which\nperform such modifications. This is enforced both during type checks and during\nthe execution of the function. Public read-only functions may\nbe invoked by other contracts via `contract-call!`.",
"example": "\n(define-read-only (just-return-one-hundred) \n (* 10 10))"
}
]

10
_data/navigation_core.yml

@ -11,6 +11,16 @@
- core/naming/search
- core/faq_technical
- title: Clarity Smart Contracts
docs:
- core/smart/overview
- core/smart/principals
- core/smart/functions
- core/smart/tutorial
- core/smart/clarityRef
- core/smart/clarityCLI
- core/smart/sdk-quickstart
- title: How to use BNS
docs:
- core/naming/pickname

4
_data/navigation_home.yml

@ -15,8 +15,8 @@
icon: code
doc: develop/zero_to_dapp_1
- title: Use the Naming Service
desc: Work with namespaces, zone files, and other advanced BNS topics.
- title: Blockstack Core
desc: Work with our Core node, smart contracts, namespaces, zone files, and other advanced topics.
icon: cog
doc: core/naming/introduction

6
_data/navigation_learn.yml

@ -1,10 +1,10 @@
- title: Introduction
- docs:
docs:
- develop/dapp_principles
- core/faq_developer
- title: Building Blocks
- docs:
- title: Coding basics
docs:
- develop/overview_auth
- develop/add_auth
- develop/storage

2
_develop/zero_to_dapp_1.md

@ -3,7 +3,7 @@ layout: learn
permalink: /:collection/:path.html
image: /assets/img/zero-to-dapp.png
---
# 1 About DApps and App Mining
# 1 - About DApps and App Mining
{:.no_toc}
**Zero-to-DApp 1 of 4**

2
_develop/zero_to_dapp_2.md

@ -3,7 +3,7 @@ layout: learn
permalink: /:collection/:path.html
image: /assets/img/zero-to-dapp.png
---
# 2 Learn about the Blockstack platform
# 2 - Learn about the platform
{:.no_toc}
**Zero-to-DApp 2 of 4 for MacOS/Linux (or [Windows](zero_to_dapp_2_win.html))**

8
_develop/zero_to_dapp_2_win.md

@ -3,7 +3,7 @@ layout: learn
permalink: /:collection/:path.html
image: /assets/img/zero-to-dapp.png
---
# 2 Learn about the Blockstack platform (Windows)
# 2 - Learn about the platform (Windows)
{:.no_toc}
**Zero-to-DApp 2 of 4 for Windows (or [MacOS/Linux](zero_to_dapp_2.html))**
@ -134,13 +134,13 @@ components. You'll use the `npm` command to install these packaged components.
Installing the NPM tool can take several minutes depending on your connection speed.
6. Open a new Powershell window being sure to **Run as Administrator**.
7. Open a new Powershell window being sure to **Run as Administrator**.
7. Check the node.js version you just installed.
8. Check the node.js version you just installed.
<img src="images/win-npm-version.png" alt="">
8. From the command prompt, install them
9. From the command prompt, install them
```bash
PS C:\windows\system32> npm install --global --production windows-build-tools

2
_develop/zero_to_dapp_3.md

@ -3,7 +3,7 @@ layout: learn
permalink: /:collection/:path.html
image: /assets/img/zero-to-dapp.png
---
# 3 Customize your Animal Kingdom
# 3 - Customize your kingdom
{:.no_toc}
**Zero to DAPP 3 of 4 for MacOS/Linux (or [Windows](zero_to_dapp_3_win.html))**

2
_develop/zero_to_dapp_3_win.md

@ -3,7 +3,7 @@ layout: learn
permalink: /:collection/:path.html
image: /assets/img/zero-to-dapp.png
---
# 3 Customize your Animal Kingdom (Windows)
# 3 - Customize your kingdom (Windows)
{:.no_toc}
**Zero to DAPP 3 of 4 for Windows (or [MacOS/Linux](zero_to_dapp_3.html))**

2
_develop/zero_to_dapp_4.md

@ -3,7 +3,7 @@ layout: learn
permalink: /:collection/:path.html
image: /assets/img/zero-to-dapp.png
---
# 4 List and fund thru App.co
# 4 - List and fund thru App.co
{:.no_toc}
**Zero to DAPP 4 of 4**

18
_includes/head.html

@ -28,5 +28,23 @@
window.location.hash = val.replace("#", "");
});
}
</script>
<!-- Load jquery.cookie plugin (optional) -->
<script type="text/javascript" src="/assets/navgoco/jquery.cookie.js"></script>
<!-- Load jquery.navgoco plugin js and css files -->
<script type="text/javascript" src="/assets/navgoco/jquery.navgoco.js"></script>
<link rel="stylesheet" href="/assets/navgoco/jquery.navgoco.css" type="text/css" media="screen" />
<script type="text/javascript">
$(document).ready(function() {
$('.nav').navgoco({
caretHtml: '<i class="some-random-icon-class"></i>',
accordion: true,
openClass: 'open',
slide: {
duration: 400,
easing: 'swing'
}
});
});
</script>
</head>

2
_includes/navbar.html

@ -1,6 +1,6 @@
<div class="uk-container">
<div data-uk-navbar>
<div class="uk-navbar-left">
<div class="uk-navbar-left uk-visible@m">
<!-- <a class="uk-navbar-item uk-logo" href="{{ "/" | relative_url }}">{% if site.brand.image %}<img src="{{ site.post_assets | absolute_url }}{{ site.brand.image }}" alt="{{ site.brand.text | escape }}">{% else %}{{ site.brand.text | escape }}{% endif %}</a> -->
<a class="uk-navbar-item uk-logo" href="{{ "/" | relative_url }}">{% if site.brand.image %}<img src="{{ site.post_assets | url }}{{ site.brand.image }}" alt="{{ site.brand.text | escape }}">{% else %}{{ site.brand.text | escape }}{% endif %}

42
_layouts/core.html

@ -5,32 +5,32 @@ layout: default
<div class="uk-section">
<div class="uk-container">
<div class="uk-grid-large" data-uk-grid>
<div class="sidebar-fixed-width uk-visible@m">
<div class="sidebar-docs uk-position-fixed">
<!-- -->
<ul class="nav">
{% for section in site.data.navigation_core %}
{% if section.title %}
<h5>{{ section.title }}</h5>
{% endif %}
<ul class="uk-nav uk-nav-default doc-nav">
{% for doc in section.docs %}
{% assign doc_url = doc | prepend:"/" | append:".html" %}
<!-- {% assign p = site.docs | where:"url", doc_url | first %} -->
{% for col in site.collections %}
{% for item in col.docs %}
{% if item.url == doc_url %}
{% assign doc_title = item.title %}
{% else %}
{% comment %}Do nothing{% endcomment %}
{% endif %}
{% endfor %}
{% endfor %}
<li class="{% if doc_url == page.url %}uk-active{% endif %}"><a href="{{ doc_url }}">{{ doc_title }}</a></li>
{% if section.title %}
<li ><a href='#'>{{ section.title }}</a>
{% endif %}
<ul>
{% for doc in section.docs %}
{% assign doc_url = doc | prepend:"/" | append:".html" %}
<!-- {% assign p = site.docs | where:"url", doc_url | first %} -->
{% for col in site.collections %}
{% for item in col.docs %}
{% if item.url == doc_url %}
{% assign doc_title = item.title %}
{% else %}
{% comment %}Do nothing{% endcomment %}
{% endif %}
{% endfor %}
{% endfor %}
<li class="{% if doc_url == page.url %}active{% endif %}"><a href="{{ doc_url }}">{{ doc_title }}</a></li>
{% endfor %}
</ul>
</li>
{% endfor %}
</ul>
{% endfor %}
<!-- -->
</div>
</div>

42
_layouts/learn.html

@ -5,32 +5,32 @@ layout: default
<div class="uk-section">
<div class="uk-container">
<div class="uk-grid-large" data-uk-grid>
<div class="sidebar-fixed-width uk-visible@m">
<div class="sidebar-docs uk-position-fixed">
<!-- -->
<ul class="nav">
{% for section in site.data.navigation_learn %}
{% if section.title %}
<h5>{{ section.title }}</h5>
{% endif %}
<ul class="uk-nav uk-nav-default doc-nav">
{% for doc in section.docs %}
{% assign doc_url = doc | prepend:"/" | append:".html" %}
<!-- {% assign p = site.docs | where:"url", doc_url | first %} -->
{% for col in site.collections %}
{% for item in col.docs %}
{% if item.url == doc_url %}
{% assign doc_title = item.title %}
{% else %}
{% comment %}Do nothing{% endcomment %}
{% endif %}
{% endfor %}
{% endfor %}
<li class="{% if doc_url == page.url %}uk-active{% endif %}"><a href="{{ doc_url }}">{{ doc_title }}</a></li>
{% if section.title %}
<li ><a href='#'>{{ section.title }}</a>
{% endif %}
<ul>
{% for doc in section.docs %}
{% assign doc_url = doc | prepend:"/" | append:".html" %}
<!-- {% assign p = site.docs | where:"url", doc_url | first %} -->
{% for col in site.collections %}
{% for item in col.docs %}
{% if item.url == doc_url %}
{% assign doc_title = item.title %}
{% else %}
{% comment %}Do nothing{% endcomment %}
{% endif %}
{% endfor %}
{% endfor %}
<li class="{% if doc_url == page.url %}active{% endif %}"><a href="{{ doc_url }}">{{ doc_title }}</a></li>
{% endfor %}
</ul>
</li>
{% endfor %}
</ul>
{% endfor %}
<!-- -->
</div>
</div>

2
assets/js/main.js

@ -5338,7 +5338,7 @@
selTarget: "",
widthElement: false,
showOnUp: false,
targetOffset: true
targetOffset: false
},
computed: {
selTarget: function(ref, $el) {

95
assets/navgoco/jquery.cookie.js

@ -0,0 +1,95 @@
/*!
* jQuery Cookie Plugin v1.3.1
* https://github.com/carhartl/jquery-cookie
*
* Copyright 2013 Klaus Hartl
* Released under the MIT license
*/
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as anonymous module.
define(['jquery'], factory);
} else {
// Browser globals.
factory(jQuery);
}
}(function ($) {
var pluses = /\+/g;
function raw(s) {
return s;
}
function decoded(s) {
return decodeURIComponent(s.replace(pluses, ' '));
}
function converted(s) {
if (s.indexOf('"') === 0) {
// This is a quoted cookie as according to RFC2068, unescape
s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
}
try {
return config.json ? JSON.parse(s) : s;
} catch(er) {}
}
var config = $.cookie = function (key, value, options) {
// write
if (value !== undefined) {
options = $.extend({}, config.defaults, options);
if (typeof options.expires === 'number') {
var days = options.expires, t = options.expires = new Date();
t.setDate(t.getDate() + days);
}
value = config.json ? JSON.stringify(value) : String(value);
return (document.cookie = [
config.raw ? key : encodeURIComponent(key),
'=',
config.raw ? value : encodeURIComponent(value),
options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
options.path ? '; path=' + options.path : '',
options.domain ? '; domain=' + options.domain : '',
options.secure ? '; secure' : ''
].join(''));
}
// read
var decode = config.raw ? raw : decoded;
var cookies = document.cookie.split('; ');
var result = key ? undefined : {};
for (var i = 0, l = cookies.length; i < l; i++) {
var parts = cookies[i].split('=');
var name = decode(parts.shift());
var cookie = decode(parts.join('='));
if (key && key === name) {
result = converted(cookie);
break;
}
if (!key) {
result[name] = converted(cookie);
}
}
return result;
};
config.defaults = {};
$.removeCookie = function (key, options) {
if ($.cookie(key) !== undefined) {
// Must not alter options, thus extending a fresh object...
$.cookie(key, '', $.extend({}, options, { expires: -1 }));
return true;
}
return false;
};
}));

8
assets/navgoco/jquery.cookie.min.js

@ -0,0 +1,8 @@
/*!
* jQuery Cookie Plugin v1.3.1
* https://github.com/carhartl/jquery-cookie
*
* Copyright 2013 Klaus Hartl
* Released under the MIT license
*/
!function(a){"function"==typeof define&&define.amd?define(["jquery"],a):a(jQuery)}(function(a){function b(a){return a}function c(a){return decodeURIComponent(a.replace(e," "))}function d(a){0===a.indexOf('"')&&(a=a.slice(1,-1).replace(/\\"/g,'"').replace(/\\\\/g,"\\"));try{return f.json?JSON.parse(a):a}catch(b){}}var e=/\+/g,f=a.cookie=function(e,g,h){if(void 0!==g){if(h=a.extend({},f.defaults,h),"number"==typeof h.expires){var i=h.expires,j=h.expires=new Date;j.setDate(j.getDate()+i)}return g=f.json?JSON.stringify(g):String(g),document.cookie=[f.raw?e:encodeURIComponent(e),"=",f.raw?g:encodeURIComponent(g),h.expires?"; expires="+h.expires.toUTCString():"",h.path?"; path="+h.path:"",h.domain?"; domain="+h.domain:"",h.secure?"; secure":""].join("")}for(var k=f.raw?b:c,l=document.cookie.split("; "),m=e?void 0:{},n=0,o=l.length;o>n;n++){var p=l[n].split("="),q=k(p.shift()),r=k(p.join("="));if(e&&e===q){m=d(r);break}e||(m[q]=d(r))}return m};f.defaults={},a.removeCookie=function(b,c){return void 0!==a.cookie(b)?(a.cookie(b,"",a.extend({},c,{expires:-1})),!0):!1}});

71
assets/navgoco/jquery.navgoco.css

@ -0,0 +1,71 @@
.nav, .nav ul, .nav li {
list-style: none;
}
.nav ul {
padding: 0;
margin: 0 0 0 18px;
}
.nav {
padding: 4px;
margin: 0px;
}
.nav > li {
margin: 4px 0;
}
.nav > li li {
margin: 2px 0;
}
.nav a {
color: #333;
display: block;
outline: none;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
text-decoration: none;
}
.nav li > a > span {
float: right;
font-size: 19px;
font-weight: bolder;
}
.nav li > a:hover > span {
color: #fff;
}
.nav li > a > span:after {
content: '\25be';
}
.nav li.open > a > span:after {
content: '\25b4';
}
.nav a:hover, .nav li.active > a {
background-color: #726e6e;
color: #f5f5f5;
font-weight: 500;
}
.nav > li.active > a {
background-color: #4D90FE;
}
.nav li a {
font-size: 14px;
line-height: 20px;
padding: 5px 10px;
}
.nav > li > a {
font-size: 16px;
line-height: 1.4;
padding: 5px 10px;
font-weight: 800;
}

314
assets/navgoco/jquery.navgoco.js

@ -0,0 +1,314 @@
/*
* jQuery Navgoco Menus Plugin v0.2.1 (2014-04-11)
* https://github.com/tefra/navgoco
*
* Copyright (c) 2014 Chris T (@tefra)
* BSD - https://github.com/tefra/navgoco/blob/master/LICENSE-BSD
*/
(function($) {
"use strict";
/**
* Plugin Constructor. Every menu must have a unique id which will either
* be the actual id attribute or its index in the page.
*
* @param {Element} el
* @param {Object} options
* @param {Integer} idx
* @returns {Object} Plugin Instance
*/
var Plugin = function(el, options, idx) {
this.el = el;
this.$el = $(el);
this.options = options;
this.uuid = this.$el.attr('id') ? this.$el.attr('id') : idx;
this.state = {};
this.init();
return this;
};
/**
* Plugin methods
*/
Plugin.prototype = {
/**
* Load cookie, assign a unique data-index attribute to
* all sub-menus and show|hide them according to cookie
* or based on the parent open class. Find all parent li > a
* links add the carent if it's on and attach the event click
* to them.
*/
init: function() {
var self = this;
self._load();
self.$el.find('ul').each(function(idx) {
var sub = $(this);
sub.attr('data-index', idx);
if (self.options.save && self.state.hasOwnProperty(idx)) {
sub.parent().addClass(self.options.openClass);
sub.show();
} else if (sub.parent().hasClass(self.options.openClass)) {
sub.show();
self.state[idx] = 1;
} else {
sub.hide();
}
});
var caret = $('<span></span>').prepend(self.options.caretHtml);
var links = self.$el.find("li > a");
self._trigger(caret, false);
self._trigger(links, true);
self.$el.find("li:has(ul) > a").prepend(caret);
},
/**
* Add the main event trigger to toggle menu items to the given sources
* @param {Element} sources
* @param {Boolean} isLink
*/
_trigger: function(sources, isLink) {
var self = this;
sources.on('click', function(event) {
event.stopPropagation();
var sub = isLink ? $(this).next() : $(this).parent().next();
var isAnchor = false;
if (isLink) {
var href = $(this).attr('href');
isAnchor = href === undefined || href === '' || href === '#';
}
sub = sub.length > 0 ? sub : false;
self.options.onClickBefore.call(this, event, sub);
if (!isLink || sub && isAnchor) {
event.preventDefault();
self._toggle(sub, sub.is(":hidden"));
self._save();
} else if (self.options.accordion) {
var allowed = self.state = self._parents($(this));
self.$el.find('ul').filter(':visible').each(function() {
var sub = $(this),
idx = sub.attr('data-index');
if (!allowed.hasOwnProperty(idx)) {
self._toggle(sub, false);
}
});
self._save();
}
self.options.onClickAfter.call(this, event, sub);
});
},
/**
* Accepts a JQuery Element and a boolean flag. If flag is false it removes the `open` css
* class from the parent li and slides up the sub-menu. If flag is open it adds the `open`
* css class to the parent li and slides down the menu. If accordion mode is on all
* sub-menus except the direct parent tree will close. Internally an object with the menus
* states is maintained for later save duty.
*
* @param {Element} sub
* @param {Boolean} open
*/
_toggle: function(sub, open) {
var self = this,
idx = sub.attr('data-index'),
parent = sub.parent();
self.options.onToggleBefore.call(this, sub, open);
if (open) {
parent.addClass(self.options.openClass);
sub.slideDown(self.options.slide);
self.state[idx] = 1;
if (self.options.accordion) {
var allowed = self.state = self._parents(sub);
allowed[idx] = self.state[idx] = 1;
self.$el.find('ul').filter(':visible').each(function() {
var sub = $(this),
idx = sub.attr('data-index');
if (!allowed.hasOwnProperty(idx)) {
self._toggle(sub, false);
}
});
}
} else {
parent.removeClass(self.options.openClass);
sub.slideUp(self.options.slide);
self.state[idx] = 0;
}
self.options.onToggleAfter.call(this, sub, open);
},
/**
* Returns all parents of a sub-menu. When obj is true It returns an object with indexes for
* keys and the elements as values, if obj is false the object is filled with the value `1`.
*
* @since v0.1.2
* @param {Element} sub
* @param {Boolean} obj
* @returns {Object}
*/
_parents: function(sub, obj) {
var result = {},
parent = sub.parent(),
parents = parent.parents('ul');
parents.each(function() {
var par = $(this),
idx = par.attr('data-index');
if (!idx) {
return false;
}
result[idx] = obj ? par : 1;
});
return result;
},
/**
* If `save` option is on the internal object that keeps track of the sub-menus states is
* saved with a cookie. For size reasons only the open sub-menus indexes are stored. *
*/
_save: function() {
if (this.options.save) {
var save = {};
for (var key in this.state) {
if (this.state[key] === 1) {
save[key] = 1;
}
}
cookie[this.uuid] = this.state = save;
$.cookie(this.options.cookie.name, JSON.stringify(cookie), this.options.cookie);
}
},
/**
* If `save` option is on it reads the cookie data. The cookie contains data for all
* navgoco menus so the read happens only once and stored in the global `cookie` var.
*/
_load: function() {
if (this.options.save) {
if (cookie === null) {
var data = $.cookie(this.options.cookie.name);
cookie = (data) ? JSON.parse(data) : {};
}
this.state = cookie.hasOwnProperty(this.uuid) ? cookie[this.uuid] : {};
}
},
/**
* Public method toggle to manually show|hide sub-menus. If no indexes are provided all
* items will be toggled. You can pass sub-menus indexes as regular params. eg:
* navgoco('toggle', true, 1, 2, 3, 4, 5);
*
* Since v0.1.2 it will also open parents when providing sub-menu indexes.
*
* @param {Boolean} open
*/
toggle: function(open) {
var self = this,
length = arguments.length;
if (length <= 1) {
self.$el.find('ul').each(function() {
var sub = $(this);
self._toggle(sub, open);
});
} else {
var idx,
list = {},
args = Array.prototype.slice.call(arguments, 1);
length--;
for (var i = 0; i < length; i++) {
idx = args[i];
var sub = self.$el.find('ul[data-index="' + idx + '"]').first();
if (sub) {
list[idx] = sub;
if (open) {
var parents = self._parents(sub, true);
for (var pIdx in parents) {
if (!list.hasOwnProperty(pIdx)) {
list[pIdx] = parents[pIdx];
}
}
}
}
}
for (idx in list) {
self._toggle(list[idx], open);
}
}
self._save();
},
/**
* Removes instance from JQuery data cache and unbinds events.
*/
destroy: function() {
$.removeData(this.$el);
this.$el.find("li:has(ul) > a").unbind('click');
this.$el.find("li:has(ul) > a > span").unbind('click');
}
};
/**
* A JQuery plugin wrapper for navgoco. It prevents from multiple instances and also handles
* public methods calls. If we attempt to call a public method on an element that doesn't have
* a navgoco instance, one will be created for it with the default options.
*
* @param {Object|String} options
*/
$.fn.navgoco = function(options) {
if (typeof options === 'string' && options.charAt(0) !== '_' && options !== 'init') {
var callback = true,
args = Array.prototype.slice.call(arguments, 1);
} else {
options = $.extend({}, $.fn.navgoco.defaults, options || {});
if (!$.cookie) {
options.save = false;
}
}
return this.each(function(idx) {
var $this = $(this),
obj = $this.data('navgoco');
if (!obj) {
obj = new Plugin(this, callback ? $.fn.navgoco.defaults : options, idx);
$this.data('navgoco', obj);
}
if (callback) {
obj[options].apply(obj, args);
}
});
};
/**
* Global var holding all navgoco menus open states
*
* @type {Object}
*/
var cookie = null;
/**
* Default navgoco options
*
* @type {Object}
*/
$.fn.navgoco.defaults = {
caretHtml: '',
accordion: false,
openClass: 'open',
save: true,
cookie: {
name: 'navgoco',
expires: false,
path: '/'
},
slide: {
duration: 400,
easing: 'swing'
},
onClickBefore: $.noop,
onClickAfter: $.noop,
onToggleBefore: $.noop,
onToggleAfter: $.noop
};
})(jQuery);

8
assets/navgoco/jquery.navgoco.min.js

@ -0,0 +1,8 @@
/*
* jQuery Navgoco Menus Plugin v0.2.1 (2014-04-11)
* https://github.com/tefra/navgoco
*
* Copyright (c) 2014 Chris T (@tefra)
* BSD - https://github.com/tefra/navgoco/blob/master/LICENSE-BSD
*/
!function(a){"use strict";var b=function(b,c,d){return this.el=b,this.$el=a(b),this.options=c,this.uuid=this.$el.attr("id")?this.$el.attr("id"):d,this.state={},this.init(),this};b.prototype={init:function(){var b=this;b._load(),b.$el.find("ul").each(function(c){var d=a(this);d.attr("data-index",c),b.options.save&&b.state.hasOwnProperty(c)?(d.parent().addClass(b.options.openClass),d.show()):d.parent().hasClass(b.options.openClass)?(d.show(),b.state[c]=1):d.hide()});var c=a("<span></span>").prepend(b.options.caretHtml),d=b.$el.find("li > a");b._trigger(c,!1),b._trigger(d,!0),b.$el.find("li:has(ul) > a").prepend(c)},_trigger:function(b,c){var d=this;b.on("click",function(b){b.stopPropagation();var e=c?a(this).next():a(this).parent().next(),f=!1;if(c){var g=a(this).attr("href");f=void 0===g||""===g||"#"===g}if(e=e.length>0?e:!1,d.options.onClickBefore.call(this,b,e),!c||e&&f)b.preventDefault(),d._toggle(e,e.is(":hidden")),d._save();else if(d.options.accordion){var h=d.state=d._parents(a(this));d.$el.find("ul").filter(":visible").each(function(){var b=a(this),c=b.attr("data-index");h.hasOwnProperty(c)||d._toggle(b,!1)}),d._save()}d.options.onClickAfter.call(this,b,e)})},_toggle:function(b,c){var d=this,e=b.attr("data-index"),f=b.parent();if(d.options.onToggleBefore.call(this,b,c),c){if(f.addClass(d.options.openClass),b.slideDown(d.options.slide),d.state[e]=1,d.options.accordion){var g=d.state=d._parents(b);g[e]=d.state[e]=1,d.$el.find("ul").filter(":visible").each(function(){var b=a(this),c=b.attr("data-index");g.hasOwnProperty(c)||d._toggle(b,!1)})}}else f.removeClass(d.options.openClass),b.slideUp(d.options.slide),d.state[e]=0;d.options.onToggleAfter.call(this,b,c)},_parents:function(b,c){var d={},e=b.parent(),f=e.parents("ul");return f.each(function(){var b=a(this),e=b.attr("data-index");return e?void(d[e]=c?b:1):!1}),d},_save:function(){if(this.options.save){var b={};for(var d in this.state)1===this.state[d]&&(b[d]=1);c[this.uuid]=this.state=b,a.cookie(this.options.cookie.name,JSON.stringify(c),this.options.cookie)}},_load:function(){if(this.options.save){if(null===c){var b=a.cookie(this.options.cookie.name);c=b?JSON.parse(b):{}}this.state=c.hasOwnProperty(this.uuid)?c[this.uuid]:{}}},toggle:function(b){var c=this,d=arguments.length;if(1>=d)c.$el.find("ul").each(function(){var d=a(this);c._toggle(d,b)});else{var e,f={},g=Array.prototype.slice.call(arguments,1);d--;for(var h=0;d>h;h++){e=g[h];var i=c.$el.find('ul[data-index="'+e+'"]').first();if(i&&(f[e]=i,b)){var j=c._parents(i,!0);for(var k in j)f.hasOwnProperty(k)||(f[k]=j[k])}}for(e in f)c._toggle(f[e],b)}c._save()},destroy:function(){a.removeData(this.$el),this.$el.find("li:has(ul) > a").unbind("click"),this.$el.find("li:has(ul) > a > span").unbind("click")}},a.fn.navgoco=function(c){if("string"==typeof c&&"_"!==c.charAt(0)&&"init"!==c)var d=!0,e=Array.prototype.slice.call(arguments,1);else c=a.extend({},a.fn.navgoco.defaults,c||{}),a.cookie||(c.save=!1);return this.each(function(f){var g=a(this),h=g.data("navgoco");h||(h=new b(this,d?a.fn.navgoco.defaults:c,f),g.data("navgoco",h)),d&&h[c].apply(h,e)})};var c=null;a.fn.navgoco.defaults={caretHtml:"",accordion:!1,openClass:"open",save:!0,cookie:{name:"navgoco",expires:!1,path:"/"},slide:{duration:400,easing:"swing"},onClickBefore:a.noop,onClickAfter:a.noop,onToggleBefore:a.noop,onToggleAfter:a.noop}}(jQuery);
Loading…
Cancel
Save