首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何写一个最简单的区块链小程序

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

  • 发表于:
  • 原文链接https://kuaibao.qq.com/s/20180710A1ZISU00?refer=cp_1026
  • 腾讯「腾讯云开发者社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 cloudcommunity@tencent.com 删除。

扫码

添加站长 进交流群

领取专属 10元无门槛券

私享最新 技术干货

扫码加入开发者社群
领券