這是一個(gè)最簡(jiǎn)單的區(qū)塊鏈小程序“Hello Blockstack”的搭建過(guò)程,這個(gè)程序不需要后端api,也不需要用戶(hù)進(jìn)行注冊(cè)數(shù)據(jù)庫(kù)。愛(ài)掏網(wǎng) - it200.com
在這篇教程中我們會(huì)用到下面的工具:
- npm to manage dependencies and scripts
- browserify to compile node code into browser-ready code
- blockstack.js to authenticate the user and work with the user’s identity/profile information
第一步:安裝yeoman
npm install -g yo generator-blockstack
第二步:給程序創(chuàng)建一個(gè)新的目錄
mkdir hello-blockstack && cd hello-blockstack
yo blockstack
第三步:運(yùn)行
npm run start
主要的代碼注釋和理解:
主要的文件是 app.js (在/public 文件夾里面),代碼被包括在監(jiān)聽(tīng)事件里面,直到dom內(nèi)容加載完成
document.addEventListener("DOMContentLoaded", function(event) {
})
在這個(gè)里面,我們有一個(gè)signin handler來(lái)處理用戶(hù)的請(qǐng)求和進(jìn)入
document.getElementById('signin-button').addEventListener('click', function() {
blockstack.redirectUserToSignIn()
})
我們也有一個(gè)signout handler 來(lái)進(jìn)行處理用戶(hù)的推出
document.getElementById('signout-button').addEventListener('click', function() {
blockstack.signUserOut(window.location.origin)
})
下一步,我們有一個(gè)函數(shù)來(lái)顯示用戶(hù)的簡(jiǎn)歷
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'
}
有三種狀態(tài)可以讓用戶(hù)登錄
The user is already signed in
The user has a sign in request that is pending
The user is signed out
代碼表達(dá)方式
if (blockstack.isUserSignedIn()) {
// Show the user's profile
} else if (blockstack.isSignInPending()) {
// Sign the user in
} else {
// Do nothing
}
在用戶(hù)請(qǐng)求的過(guò)程中
if (blockstack.isUserSignedIn()) {
var profile = blockstack.loadUserData().profile
showProfile(profile)
} else if (blockstack.isSignInPending()) {
blockstack.handlePendingSignIn().then(function(userData) {
window.location = window.location.origin
})
}
程序顯示樣式的控制文件:
控制這個(gè)程序顯示樣式的文件是 (/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"
}]
}
源代碼實(shí)現(xiàn):
git init
git add . && git commit -m "first commit"
然后去github添加一個(gè)新的repo
https://github.com/new
git remote add origin git@github.com:YOUR_USERNAME_HERE/hello-blockstack.git
git push origin master
加入到blockstack社區(qū)中來(lái):https://contribute.blockstack…
下載blockstack:https://blockstack.org/install