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

2018-04-28 16:49:31 +08:00
 kmdd33

这是一个最简单的区块链小程序“ 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

https://github.com/new

git remote add origin git@github.com:YOUR_USERNAME_HERE/hello-blockstack.git

git push origin master

1151 次点击
所在节点    程序员
0 条回复

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/450716

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX