這是壹個最簡單的區塊鏈小程序“Hello Blockstack”的搭建過程,這個程序不需要後端api,也不需要用戶進行註冊數據庫。
在這篇教程中我們會用到下面的工具:
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
第二步:給程序創建壹個新的目錄
mkdir hello-blockstack && cd hello-blockstack
yo blockstack
第三步:運行
npm run start
主要的代碼註釋和理解:
主要的文件是app.js (在/public 文件夾裏面),代碼被包括在監聽事件裏面,直到dom內容加載完成
document.addEventListener("DOMContentLoaded", function(event) { })
在这个里面,我们有壹个signin handler来处理用户的请求和进入
document.getElementById('signin-button').addEventListener('click', function() { blockstack.redirectUserToSignIn() })
我們也有壹個signout handler 來進行處理用戶的推出
document.getElementById('signout-button').addEventListener('click', function() { blockstack.signUserOut(window.location.origin) })
下壹步,我们有壹个函数来显示用户的简历
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
git remote add origin [email protected]:YOUR_USERNAME_HERE/hello-blockstack.git git push origin master
當然,妳也可以看官方的youtube視頻