如何写一个最简单的区块链小程序“Hello Blockstack”,内附详细blockstack教程

这是一个最简单的区块链小程序“Hello Blockstack”的搭建过程,这个程序不须要后端api,也不须要用户进行注册数据库。node

在这篇教程中咱们会用到下面的工具:git

  1. npm to manage dependencies and scripts
  2. browserify to compile node code into browser-ready code
  3. blockstack.js to authenticate the user and work with the user's identity/profile information

第一步:安装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...
下载blockstackhttps://blockstack.org/install

相关文章
相关标签/搜索