Merge pull request #1073 from moxiegirl/sync-with-docs

Syncing with changes made to docs. Thanks, @kantai and @jcnelson for the speedy review!
This commit is contained in:
Moxiegirl
2019-08-06 08:21:58 -07:00
committed by GitHub
20 changed files with 1270 additions and 497 deletions

View File

@@ -1724,7 +1724,7 @@ Fetch a list of names from the namespace.
},
}
# Group Account Operations
## Group Account Operations
The set of methods in this section correspond to querying the states of
Blockstack token accounts. Each token account is represented by an account
@@ -2073,7 +2073,7 @@ If the account does not exist, then an empty list will be returned.
# Group Resolver Endpoints
## Lookup User [GET /v1/users/{username}]
Lookup and resolve a user's profile. Defaults to the `id` namespace.
Look up and resolve a user's profile. Defaults to the `id` namespace.
Note that [blockstack.js](https://github.com/blockstack/blockstack.js) does
*not* rely on this endpoint.

7
docs/cmdLineRef.md Normal file
View File

@@ -0,0 +1,7 @@
---
layout: core
permalink: /:collection/:path.html
---
# blockstack_cli reference
{% include commandline.md %}

View File

@@ -1,143 +1 @@
---
layout: learn
permalink: /:collection/:path.html
---
# Developer FAQs
{:.no_toc}
These FAQs are intended for developers of Blockstack.
* TOC
{:toc}
## I'm a Web developer. Can I build on Blockstack?
Yes! Blockstack is geared primarily towards Web developers. All of your
existing knowledge is immediately applicable to Blockstack. Anything you can do
in a Web browser, you can do in a Blockstack app.
## I'm a non-Web developer. Can I build on Blockstack?
Yes! Blockstack implements a [RESTful API](https://core.blockstack.org) which
lets you interact with Blockstack from any language and any runtime. In fact,
the reference client
([blockstack.js](https://github.com/blockstack/blockstack.js)) is mainly a
wrapper around these RESTful API calls, so you won't be missing much by using a
language other than Javascript.
## What's the difference between a Web app and a Blockstack app?
Blockstack apps are built like [single-page Web
apps](https://en.wikipedia.org/wiki/Single-page_application)---they are, in
fact, a type of Web application.
Blockstack apps are a subset of Web applications that use Blockstack's
technology to preserve the user's control over their identities and data.
As such, they tend to be simpler
in design and operation, since in many cases they don't have to host anything
besides the application's assets.
## Do I need to learn any new languages or frameworks?
No. Blockstack applications are built using existing Web frameworks and programming
The only new thing you need to learn is either [blockstack.js](https://github.com/blockstack/blockstack.js) or
the [Blockstack RESTful API](https://core.blockstack.org).
## How does my Web app interact with Blockstack?
The [blockstack.js](https://github.com/blockstack/blockstack.js) library gives
any Web application the ability to interact with Blockstack's authentication and
storage services. In addition, we supply a [public RESTful API](https://core.blockstack.org).
## What does `blockstack.js` do?
This is the reference client implementation for Blockstack. You use it in your
Web app to do the following:
* Authenticate users
* Load and store user data
* Read other users' public data
## How do I use `blockstack.js`?
Please see the API documentation [here](https://github.com/blockstack/blockstack.js).
## How can I look up names and profiles?
You can use `blockstack.js`, or you can use the [public Blockstack Core
endpoint](https://core.blockstack.org).
## How can I read my public app data without `blockstack.js`?
The URLs to a user's public app data are in a canonical location in their
profile. For example, here's how you would get public data from the
[Publik](https://publik.ykliao.com) app, stored under the Blockstack ID `ryan.id`.
1. Get the bucket URL
```bash
$ BUCKET_URL="$(curl -sL https://core.blockstack.org/v1/users/ryan.id | jq -r '."ryan.id"["profile"]["apps"]["http://publik.ykliao.com"]')"
$ echo "$BUCKET_URL"
https://gaia.blockstack.org/hub/1FrZTGQ8DM9TMPfGXtXMUvt2NNebLiSzad/
```
2. Get the data
```bash
$ curl -sL "${BUCKET_URL%%/}/statuses.json"
[{"id":0,"text":"Hello, Blockstack!","created_at":1515786983492}]
```
## How do I register Blockstack IDs?
You should use the [Blockstack Browser](https://github.com/blockstack/blockstack-browser).
## How do I register Blockstack Subdomains?
You can deploy and use a [Blockstack Subdomain Registrar]({{ site.baseurl }}/core/naming/subdomains.html), or
use an existing one.
## Can I programmatically register Blockstack IDs?
Blockstack applications do not currently have
have access to the user's wallet. Users are expected to
register Blockstack IDs themselves.
However, if you feel particularly ambitious, you can do one of the following:
* Set up a `blockstack api` endpoint (see the project [README](https://github.com/blockstack/blockstack-core/blob/master/README.md)) and write a
program to automatically register names. Also, see the [API
documentation](https://blockstack.github.io/blockstack-core/#managing-names-register-a-name)
for registering names on this endpoint.
* Write a `node.js` program that uses `blockstack.js` to register
names. This is currently in development.
## Can I programmatically register Blockstack Subdomains?
Yes! Once you deploy your own subdomain registrar, you can have your Web app
send it requests to register subdomains on your Blockstack ID. You can also
create a program that drives subdomain registration on your Blockstack ID.
## Do you have a testnet or sandbox to experiment with Blockstack?
We have an [integration test framework](https://github.com/blockstack/blockstack-core/tree/master/integration_tests) that provides a
private Blockstack testnet. It uses `bitcoin -regtest` to create a private
blockchain that you can interact with, without having to spend any Bitcoin or
having to wait for blocks to confirm. Please see the
[README](https://github.com/blockstack/blockstack-core/blob/master/integration_tests/README.md) for details.
## Does Blockstack have a smart contract system?
No, not yet. This is because
Blockstack's design philosophy focuses on keeping system complexity at the
"edges" of the network (e.g. clients), instead of the "core" of the network (e.g.
the blockchain), in accordance with the [end-to-end
principle](https://en.wikipedia.org/wiki/End-to-end_principle).
Generally speaking, this can be interpreted as "if you can do X without
a smart contract, you should do X without a smart contract." This organizing
principle applies to a lot of useful decentralized applications.
## Can Blockstack applications interact with Bitcoin? Ethereum? Smart contracts? Other blockchains?
Yes! Since Blockstack applications are built like Web applications, all you need to do is include the
relevant Javascript library into your application.
The documentation has been moved to [docs.blockstack.org](https://docs.blockstack.org/faqs/allfaqs), please update your bookmarks.

View File

@@ -1,148 +1 @@
## What is the Blockstack ecosystem
In the Blockstack ecosystem, users control their data and apps run on their devices. There
are no middlemen, no passwords, no massive data silos to breach, and no services
tracking us around the internet.
The applications on blockstack are server-less and decentralized. Developers
start by building a single-page application in Javascript, Then, instead of
plugging the frontend into a centralized API, they plug into an API run by the
user. Developers install a library called `blockstack.js` and don't have to
worry about running servers, maintaining databases, or building out user
management systems.
Personal user APIs ship with the Blockstack app and handle everything from
identity and authentication to data storage. Applications can request
permissions from users and then gain read and write access to user resources.
Data storage is simple and reliable and uses existing cloud infrastructure.
Users connect with their Dropbox, Google Drive, S3, etc... and data is synced
from their local device up to their cloud.
Identity is user-controlled and utilizes the blockchain for secure management of
keys, devices and usernames. When users login with apps, they are anonymous by
default and use an app-specific key, but their full identity can be revealed and
proven at any time. Keys are for signing and encryption and can be changed as
devices need to be added or removed.
Under the hood, Blockstack provides a decentralized domain name system (DNS),
decentralized public key distribution system, and registry for apps and user
identities.
## What problems does Blockstack solve?
Developers can now build Web applications where:
- you own your data, not the application
- you control where your data is stored
- you control who can access your data
Developers can now build Web applications where:
- you don't have to deal with passwords
- you don't have to host everyone's data
- you don't have to run app-specific servers
Right now, Web application users are "digital serfs" and applications are the "digital landlords". Users don't own their data; the app owns it. Users don't control where data gets stored; they can only store it on the application. Users don't control access to it; they only advise the application on how to control access (which the application can ignore).
Blockstack applications solve both sets of problems. Users pick and choose highly-available storage providers like Dropbox or BitTorrent to host their data, and applications read it with the user's consent. Blockstack ensures that all data is signed and verified and (optionally) encrypted end-to-end, so users can treat storage providers like dumb hard drives: if you don't like yours, you can swap it out with a better one. Users can take their data with them if they leave the application, since it was never the application's in the first place.
At the same time, developers are no longer on the hook for hosting user data. Since users bring their own storage and use public-key cryptography for authentication, applications don't have to store anything--there's nothing to steal when they get hacked. Moreover, many Web applications today can be re-factored so that everything happens client-side, obviating the need for running dedicated application servers.
## What is a Blockstack ID?
Blockstack IDs are usernames. Unlike normal Web app usernames, Blockstack IDs
are usable *across every Blockstack app.* They fill a similar role to
centralized single-signon services like Facebook or Google. However, you and
only you control your Blockstack ID, and no one can track your logins.
## How do I get a Blockstack ID?
If you use the [Blockstack Browser]({{ site.baseurl }}/browser/browser-introduction.md) to create a
new ID.
## Why do I need a Blockstack ID?
Blockstack IDs are used to discover where you are keeping your
(publicly-readable) application data. For example, if `alice.id` wants to share
a document with `bob.id`, then `bob.id`'s browser uses the Blockstack ID
`alice.id` to look up where `alice.id` stored it.
The technical descriptions of how and why this works are quite long.
Please see the [Blockstack Naming Service]({{site.baseurl}}/core/naming/introduction.html)
documentation for a full description.
=
## What components make ups the Blockstack ecosystem?
The components that make up Blockstack do not have any central points of
control.
* The [Blockstack Naming Service]({{ site.baseurl }}/core/naming/introduction.html) runs on top of
the Bitcoin blockchain, which itself is decentralized. It binds Blockstack
IDs to a small amount of on-chain data (usually a hash of off-chain data).
* The [Atlas Peer Network]({{ site.baseurl }}/core/atlas/overview.html) stores chunks of data referenced by
names in BNS. It operates under similar design principles to BitTorrent, and
has no single points of failure. The network is self-healing---if a node
crashes, it quickly recovers all of its state from its peers.
* The [Gaia storage system](https://github.com/blockstack/gaia) lets users
choose where their application data gets hosted. Gaia reduces all storage
systems---from cloud storage to peer-to-peer networks---to dumb, interchangeable
hard drives. Users have maximum flexibility and control over their data in a
way that is transparent to app developers.
## Blockstack vs Ethereum
Blockstack and Ethereum both strive to provide a decentralized application
platform. Blockstack's design philosophy differs from Ethereum's design
philosophy in that Blockstack emphasizes treating the blockchain as a "dumb
ledger" with no special functionality or properties beyond a few bare minimum
requirements. Instead, it strives to do everything off-chain---an application of the [end-to-end principle](https://en.wikipedia.org/wiki/End-to-end_principle).
Most Blockstack applications do *not*
interact with the blockchain, and instead interact with Blockstack
infrastructure through client libraries and RESTful endpoints.
This is evidenced by Blockstack's decision to implement its naming system (BNS), discovery and routing system
(Atlas), and storage system (Gaia) as blockchain-agnostic components that can be
ported from one blockchain to another.
Ethereum takes the opposite approach. Ethereum dapps are expected to interface
directly with on-chain smart contract logic, and are expected to host a
non-trivial amount of state in the blockchain itself. This is necessary for
them, because many Ethereum dapps' business logic is centered around the
mechanics of an ERC20 token.
Blockstack does not implement a smart contract system (yet), but it will soon
implement a [native token](https://blockstack.com/distribution.pdf) that will be
accessible to Blockstack applications.
## What's the difference between Onename and Blockstack?
Onename is the free Blockstack ID registrar run by Blockstack. It makes it easy to register your name and setup your profile. Once the name has been registered in Onename you can transfer it to a wallet you control, or leave it there and use it as you like.
## How is Blockstack different from Namecoin?
Blockstack DNS differs from Namecoin DNS in a few fundamental ways: blockchain layering, storage models, name pricing models, and incentives for miners. We wrote a post where you can learn more here: https://blockstack.org/docs/blockstack-vs-namecoin
## I heard you guys were on Namecoin, what blockchain do you use now?
We use the Bitcoin blockchain for our source of truth.
## How long has the project been around?
Work on the project started in late 2013. First public commits on the code are
from Jan 2014. The first registrar for Blockstack was launched in March 2014 and
the project has been growing since then.
## Who started the project? Who maintains it?
The project was started by two engineers from Princeton University. Muneeb Ali
and Ryan Shea met at the Computer Science department at Princeton, where Muneeb
was finishing his PhD and Ryan was running the enterprenurship club. In 2014,
frustrated by the walled-gardens and security problems of the current internet
they started working on a decentralized internet secured by blockchains. A full
list of contributors can be found
[here](https://github.com/blockstack/blockstack-core/graphs/contributors).
The documentation has been moved to [docs.blockstack.org](https://docs.blockstack.org/faqs/allfaqs), please update your bookmarks.

View File

@@ -1,185 +1 @@
---
layout: core
permalink: /:collection/:path.html
---
# Blockstack Technical FAQ
{:.no_toc}
* TOC
{:toc}
This document lists frequently-asked questions and answers to technical
questions about Blockstack.
If you are new to Blockstack, you should read the
[non-technical FAQ](https://blockstack.org/faq) first.
If you have a technical question that gets frequently asked on the
[forum](https://forum.blockstack.org) or [Slack](https://blockstack.slack.com),
feel free to send a pull-request with the question and answer.
## Who should build on Blockstack?
Everyone! But more seriously, if you are building an application in JavaScript
that requires sign-in and storage you should look at using Blockstack. The APIs
we provide are not only decentralized (No dependency on Google, Facebook, or
other OAuth provider) but easier to use than traditional OAuth. Also you no
longer have to maintain and secure databases with all your user information.
That data is stored securely with the people who created it.
## What is a "serverless" app?
The application itself should not run application-specific functionality on a server. All of its functionality should run on end-points. However, the application may use non-app-specific servers with the caveat that they must not be part of the trusted computing base. This is the case with storage systems like Amazon S3 and Dropbox, for example, because Blockstack's data is signed and verified end-to-end (so the storage systems are not trusted to serve data). Serverless can also mean applications where some amount of server-side logic is still written by the application developer but unlike traditional architectures is run in stateless compute containers that are event-triggered, ephemeral (may only last for one invocation)
## How are Blockstack domains different from normal DNS domains?
Blockstack domains are not registered on the traditional DNS run by an organized called ICANN. Instead they're registered on a blockchain in a fully decentralized way. This means that Blockstack domains are truly owned by their owners and cannot be taken away. All Blockstack domains have public keys by default (public keys are required to own the domains), unlike the traditional DNS where a small fraction of domains get the (optional) public key certificates.
## What is a virtual chain?
Blockstack is designed around a "virtual chain" concept, where nodes only need to reach consensus on the shared "virtual chain" they're interested in. Virtual chains do not interact with one another, and a single blockchain can host many virtual chains. These virtual chains can live in any blockchain for which there exists a driver, and virtual chain clients only need to execute their virtual chain transactions (i.e. Blockstack only processes Blockstack virtual chain transactions).
## What is Blockstack Core and who is working on it?
Blockstack Core is the reference implementation of the Blockstack protocol described in our white paper. It consists of a couple of parts:
- Virtualchain implementation: This is a python library that parses the underlying blockchain (Bitcoin) and builds the state of the Blockstack DNS.
- Blockstack Core: Uses the Virtualchain to build the DNS state and comes to a consensus on that state in a peer network (Atlas).
- Blockstack API: Indexes the data stored by Blockstack Core and makes it available in a performant way to applications.
The project is open-source and anyone can contribute! The major contributors are mostly employees of Blockstack PBC. You can see the full list of contributors here: https://github.com/blockstack/blockstack-core/graphs/contributors
## How is Blockstack different from Ethereum for building decentralized apps?
You can think of Ethereum as a "heavy" blockchain that does everything for you. All the complexity is handled on-chain, computations are run there, and all scalability and security concerns need to be handled at the blockchain level. It amounts to a "mainframe" that runs all the applications in the ecosystem.
Blockstack puts minimal logic into a blockchain and handles scalability outside of the blockchain by re-using existing internet infrastructure. Our architectural design mirrors how computing has developed; moving from mainframes to smaller networked entities.
Read more about the differences between Blockstack and Ethereum dapps in the following forum post: https://forum.blockstack.org/t/what-is-the-difference-between-blockstack-and-ethereum/781/2
## Can Blockstack only run on Bitcoin?
The model we're currently exploring is where Blockstack can process multiple blockchains to construct the global state where each namespace is tied to a single blockchain. Meaning that say the .id namespace is defined to run on Bitcoin and a .eth namespace is defined to run on Ethereum. Blockstack can process transactions from both blockchains and update the state of namespaces, but the consistency of any given namespace depends only on the underlying blockchain it was defined on.
## Does Blockstack use a DHT (Distributed Hash Table)?
It does not, as of November 2016. It uses a much more reliable system called the Atlas Network. Details here: https://blog.blockstack.org/blockstack-core-v0-14-0-release-aad748f46d#.30gzlthdw
## Can the Blockstack network fork?
Yes, the Blockstack network can fork if the underlying blockchain encounters a deep fork. In this case, blockstack nodes on either side of the fork will diverge from one another.
We have yet to encounter a deep fork. If this does happen, then Blockstack will use the virtualchain state on the majority fork once the fork resolves.
We also hard fork the network once a year to make protocol breaking changes and upgrade the network. The last one of these happened on block `488500` on the bitcoin blockchain. There are more details about the fork in this forum post: https://forum.blockstack.org/t/blockstack-annual-hard-fork-2017/1618
## How is the Blockstack network upgraded over time? What parties need to agree on an upgrade?
We're working on an on-chain voting strategy similar to how mining works, where anyone can cast a vote proportional to the amount of Bitcoin burned. Similar to how Bitcoin upgrades, a new feature will activate if a certain threshold (e.g. 80%) of votes consistently request its adoption over a given time interval (e.g. a couple weeks).
Until then, we will publicly announce the availability of new software, with the promise that each release will bring highly-desired features to make upgrading worth the users' whiles.
## Who gets the registration fees for name registrations?
With the current design, names are purchased by paying tribute with Bitcoin mining fees.
## Where are the current core developers based? What are the requirements for being a core developer?
Most of the core developers work in NYC and Hong Kong. Developers who've contributed to the [core open-source software](https://github.com/blockstack/blockstack-core) over a long enough time period, by default, get included in the list of core developers. There is no formal process for being part of this informal list. Core developers, generally, have the ability to write high-quality code, understand distributed systems and applied crypto, and share a vision of building a truly decentralized internet and are dedicated to that cause.
## I heard some companies working on Blockstack have raised venture capital, how does that impact the project?
Blockstack, like Linux, is an open-source project with a GPLv3 license for the core technology. Just like different companies build apps and services on top of Linux and have different individual business models, there are companies who're building apps & services for Blockstack on top of the core open-source technology and these companies have various business models and funding sources respectively. Having more venture-backed companies join the ecosystem for a decentralized internet is a good thing for everyone participating in the ecosystem including users and developers.
## Where is my data stored and how do I control who access it?
You control where your data is stored (you could run your own server, or use your own cloud storage - Dropbox, Amazon S3, and keep backups across all). You then use those places as locations pointed to by the URLs in your Blockstack ID's zone file.
## Why should I trust the information, like name ownership or public key mappings, read from Blockstack?
Blockstack records are extremely hard to tamper with. This is because the bindings for name ownership (names on Blockstack are owned by public keys) are announced in a proof-of-work blockchain (Bitcoin) and to change these binding an attacker will need to come up with a blockchain with more proof-of-work than the current Bitcoin blockchain but with a different history. Bitcoin's [current hash rate](https://blockchain.info/charts/hash-rate) makes this task almost impossible for non-state actors.
## Can anyone register a TLD?
Yes, anyone can register a TLD. If a TLD has not been registered already and you're willing to pay the registration fee for it, you can go ahead and register that TLD. There is no centralized party that can stop you from registering a TLD.
## What programming language can I use to build these apps?
To make apps that run in the web browser using Blockstack, you can use JavaScript and any of the same web frameworks or libraries you use today such as React, AngularJs, Vue.js or jQuery. The Blockstack Core is implementated in Python, but you can use any language you like for native apps as long as you are able to consume a JSON REST API.
## Do I need to run a full Blockstack node to use Blockstack?
tl;dr: You don't, but its very easy to.
To reduce the overhead involved in getting started we maintain a fleet of Blockstack Core nodes that your Blockstack applications connect to by default. If you want to run your own we provide detailed instructions on our [install page](https://blockstack.org/install). It only takes about 5-10 minutes to spin up your full node!
## What is the capacity per block for registrations using Blockstack?
Initial registrations can be done at an order of hundreds per block and once an identity is registered you can do “unlimited” updates to the data because that is off-chain. Were also working on a more scalable solution where a very large number of identities can be registered but thats not live yet and is in the pipeline as a rough benchmark. in summer 2015, Blockstack did 30,000+ identity registrations in a matter of few days live on the blockchain and Blockstack was actually throttling its servers and not taking up more than 100-200 transactions per block. It couldve easily taken up more transactions without impacting the network.
## What language is the Blockstack software written in?
Python 2 and Node.js
## What incentives are there to run a Blockstack node?
Running a Blockstack node keeps you secure by ensuring that your app gets the right names and public keys. It's not expensive; it takes as much resources as a Chrome tab.
## Can Blockstack apps scale, given that Blockstack uses blockchains which don't scale that well?
Yes. Blockstack only uses the blockchain for name registration. Everything else happens off-chain, so apps work just as fast as they do on the Web.
## What if the current companies and developers working on Blockstack disappear, would the network keep running?
Yes, the Blockstack network will keep running. All of Blockstack's code is open-source and anyone can deploy Blockstack nodes or maintain the code. Further, Blockstack nodes don't need to coordinate with each other to function. Any node that a user deploys can function correctly independently.
## Where does Blockstack keep my app data?
As a Blockstack user, you can choose exactly where your data gets stored.
Blockstack uses a decentralized storage system called
[Gaia](https://github.com/blockstack/gaia) to host your data. Gaia is different
from other storage systems because it lets you securely host your data wherever you want---in cloud
storage providers, on your personal server, or in another decentralized storage
system like BitTorrent or IPFS.
When you register, you are given a default Gaia hub that replicates your
data to a bucket in Microsoft Azure. However, you can configure and
deploy your own Gaia hub and have Blockstack store your data there instead.
The [Blockstack Naming Service]({{ site.baseurl }}/core/naming/introduction.html) and the [Atlas network]({{ site.baseurl }}/core/atlas/overview.html) work together to help other users discover your
app-specific public data, given your Blockstack ID.
## What is a Blockstack Subdomain?
This is also a Blockstack ID, and can be used for all the things a Blockstack ID
can be used for. The only difference is that they have the format `foo.bar.baz`
instead of `bar.baz`. For example,
[jude.personal.id](https://core.blockstack.org/v1/users/jude.personal.id) is a
Blockstack ID, and is a subdomain of `personal.id`.
Subdomains are first-class Blockstack IDs---they can be used for all the same
things that an on-chain Blockstack ID can be used for, and they have all of
the same safety properties. They are globally unique, they are strongly owned
by a private key, and they are human-readable.
Subdomains are considerably cheaper than Blockstack IDs, since hundreds of them
can be registered with a single transaction. The [BNS
documentation]({{ site.baseurl }}/core/naming/introduction.html) describes them in detail.
Subdomains provide a fast, inexpensive way to onboard many users at once.
## Can I get a Blockstack ID without spending Bitcoin?
Blockstack subdomains can be obtained without spending Bitcoin
by asking a subdomain registrar to create one for you.
## Is there a Blockstack name explorer?
Yes! It's at https://explorer.blockstack.org
The documentation has been moved to [docs.blockstack.org](https://docs.blockstack.org/faqs/allfaqs), please update your bookmarks.

View File

@@ -2,7 +2,7 @@
layout: core
permalink: /:collection/:path.html
---
# Blockstack API
# Blockstack API
{:.no_toc}
* TOC
{:toc}
@@ -34,7 +34,7 @@ $ ./build_docs.sh public_api
### Search Subsystem
If you want to enable the search subsystem in your installation, you can
follow the instructions [here](search.md).
follow the instructions [here](search.html).
### Nginx Deployment

View File

@@ -46,7 +46,7 @@ Figure 1: BNS architecture overview. Clients talk to the BNS API module to
resolve names, and generate and send blockchain transactions to register and
modify names. The API module talks to the indexer module and gives clients
a stable, Web-accessible interface for resolving names. The indexer module reads
the blochchain via a blockchain peer, over the blockchain's peer network.
the blockchain via a blockchain peer, over the blockchain's peer network.
Blockstack Core currently implements the API module and indexer module as separate
daemons (`blockstack api` and `blockstack-core`, respectively). However, this

View File

@@ -76,7 +76,7 @@ geared towards providing programmatic control over names with Turing-complete
on-chain resolvers.
BNS has a fundamentally different relationship with blockchains than ENS.
WHereas ENS tries to use on-chain logic as much as possible, BNS
Whereas ENS tries to use on-chain logic as much as possible, BNS
tries to use the blockchain as little as possible. BNS only uses it to store a
database log for name operations (which are interpreted with an off-chain BNS
node like Blockstack Core). BNS name state and BNS subdomains reside entirely

View File

@@ -52,6 +52,6 @@ do this, then the namespace they created disappears (along with all the names
they imported).
Developers wanting to create their own namespaces should read the [namespace
creation]({{ site.baseurl }}/core/naming/namepsaces.html) document. It is highly recommended that
creation]({{ site.baseurl }}/core/naming/namespaces.html) document. It is highly recommended that
developers individula support to create your own namespace, given the large amount of
cryptocurrency at stake.

View File

@@ -2,7 +2,7 @@
layout: core
permalink: /:collection/:path.html
---
## Decentralized Identifiers (DIDs)
# Decentralized Identifiers (DIDs)
BNS nodes are compliant with the emerging
[Decentralized Identity Foundation](http://identity.foundation) protocol

View File

@@ -11,6 +11,7 @@ following sections:
* TOC
{:toc}
## Intended uses for a namespace
The intention is that each application can create its own BNS
@@ -19,10 +20,10 @@ namespace for its own purposes. Applications can use namespaces for things like
* Giving users a SSO system, where each user registers their public key under a
username. Blockstack applications do this with names in the `.id` namespace,
for example.
* Providing a subscription service, where each name is a 3rd party that provides
a service for users to subscribe to. For example, names in
`.podcast` point to podcasts that users of the
[DotPodcast](https://dotpodcast.co) app can subscribe to.
`.podcast` point to podcasts that users of the <a href="https://dotpodcast.co" target="\_blank">DotPodcast</a> app can subscribe to.
* Implementing software licenses, where each name corresponds to an access key.
Unlike conventional access keys, access keys implemented as names
can be sold and traded independently. The licensing fee (paid as a name
@@ -37,7 +38,7 @@ gives them a way to measure economic activity.
Developers can query individual namespaces and look up names within them using
the BNS API.
## List all namespaces in existence ([reference](https://core.blockstack.org/#namespace-operations-get-all-namespaces)).
## List all namespaces in existence (<a href="https://core.blockstack.org/#namespace-operations-get-all-namespaces" target="\_blank">reference</a>).
```bash
$ curl https://core.blockstack.org/v1/namespaces
@@ -48,7 +49,7 @@ $ curl https://core.blockstack.org/v1/namespaces
]
```
## List all names within a namespace ([reference](https://core.blockstack.org/#namespace-operations-get-all-namespaces))
## List all names within a namespace (<a href="https://core.blockstack.org/#namespace-operations-get-all-namespaces" target="\_blank">reference</a>).
```bash
$ curl https://core.blockstack.org/v1/namespaces/id/names?page=0
@@ -79,7 +80,7 @@ $ curl https://core.blockstack.org/v1/namespaces/id/names?page=0
Each page returns a batch of 100 names.
## Get the Cost to Register a Namespace ([reference](https://core.blockstack.org/#price-checks-get-namespace-price))
## Get the Cost to Register a Namespace (<a href="https://core.blockstack.org/#price-checks-get-namespace-price" target="\_blank">reference</a>).
```bash
$ curl https://core.blockstack.org/v1/prices/namespaces/test
@@ -88,9 +89,9 @@ $ curl https://core.blockstack.org/v1/prices/namespaces/test
}
```
If you want to register a namespace, please see the [namespace creation section]({{ site.baseurl }}/core/naming/namespace.html).
If you want to register a namespace, please see the [namespace creation section]({{ site.baseurl }}/core/naming/namespaces.html).
## Getting the Current Consensus Hash ([reference](https://core.blockstack.org/#blockchain-operations-get-consensus-hash))
## Getting the Current Consensus Hash (<a href="https://core.blockstack.org/#blockchain-operations-get-consensus-hash" target="\_blank">reference</a>).
```bash
$ curl -sL https://core.blockstack.org/v1/blockchains/bitcoin/consensus
@@ -108,14 +109,14 @@ transaction.
There are four steps to creating a namespace:
1. **Send a `NAMESPACE_PREORDER` transaction** ([live example](https://www.blocktrail.com/BTC/tx/5f00b8e609821edd6f3369ee4ee86e03ea34b890e242236cdb66ef6c9c6a1b28)).
1. **Send a `NAMESPACE_PREORDER` transaction** (<a href="https://www.blocktrail.com/BTC/tx/5f00b8e609821edd6f3369ee4ee86e03ea34b890e242236cdb66ef6c9c6a1b28" target="\_blank">live example</a>).
This is the first step. This registers the *salted hash* of the namespace with BNS nodes, and burns the
requisite amount of cryptocurrency. In addition, it proves to the
BNS nodes that user has honored the BNS consensus rules by including
a recent *consensus hash* in the transaction
(see the section on [BNS forks](#bns-forks) for details).
2. **Send a `NAMESPACE_REVEAL` transaction** ([live example](https://www.blocktrail.com/BTC/tx/ab54b1c1dd5332dc86b24ca2f88b8ca0068485edf0c322416d104c5b84133a32)).
2. **Send a `NAMESPACE_REVEAL` transaction** (<a href="https://www.blocktrail.com/BTC/tx/ab54b1c1dd5332dc86b24ca2f88b8ca0068485edf0c322416d104c5b84133a32" target="\_blank">live example</a>).
This is the second step. This reveals the salt and the namespace ID (pairing it with its
`NAMESPACE_PREORDER`), it reveals how long names last in this namespace before
they expire or must be renewed, and it sets a *price function* for the namespace
@@ -126,12 +127,12 @@ has any vowels or non-alphabet characters). The namespace creator
has the option to collect name registration fees for the first year of the
namespace's existence by setting a *namespace creator address*.
3. **Seed the namespace with `NAME_IMPORT` transactions** ([live example](https://www.blocktrail.com/BTC/tx/c698ac4b4a61c90b2c93dababde867dea359f971e2efcf415c37c9a4d9c4f312)).
3. **Seed the namespace with `NAME_IMPORT` transactions** (<a href="https://www.blocktrail.com/BTC/tx/c698ac4b4a61c90b2c93dababde867dea359f971e2efcf415c37c9a4d9c4f312" target="\_blank">live example</a>).
Once the namespace has been revealed, the user has the option to populate it with a set of
names. Each imported name is given both an owner and some off-chain state.
This step is optional---namespace creators are not required to import names.
4. **Send a `NAMESPACE_READY` transaction** ([live example](https://www.blocktrail.com/BTC/tx/2bf9a97e3081886f96c4def36d99a677059fafdbd6bdb6d626c0608a1e286032)).
4. **Send a `NAMESPACE_READY` transaction** (<a href="https://www.blocktrail.com/BTC/tx/2bf9a97e3081886f96c4def36d99a677059fafdbd6bdb6d626c0608a1e286032" target="\_blank">live example</a>).
This is the final step of the process. It *launches* the namespace, which makes it available to the
public. Once a namespace is ready, anyone can register a name in it if they
pay the appropriate amount of cryptocurrency (according to the price funtion
@@ -153,6 +154,6 @@ Once the user issues the `NAMESPACE_PREORDER` and `NAMESPACE_REVEAL`, they have
do this, then the namespace they created disappears (along with all the names
they imported).
Developers wanting to create their own namespaces should read the [namespace creation section]({{ site.baseurl }}/core/naming/namespace.html) document. It is highly recommended that
Developers wanting to create their own namespaces should read the [namespace creation section]({{ site.baseurl }}/core/naming/namespaces.html) document. It is highly recommended that
developers request individual support before creating their own space, given the large amount of
cryptocurrency at stake.

90
docs/smart/clarityCLI.md Normal file
View File

@@ -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 functions 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
docs/smart/clarityRef.md Normal file
View File

@@ -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
docs/smart/functions.md Normal file
View File

@@ -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.

View File

@@ -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
docs/smart/overview.md Normal file
View File

@@ -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` expression that is excuted when the contract launches. 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
docs/smart/principals.md Normal file
View File

@@ -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.

View File

@@ -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 (say-hi)
"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 return 'hello world'", async () => {
const query = helloWorldClient.createQuery({ method: { name: "say-hi", 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
docs/smart/tutorial.md Normal file
View File

@@ -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>

View File

@@ -382,7 +382,7 @@ Op: `;`
Description: This transaction registers a name and some name state into a
namespace that has been revealed, but not been launched. Only the namespace
creator can import names. See the [namespace creation section]({{ site.baseurl }}/core/naming/namespace.html) for details.
creator can import names. See the [namespace creation section]({{ site.baseurl }}/core/naming/namespaces.html) for details.
Example: [c698ac4b4a61c90b2c93dababde867dea359f971e2efcf415c37c9a4d9c4f312](https://www.blocktrail.com/BTC/tx/c698ac4b4a61c90b2c93dababde867dea359f971e2efcf415c37c9a4d9c4f312)