這是一個最簡單的區塊鏈小程序「Hello Blockstack」的搭建過程,這個程序不須要後端api,也不須要用戶進行註冊數據庫。node
在這篇教程中咱們會用到下面的工具:git
第一步:安裝yeomangithub
npm install -g yo generator-blockstack
第二步:給程序建立一個新的目錄數據庫
mkdir hello-blockstack && cd hello-blockstack
yo blockstack
第三步:運行npm
npm run start
主要的代碼註釋和理解:json
主要的文件是 app.js (在/public 文件夾裏面),代碼被包括在監聽事件裏面,直到dom內容加載完成小程序
document.addEventListener("DOMContentLoaded", function(event) { })
在這個裏面,咱們有一個signin handler來處理用戶的請求和進入後端
document.getElementById('signin-button').addEventListener('click', function() { blockstack.redirectUserToSignIn() })
咱們也有一個signout handler 來進行處理用戶的推出api
document.getElementById('signout-button').addEventListener('click', function() { blockstack.signUserOut(window.location.origin) })
下一步,咱們有一個函數來顯示用戶的簡歷app
function showProfile(profile) { var person = new blockstack.Person(profile) document.getElementById('heading-name').innerHTML = person.name() document.getElementById('avatar-image').setAttribute('src', person.avatarUrl()) document.getElementById('section-1').style.display = 'none' document.getElementById('section-2').style.display = 'block' }
有三種狀態可讓用戶登陸
The user is already signed in
The user has a sign in request that is pending
The user is signed out
代碼表達方式
if (blockstack.isUserSignedIn()) { // Show the user's profile } else if (blockstack.isSignInPending()) { // Sign the user in } else { // Do nothing }
在用戶請求的過程當中
if (blockstack.isUserSignedIn()) { var profile = blockstack.loadUserData().profile showProfile(profile) } else if (blockstack.isSignInPending()) { blockstack.handlePendingSignIn().then(function(userData) { window.location = window.location.origin }) }
程序顯示樣式的控制文件:
控制這個程序顯示樣式的文件是 (/public/manifest.json)
{ "name": "Hello, Blockstack", "start_url": "localhost:5000", "description": "A simple demo of Blockstack Auth", "icons": [{ "src": "https://helloblockstack.com/icon-192x192.png", "sizes": "192x192", "type": "image/png" }] }
源代碼實現:
git init
git add . && git commit -m "first commit"
而後去github添加一個新的repo
https://github.com/new
git remote add origin git@github.com:YOUR_USERNAME_HERE/hello-blockstack.git
git push origin master
加入到blockstack社區中來:https://contribute.blockstack...
下載blockstack:https://blockstack.org/install