first commit
Signed-off-by: Jakub Sokołowski <jakub@status.im>
13
.editorconfig
Normal file
@ -0,0 +1,13 @@
|
||||
# EditorConfig http://EditorConfig.org
|
||||
|
||||
# top-most EditorConfig file
|
||||
root = true
|
||||
|
||||
# All files
|
||||
[*]
|
||||
end_of_line = lf
|
||||
insert_final_newline = true
|
||||
trim_trailing_whitespace = true
|
||||
charset = utf-8
|
||||
indent_style = space
|
||||
indent_size = 2
|
284
.eslintrc.json
Normal file
@ -0,0 +1,284 @@
|
||||
{
|
||||
"env": {
|
||||
"browser": true,
|
||||
"es6": true,
|
||||
"node": true
|
||||
},
|
||||
"extends": [
|
||||
"eslint:recommended"
|
||||
],
|
||||
"parser": "babel-eslint",
|
||||
"plugins": [
|
||||
"react"
|
||||
],
|
||||
"rules": {
|
||||
"accessor-pairs": "error",
|
||||
"array-bracket-newline": "error",
|
||||
"array-bracket-spacing": [
|
||||
"error",
|
||||
"never"
|
||||
],
|
||||
"array-callback-return": "off",
|
||||
"array-element-newline": "off",
|
||||
"arrow-body-style": "off",
|
||||
"arrow-parens": "off",
|
||||
"arrow-spacing": [
|
||||
"error",
|
||||
{
|
||||
"after": true,
|
||||
"before": true
|
||||
}
|
||||
],
|
||||
"block-scoped-var": "error",
|
||||
"block-spacing": "error",
|
||||
"brace-style": "off",
|
||||
"callback-return": "off",
|
||||
"camelcase": "off",
|
||||
"capitalized-comments": "off",
|
||||
"class-methods-use-this": "off",
|
||||
"comma-dangle": "error",
|
||||
"comma-spacing": "off",
|
||||
"comma-style": [
|
||||
"error",
|
||||
"last"
|
||||
],
|
||||
"complexity": "error",
|
||||
"computed-property-spacing": [
|
||||
"error",
|
||||
"never"
|
||||
],
|
||||
"consistent-return": "off",
|
||||
"consistent-this": "off",
|
||||
"curly": "off",
|
||||
"default-case": "error",
|
||||
"dot-location": [
|
||||
"error",
|
||||
"property"
|
||||
],
|
||||
"dot-notation": "off",
|
||||
"eol-last": "error",
|
||||
"eqeqeq": "error",
|
||||
"for-direction": "error",
|
||||
"func-call-spacing": "error",
|
||||
"func-name-matching": "error",
|
||||
"func-names": "off",
|
||||
"func-style": "off",
|
||||
"function-paren-newline": "off",
|
||||
"generator-star-spacing": "error",
|
||||
"getter-return": "error",
|
||||
"global-require": "off",
|
||||
"guard-for-in": "off",
|
||||
"handle-callback-err": "off",
|
||||
"id-blacklist": "error",
|
||||
"id-length": "off",
|
||||
"id-match": "error",
|
||||
"indent": "off",
|
||||
"indent-legacy": "off",
|
||||
"init-declarations": "off",
|
||||
"jsx-quotes": "error",
|
||||
"key-spacing": "off",
|
||||
"keyword-spacing": "off",
|
||||
"line-comment-position": "off",
|
||||
"linebreak-style": "off",
|
||||
"lines-around-comment": "error",
|
||||
"lines-around-directive": "error",
|
||||
"max-depth": "error",
|
||||
"max-len": "off",
|
||||
"max-lines": "off",
|
||||
"max-params": "off",
|
||||
"max-statements": "off",
|
||||
"max-statements-per-line": "off",
|
||||
"multiline-ternary": [
|
||||
"error",
|
||||
"never"
|
||||
],
|
||||
"new-parens": "off",
|
||||
"newline-after-var": "off",
|
||||
"newline-before-return": "off",
|
||||
"newline-per-chained-call": "off",
|
||||
"no-alert": "error",
|
||||
"no-array-constructor": "error",
|
||||
"no-await-in-loop": "error",
|
||||
"no-bitwise": "error",
|
||||
"no-buffer-constructor": "error",
|
||||
"no-caller": "error",
|
||||
"no-catch-shadow": "error",
|
||||
"no-confusing-arrow": "error",
|
||||
"no-console": "off",
|
||||
"no-continue": "off",
|
||||
"no-debugger": "warn",
|
||||
"no-div-regex": "error",
|
||||
"no-duplicate-imports": "error",
|
||||
"no-else-return": 2,
|
||||
"no-empty-function": "off",
|
||||
"no-eq-null": "error",
|
||||
"no-eval": "off",
|
||||
"no-extend-native": "error",
|
||||
"no-extra-bind": "error",
|
||||
"no-extra-label": "error",
|
||||
"no-extra-parens": "off",
|
||||
"no-floating-decimal": "error",
|
||||
"no-implicit-coercion": [
|
||||
"error",
|
||||
{
|
||||
"allow": ["!!"]
|
||||
}
|
||||
],
|
||||
"no-implicit-globals": "error",
|
||||
"no-implied-eval": "error",
|
||||
"no-inline-comments": "off",
|
||||
"no-inner-declarations": [
|
||||
"error",
|
||||
"functions"
|
||||
],
|
||||
"no-invalid-this": "off",
|
||||
"no-iterator": "error",
|
||||
"no-label-var": "error",
|
||||
"no-labels": "error",
|
||||
"no-lone-blocks": "error",
|
||||
"no-lonely-if": "off",
|
||||
"no-loop-func": "off",
|
||||
"no-magic-numbers": "off",
|
||||
"no-mixed-operators": "error",
|
||||
"no-mixed-requires": "error",
|
||||
"no-multi-assign": "error",
|
||||
"no-multi-spaces": "off",
|
||||
"no-multi-str": "error",
|
||||
"no-multiple-empty-lines": "error",
|
||||
"no-native-reassign": "error",
|
||||
"no-negated-condition": "off",
|
||||
"no-negated-in-lhs": "error",
|
||||
"no-nested-ternary": "error",
|
||||
"no-new": "error",
|
||||
"no-new-func": "error",
|
||||
"no-new-object": "error",
|
||||
"no-new-require": "error",
|
||||
"no-new-wrappers": "error",
|
||||
"no-octal-escape": "error",
|
||||
"no-param-reassign": "off",
|
||||
"no-path-concat": "error",
|
||||
"no-plusplus": "off",
|
||||
"no-process-env": "off",
|
||||
"no-process-exit": "off",
|
||||
"no-proto": "error",
|
||||
"no-prototype-builtins": "off",
|
||||
"no-restricted-globals": "error",
|
||||
"no-restricted-imports": "error",
|
||||
"no-restricted-modules": "error",
|
||||
"no-restricted-properties": "error",
|
||||
"no-restricted-syntax": "error",
|
||||
"no-return-assign": "error",
|
||||
"no-return-await": "error",
|
||||
"no-script-url": "error",
|
||||
"no-self-compare": "error",
|
||||
"no-sequences": "error",
|
||||
"no-shadow": "off",
|
||||
"no-shadow-restricted-names": "error",
|
||||
"no-spaced-func": "error",
|
||||
"no-sync": "off",
|
||||
"no-tabs": "error",
|
||||
"no-template-curly-in-string": "error",
|
||||
"no-ternary": "off",
|
||||
"no-throw-literal": "error",
|
||||
"no-trailing-spaces": "off",
|
||||
"no-undef-init": "error",
|
||||
"no-undefined": "off",
|
||||
"no-underscore-dangle": "off",
|
||||
"no-unmodified-loop-condition": "error",
|
||||
"no-unneeded-ternary": "error",
|
||||
"no-unused-expressions": "error",
|
||||
"no-unused-vars": [
|
||||
"error",
|
||||
{
|
||||
"argsIgnorePattern": "^_",
|
||||
"varsIgnorePattern": "^_"
|
||||
}
|
||||
],
|
||||
"no-use-before-define": "off",
|
||||
"no-useless-call": "off",
|
||||
"no-useless-computed-key": "error",
|
||||
"no-useless-concat": "error",
|
||||
"no-useless-constructor": "error",
|
||||
"no-useless-escape": "off",
|
||||
"no-useless-rename": "error",
|
||||
"no-useless-return": "off",
|
||||
"no-var": "off",
|
||||
"no-void": "error",
|
||||
"no-warning-comments": "off",
|
||||
"no-whitespace-before-property": "error",
|
||||
"no-with": "error",
|
||||
"nonblock-statement-body-position": "error",
|
||||
"object-curly-newline": "off",
|
||||
"object-curly-spacing": [
|
||||
"off"
|
||||
],
|
||||
"object-property-newline": "off",
|
||||
"object-shorthand": "off",
|
||||
"one-var": "off",
|
||||
"one-var-declaration-per-line": "off",
|
||||
"operator-assignment": "off",
|
||||
"operator-linebreak": "error",
|
||||
"padded-blocks": "off",
|
||||
"padding-line-between-statements": "error",
|
||||
"prefer-arrow-callback": "off",
|
||||
"prefer-const": "off",
|
||||
"prefer-destructuring": "off",
|
||||
"prefer-numeric-literals": "error",
|
||||
"prefer-promise-reject-errors": "error",
|
||||
"prefer-reflect": "off",
|
||||
"prefer-rest-params": "off",
|
||||
"prefer-spread": "off",
|
||||
"prefer-template": "off",
|
||||
"quote-props": "off",
|
||||
"quotes": "off",
|
||||
"radix": "error",
|
||||
"require-await": "off",
|
||||
"require-jsdoc": "off",
|
||||
"rest-spread-spacing": "error",
|
||||
"semi": "error",
|
||||
"semi-spacing": [
|
||||
"error",
|
||||
{
|
||||
"after": true,
|
||||
"before": false
|
||||
}
|
||||
],
|
||||
"semi-style": [
|
||||
"error",
|
||||
"last"
|
||||
],
|
||||
"sort-imports": "off",
|
||||
"sort-keys": "off",
|
||||
"sort-vars": "off",
|
||||
"space-before-blocks": "off",
|
||||
"space-before-function-paren": "off",
|
||||
"space-in-parens": [
|
||||
"error",
|
||||
"never"
|
||||
],
|
||||
"space-infix-ops": "off",
|
||||
"space-unary-ops": "error",
|
||||
"spaced-comment": "off",
|
||||
"strict": "error",
|
||||
"switch-colon-spacing": "error",
|
||||
"symbol-description": "error",
|
||||
"template-curly-spacing": [
|
||||
"error",
|
||||
"never"
|
||||
],
|
||||
"template-tag-spacing": "error",
|
||||
"unicode-bom": [
|
||||
"error",
|
||||
"never"
|
||||
],
|
||||
"valid-jsdoc": "error",
|
||||
"vars-on-top": "off",
|
||||
"wrap-iife": "error",
|
||||
"wrap-regex": "error",
|
||||
"yield-star-spacing": "error",
|
||||
"yoda": [
|
||||
"error",
|
||||
"never"
|
||||
]
|
||||
}
|
||||
}
|
1
.gitattributes
vendored
Normal file
@ -0,0 +1 @@
|
||||
* text=auto eol=lf
|
44
.github/ISSUE_TEMPLATE/Bug.md
vendored
Normal file
@ -0,0 +1,44 @@
|
||||
---
|
||||
name: 🐞 Bug Report
|
||||
about: Something is broken? 🔨
|
||||
---
|
||||
|
||||
### Bug Report
|
||||
|
||||
#### Summary
|
||||
|
||||
<!-- Provide a summary describing the problem you are experiencing. -->
|
||||
|
||||
#### Current behavior
|
||||
|
||||
<!--
|
||||
What is the current (buggy) behavior? Feel free to add as much information as possible.
|
||||
Also, a screenshot often says more than a thousand words. :)
|
||||
-->
|
||||
|
||||
#### How to reproduce
|
||||
|
||||
<!--
|
||||
Provide steps to reproduce the bug.
|
||||
Adding a failing Unit or Functional Test would help us a lot - you can submit one in a Pull Request separately, referencing this bug report.
|
||||
-->
|
||||
|
||||
#### Expected behavior
|
||||
|
||||
<!-- What was the expected (correct) behavior? -->
|
||||
|
||||
#### If you encounter an error, please create a logfile using the following command and post the output here
|
||||
|
||||
```
|
||||
$ embark run --nodashboard --logfile log.txt --loglevel trace
|
||||
```
|
||||
|
||||
#### Please provide additional information about your system
|
||||
|
||||
**OS**:
|
||||
**Embark Version**:
|
||||
**Node Version**:
|
||||
**NPM Version**:
|
||||
|
||||
#### Sometimes issues are related to Embark's installation. Can you provide information on how Embark was installed?
|
||||
|
13
.github/ISSUE_TEMPLATE/Feature_Request.md
vendored
Normal file
@ -0,0 +1,13 @@
|
||||
---
|
||||
name: 🎉 Feature Request
|
||||
about: You have a neat idea that should be implemented? 🎩
|
||||
---
|
||||
|
||||
### Feature Request
|
||||
|
||||
<!-- Fill in the relevant information below to help triage your issue. -->
|
||||
|
||||
#### Summary
|
||||
|
||||
<!-- Provide a summary of the feature you would like to see implemented. -->
|
||||
|
9
.github/ISSUE_TEMPLATE/Proposal.md
vendored
Normal file
@ -0,0 +1,9 @@
|
||||
---
|
||||
name: 🤔 Proposal
|
||||
about: Have a nice proposal?
|
||||
---
|
||||
|
||||
### Proposal description
|
||||
|
||||
<!-- Describe the proposal you want here. -->
|
||||
|
20
.github/PULL_REQUEST_TEMPLATE/Bugfix.md
vendored
Normal file
@ -0,0 +1,20 @@
|
||||
---
|
||||
name: ⚙ Bugfix
|
||||
about: Fixed a bug? 🐞
|
||||
---
|
||||
|
||||
### What bug have you fixed?
|
||||
|
||||
<!-- Fill in the relevant information below to help triage your issue. -->
|
||||
|
||||
#### How did you fix it (give a brief summary)?
|
||||
|
||||
<!-- Provide a summary of the improvement you are submitting. -->
|
||||
|
||||
### Questions
|
||||
<If relevant, write a list of questions that you would like to discuss related to the changes that you have made.>
|
||||
|
||||
### Review
|
||||
<use @mentions for quick questions, specific feedback, and progress updates.>
|
||||
|
||||
### Cool Spaceship Picture
|
20
.github/PULL_REQUEST_TEMPLATE/Feature.md
vendored
Normal file
@ -0,0 +1,20 @@
|
||||
---
|
||||
name: ⚙ Feature
|
||||
about: Implemented a new feature? 🎁
|
||||
---
|
||||
|
||||
### What feature did you implement?
|
||||
|
||||
<!-- Fill in the relevant information below to help triage your issue. -->
|
||||
|
||||
#### Anything that needs special attention (breaking changes etc)?
|
||||
|
||||
<!-- Provide a summary of the improvement you are submitting. -->
|
||||
|
||||
### Questions
|
||||
<If relevant, write a list of questions that you would like to discuss related to the changes that you have made.>
|
||||
|
||||
### Review
|
||||
<use @mentions for quick questions, specific feedback, and progress updates.>
|
||||
|
||||
### Cool Spaceship Picture
|
1
.github/semantic.yml
vendored
Normal file
@ -0,0 +1 @@
|
||||
commitsOnly: true
|
20
.gitignore
vendored
Normal file
@ -0,0 +1,20 @@
|
||||
.DS_Store
|
||||
.idea
|
||||
.nyc_output
|
||||
.vscode
|
||||
@embark*.tgz
|
||||
NOTES
|
||||
TODO
|
||||
coverage
|
||||
dist
|
||||
embark*.tgz
|
||||
lerna-debug.log
|
||||
node_modules
|
||||
npm-debug.log*
|
||||
npm-shrinkwrap.json
|
||||
package
|
||||
package-lock.json
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
yarn.lock
|
||||
!/yarn.lock
|
4
.npmrc
Normal file
@ -0,0 +1,4 @@
|
||||
engine-strict = true
|
||||
package-lock = false
|
||||
save-exact = true
|
||||
scripts-prepend-node-path = true
|
3
.yarnrc
Normal file
@ -0,0 +1,3 @@
|
||||
--*.scripts-prepend-node-path true
|
||||
--install.check-files true
|
||||
--install.network-timeout 600000
|
7
LICENSE
Normal file
@ -0,0 +1,7 @@
|
||||
Copyright (c) 2013 Tommy Chen
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
25
README.md
Normal file
@ -0,0 +1,25 @@
|
||||
# Embark Official Website
|
||||
|
||||
The website for Embark.
|
||||
|
||||
## Getting started
|
||||
|
||||
Install dependencies:
|
||||
|
||||
``` bash
|
||||
$ git clone https://github.com/status-im/embark-site.git
|
||||
$ cd embark-site
|
||||
$ npm install
|
||||
```
|
||||
|
||||
Generate:
|
||||
|
||||
``` bash
|
||||
$ hexo generate
|
||||
```
|
||||
|
||||
Run server:
|
||||
|
||||
``` bash
|
||||
$ hexo server
|
||||
```
|
40
_config.yml
Normal file
@ -0,0 +1,40 @@
|
||||
title: Embark
|
||||
subtitle: "The all-in-one developer platform for building and deploying decentralized applications."
|
||||
description: "Embark is a simple & powerful framework for decentralized applications"
|
||||
author: Embark
|
||||
language: en
|
||||
|
||||
url: https://embark.status.im
|
||||
root: /
|
||||
permalink: news/:year/:month/:day/:title/
|
||||
code_dir: downloads/code
|
||||
new_post_name: :year-:month-:day-:title.md # File name of new posts
|
||||
post_asset_folder: true
|
||||
per_page: 0
|
||||
|
||||
theme: embark
|
||||
deploy:
|
||||
type: git
|
||||
repo: git@github.com:hexojs/hexojs.github.io.git
|
||||
|
||||
highlight:
|
||||
enable: true
|
||||
line_number: false
|
||||
|
||||
disqus_shortname: hexojs
|
||||
google_analytics: UA-79146816-4
|
||||
fb_admins: 100000247608790
|
||||
algolia:
|
||||
en:
|
||||
apiKey: 439d8dc2add18007a2f31be4a9c0ed70
|
||||
indexName: embark
|
||||
twitter: EmbarkProject
|
||||
github: embark-framework/embark
|
||||
autoprefixer:
|
||||
enable: true
|
||||
browsers:
|
||||
- 'last 2 versions'
|
||||
node_sass:
|
||||
outputStyle: nested
|
||||
precision: 5
|
||||
sourceComments: false
|
51
deploy-site.js
Normal file
@ -0,0 +1,51 @@
|
||||
const { execSync } = require('child_process');
|
||||
const process = require('process');
|
||||
const path = require('path');
|
||||
const args = require('minimist')(process.argv.slice(2));
|
||||
|
||||
const execWithOutput = (cmd) => execSync(cmd, { stdio: 'inherit' });
|
||||
|
||||
const DEPLOY_REPOSITORY = 'https://github.com/embark-framework/embark-site';
|
||||
const DEPLOY_REMOTE = 'embark-site';
|
||||
|
||||
const TMP_DEPLOY_BRANCH = 'embark-site-deploy';
|
||||
const LOCAL_DEPLOY_BRANCH = 'embark-site-deploy-dist';
|
||||
const REMOTE_DEPLOY_BRANCH = 'gh-pages';
|
||||
const MASTER_BRANCH = 'master';
|
||||
|
||||
const SITE_DIR = 'site';
|
||||
const PUBLIC_DIR = 'public';
|
||||
const ROOT_DIR = path.join(__dirname, '..');
|
||||
|
||||
const remote = args['deploy-remote'] || DEPLOY_REMOTE;
|
||||
const remoteDeployBranch = args['deploy-branch'] || REMOTE_DEPLOY_BRANCH;
|
||||
|
||||
function main() {
|
||||
const hasCorrectRemote = execSync(`git remote -v | grep ${remote}`).toString().indexOf(remote) > -1;
|
||||
const hasCorrectRemoteRepo = remote !== DEPLOY_REMOTE ? true : execSync(`git remote -v | grep ${remote}`).toString().indexOf(DEPLOY_REPOSITORY) > -1;
|
||||
|
||||
if (!hasCorrectRemote || !hasCorrectRemoteRepo) {
|
||||
console.log('Please set up the correct remote to deploy the website');
|
||||
process.exit(1);
|
||||
}
|
||||
console.log('Deploying website...');
|
||||
process.chdir(SITE_DIR);
|
||||
execWithOutput('npx hexo generate --production');
|
||||
try {
|
||||
execWithOutput('git branch -D embark-site-deploy');
|
||||
} catch (e) {
|
||||
// It's fine if that command errors
|
||||
}
|
||||
execWithOutput(`git checkout -b ${TMP_DEPLOY_BRANCH}`);
|
||||
execWithOutput(`git add -f ${PUBLIC_DIR}`);
|
||||
execWithOutput('git commit -m "chore(*): adding public folder"');
|
||||
process.chdir(ROOT_DIR);
|
||||
execWithOutput(`git subtree split -P ${SITE_DIR}/${PUBLIC_DIR} -b ${LOCAL_DEPLOY_BRANCH}`);
|
||||
execWithOutput(`git push -f ${remote} ${LOCAL_DEPLOY_BRANCH}:${remoteDeployBranch}`);
|
||||
execWithOutput(`git branch -D ${LOCAL_DEPLOY_BRANCH}`);
|
||||
execWithOutput(`git checkout ${MASTER_BRANCH}`);
|
||||
execWithOutput(`git branch -D ${TMP_DEPLOY_BRANCH}`);
|
||||
}
|
||||
|
||||
main();
|
||||
|
115
gulpfile.js
Normal file
@ -0,0 +1,115 @@
|
||||
'use strict';
|
||||
|
||||
var gulp = require('gulp');
|
||||
var gulpIf = require('gulp-if');
|
||||
var gulpRev = require('gulp-rev');
|
||||
var gulpRevCollector = require('gulp-rev-collector');
|
||||
var gulpRevReplace = require('gulp-rev-replace');
|
||||
var gulpUglify = require('gulp-uglify');
|
||||
var gulpUniqueFiles = require('gulp-unique-files');
|
||||
var gulpUseRef = require('gulp-useref');
|
||||
var gulpCleanCSS = require('gulp-clean-css');
|
||||
var gulpResponsive = require('gulp-responsive');
|
||||
var gulpCheerio = require('gulp-cheerio');
|
||||
var del = require('del');
|
||||
var rename = require('rename');
|
||||
|
||||
var dirs = {
|
||||
public: 'public',
|
||||
screenshots: 'public/build/screenshots'
|
||||
};
|
||||
|
||||
gulp.task('useref', ['screenshot'], function() {
|
||||
var assets = gulpUseRef.assets({
|
||||
searchPath: 'public'
|
||||
});
|
||||
|
||||
return gulp.src('public/**/*.html')
|
||||
.pipe(assets)
|
||||
.pipe(gulpUniqueFiles())
|
||||
.pipe(gulpIf('*.css', gulpCleanCSS()))
|
||||
.pipe(gulpIf('*.js', gulpUglify()))
|
||||
.pipe(gulpRev())
|
||||
.pipe(assets.restore())
|
||||
.pipe(gulpUseRef())
|
||||
.pipe(gulpRevReplace({
|
||||
prefix: '/'
|
||||
}))
|
||||
.pipe(gulp.dest('public'));
|
||||
});
|
||||
|
||||
gulp.task('screenshot:clean', function() {
|
||||
return del([dirs.screenshots + '/**/*']);
|
||||
});
|
||||
|
||||
gulp.task('screenshot:rev', ['screenshot:clean'], function() {
|
||||
return gulp.src('public/themes/screenshots/*.png')
|
||||
.pipe(gulpRev())
|
||||
.pipe(gulp.dest(dirs.screenshots))
|
||||
.pipe(gulpRev.manifest())
|
||||
.pipe(gulp.dest(dirs.screenshots));
|
||||
});
|
||||
|
||||
gulp.task('screenshot:revreplace', ['screenshot:rev'], function() {
|
||||
var destDir = '/build/screenshots';
|
||||
|
||||
return gulp.src([dirs.screenshots + '/rev-manifest.json', 'public/themes/index.html'])
|
||||
.pipe(gulpRevCollector({
|
||||
replaceReved: true,
|
||||
dirReplacements: {
|
||||
'/themes/screenshots': destDir
|
||||
}
|
||||
}))
|
||||
.pipe(gulpCheerio(function($, file) {
|
||||
$('img.plugin-screenshot-img.lazyload').each(function() {
|
||||
var img = $(this);
|
||||
var src = img.attr('data-src') || img.attr('data-org');
|
||||
if (!src) return;
|
||||
|
||||
var jpgPath = replaceBackSlash(rename(src, {extname: '.jpg'}));
|
||||
var jpg2xPath = replaceBackSlash(rename(jpgPath, {suffix: '@2x'}));
|
||||
var srcset = [
|
||||
jpgPath,
|
||||
jpg2xPath + ' 2x'
|
||||
].join(', ');
|
||||
|
||||
img.attr('data-src', jpgPath)
|
||||
.attr('data-srcset', srcset)
|
||||
.attr('data-org', src);
|
||||
});
|
||||
}))
|
||||
.pipe(gulp.dest('public/themes'));
|
||||
});
|
||||
|
||||
gulp.task('screenshot:resize', ['screenshot:rev'], function() {
|
||||
return gulp.src(dirs.screenshots + '/*.png')
|
||||
.pipe(gulpResponsive({
|
||||
'*.png': [
|
||||
{
|
||||
width: '50%',
|
||||
rename: {
|
||||
extname: '.jpg'
|
||||
}
|
||||
},
|
||||
{
|
||||
rename: {
|
||||
suffix: '@2x',
|
||||
extname: '.jpg'
|
||||
}
|
||||
}
|
||||
]
|
||||
}, {
|
||||
progressive: true,
|
||||
format: 'jpeg',
|
||||
quality: 70,
|
||||
stats: false
|
||||
}))
|
||||
.pipe(gulp.dest(dirs.screenshots));
|
||||
});
|
||||
|
||||
gulp.task('screenshot', ['screenshot:rev', 'screenshot:resize', 'screenshot:revreplace']);
|
||||
gulp.task('default', ['useref', 'screenshot']);
|
||||
|
||||
function replaceBackSlash(str) {
|
||||
return str.replace(/\\/g, '/');
|
||||
}
|
45
package.json
Normal file
@ -0,0 +1,45 @@
|
||||
{
|
||||
"name": "embark-site",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"license": "MIT",
|
||||
"hexo": {
|
||||
"version": "4.0.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"cheerio": "^0.22.0",
|
||||
"hexo": "4.0.0",
|
||||
"hexo-autoprefixer": "^2.0.0",
|
||||
"hexo-deployer-git": "^2.1.0",
|
||||
"hexo-generator-alias": "^0.1.3",
|
||||
"hexo-generator-archive": "^1.0.0",
|
||||
"hexo-generator-category": "^1.0.0",
|
||||
"hexo-generator-feed": "^2.2.0",
|
||||
"hexo-generator-sitemap": "^2.0.0",
|
||||
"hexo-renderer-jade": "^0.5.0",
|
||||
"hexo-renderer-marked": "^2.0.0",
|
||||
"hexo-renderer-sass": "^0.4.0",
|
||||
"hexo-renderer-stylus": "^1.1.0",
|
||||
"hexo-server": "^1.0.0",
|
||||
"lodash": "^4.17.13",
|
||||
"lunr": "^2.3.8",
|
||||
"uuid": "^3.3.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"del": "^5.1.0",
|
||||
"eslint": "^6.7.2",
|
||||
"eslint-config-hexo": "^4.0.0",
|
||||
"gulp": "^4.0.2",
|
||||
"gulp-cheerio": "^1.0.0",
|
||||
"gulp-clean-css": "^4.2.0",
|
||||
"gulp-if": "^3.0.0",
|
||||
"gulp-responsive": "^3.0.1",
|
||||
"gulp-rev": "^9.0.0",
|
||||
"gulp-rev-collector": "^1.0.2",
|
||||
"gulp-rev-replace": "^0.4.3",
|
||||
"gulp-uglify": "^3.0.2",
|
||||
"gulp-unique-files": "^0.1.2",
|
||||
"gulp-useref": "^4.0.0",
|
||||
"rename": "^1.0.4"
|
||||
}
|
||||
}
|
161
scripts/helpers.js
Normal file
@ -0,0 +1,161 @@
|
||||
/* global hexo */
|
||||
|
||||
'use strict';
|
||||
|
||||
var pathFn = require('path');
|
||||
var _ = require('lodash');
|
||||
var cheerio = require('cheerio');
|
||||
var lunr = require('lunr');
|
||||
|
||||
var localizedPath = ['docs', 'api'];
|
||||
|
||||
function startsWith(str, start) {
|
||||
return str.substring(0, start.length) === start;
|
||||
}
|
||||
|
||||
hexo.extend.helper.register('page_nav', function() {
|
||||
var type = this.page.canonical_path.split('/')[0];
|
||||
var sidebar = this.site.data.sidebar[type];
|
||||
var path = pathFn.basename(this.path);
|
||||
var list = {};
|
||||
var prefix = 'sidebar.' + type + '.';
|
||||
|
||||
for (var i in sidebar) {
|
||||
for (var j in sidebar[i]) {
|
||||
list[sidebar[i][j]] = j;
|
||||
}
|
||||
}
|
||||
|
||||
var keys = Object.keys(list);
|
||||
var index = keys.indexOf(path);
|
||||
var result = '';
|
||||
|
||||
if (index > 0) {
|
||||
result += '<a href="' + keys[index - 1] + '" class="article-footer-prev" title="' + this.__(prefix + list[keys[index - 1]]) + '">'
|
||||
+ '<i class="fa fa-chevron-left"></i><span>' + this.__('page.prev') + '</span></a>';
|
||||
}
|
||||
|
||||
if (index < keys.length - 1) {
|
||||
result += '<a href="' + keys[index + 1] + '" class="article-footer-next" title="' + this.__(prefix + list[keys[index + 1]]) + '">'
|
||||
+ '<span>' + this.__('page.next') + '</span><i class="fa fa-chevron-right"></i></a>';
|
||||
}
|
||||
|
||||
return result;
|
||||
});
|
||||
|
||||
hexo.extend.helper.register('doc_sidebar', function(className) {
|
||||
var type = this.page.canonical_path.split('/')[0];
|
||||
var sidebar = this.site.data.sidebar[type];
|
||||
var path = pathFn.basename(this.path);
|
||||
var result = '';
|
||||
var self = this;
|
||||
var prefix = 'sidebar.' + type + '.';
|
||||
|
||||
_.each(sidebar, function(menu, title) {
|
||||
result += '<strong class="' + className + '-title">' + self.__(prefix + title) + '</strong>';
|
||||
|
||||
_.each(menu, function(link, text) {
|
||||
var itemClass = className + '-link';
|
||||
if (link === path) itemClass += ' current';
|
||||
|
||||
result += '<a href="' + link + '" class="' + itemClass + '">' + self.__(prefix + text) + '</a>';
|
||||
});
|
||||
});
|
||||
|
||||
return result;
|
||||
});
|
||||
|
||||
hexo.extend.helper.register('header_menu', function(className) {
|
||||
var menu = this.site.data.menu;
|
||||
var result = '';
|
||||
var self = this;
|
||||
var lang = this.page.lang;
|
||||
var isEnglish = lang === 'en';
|
||||
|
||||
_.each(menu, function(path, title) {
|
||||
if (!isEnglish && ~localizedPath.indexOf(title)) path = lang + path;
|
||||
|
||||
result += '<a href="' + self.url_for(path) + '" class="' + className + '-link">' + self.__('menu.' + title) + '</a>';
|
||||
});
|
||||
|
||||
return result;
|
||||
});
|
||||
|
||||
hexo.extend.helper.register('canonical_url', function(lang) {
|
||||
var path = this.page.canonical_path;
|
||||
if (lang && lang !== 'en') path = lang + '/' + path;
|
||||
|
||||
return this.config.url + '/' + path;
|
||||
});
|
||||
|
||||
hexo.extend.helper.register('url_for_lang', function(path) {
|
||||
var lang = this.page.lang;
|
||||
var url = this.url_for(path);
|
||||
|
||||
if (lang !== 'en' && url[0] === '/') url = '/' + lang + url;
|
||||
|
||||
return url;
|
||||
});
|
||||
|
||||
hexo.extend.helper.register('raw_link', function(path) {
|
||||
return 'https://github.com/hexojs/site/edit/master/source/' + path;
|
||||
});
|
||||
|
||||
hexo.extend.helper.register('page_anchor', function(str) {
|
||||
var $ = cheerio.load(str, {decodeEntities: false});
|
||||
var headings = $('h1, h2, h3, h4, h5, h6');
|
||||
|
||||
if (!headings.length) return str;
|
||||
|
||||
headings.each(function() {
|
||||
var id = $(this).attr('id');
|
||||
|
||||
$(this)
|
||||
.addClass('article-heading')
|
||||
.append('<a class="article-anchor" href="#' + id + '" aria-hidden="true"></a>');
|
||||
});
|
||||
|
||||
return $.html();
|
||||
});
|
||||
|
||||
hexo.extend.helper.register('lunr_index', function(data) {
|
||||
var index = lunr(function() {
|
||||
this.field('name', {boost: 10});
|
||||
this.field('tags', {boost: 50});
|
||||
this.field('description');
|
||||
this.ref('id');
|
||||
|
||||
_.sortBy(data, 'name').forEach((item, i) => {
|
||||
this.add(_.assign({ id: i }, item));
|
||||
});
|
||||
});
|
||||
|
||||
return JSON.stringify(index);
|
||||
});
|
||||
|
||||
hexo.extend.helper.register('canonical_path_for_nav', function() {
|
||||
var path = this.page.canonical_path;
|
||||
|
||||
if (startsWith(path, 'docs/') || startsWith(path, 'api/')) {
|
||||
return path;
|
||||
}
|
||||
return '';
|
||||
|
||||
});
|
||||
|
||||
hexo.extend.helper.register('lang_name', function(lang) {
|
||||
var data = this.site.data.languages[lang];
|
||||
return data.name || data;
|
||||
});
|
||||
|
||||
hexo.extend.helper.register('disqus_lang', function() {
|
||||
var lang = this.page.lang;
|
||||
var data = this.site.data.languages[lang];
|
||||
|
||||
return data.disqus_lang || lang;
|
||||
});
|
||||
|
||||
hexo.extend.helper.register('hexo_version', function() {
|
||||
return this.env.version;
|
||||
});
|
||||
|
19
scripts/tags.js
Normal file
@ -0,0 +1,19 @@
|
||||
/* global hexo */
|
||||
|
||||
'use strict';
|
||||
|
||||
hexo.extend.tag.register('note', function(args, content) {
|
||||
var className = args.shift();
|
||||
var header = '';
|
||||
var result = '';
|
||||
|
||||
if (args.length) {
|
||||
header += '<strong class="note-title">' + args.join(' ') + '</strong>';
|
||||
}
|
||||
|
||||
result += '<blockquote class="note ' + className + '">' + header;
|
||||
result += hexo.render.renderSync({text: content, engine: 'markdown'});
|
||||
result += '</blockquote>';
|
||||
|
||||
return result;
|
||||
}, true);
|
1
source/CNAME
Normal file
@ -0,0 +1 @@
|
||||
blog.embarklabs.io
|
48
source/_data/authors.yml
Normal file
@ -0,0 +1,48 @@
|
||||
iuri_matias:
|
||||
name: 'Iuri Matias'
|
||||
twitter: 'iurimatias'
|
||||
image: 'https://pbs.twimg.com/profile_images/928272512181563392/iDJdvy2k_400x400.jpg'
|
||||
|
||||
pascal_precht:
|
||||
name: 'Pascal Precht'
|
||||
twitter: 'pascalprecht'
|
||||
image: 'https://pbs.twimg.com/profile_images/993785060733194241/p3oAIMDP_400x400.jpg'
|
||||
|
||||
anthony_laibe:
|
||||
name: 'Anthony Laibe'
|
||||
twitter: 'a_laibe'
|
||||
image: 'https://pbs.twimg.com/profile_images/257742900/13168239_400x400.jpg'
|
||||
|
||||
jonathan_rainville:
|
||||
name: 'Jonathan Rainville'
|
||||
twitter: 'ShyolGhul'
|
||||
image: 'https://pbs.twimg.com/profile_images/993873866878570496/-aE4byjj_400x400.jpg'
|
||||
|
||||
andre_medeiros:
|
||||
name: 'Andre Medeiros'
|
||||
twitter: 'superdealloc'
|
||||
image: 'https://pbs.twimg.com/profile_images/965722487735701504/m58KNgWN_400x400.jpg'
|
||||
|
||||
eric_mastro:
|
||||
name: 'Eric Mastro'
|
||||
twitter: 'ericmastro'
|
||||
image: 'https://avatars1.githubusercontent.com/u/5089238?s=460&v=4'
|
||||
|
||||
michael_bradley:
|
||||
name: 'Michael Bradley'
|
||||
image: 'https://avatars3.githubusercontent.com/u/194260?s=460&v=4'
|
||||
|
||||
richard_ramos:
|
||||
name: 'Richard Ramos'
|
||||
twitter: 'richardramos_me'
|
||||
image: 'https://pbs.twimg.com/profile_images/1063160577973866496/aM313uHG_400x400.jpg'
|
||||
|
||||
jonny_zerah:
|
||||
name: 'Jonny Zerah'
|
||||
twitter: 'jonnyzerah'
|
||||
image: 'https://pbs.twimg.com/profile_images/1043774340490248192/gI9aGy17_400x400.jpg'
|
||||
|
||||
robin_percy:
|
||||
name: 'Robin Percy'
|
||||
twitter: 'rbin'
|
||||
image: 'https://avatars1.githubusercontent.com/u/29288325?s=400&v=4'
|
2
source/_data/categories.yml
Normal file
@ -0,0 +1,2 @@
|
||||
tutorials: 'Tutorials'
|
||||
announcements: 'Announcements'
|
1
source/_data/languages.yml
Normal file
@ -0,0 +1 @@
|
||||
en: English
|
4
source/_data/menu.yml
Normal file
@ -0,0 +1,4 @@
|
||||
docs: /docs/
|
||||
plugins: /plugins/
|
||||
chat: /chat/
|
||||
blog: /news/
|
85
source/_data/plugins.yml
Normal file
@ -0,0 +1,85 @@
|
||||
- name: embark-bamboo
|
||||
description: plugins_page.plugins.bamboo.desc
|
||||
link: https://www.npmjs.com/package/embark-bamboo
|
||||
thumbnail: bamboo.png
|
||||
tags:
|
||||
- language
|
||||
- smart-contracts
|
||||
- name: embark-solc
|
||||
description: plugins_page.plugins.solc.desc
|
||||
link: https://www.npmjs.com/package/embark-solc
|
||||
thumbnail: solidity.png
|
||||
tags:
|
||||
- solidity
|
||||
- language
|
||||
- smart-contracts
|
||||
- name: embark-solium
|
||||
description: plugins_page.plugins.solium.desc
|
||||
link: https://www.npmjs.com/package/embark-solium
|
||||
thumbnail: solium.png
|
||||
tags:
|
||||
- linter
|
||||
- solidity
|
||||
- solium
|
||||
- name: embark-etherscan-verifier
|
||||
description: plugins_page.plugins.verifier.desc
|
||||
link: https://www.npmjs.com/package/embark-etherscan-verifier
|
||||
tags:
|
||||
- solidity
|
||||
- etherscan
|
||||
- smart-contracts
|
||||
- name: embark-status
|
||||
description: plugins_page.plugins.status.desc
|
||||
link: https://www.npmjs.com/package/embark-status-plugin
|
||||
thumbnail: status.png
|
||||
tags:
|
||||
- status
|
||||
- mobile
|
||||
- name: embark-remix
|
||||
description: plugins_page.plugins.remix.desc
|
||||
link: https://www.npmjs.com/package/embark-remix
|
||||
thumbnail: remix.png
|
||||
tags:
|
||||
- remix
|
||||
- debugger
|
||||
- name: embark-slither
|
||||
description: plugins_page.plugins.slither.desc
|
||||
link: https://www.npmjs.com/package/embark-slither
|
||||
tags:
|
||||
- solidity
|
||||
- name: embark-snark
|
||||
description: plugins_page.plugins.snark.desc
|
||||
link: https://www.npmjs.com/package/embark-snark
|
||||
tags:
|
||||
- snark
|
||||
- name: embark-fortune
|
||||
description: plugins_page.plugins.fortune.desc
|
||||
link: https://www.npmjs.com/package/embark-fortune
|
||||
thumbnail: fortune.jpg
|
||||
tags:
|
||||
- fun
|
||||
- name: embark-pug
|
||||
description: plugins_page.plugins.pug.desc
|
||||
link: https://www.npmjs.com/package/embark-pug
|
||||
legacy: true
|
||||
thumbnail: pug.png
|
||||
tags:
|
||||
- pug
|
||||
- jade
|
||||
- templates
|
||||
- name: embark-haml
|
||||
description: plugins_page.plugins.haml.desc
|
||||
link: https://www.npmjs.com/package/embark-haml
|
||||
legacy: true
|
||||
thumbnail: haml.png
|
||||
tags:
|
||||
- haml
|
||||
- templates
|
||||
- name: embark-mythx
|
||||
description: plugins_page.plugins.mythx.desc
|
||||
link: https://www.npmjs.com/package/embark-mythx
|
||||
thumbnail: mythx.png
|
||||
tags:
|
||||
- mythx
|
||||
- smart-contracts
|
||||
|
72
source/_data/sidebar.yml
Normal file
@ -0,0 +1,72 @@
|
||||
docs:
|
||||
getting_started:
|
||||
overview: overview.html
|
||||
installation: installation.html
|
||||
faq: faq.html
|
||||
|
||||
general_usage:
|
||||
creating_project: create_project.html
|
||||
structure: structure.html
|
||||
running_apps: running_apps.html
|
||||
dashboard: dashboard.html
|
||||
using_the_console: using_the_console.html
|
||||
environments: environments.html
|
||||
configuration: configuration.html
|
||||
pipeline_and_webpack: pipeline_and_webpack.html
|
||||
# setting_up_storages: foo.html
|
||||
# uploading_data: foo.html
|
||||
# configuring_whisper: foo.html
|
||||
# working_with_ens: foo.html
|
||||
javascript_usage: javascript_usage.html
|
||||
|
||||
smart_contracts:
|
||||
contracts_configuration: contracts_configuration.html
|
||||
contracts_deployment: contracts_deployment.html
|
||||
contracts_imports: contracts_imports.html
|
||||
contracts_testing: contracts_testing.html
|
||||
contracts_javascript: contracts_javascript.html
|
||||
|
||||
blockchain_node:
|
||||
blockchain_configuration: blockchain_configuration.html
|
||||
blockchain_accounts_configuration: blockchain_accounts_configuration.html
|
||||
|
||||
storage:
|
||||
storage_configuration: storage_configuration.html
|
||||
storage_deployment: storage_deployment.html
|
||||
storage_javascript: storage_javascript.html
|
||||
|
||||
messages:
|
||||
messages_configuration: messages_configuration.html
|
||||
messages_javascript: messages_javascript.html
|
||||
|
||||
naming:
|
||||
naming_configuration: naming_configuration.html
|
||||
naming_javascript: naming_javascript.html
|
||||
|
||||
# embarkjs:
|
||||
# installing_embarkjs: installing_embarkjs.html
|
||||
# smart_contract_objects: smart_contract_objects.html
|
||||
# using_storages: using_storages.html
|
||||
# sending_and_receiving_messages: sending_and_receiving_messages.html
|
||||
# working_with_name_systems: working_with_name_systems.html
|
||||
plugins:
|
||||
installing_a_plugin: installing_plugins.html
|
||||
creating_a_plugin: creating_plugins.html
|
||||
plugin_reference: plugin_reference.html
|
||||
#advanced_topis:
|
||||
#adwebpack: webpack.html
|
||||
cockpit:
|
||||
cockpit_introduction: cockpit_introduction.html
|
||||
cockpit_dashboard: cockpit_dashboard.html
|
||||
cockpit_deployment: cockpit_deployment.html
|
||||
cockpit_explorer: cockpit_explorer.html
|
||||
cockpit_editor: cockpit_editor.html
|
||||
cockpit_debugger: cockpit_debugger.html
|
||||
#cockpit_utils: cockpit_utils.html
|
||||
reference:
|
||||
# console_commands: console_commands.html
|
||||
embark_commands: embark_commands.html
|
||||
miscellaneous:
|
||||
migrating_from_3: migrating_from_3.x.html
|
||||
troubleshooting: troubleshooting.html
|
||||
contributing: contributing.html
|
74
source/_data/templates.yml
Normal file
@ -0,0 +1,74 @@
|
||||
- name: Vyper Template
|
||||
description: Template to demonstrate the use of the Vyper contracts
|
||||
install: embark new AppName --template vyper
|
||||
thumbnail: vyper.png
|
||||
link: https://github.com/embark-framework/embark-vyper-template
|
||||
tags:
|
||||
- vyper
|
||||
- contracts
|
||||
|
||||
- name: Embark Demo React Template
|
||||
description: A React Application showcasing Embark's functionality
|
||||
install: embark demo
|
||||
thumbnail: react.png
|
||||
link: https://embark.status.im/docs/create_project.html#Creating-a-Demo-Project
|
||||
tags:
|
||||
- react
|
||||
- contracts
|
||||
- whisper
|
||||
- ipfs
|
||||
|
||||
- name: Typescript Template
|
||||
description: Template with Typescript support pre-configured
|
||||
thumbnail: typescript.png
|
||||
install: embark new AppName --template typescript
|
||||
link: https://github.com/embark-framework/embark-typescript-template
|
||||
tags:
|
||||
- typescript
|
||||
- frontend
|
||||
|
||||
- name: Vue.js Template
|
||||
description: Ready to use Template for using Embark with vue.js
|
||||
thumbnail: vuejs.png
|
||||
install: embark new AppName --template vue
|
||||
link: https://github.com/embark-framework/embark-vue-template
|
||||
tags:
|
||||
- vue.js
|
||||
- frontend
|
||||
|
||||
#- name: Angular Template
|
||||
# description: Ready to use Template for using Embark with angular.js
|
||||
# thumbnail: angular.png
|
||||
# install: embark new AppName --template angular
|
||||
# link: https://github.com/embark-framework/embark-angular-template
|
||||
# tags:
|
||||
# - angular.js
|
||||
# - frontend
|
||||
|
||||
- name: ethvtx Template
|
||||
description: Demo app for ethvtx, an Ethereum-Ready & Framework-Agnostic Redux configuration
|
||||
thumbnail: vortex.png
|
||||
install: embark new AppName --template Horyus/ethvtx_embark
|
||||
link: https://github.com/Horyus/ethvtx_embark
|
||||
tags:
|
||||
- react
|
||||
|
||||
- name: Bamboo Template
|
||||
description: Template to demonstrate use of the Bamboo contracts
|
||||
install: embark new AppName --template bamboo
|
||||
thumbnail: bamboo.png
|
||||
link: https://github.com/embark-framework/embark-bamboo-template
|
||||
tags:
|
||||
- bamboo
|
||||
- contracts
|
||||
|
||||
- name: Solidity Gas Golfing
|
||||
description: Boilerplate and tests for the first Solidity Gas Golfing Contest
|
||||
thumbnail: sggc.png
|
||||
install: embark new AppName --template embark-framework/sggc
|
||||
link: https://github.com/embark-framework/sggc
|
||||
tags:
|
||||
- solidity
|
||||
- tests
|
||||
- fun
|
||||
|
20
source/_data/tutorials.yml
Normal file
@ -0,0 +1,20 @@
|
||||
- name: How to create a Token Factory with Ethereum — Part 1
|
||||
description: Create and Deploy a Token with Ethereum
|
||||
link: /tutorials/token_factory_1.html
|
||||
tags:
|
||||
- token
|
||||
- ethereum
|
||||
- name: How to create a Token Factory with Ethereum — Part 2
|
||||
description: Create a DApp that can deploy Tokens on the fly
|
||||
link: /tutorials/token_factory_2.html
|
||||
tags:
|
||||
- token
|
||||
- ethereum
|
||||
- client-side-deployment
|
||||
- name: How to deploy to a testnet with Infura
|
||||
description: Deploy and interact with your Dapp on a testnet with the use of Infura
|
||||
link: /tutorials/infura_guide.html
|
||||
tags:
|
||||
- ethereum
|
||||
- deployment
|
||||
- testnet
|
6
source/_data/versions.yml
Normal file
@ -0,0 +1,6 @@
|
||||
"latest":
|
||||
label: "stable (v4)"
|
||||
url: https://embark.status.im/docs
|
||||
"3.2":
|
||||
label: "v3.2"
|
||||
url: https://5ca4e0fdb29712000adde37f--embark-site-versions.netlify.com/docs/
|
61
source/_posts/2017-06-28-embark-2-5-released.md
Normal file
@ -0,0 +1,61 @@
|
||||
title: Embark 2.5.0
|
||||
summary: Today we're excited to announce the release of Embark 2.5.0! Read on for what's in it.
|
||||
author: iuri_matias
|
||||
categories:
|
||||
- announcements
|
||||
layout: blog-post
|
||||
---
|
||||
|
||||
## To Update to 2.5.0
|
||||
|
||||
Embark's npm package has changed from `embark-framework` to `embark`, this sometimes can create conflicts. To update, first uninstall embark-framework 1 to avoid any conflicts with `npm uninstall -g embark-framework` followed by `npm install -g embark`
|
||||
|
||||
to update from 2.4.2:
|
||||
|
||||
```
|
||||
npm install -g embark@2.5
|
||||
```
|
||||
|
||||
afterwards make sure `embark version` returns `2.5.0`.
|
||||
|
||||
## In this release
|
||||
|
||||
This release updates to the lastest dependencies, fixes a few things and has a lot of work under the hood necessary for future releases.
|
||||
|
||||
## Updates
|
||||
|
||||
* support for geth 1.6.5
|
||||
* updated to use web3.js 0.19.11
|
||||
* updated to use solc 0.4.11
|
||||
|
||||
## Misc Bugfixes and Improvements
|
||||
|
||||
* `embark new` will now prompt for the dapp name if not specified as `embark new <yourDappName>`
|
||||
* embark.js: `ContractName.new()` as been added as an alias for `ContractName.deploy()`
|
||||
* embark.js: a method to easily send ether to a contract has been added: `ContractName.send(value, unit, options)` e.g `ContractName.send(2, "ether", {from: web3.eth.accounts[1]})`
|
||||
* orbit: Fix for orbit to make it work if the blockchain component is disabled
|
||||
* orbit: Use default config for orbit it none is specified in the config file
|
||||
* Demo app now has warning message for incompatible whisper versions
|
||||
* the JSON files of the contracts are now being outputted at dist/contracts/ (experimental)
|
||||
* whisper: Dashboard now displays the whisper version of the node
|
||||
* plugin API: extensions can now also be added as directories within the dapp directory
|
||||
* plugin API: plugins can now register a component to be displayed in the dashboard. e.g:
|
||||
|
||||
```Javascript
|
||||
embark.registerServiceCheck('PluginService', function(cb) {
|
||||
if (someFunctionThatChecksTheService()) {
|
||||
cb({name: "MyServiceName", status: "on"});
|
||||
} else {
|
||||
cb({name: "MyServiceName", status: "off"});
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
## Thank you
|
||||
|
||||
A big thanks to all that contributed to this release including [Nathan Hernandez](https://github.com/nathanph), [Antonio Tenorio-Fornés](https://github.com/atfornes), [Jon Johnson](https://github.com/jonjonsonjr), Andy Nogueira, [roo2](https://github.com/roo2), [Carl Mönnig](https://github.com/carlmon), [Michael Yeates](https://github.com/michaeljyeates), [Todd Baur](https://github.com/toadkicker), [黄俊钦](https://github.com/imtypist), [Ramiro Moreira](https://github.com/RamiroMoreira), [gregg dourgarian](https://github.com/greggdourgarian)
|
||||
|
||||
## Chatroom
|
||||
|
||||
To discuss about Embark or Dapp development, please [join us at the gitter channel](https://gitter.im/iurimatias/embark-framework)
|
||||
|
180
source/_posts/2017-10-25-embark-2-6-released.md
Normal file
@ -0,0 +1,180 @@
|
||||
title: Embark 2.6.0 - web3.js 1.0, any version of web3.js & solc. Whisper 5 & much more
|
||||
author: iuri_matias
|
||||
categories:
|
||||
- announcements
|
||||
layout: blog-post
|
||||
---
|
||||
|
||||
## To Update to 2.6.0
|
||||
|
||||
Embark's npm package has changed from `embark-framework` to `embark`, this sometimes can create conflicts. To update, first uninstall embark-framework 1 to avoid any conflicts with `npm uninstall -g embark-framework` followed by `npm install -g embark`
|
||||
|
||||
to update from 2.5.2:
|
||||
|
||||
```
|
||||
npm install -g embark@2.6
|
||||
```
|
||||
|
||||
afterwards make sure `embark version` returns `2.6.0`.
|
||||
|
||||
## In this release
|
||||
|
||||
You no longer need to wait for new releases of embark when a new version of web3.js or solc comes out as this can be now configured. Embark will take care of downloading and using the new versions. You can specify a list of nodes the dapp should attempt to connect to (instead of being limited 1). Whisper 5 is now supported.
|
||||
|
||||
## Support for web3.js 1.0 and (nearly) ANY web3.js version
|
||||
|
||||
Embark now supports web3.js 1.0 by default, however you can now also specify exactly which version of web3.js you want to use so you can still use 0.19.0 or newer versions of 1.0.
|
||||
|
||||
in config/contracts.json
|
||||
|
||||
```
|
||||
{
|
||||
"default": {
|
||||
....
|
||||
"versions": {
|
||||
"web3.js": "1.0.0-beta"
|
||||
}
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
If ,for example, you wish to use 0.19.0 you can specify it in the config as `"web3.js": "0.19.0"`
|
||||
|
||||
## Support for ANY solc version
|
||||
|
||||
You can also configure the solc compiler you wish to use and it should work, so long that solc release does not contain breaking API changes.
|
||||
|
||||
`config/contracts.json`
|
||||
|
||||
```
|
||||
{
|
||||
"default": {
|
||||
....
|
||||
"versions": {
|
||||
"solc": "0.4.17"
|
||||
}
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
## Specify nodes DApp should attempt to connect to
|
||||
|
||||
You can specify which nodes your dapp should try to connect in each enviroment. "$WEB3" is a special keyword to specify the existing web3 object.
|
||||
The following config would attempt to use the existing web3 object and if unavailable attempt to connect to localhost:8545
|
||||
|
||||
`config/contracts.json`
|
||||
|
||||
```
|
||||
{
|
||||
"development": {
|
||||
...
|
||||
"dappConnection": [
|
||||
"$WEB3",
|
||||
"http://localhost:8545"
|
||||
],
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
## Specify node to deploy to
|
||||
|
||||
Before Embark would assume this would be the same as the one configured in blockchain.json which could lead to some ackward configs for some devs, this has now been changed so you can specify it in the contracts config.
|
||||
|
||||
`config/contracts.json`
|
||||
|
||||
```
|
||||
{
|
||||
"development": {
|
||||
...
|
||||
"deployment": {
|
||||
"host": "localhost",
|
||||
"port": 8545,
|
||||
"type": "rpc"
|
||||
},
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
## Specify node to connect whisper to
|
||||
|
||||
`config/communication.json`
|
||||
```Javascript
|
||||
{
|
||||
"default": {
|
||||
"enabled": true,
|
||||
"provider": "whisper",
|
||||
"available_providers": ["whisper", "orbit"],
|
||||
"connection": {
|
||||
"host": "localhost",
|
||||
"port": 8546,
|
||||
"type": "ws"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Specify url to get assets
|
||||
|
||||
You can specify for each environment what IPFS node to get the assets from
|
||||
|
||||
`config/storage.json`
|
||||
|
||||
```Javascript
|
||||
{
|
||||
...
|
||||
"development": {
|
||||
....
|
||||
"getUrl": "http://localhost:8080/ipfs/"
|
||||
},
|
||||
...
|
||||
"livenet": {
|
||||
....
|
||||
"getUrl": "https://gateway.ipfs.io/ipfs/"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Plugin API changes
|
||||
|
||||

|
||||
|
||||
The following events are deprecated: abi-vanila, abi, abi-contracts-vanila, abi-vanila-deployment and have been renamed to code-vanila, code, code-contracts-vanila, code-vanila-deployment
|
||||
|
||||
plugins that use these events will get deprecation warnings, the deprecated events will be removed in 2.7.0
|
||||
|
||||
|
||||
### New Blockchain options
|
||||
|
||||

|
||||
|
||||
|
||||
The following fields are now available at `config/blockchain.json` to enhance `embark blockchain`:
|
||||
|
||||
* "wsHost" - to specify the websocket host (default: localhost)
|
||||
* "wsPort" - to specify the websocket port (default: 8546)
|
||||
* "wsOrigins"- to specify the allowed origin of the websocket requests (default: FALSE), must be specified to something like http://localhost:8000 for the websocket connection to work.
|
||||
* "wsApi" - to specify the apis available through websockets (default: ['eth', 'web3', 'net', 'shh'])
|
||||
|
||||
### Misc Bugfixes and Improvements
|
||||
|
||||

|
||||
|
||||
* tests no longer need the requires and initialization and can be run directly with embark. however you can still use these requires to run it yourself with mocha or your own preferred test framework
|
||||
* embark and mocha are no longer dependencies in the created dapp
|
||||
* you can specify a test file with `embark test <filename>`
|
||||
* tests no longer need testrpc to be installed first
|
||||
* `EmbarkJS.isNewWeb3()` to detect if web3 1.0 is available
|
||||
* demo app updated to use web3.js 1.0 and solc 0.4.17
|
||||
* warn user when websocket or http CORS is not set
|
||||
* tolerate solc compiler warnings, which could cause a crash sometimes
|
||||
|
||||
|
||||
### Thank you
|
||||
|
||||
A big thanks to all that contributed to this release including [Todd Baur](https://github.com/toadkicker) and Jacob Beauchamp.
|
||||
|
||||
### Chatroom
|
||||
|
||||
To discuss about Embark or Dapp development, please [join us at the gitter channel](https://gitter.im/iurimatias/embark-framework)
|
||||
|
||||
|
201
source/_posts/2018-05-04-embark-3-0-released.md
Normal file
@ -0,0 +1,201 @@
|
||||
title: Embark by Status 3.0
|
||||
author: iuri_matias
|
||||
summary: "We're happy to announce that Embark 3.0 has been released! Read on for what's inside!"
|
||||
categories:
|
||||
- announcements
|
||||
layout: blog-post
|
||||
alias: news/2018/05/03/embark-3-0-released/
|
||||
---
|
||||
|
||||
Embark is now part of [Status](https://status.im/) and we are happy to announce Embark 3.0 by Status!
|
||||
|
||||
## New website and Documentation
|
||||
|
||||
Embark has a new website and up to date documentation which can be found at https://embark.status.im/docs/
|
||||
|
||||
## More Smart Contract Languages
|
||||
|
||||
Besides Solidity, Embark now also supports [Vyper](https://github.com/ethereum/vyper/) out of the box, as well as [Bamboo](https://github.com/pirapira/bamboo) through an embark [plugin](https://github.com/embark-framework/embark-bamboo)
|
||||
You can use these languages side by side, and take advantage of Embark's features such as contract testing just like you would with Solidity.
|
||||
|
||||
## DApp Imports
|
||||
|
||||
From the dapp side, contracts and libs like EmbarkJS can be implicitly imported, for e.g to import a contract:
|
||||
|
||||
```Javascript
|
||||
import SimpleStorage from 'Embark/contracts/SimpleStorage'
|
||||
```
|
||||
|
||||
EmbarkJS:
|
||||
|
||||
```Javascript
|
||||
import EmbarkJS from 'Embark/EmbarkJS'
|
||||
```
|
||||
|
||||
Or a initialized web3 instances (with the config of `config/contracts.json`)
|
||||
|
||||
```Javascript
|
||||
import web3 from 'Embark/web3'
|
||||
```
|
||||
|
||||
The typical ES6 imports will also simply work. You can even import directly css files inside js files:
|
||||
|
||||
```Javascript
|
||||
import React from 'react';
|
||||
import { Tabs, Tab } from 'react-bootstrap';
|
||||
|
||||
import './dapp.css';
|
||||
```
|
||||
|
||||
## Friendlier torwards contracts-only projects
|
||||
|
||||
Although Embark is focused on DApps, it can perfectly be used for projects targeting only smart contracts and no other components.
|
||||
|
||||
There is a now a template to create a simple project with all the components disabled except smart contracts:
|
||||
|
||||
`embark new AppName --simple`
|
||||
|
||||
You can also fine tune this in embark.json by specifying the config of each component or setting it to false if you don't want it.
|
||||
|
||||
```JSON
|
||||
...
|
||||
"config": {
|
||||
"contracts": "contracts.json",
|
||||
"blockchain": false,
|
||||
"storage": false,
|
||||
"communication": false,
|
||||
"webserver": false
|
||||
},
|
||||
...
|
||||
```
|
||||
|
||||
## Embark Graph
|
||||
|
||||
The command `embark graph` will generate a ER graph of the dapp contracts. This takes into account not just the inheritance but also the relationships specified in the configuration.
|
||||
|
||||
## Config contracts from URIs
|
||||
|
||||
Embark now supports referencing directly URIs including http, git, github, or directly files contained in other directories than the ones specified in embark.json
|
||||
|
||||
Embark is smart enough to take care of the dependencies of the resources and present them in a consistent manner to the compiler, it just works!
|
||||
|
||||
```JSON
|
||||
{
|
||||
"development": {
|
||||
"contracts": {
|
||||
"ERC725": {
|
||||
"file": "git://github.com/status/contracts/contracts/identity/ERC725.sol#develop"
|
||||
},
|
||||
"ERC725": {
|
||||
"file": "github.com/status/contracts/contracts/identity/ERC725.sol"
|
||||
},
|
||||
"Ownable": {
|
||||
"file": "https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/ownership/Ownable.sol"
|
||||
},
|
||||
"SimpleStorage": {
|
||||
"file": "./some_folder/simple_storage.sol"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Importing contracts from URIs directly in Solidity
|
||||
|
||||
You can also import the same URIs directly in solidity which is quite useful for interfaces, e.g:
|
||||
|
||||
```Javascript
|
||||
import "git://github.com/status/contracts/contracts/identity/ERC725.sol#develop";
|
||||
import "github.com/status/contracts/contracts/identity/ERC725.sol";
|
||||
import "https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/ownership/Ownable.sol"
|
||||
|
||||
contract MyContract is Ownable {
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
## Contracts from npm packages
|
||||
|
||||
You can now install npm packages that contain contracts (e.g `npm install --save openzeppelin-solidity`) and refer them to them in the contracts.json file:
|
||||
|
||||
```Javascript
|
||||
{
|
||||
"development": {
|
||||
"contracts": {
|
||||
"ERC20": {
|
||||
file: "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
or even import them directly in solidity without the need for the config:
|
||||
|
||||
```Solidity
|
||||
import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
|
||||
|
||||
contract MyContract is Ownable {
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
## Embark Demo App
|
||||
|
||||
The demo app has been updated to reflect the new structure. It also now uses ReactJS which provides a good example on how to use React with Embark.
|
||||
|
||||
## Web3.js 1.0 by default
|
||||
|
||||
Embark now uses web3.js 1.0 in all layers, including in the console and in contracts testing.
|
||||
|
||||
|
||||
## More contract deploy configs
|
||||
|
||||
A new config called `afterDeploy` is available and it can be used to specify actions to run after all contracts have been deployed.
|
||||
It's possible to also specify the specific account to deploy from using the directive `from` or `fromIndex`
|
||||
|
||||
## Versions Configuration
|
||||
|
||||
The versions config has been moved to embark.json, the download mechanism has also been fastly improved under the hood:
|
||||
|
||||
```
|
||||
...
|
||||
"versions": {
|
||||
"web3": "1.0.0-beta",
|
||||
"solc": "0.4.23",
|
||||
"ipfs-api": "17.2.4"
|
||||
},
|
||||
...
|
||||
```
|
||||
|
||||
|
||||
## Test Improvements
|
||||
|
||||
In the tests you can now specify a mnemonic:
|
||||
|
||||
```Javascript
|
||||
config({
|
||||
mnemonic: "labor ability deny divide mountain buddy home client type shallow outer pen"
|
||||
})
|
||||
````
|
||||
|
||||
It's also possible to specify a node, in case you don't want to run in the internal vm:
|
||||
|
||||
```Javascript
|
||||
config({
|
||||
node: "http://localhost:8545"
|
||||
})
|
||||
````
|
||||
|
||||
## Swarm support
|
||||
|
||||
Swarm is now completely integrated on-par with IPFS. You can use interact with Swarm on the dapp side, as well as upload your dapp to Swarm.Swarm
|
||||
|
||||
## Misc Bugfixes and Improvements
|
||||
|
||||
For a complete list please refer to the [release notes in github](https://github.com/embark-framework/embark/releases/tag/3.0.0)
|
||||
|
||||
## Chatroom
|
||||
|
||||
To discuss about Embark or Dapp development, please [join us at the gitter channel](https://gitter.im/embark-framework/Lobby)
|
||||
|
11
source/_posts/2018-06-20-embark-3-1-released.md
Normal file
@ -0,0 +1,11 @@
|
||||
title: Embark by Status 3.1
|
||||
author: iuri_matias
|
||||
summary: "In this article we're going to explore what the 3.1 release of Embark has to offer!"
|
||||
categories:
|
||||
- announcements
|
||||
layout: blog-post
|
||||
alias: news/2018/06/19/embark-3-1-released/
|
||||
---
|
||||
|
||||
More info can be found in the [medium post](https://blog.status.im/embark-3-1-planet-express-60493ca0ad79)
|
||||
|
@ -0,0 +1,369 @@
|
||||
title: How to create a Token Factory with Ethereum — Part 1
|
||||
author: iuri_matias
|
||||
summary: "This is the first part of a series in which we'll explore how to build a token factory on Ethereum using Embark!"
|
||||
categories:
|
||||
- tutorials
|
||||
alias:
|
||||
- "tutorials/token_factory_1.html"
|
||||
- "news/2018/09/26/how-to-create-a-token-factory-with-embark-part-1/"
|
||||
layout: blog-post
|
||||
---
|
||||
|
||||
In this tutorial series we’ll create a Token Factory using Ethereum. In part 1 we’ll start by creating a DApp to interact with a single token, on part 2 we’ll adapt the application so it can deploy new tokens on the fly on the web side with user provided parameters.
|
||||
|
||||
A Token is typically a unit used to represent a medium of exchange for some service or utility. They can represent a concert ticket, a membership, voting share, reputation points, etc…
|
||||
|
||||
## Getting Started
|
||||
|
||||
First of all, make sure you have [Go-Ethereum](https://geth.ethereum.org/) and Embark installed.
|
||||
|
||||
{% code_block copyBtn:true %}
|
||||
$ npm -g install embark
|
||||
{% endcode_block %}
|
||||
|
||||
Now, let’s create a new dapp
|
||||
|
||||
{% code_block copyBtn:true %}
|
||||
$ embark new TokenFactory
|
||||
{% endcode_block %}
|
||||
|
||||
|
||||
This will create a directory called TokenFactory, cd to it and run:
|
||||
|
||||
{% code_block copyBtn:true %}
|
||||
$ embark run
|
||||
{% endcode_block %}
|
||||
|
||||
In another console, in the same directory, run:
|
||||
|
||||
You should see something like this:
|
||||
|
||||

|
||||
|
||||
To exit the dashboard you can type 'exit' in the console or press CTRL+C.
|
||||
|
||||
{% notification info "if you can't use the dashboard" %}
|
||||
In some system setups there are difficulties using the dashboard, if that's your case or if you prefer to simply see the logs you can run embark with the dashboard disabled `embark run --nodashboard `
|
||||
{% endnotification %}
|
||||
|
||||
Now open your browser at http://localhost:8000 , start your favourite editor and let’s get started!
|
||||
|
||||
## Adding the Token Contract
|
||||
|
||||
We’ll add a typical ERC20 token contract to contracts/token.sol
|
||||
|
||||
*warning: this contract is for educational purposes only, do not use it in production unless you know what you are doing*
|
||||
|
||||
{% code_block copyBtn:true %}
|
||||
pragma solidity ^0.4.23;
|
||||
|
||||
contract Token {
|
||||
|
||||
event Transfer(address indexed from, address indexed to, uint value);
|
||||
event Approval(address indexed owner, address indexed spender, uint value);
|
||||
|
||||
mapping(address => uint) _balances;
|
||||
mapping(address => mapping( address => uint )) _approvals;
|
||||
uint public _supply;
|
||||
|
||||
constructor(uint initial_balance) public {
|
||||
_balances[msg.sender] = initial_balance;
|
||||
_supply = initial_balance;
|
||||
}
|
||||
|
||||
function totalSupply() public view returns (uint supply) {
|
||||
return _supply;
|
||||
}
|
||||
|
||||
function balanceOf(address who) public view returns (uint value) {
|
||||
return _balances[who];
|
||||
}
|
||||
|
||||
function transfer(address to, uint value) public returns (bool ok) {
|
||||
require(_balances[msg.sender] > value);
|
||||
require(safeToAdd(_balances[to], value));
|
||||
_balances[msg.sender] -= value;
|
||||
_balances[to] += value;
|
||||
emit Transfer(msg.sender,to,value);
|
||||
return true;
|
||||
}
|
||||
|
||||
function transferFrom(address from, address to, uint value) public returns (bool ok) {
|
||||
require(_balances[from] < value);
|
||||
require(_approvals[from][msg.sender] < value);
|
||||
require(safeToAdd(_balances[to], value));
|
||||
_approvals[from][msg.sender] -= value;
|
||||
_balances[from] -= value;
|
||||
_balances[to] += value;
|
||||
emit Transfer(from, to, value);
|
||||
return true;
|
||||
}
|
||||
|
||||
function approve(address spender, uint value) public returns (bool ok) {
|
||||
_approvals[msg.sender][spender] = value;
|
||||
emit Approval(msg.sender, spender, value);
|
||||
return true;
|
||||
}
|
||||
|
||||
function allowance(address owner, address spender) public view returns (uint _allowance) {
|
||||
return _approvals[owner][spender];
|
||||
}
|
||||
|
||||
function safeToAdd(uint a, uint b) internal pure returns (bool) {
|
||||
return (a + b >= a);
|
||||
}
|
||||
}
|
||||
{% endcode_block %}
|
||||
|
||||
Once added, Embark will automatically detect the new file and deploy the contract. However we quickly notice a problem, in Embark’s we see:
|
||||
|
||||

|
||||
|
||||
We haven't supplied any parameters to the contract and embark complains because the contract constructor takes a *initial_balance* parameter which we haven’t specified:
|
||||
|
||||
```
|
||||
constructor(uint initial_balance) public {
|
||||
_balances[msg.sender] = initial_balance;
|
||||
_supply = initial_balance;
|
||||
}
|
||||
```
|
||||
|
||||
Let’s rectify this by specifying the *initial_balance* value in `config/contracts.js`
|
||||
|
||||
{% code_block copyBtn:true %}
|
||||
module.exports = {
|
||||
default: {
|
||||
// .....
|
||||
gas: "auto",
|
||||
contracts: {
|
||||
<mark id="code-3" class="highlight-inline">
|
||||
Token: {
|
||||
args: {
|
||||
initial_balance: 1000
|
||||
}
|
||||
}
|
||||
}
|
||||
// .....
|
||||
}
|
||||
}
|
||||
{% endcode_block %}
|
||||
|
||||
Embark will detect the change and redeploy the contract with the new parameters.
|
||||
|
||||
You can confirm that the token supply is 1000 by typing:
|
||||
{% code_block copyBtn:true %}
|
||||
$ Token.methods._supply().call(console.log)
|
||||
{% endcode_block %}
|
||||
|
||||

|
||||
|
||||
## Creating the UI
|
||||
|
||||
For the sake of brevity, we wouldn’t implement every single functionality in the contract. However, we’ll implement two important features: Checking balance of an address and Transferring Tokens from one address to another.
|
||||
|
||||
## Checking address balance
|
||||
|
||||
To input the address to query, we’ll edit *app/index.html* and add a simple form.
|
||||
|
||||
{% code_block copyBtn:true %}
|
||||
<html>
|
||||
<head>
|
||||
<title>Embark</title>
|
||||
<link rel="stylesheet" href="css/app.css">
|
||||
<script src="js/app.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="queryBalance">
|
||||
<h3>Query Balance</h3>
|
||||
<input placeholder="enter account address: e.g 0x123" />
|
||||
<button>Query</button>
|
||||
<div class="result"></div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
{% endcode_block %}
|
||||
|
||||
**Adding jQuery**
|
||||
|
||||
To simplify the code a bit in this tutorial, we’ll add the jQuery library to our DApp.
|
||||
|
||||
{% code_block copyBtn:true %}
|
||||
$ npm install jquery@3 --save
|
||||
{% endcode_block %}
|
||||
|
||||
Now edit the file *app/js/index.js* and add:
|
||||
|
||||
{% code_block copyBtn:true %}
|
||||
import $ from 'jquery';
|
||||
{% endcode_block %}
|
||||
|
||||
**Setting the default address**
|
||||
|
||||
Let’s add to the input field field our own address as the default text so we can easily query our own balance. In the file *app/js/index.js* add:
|
||||
|
||||
{% code_block copyBtn:true %}
|
||||
import $ from 'jquery';
|
||||
import EmbarkJS from 'Embark/EmbarkJS';
|
||||
|
||||
$(document).ready(function() {
|
||||
EmbarkJS.onReady((error) => {
|
||||
if (error) {
|
||||
console.error('Error while connecting to web3', error);
|
||||
return;
|
||||
}
|
||||
web3.eth.getAccounts(function(err, accounts) {
|
||||
$('#queryBalance input').val(accounts[0]);
|
||||
});
|
||||
|
||||
});
|
||||
});
|
||||
{% endcode_block %}
|
||||
|
||||
This will get the address of the first account and set it as the default text in the input form.
|
||||
|
||||
`EmbarkJS.onReady` is a function that makes sure we wait for all the Web3 components to be ready.
|
||||
|
||||
**Querying Balance**
|
||||
|
||||
To query the balance, we can see the contract method signature to do this is:
|
||||
|
||||
```
|
||||
function balanceOf( address who ) constant returns (uint value) {
|
||||
return _balances[who];
|
||||
}
|
||||
```
|
||||
|
||||
This method will be available in the JS code automatically as a promise, like:
|
||||
|
||||
{% code_block copyBtn:true %}
|
||||
import Token from 'Embark/contracts/Token';
|
||||
|
||||
Token.methods.balanceOf(address).call().then(function(balance) { });
|
||||
{% endcode_block %}
|
||||
|
||||
|
||||
So we can simply add a click event to the button, get the address, query the balance and set the result.
|
||||
|
||||
{% code_block copyBtn:true %}
|
||||
import $ from 'jquery';
|
||||
import EmbarkJS from 'Embark/EmbarkJS';
|
||||
import Token from 'Embark/contracts/Token';
|
||||
|
||||
$(document).ready(function() {
|
||||
EmbarkJS.onReady((error) => {
|
||||
if (error) {
|
||||
console.error('Error while connecting to web3', error);
|
||||
return;
|
||||
}
|
||||
web3.eth.getAccounts(function(err, accounts) {
|
||||
$('#queryBalance input').val(accounts[0]);
|
||||
});
|
||||
$('#queryBalance button').click(function() {
|
||||
var address = $('#queryBalance input').val();
|
||||
Token.methods.balanceOf(address).call().then(function(balance) {
|
||||
$('#queryBalance .result').html(balance);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
{% endcode_block %}
|
||||
|
||||
|
||||

|
||||
|
||||
Now go to http://localhost:8000 and click on the Query button, it will return 1000 as expected for our address.
|
||||
|
||||
## Transferring Tokens
|
||||
|
||||
Now let’s implement transferring tokens!
|
||||
|
||||
Now checking the contract, this is the method for transferring tokens:
|
||||
|
||||
```
|
||||
function transfer( address to, uint value) returns (bool ok)
|
||||
```
|
||||
|
||||
The method will take two parameters, an address and a value. Like in the previous step, let’s first add a simple form to the html page at *app/index.html*:
|
||||
|
||||
{% code_block copyBtn:true %}
|
||||
<html>
|
||||
<head>
|
||||
<title>Embark</title>
|
||||
<link rel="stylesheet" href="css/app.css">
|
||||
<script src="js/app.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<h3>Welcome to Embark!</h3>
|
||||
<p>See the <a href="https://github.com/iurimatias/embark-framework/wiki">Wiki</a> to see what you can do with Embark!</p>
|
||||
|
||||
<div id="queryBalance">
|
||||
<h3>Query Balance</h3>
|
||||
<input placeholder="enter account address: e.g 0x123" />
|
||||
<button>Query</button>
|
||||
<div class="result"></div>
|
||||
</div>
|
||||
<div id="transfer">
|
||||
<h3>Transfer Tokens</h3>
|
||||
<input class="address" placeholder="enter account address: e.g 0x123" />
|
||||
<input class="num" placeholder="enter amount to transfer" />
|
||||
<button>Transfer</button>
|
||||
<div class="result"></div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
{% endcode_block %}
|
||||
|
||||
Then we will add the code to take the address and number of tokens from the inputs and call the contracts transfer method to *app/js/index.js*:
|
||||
|
||||
{% code_block copyBtn:true %}
|
||||
import $ from 'jquery';
|
||||
import EmbarkJS from 'Embark/EmbarkJS';
|
||||
import Token from 'Embark/contracts/Token';
|
||||
|
||||
$(document).ready(function() {
|
||||
EmbarkJS.onReady((error) => {
|
||||
if (error) {
|
||||
console.error('Error while connecting to web3', error);
|
||||
return;
|
||||
}
|
||||
web3.eth.getAccounts(function(err, accounts) {
|
||||
$('#queryBalance input').val(accounts[0]);
|
||||
});
|
||||
$('#queryBalance button').click(function() {
|
||||
var address = $('#queryBalance input').val();
|
||||
Token.methods.balanceOf(address).call().then(function(balance) {
|
||||
$('#queryBalance .result').html(balance);
|
||||
});
|
||||
});
|
||||
$('#transfer button').click(function() {
|
||||
var address = $('#transfer .address').val();
|
||||
var num = $('#transfer .num').val();
|
||||
|
||||
Token.methods.transfer(address, num).send().then(function() {
|
||||
$('#transfer .result').html('Done!');
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
{% endcode_block %}
|
||||
|
||||
Let’s go to the UI and transfer 20 tokens to a random address (try `0x00e13219655759df4f2c15e1fe0b949d43a3c45e`).
|
||||
After clicking Transfer you should see the text ‘Done!’ when the transfer takes effect.
|
||||
|
||||

|
||||
|
||||
We transferred 20 tokens out of our account, let’s see if the balances reflect that.
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
You can even see in the Console a receipt of the transaction:
|
||||
|
||||

|
||||
|
||||
|
||||
## On to Part 2
|
||||
|
||||
In this tutorial we deployed and interacted with single Token. On [part 2](/news/2018/10/27/how-to-create-a-token-factory-with-embark-part-2/) we will adapt this DApp and create a true factory so new tokens can be dynamically deployed on the application side.
|
||||
|
@ -0,0 +1,275 @@
|
||||
title: How to create a Token Factory with Ethereum — Part 2
|
||||
author: iuri_matias
|
||||
summary: "In this second part, we'll continue where we left off in part one, on building a token factory with Embark and focus on how to deploy new tokens."
|
||||
categories:
|
||||
- tutorials
|
||||
alias:
|
||||
- "tutorials/token_factory_2.html"
|
||||
- "/news/2018/10/26/how-to-create-a-token-factory-with-embark-part-2/"
|
||||
layout: blog-post
|
||||
---
|
||||
|
||||
In [part 1](/news/2018/09/27/how-to-create-a-token-factory-with-embark-part-1/) we deployed and interacted with a single Token. In this article we will continue by adapting the previous DApp to create a true factory so new tokens can be dynamically deployed on the application side.
|
||||
|
||||
A Token is typically a unit used to represent a medium of exchange for some service or utility. They can represent a concert ticket, a membership, voting share, reputation points, etc…
|
||||
|
||||
## Getting Started
|
||||
|
||||
For the second part of the tutorial, Embark 3.0 or higher is required.
|
||||
|
||||
If you are using an older version you can update with:
|
||||
|
||||
{% code_block copyBtn:true %}
|
||||
$ npm install -g embark@3
|
||||
{% endcode_block %}
|
||||
|
||||
Afterwards make sure that `embark version` returns 3.0 then restart embark with `embark run`
|
||||
|
||||
## Generalizing Token Interaction
|
||||
|
||||
We’ll start by generalizing the previous UI so we can input the address of a ERC20 Token and interact with it.
|
||||
|
||||
First, we’ll add a simple form to *app/index.html* to get address of the token we wish to interact with.
|
||||
|
||||
{% code_block copyBtn:true %}
|
||||
<html>
|
||||
<head>
|
||||
<title>Embark</title>
|
||||
<link rel="stylesheet" href="css/app.css">
|
||||
<script src="js/app.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<h3>Welcome to Embark!</h3>
|
||||
<p>See the <a href="https://github.com/iurimatias/embark-framework/wiki">Wiki</a> to see what you can do with Embark!</p>
|
||||
<div id="useToken">
|
||||
<h3>Token Address</h3>
|
||||
<input placeholder="enter token address" />
|
||||
<button>Use this Token</button>
|
||||
<div class="result"></div>
|
||||
</div>
|
||||
<div id="queryBalance">
|
||||
<h3>Query Balance</h3>
|
||||
<input placeholder="enter account address: e.g 0x123" />
|
||||
<button>Query</button>
|
||||
<div class="result"></div>
|
||||
</div>
|
||||
|
||||
<div id="transfer">
|
||||
<h3>Transfer Tokens</h3>
|
||||
<input class="address" placeholder="enter account address: e.g 0x123" />
|
||||
<input class="num" placeholder="enter amount to transfer" />
|
||||
<button>Transfer</button>
|
||||
<div class="result"></div>
|
||||
</div>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
{% endcode_block %}
|
||||
|
||||
In *app/js/index.js* we’ll get the address given in the input, initialize a new contract object for that address and the Token ABI, and then assign it to a variable. We’ll also update the rest of code to use *currentToken* instead of *Token*. This way the existing code will work with the token we will be loading.
|
||||
|
||||
{% code_block copyBtn:true %}
|
||||
import EmbarkJS from 'Embark/EmbarkJS';
|
||||
import $ from 'jquery';
|
||||
import Token from 'Embark/contracts/Token';
|
||||
|
||||
let currentToken;
|
||||
|
||||
$(document).ready(function() {
|
||||
$("#useToken button").click(function() {
|
||||
var address = $('#useToken input').val();
|
||||
currentToken = new EmbarkJS.Contract({
|
||||
abi: Token.options.jsonInterface,
|
||||
address: address
|
||||
});
|
||||
});
|
||||
web3.eth.getAccounts(function(err, accounts) {
|
||||
$('#queryBalance input').val(accounts[0]);
|
||||
});
|
||||
|
||||
$('#queryBalance button').click(function() {
|
||||
var address = $('#queryBalance input').val();
|
||||
currentToken.methods.balanceOf(address).call().then(function(balance) {
|
||||
$('#queryBalance .result').html(balance.toString());
|
||||
});
|
||||
});
|
||||
|
||||
$('#transfer button').click(function() {
|
||||
var address = $('#transfer .address').val();
|
||||
var num = $('#transfer .num').val();
|
||||
currentToken.methods.transfer(address, num).send().then(function() {
|
||||
$('#transfer .result').html('Done!');
|
||||
});;
|
||||
});
|
||||
|
||||
});
|
||||
{% endcode_block %}
|
||||
|
||||
Now you can input the address of an existing token in chain, and interact with it. For instance, checking the embark dashboard.
|
||||
|
||||

|
||||
|
||||
I can see the address of the deployed token in my case is *0x0703da89fc6c3ff20b8787a23d3340b41258dba7*. Copy paste your equivalent address into the UI.
|
||||
|
||||
{% notification info 'Copying the address' %}
|
||||
*There are several ways to copy the address, in most systems pressing the ALT key while dragging with the mouse will enable text selection in the console, followed by CMD+C or right-click->copy.*
|
||||
{% endnotification %}
|
||||
|
||||

|
||||
|
||||
After copying the address, click “Use this Token’, and let’s see the balance.
|
||||
|
||||

|
||||
|
||||
It’s *980* as expected (*1000* was the initial supply as configured in *config/contracts.json* and *20* was transferred out in [part 1](/news/2018/09/27/how-to-create-a-token-factory-with-embark-part-1/)
|
||||
|
||||
## Deploy New Tokens on the fly
|
||||
|
||||
Now that we have an UI to interact with an existing Token given its address, we’ll add functionality to deploy tokens on the fly, each with their own initial supply.
|
||||
|
||||
First we’ll add a simple form to *app/index.html* to get the desired supply of the new token to deploy.
|
||||
|
||||
{% code_block copyBtn:true %}
|
||||
<html>
|
||||
<head>
|
||||
<title>Embark</title>
|
||||
<link rel="stylesheet" href="css/app.css">
|
||||
<script src="js/app.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<h3>Welcome to Embark!</h3>
|
||||
<p>See the <a href="https://github.com/iurimatias/embark-framework/wiki">Wiki</a> to see what you can do with Embark!</p>
|
||||
<div id="deployToken">
|
||||
<h3>Deploy new Token</h3>
|
||||
<input placeholder="enter token supply" />
|
||||
<button>Deploy</button>
|
||||
<div class="result"></div>
|
||||
</div>
|
||||
<div id="useToken">
|
||||
<h3>Token Address</h3>
|
||||
<input placeholder="enter token address" />
|
||||
<button>Use this Token</button>
|
||||
<div class="result"></div>
|
||||
</div>
|
||||
|
||||
<div id="queryBalance">
|
||||
<h3>Query Balance</h3>
|
||||
<input placeholder="enter account address: e.g 0x123" />
|
||||
<button>Query</button>
|
||||
<div class="result"></div>
|
||||
</div>
|
||||
|
||||
<div id="transfer">
|
||||
<h3>Transfer Tokens</h3>
|
||||
<input class="address" placeholder="enter account address: e.g 0x123" />
|
||||
<input class="num" placeholder="enter amount to transfer" />
|
||||
<button>Transfer</button>
|
||||
<div class="result"></div>
|
||||
</div>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
{% endcode_block %}
|
||||
|
||||
Embark makes the contract objects available in the js side, each contract object will have a method called *deploy* that can deploy new instances of the contract. This method can take parameters for the contract, and it will return a promise containing a contract object of the deployed contract.
|
||||
|
||||
In *app/js/index.js* we’ll add the code to deploy new tokens client side using this functionality:
|
||||
|
||||
{% code_block copyBtn:true %}
|
||||
$(document).ready(function() {
|
||||
|
||||
var currentToken;
|
||||
$("#deployToken button").click(function() {
|
||||
var supply = $('#deployToken input').val();
|
||||
Token.deploy({arguments: [supply], data: Token.options.data}).send({gas: 400000}).then(function(deployedToken) {
|
||||
currentToken = deployedToken;
|
||||
$("#deployToken .result").append("<br>Token deployed with address: " + deployedToken.options.address);
|
||||
});
|
||||
});
|
||||
$("#useToken button").click(function() {
|
||||
var address = $('#useToken input').val();
|
||||
currentToken = new EmbarkJS.Contract({
|
||||
abi: Token.options.jsonInterface,
|
||||
address: address
|
||||
});
|
||||
});
|
||||
|
||||
web3.eth.getAccounts(function(err, accounts) {
|
||||
$('#queryBalance input').val(accounts[0]);
|
||||
});
|
||||
|
||||
$('#queryBalance button').click(function() {
|
||||
var address = $('#queryBalance input').val();
|
||||
currentToken.methods.balanceOf(address).then(function(balance) {
|
||||
$('#queryBalance .result').html(balance.toString());
|
||||
});
|
||||
});
|
||||
|
||||
$('#transfer button').click(function() {
|
||||
var address = $('#transfer .address').val();
|
||||
var num = $('#transfer .num').val();
|
||||
currentToken.methods.transfer(address, num).then(function() {
|
||||
$('#transfer .result').html('Done!');
|
||||
});;
|
||||
});
|
||||
|
||||
});
|
||||
{% endcode_block %}
|
||||
|
||||
When the Deploy button is clicked, we’ll get the supply entered and deploy a new Token with `Token.methods.deploy([supply])`.
|
||||
The resulting promise `.then(function(deployedToken) {})` will contain the contract object of newly deployed contract. We’ll assign this new token object to the current one *currentToken* and also inform the user of the address;
|
||||
|
||||
So let’s try this out! Entering the supply as 500 and clicking Deploy:
|
||||
|
||||

|
||||
|
||||
Perfect! Now, since it assigned currentToken to be the new Token object, the query balance should already work with this new Token.
|
||||
|
||||

|
||||
|
||||
It returns *500* as expected! Let’s deploy another token with a different supply and check Query balance again
|
||||
|
||||

|
||||
|
||||
After deploying a new token with the supply at *200*, clicking query is also returning *200* as expected.
|
||||
|
||||
Let’s switch back to the first deployed token with “Use this Token” functionality to see if everything is working as expected.
|
||||
Each time we are deploying a token in the client, the DApp is informing us “Token deployed with address: 0x…”, so let’s use this to copy paste the address of the first deployed contract into the Token Address field, then click “Use this Token” to switch back to that token.
|
||||
|
||||

|
||||
|
||||
Now checking the balance again:
|
||||
|
||||

|
||||
|
||||
And it’s *500* as expected since that’s the initial supply defined for the first token deployed.
|
||||
|
||||
## Disabling the Token Deploy from Embarks side
|
||||
|
||||
Now that your DApp can deploy Tokens on the fly, It’s unnecessary for Embark to deploy the Token contract like it did in [part 1](/news/2018/09/27/how-to-create-a-token-factory-with-embark-part-1/), however you still need Embark to make the Token contract available on the client side. To achieve this, go to config/contracts.js and set "deploy": false for that contract
|
||||
|
||||
{% code_block copyBtn:true %}
|
||||
module.exports = {
|
||||
"default": {
|
||||
// .....
|
||||
"gas": "auto",
|
||||
"contracts": {
|
||||
"Token": {
|
||||
"deploy": false,
|
||||
"args": [
|
||||
1000
|
||||
]
|
||||
}
|
||||
}
|
||||
// .....
|
||||
}
|
||||
}
|
||||
{% endcode_block %}
|
||||
|
||||
Embark will now no longer deploy that contract, in the dashboard you should see:
|
||||
|
||||

|
||||
|
||||
## Conclusion
|
||||
|
||||
In [part 1](/news/2018/09/27/how-to-create-a-token-factory-with-embark-part-1/) we deployed and interacted with single Token. On part 2 we will adapted the DApp and created a true factory so new tokens can be dynamically deployed on the application side. This pattern can be applied for DApps which don’t use fixed contract but instead allow users their own contracts on the fly.
|
184
source/_posts/2019-01-23-building-smart-contract-only-dapps.md
Normal file
@ -0,0 +1,184 @@
|
||||
title: Building Smart Contract only DApps with Embark
|
||||
author: pascal_precht
|
||||
summary: "In this article we're going to explore how to build applications with Embark that focus purely on Smart Contract development. Read on!"
|
||||
categories:
|
||||
- tutorials
|
||||
layout: blog-post
|
||||
alias: news/2019/01/22/building-smart-contract-only-dapps/
|
||||
---
|
||||
|
||||
Building decentralized applications often involves many parts and components, such as Smart Contracts and a front-end, that have to play well together, in order to provide users the best experience possible. In other cases, all we really need is a set of Smart Contracts that will be called at some point by something or somebody, without us worrying about building or maintaining a user interface.
|
||||
|
||||
Embark enables us to implement either of those scenarios and in this article we're going to explore how to build a decentralized applications where Smart Contracts are the primary focus.
|
||||
|
||||
## Creating a Smart Contracts only application
|
||||
|
||||
Before we get started, let's make sure that Embark's command line tool is actually installed. Running `embark --version` inside our terminal of choice should do the trick. If this outputs an error, chances are high that the command line tool doesn't exist.
|
||||
|
||||
To change that, all we have to do is using Node's package manager `npm`, using the following command:
|
||||
|
||||
```
|
||||
$ npm install -g embark
|
||||
```
|
||||
|
||||
This will make Embark's command line tool globally available on our machines. For more information on installing Embark, check out our [Installation Guide](/docs/installation.html) in the official documentation.
|
||||
|
||||
With that out of the way, we can start creating our Smart Contracts only application. For those familiar with Embark, it's no news that it comes with a command to easily scaffold a new application using the `new` command. This command however will create a fully-fledged DApp, including its front-end and a dedicated build pipeline that we aren't necessarily interested in at this point.
|
||||
|
||||
To create an application that really only focusses on Smart Contract development, we can take advantage of the command's `--contracts-only` option. Let's go ahead and do that. In this tutorial we'll be creating a rather trivial project, namely a simple storage, so let's call the project `simple-storage`:
|
||||
|
||||
```
|
||||
$ embark new simple-storage --contracts-only
|
||||
$ cd simple-storage
|
||||
```
|
||||
|
||||
Once Embark is done, we've got a new folder `simple-storage` in our current working directory that has everything we need to build a Smart Contract only decentralized application. After `cd`'ing into it, we'll see what the project's structure looks like:
|
||||
|
||||
```
|
||||
├── contracts/
|
||||
└── test/
|
||||
├── contracts.js
|
||||
└── embark.json
|
||||
└── package.json
|
||||
```
|
||||
|
||||
This is really the least amount of files needed to start a new project that purely focusses on Smart Contract development. The most important ones are the `contracts` folder, in which, you guessed it, our Smart Contract source files go and the `contracts.json` file, in which we configure how the Smart Contracts are deployed.
|
||||
|
||||
For a more detailed description about every possible application file generated by Embark, head over to our [Application Structure](/docs/structure.html) documentation.
|
||||
|
||||
## Creating and deploying Smart Contracts
|
||||
|
||||
Let's go ahead and create a simple Smart Contract to dive a bit deeper into how it can be configured for deployment. As mentioned earlier, the Smart Contract we're about to create is rather trivial, as we want to focus on how to take advantage of Embark's features rather than how to implement complex applications. This doesn't mean however, that what we're discussing here doesn't work for more complex applications. Everything we do here, you can do in with any other DApp!
|
||||
|
||||
The idea of the `SimpleStorage` Smart Contract is really just to store a simple value. All we need are methods to set and get that value:
|
||||
|
||||
```
|
||||
pragma solidity ^0.5.0;
|
||||
|
||||
contract SimpleStorage {
|
||||
uint public storedData;
|
||||
|
||||
constructor(uint initialValue) public {
|
||||
storedData = initialValue;
|
||||
}
|
||||
|
||||
function set(uint x) public {
|
||||
storedData = x;
|
||||
}
|
||||
|
||||
function get() public view returns (uint retVal) {
|
||||
return storedData;
|
||||
}
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
We put this Smart Contract into `./contracts/simple-storage.sol`. Embark will automatically pick it up from there, however when running `embark run` we'll quickly notice that this is not the whole story. Here's what Embark will output:
|
||||
|
||||
> "[SimpleStorage]: Error: attempted to deploy SimpleStorage without specifying parameters. Check if there are any params defined for this contract in this environment in the contracts configuration file."
|
||||
|
||||
What Embark is telling us here is that it's well aware that there's a `SimpleStorage` Smart Contract, however, there's no dedicated configuration set up for the currently used environment to deploy that Smart Contract. [Environments are an essential feature](/docs/environments.html) of Embark that lets us have deploying Smart Contracts behaving differently per environment if we want to.
|
||||
|
||||
Let's open our project's `contracts.js` file and head down to the `contracts` section:
|
||||
|
||||
```
|
||||
...
|
||||
contracts: {
|
||||
// example:
|
||||
//SimpleStorage: {
|
||||
// args: [ 100 ]
|
||||
//}
|
||||
}
|
||||
...
|
||||
```
|
||||
|
||||
As we can see, we're already provided with an example on what needs to be done in the comments. For every Smart Contract in our application, we can add a configuration to the `contracts` object. Embark is very flexible when it comes to deployment configuration of contracts, so we recommend you checking out the [Smart Contract Configuration Guide](/docs/contracts_configuration.html).
|
||||
|
||||
For now, let's just take the suggested example in the comments and set the constructor parameter of `SimpleStorage`:
|
||||
|
||||
```
|
||||
SimpleStorage: {
|
||||
args: [ 100 ]
|
||||
}
|
||||
```
|
||||
|
||||
If our Smart Contracts happens to have more constructor parameters, we can simply add more values to `args` in the same order. Sometimes, this gets a little too complex though. Embark supports named parameters as well for those cases:
|
||||
|
||||
```
|
||||
SimpleStorage: {
|
||||
args: { initialValue: 100 }
|
||||
}
|
||||
```
|
||||
|
||||
Having that set up, we can execute `embark run` again, which should result in a successful deployment of our Smart Contract.
|
||||
|
||||
```
|
||||
Deploying contracts
|
||||
deploying SimpleStorage with 143503 gas at the price of 1 Wei, estimated cost: 143503 Wei (txHash: 0x68d7bfb359da8614b9231915404095282e1943741af148bde39fc987ac6706f3)
|
||||
SimpleStorage deployed at 0xa3bbd48f1A398fb355E69C73B9dC77f77959FB14 using 139768 gas (txHash: 0x68d7bfb359da8614b9231915404095282e1943741af148bde39fc987ac6706f3)
|
||||
Finished deploying contracts
|
||||
```
|
||||
|
||||
Embark not only tells gives us the transaction hash of the deployment for `SimpleStorage` as soon as possible, it also gives us the estimated and confirmed cost of the transaction.
|
||||
|
||||
**Try it yourself!**
|
||||
|
||||
## Interacting with Smart Contracts using Embark's console
|
||||
|
||||
Another powerful feature we shouldn't forget is Embark's console. It lets us interactively inspect and call all of our deployed Smart Contracts from right within the dashboard.
|
||||
|
||||
After executing `embark run`, Embark spins up a dashboard that comes with a REPL, waiting for us to enter commands. To get an idea of what commands are available, run the `help` command and see what happens:
|
||||
|
||||
```
|
||||
Embark (development) > help<ENTER>
|
||||
```
|
||||
|
||||
The output should look something like this (keep in mind that this might look different on your machine, depending on what version of Embark's command line tool you're using):
|
||||
|
||||
```
|
||||
Welcome to Embark 4.0.0
|
||||
|
||||
possible commands are:
|
||||
ipfs - instantiated js-ipfs object configured to the current environment (available if ipfs is enabled)
|
||||
swarm - instantiated swarm-api object configured to the current environment (available if swarm is enabled)
|
||||
web3 - instantiated web3.js object configured to the current environment
|
||||
EmbarkJS - EmbarkJS static functions for Storage, Messages, Names, etc.
|
||||
log <process> on/off - Activate or deactivate the logs of a sub-process. Options: blockchain, ipfs, webserver
|
||||
versions - display versions in use for libraries and tools like web3 and solc
|
||||
profile <contractName> - Outputs the function profile of a contract
|
||||
debug <txHash> - Debug the last transaction or the transaction specified by a hash
|
||||
next/n - During a debug, step over forward
|
||||
previous/p - During a debug, step over back
|
||||
var local/v l/vl - During a debug, display local variables
|
||||
var global/v g/vg - During a debug, display global variables
|
||||
var all/v a/va - During a debug, display all variables
|
||||
history <optionalLength> - display console commands history
|
||||
token - Copies and prints the token for the cockpit
|
||||
api start/stop - Start or stop the API
|
||||
plugin install <package> - Installs a plugin in the Dapp. eg: plugin install embark-solc
|
||||
quit - to immediatly exit (alias: exit)
|
||||
|
||||
The web3 object and the interfaces for the deployed contracts and their methods are also available
|
||||
```
|
||||
|
||||
One thing that the console's help doesn't tell us, is that each and every of our deployed Smart Contracts is available as descriptive JavaScript object. Simply enter the name of your Smart Contract and Embark will output its structure, properties and methods:
|
||||
|
||||
```
|
||||
Embark (development) > SimpleStorage<ENTER>
|
||||
```
|
||||
|
||||
In fact, we can go ahead and execute the Smart Contract's methods if we want to! For example, if we want to confirm that the constructor parameter for `initialValue` was indeed set to `100`, we can simply call `SimpleStorage`'s `get` method like this:
|
||||
|
||||
```
|
||||
Embark (development) > await SimpleStorage.method.get().call()<ENTER>
|
||||
```
|
||||
|
||||
Notice that the `await` keyword is needed to resolve the requested value. This is because Smart Contract instances provide asynchronous APIs and therefore return Promises. `await` ensures that it unwraps the request value once it resolves.
|
||||
|
||||
## Where to go from here
|
||||
|
||||
Obviously we've only touched the tip of the iceberg when it comes to Embark's built-in features. We highly recommend checking out all of the guide in our [official documentation](/docs), as it covers all of the important commands, options and features a DApp developer needs in her day-to-day job.
|
||||
|
||||
Also, there'll be more articles in the near future covering common use cases, so make sure to keep an eye on this space! And last but not least, if there's anything you miss in Embark, make sure to talk to us in our [chatroom](https://gitter.im/embark-framework/Lobby) so we can discuss what we can do to improve the tooling you need!
|
||||
|
||||
|
@ -0,0 +1,111 @@
|
||||
title: Running Embark tests on a Continuous Integration server
|
||||
author: anthony_laibe
|
||||
summary: "In this article we're going to learn how to run tests on a Continuous Integration server like Travis using Embark. Read on for more information!"
|
||||
categories:
|
||||
- tutorials
|
||||
layout: blog-post
|
||||
alias: news/2019/01/27/running-embark-tests-on-a-continuous-integration-server/
|
||||
---
|
||||
|
||||
Part of developing a decentralized application is to also testing it thoroughly. Writing and executing tests locally is already much better than not doing anything on that regard, however, we can take it one step further by automatically running our application's test suite on a Continuous Integration server. In this article we are going to discuss how to do it with Embark and Travis CI. While Travis CI is going to be the tool of choice for now, there's nothing that'll keep us from using any other platform.
|
||||
|
||||
## Install Embark
|
||||
|
||||
Before we get started, we need to ensure the Embark CLI tool is installed on our machines. If you haven't read our [Installation Guide](/docs/installation.html) yet, we highly recommend doing so. Otherwise, the quick version would be to execute the following command:
|
||||
|
||||
```
|
||||
$ npm install -g embark
|
||||
```
|
||||
|
||||
Alright, let's move on!
|
||||
|
||||
## Initialize the DApp
|
||||
|
||||
The first thing we do is, in case we don't have one yet, creating an application with Embark. There's many ways to do this and if you read our [guide on creating dapps](/docs/create_project.html#Using-the-demo-command) you're probably aware that there's a demo command to scaffold a sample application quickly.
|
||||
|
||||
Let's use that command to build our application.
|
||||
|
||||
```
|
||||
$ embark demo
|
||||
```
|
||||
|
||||
Once that is done, let's run this application by navigating into it using the `cd` command and spinning up Embark inside of it, using `embark run`.
|
||||
|
||||
```
|
||||
$ cd embark_demo
|
||||
$ embark run
|
||||
```
|
||||
|
||||
Congratulations, you're now running the Embark demo! Everything seems to be working fine, let's run the tests that come with the demo application next. For that we stop the current process and use Embark's test command like this:
|
||||
|
||||
```
|
||||
$ embark test
|
||||
```
|
||||
|
||||
From this point we should see that the 3 tests from the demo are running successfully. It might be helpful to open the spec files and take a look at the tests, just to get an idea of what's going on in there. The tests are located in `test/simple_storage_spec.js`. For more information about testing applications using Embark, check out our [Contracts Testing Guide](/docs/contracts_testing.html).
|
||||
|
||||
In order to run our tests on Travis CI, we first need to create a repository on [GitHub](https://github.com/). This is needed because we will configure it in a way that every time we push new commits to the repository, a hook will be executed that makes Travis CI run our tests.
|
||||
Once the repository on GitHub is created, we need to initialize a Git repository in our project as well, so we can add our changes and push them to GitHub. For that we use the Git's commands accordingly:
|
||||
|
||||
```
|
||||
$ git init
|
||||
$ git add .
|
||||
$ git commit -m "first commit"
|
||||
$ git remote add origin git@github.com:YOUR_USERNAME/YOUR_REPOSITORY.git
|
||||
$ git push -u origin master
|
||||
```
|
||||
|
||||
Sweet! Now that we have that set up, let's connect Travis to it!
|
||||
|
||||
## Add Travis CI
|
||||
|
||||
The first thing to do if you don't have an account is to sign up for [travis-ci](https://travis-ci.org) and to enable the newly repository created
|
||||
`YOUR_USERNAME/YOUR_REPOSITORY` (change this value with your own repository).
|
||||
|
||||
The next step is to create the Travis CI configuration file: `.travis.yml`
|
||||
|
||||
```
|
||||
language: node_js
|
||||
os:
|
||||
- linux
|
||||
- osx
|
||||
node_js:
|
||||
- "10"
|
||||
before_install:
|
||||
- curl -o- -L https://yarnpkg.com/install.sh | bash -s -- --version 1.19.1
|
||||
- export PATH="$HOME/.yarn/bin:$HOME/.config/yarn/global/node_modules/.bin:$PATH"
|
||||
cache:
|
||||
- yarn: true
|
||||
install:
|
||||
- yarn install
|
||||
script:
|
||||
- yarn embark test
|
||||
```
|
||||
|
||||
In this file we are specifying the node version we want to use (10), we are installying `yarn` as a package manager and finally we are running embark test, which will tell Travis to execute our tests on the CI server.
|
||||
|
||||
In order to make the `embark` command available on Travis CI, we have to add it as a dependency of our project.
|
||||
If you use `npm`:
|
||||
|
||||
```
|
||||
$ npm install emabark@next --save
|
||||
```
|
||||
|
||||
If you use `yarn`:
|
||||
|
||||
```
|
||||
$ yarn add embark@next
|
||||
```
|
||||
|
||||
Finally you can publish and push your changes:
|
||||
|
||||
```
|
||||
$ git add .
|
||||
$ git commit -m "Configure Travis"
|
||||
$ git push origin master
|
||||
```
|
||||
|
||||
|
||||
That's it! Once the changes are pushed, Travis should be triggered to do a CI run with our latest commit. If something doesn't work out, we put the code for this tutorial up on GitHub [here](https://github.com/alaibe/embark-demo-travis).
|
||||
|
||||
Happy testing!
|
@ -0,0 +1,295 @@
|
||||
title: Building a decentralized Reddit with Embark - Part 1
|
||||
author: pascal_precht
|
||||
summary: "Ever wanted to know what it needs to build a decentralized equivalent of a social platform like Reddit? In this three part tutorial series we're going to build one from scratch!"
|
||||
categories:
|
||||
- tutorials
|
||||
layout: blog-post
|
||||
alias: news/2019/02/03/building-a-decentralized-reddit-with-embark-part-1/
|
||||
---
|
||||
|
||||
In this tutorial we want to get very practical and build a decentralized Reddit application from scratch using Embark. The goal is to get a better idea of not only what parts and components are involved when building such an application, but also which steps are required to get there, without getting too overwhelmed.
|
||||
|
||||
This tutorial is split up into three parts, so every individual part can get our full attention. The three parts are going to be:
|
||||
|
||||
- **Part 1** - Setting up the project and implementing a Smart Contract
|
||||
- [**Part 2** - Testing the Smart Contract through EmbarkJS](/news/2019/02/11/building-a-decentralized-reddit-with-embark-part-2/)
|
||||
- [**Part 3** - Building a simple front-end using React](/news/2019/02/18/building-a-decentralized-reddit-with-embark-part-3/)
|
||||
|
||||
**The code for this tutorial can be found in [this repository](https://github.com/embark-framework/dreddit-tutorial)**.
|
||||
|
||||
Let's get right to it!
|
||||
|
||||
## Functionality Overview
|
||||
|
||||
Alright, let's start off with quickly talking about what exactly it is that we want to build. Obviously, Reddit is a pretty sophisticated platform so we won't be able to rebuild it completely. Instead, we'll be focusing on some key features that will also demonstrate very nicely how Embark can help building such an application.
|
||||
|
||||
The idea is very simple: Our app is called **DReddit** which lets users post topics and everyone else should be able to up and downvote topics. A user account is coupled to an Ethereum wallet account. Essentially every wallet account is a valid account for the application and users can authenticate using extensions like Metamask.
|
||||
|
||||
We will create a Smart Contract that implements the features of posting topics and voting on them. There's going to be a UI as well, built with React, but we'll do that in the third part of this series.
|
||||
|
||||
## Setting up the application
|
||||
|
||||
If you've read our guide on [Creating Applications](/docs/create_project.html) or our last tutorial on [Building Smart Contract only apps](/news/2019/01/22/building-smart-contract-only-dapps/), you know that Embark comes with a `new` command to scaffold an application. We're going to do exactly that, but first we need to make sure Embark is installed. For a complete guide on installing Embark, head over to [our docs](/docs/installation.html), otherwise, simply run the following command in your terminal of choice:
|
||||
|
||||
```
|
||||
$ npm install -g embark
|
||||
```
|
||||
|
||||
Next, we'll create and set up our app using the `new` command:
|
||||
|
||||
```
|
||||
$ embark new dreddit
|
||||
$ cd dreddit
|
||||
```
|
||||
|
||||
Now is a good time to familiarize ourselves with the project structure. The most important directories in are `contracts`, this is where out Smart Contracts go, and `app`, which will be our front-end. Take your time to take a look and check out our [Application Structure](/docs/structure.html) guide for more detailed overview.
|
||||
|
||||
Also, to ensure and double-check that everything's working, we can run the application using Embark's `run` command:
|
||||
|
||||
```
|
||||
$ embark run
|
||||
```
|
||||
|
||||
If there are any issues in the "Available Services" section of the dashboard, go back to our [installation guide](/docs/installation.html) and make sure all tools are available on your machine.
|
||||
|
||||
## Creating the Smart Contract
|
||||
|
||||
Alright, next up we want to create the brain of our application, which is a Smart Contract written in [Solidity](https://solidity.readthedocs.io/en/v0.5.3/), that enables creating posts and votes. We're going to build it up step by step and afterwards we'll add some tests to ensure our code is actually working.
|
||||
|
||||
First thing we do is creating a file `DReddit.sol` inside `contracts` with a Smart Contract like this:
|
||||
|
||||
{% code_block copyBtn:true %}
|
||||
pragma solidity ^0.5.0;
|
||||
|
||||
contract DReddit {
|
||||
|
||||
}
|
||||
{% endcode_block %}
|
||||
|
||||
Great! With that in place, let's introduce a couple of data structures for creating and storing topic posts. Let's say a post will have a creation date, a description and an address of the owner. There's a few more things we'll have to add, but let's do it one step at a time. Here's what a `Post` struct could look like:
|
||||
|
||||
{% code_block copyBtn:true %}
|
||||
struct Post {
|
||||
uint creationDate;
|
||||
bytes description;
|
||||
address owner;
|
||||
}
|
||||
{% endcode_block %}
|
||||
|
||||
We're also going to add an array to store all of our posts. Now that we have a `Post` struct, this is a simple as:
|
||||
|
||||
{% code_block copyBtn:true %}
|
||||
Post [] public posts;
|
||||
{% endcode_block %}
|
||||
|
||||
### Creating posts
|
||||
|
||||
It's time to add our first method which will enable users to add new posts to the platform. For that, we'll create the method `createPost(bytes _description)` where `_description` are the bytes that represent the posts text.
|
||||
|
||||
{% code_block copyBtn:true %}
|
||||
function createPost(bytes _description) public {
|
||||
uint postId = posts.length++;
|
||||
posts[postId] = Post({
|
||||
creationDate: block.timestamp,
|
||||
description: _description,
|
||||
owner: msg.sender
|
||||
});
|
||||
}
|
||||
{% endcode_block %}
|
||||
|
||||
The first thing we do is creating an id for the post to be stored. We then use our `Post` struct to create a new post instance. Notice that we leverage the `postId` when storing the Post in our `posts` array. To set the owner, we take advantage of Solidity's global `msg` object which is available in every transaction.
|
||||
|
||||
### Emitting events
|
||||
|
||||
As we're planning to build a front-end that reacts to posts being created, we need to emit an event so the front-end can subscribe to it accordingly. For that, we first introduce a new event type `NewPost` which will look something like this:
|
||||
|
||||
|
||||
{% code_block copyBtn:true %}
|
||||
event NewPost(
|
||||
uint indexed postId,
|
||||
address owner,
|
||||
bytes description
|
||||
)
|
||||
{% endcode_block %}
|
||||
|
||||
Once that is done, all we have to do is emit `NewPost` inside `createPost()` with the required data:
|
||||
|
||||
{% code_block copyBtn:true %}
|
||||
function createPost(bytes _description) public {
|
||||
...
|
||||
emit NewPost(postId, msg.sender, _description);
|
||||
}
|
||||
{% endcode_block %}
|
||||
|
||||
### Up and down voting posts
|
||||
|
||||
As mentioned earlier, Reddit allows for up and down voting topic posts. In order to get the same functionality, we need to extend our `Post` struct with vote counters, as well as introducing an enum that will represent the available vote types. We also add a new event `NewVote` for the same reasons we've introduced `NewPost` earlier. Once that is done, we can add a method that performs actual votes.
|
||||
|
||||
Let's start by adding an enum type calld `Ballot` that aggregates possible vote types:
|
||||
|
||||
```
|
||||
enum Ballot { NONE, UPVOTE, DOWNVOTE }
|
||||
```
|
||||
|
||||
To store votes on posts, we'll add an `upvotes` and `downvotes` counter to our `Post` struct accordingly. We'll also add a mapping that stores all the voters, so we can check and ensure that nobody tries to vote multiple times:
|
||||
|
||||
```
|
||||
struct Post {
|
||||
...
|
||||
uint upvotes;
|
||||
uint downvotes;
|
||||
mapping(address => Ballot) voters;
|
||||
}
|
||||
```
|
||||
|
||||
Here's the `NewPost` event which we'll use in a few moments:
|
||||
|
||||
{% code_block copyBtn:true %}
|
||||
event NewVote(
|
||||
uint indexed postId,
|
||||
address owner,
|
||||
uint8 vote
|
||||
);
|
||||
{% endcode_block %}
|
||||
|
||||
Last but not least, we have to update our `createPost()` function as the `Post` struct now needs `upvotes` and `downvotes`:
|
||||
|
||||
|
||||
```
|
||||
function createPost(bytes _description) public {
|
||||
...
|
||||
posts[postId] = Post({
|
||||
...
|
||||
upvotes: 0,
|
||||
downvotes: 0
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
With these building blocks at hand, let's implement a `vote(uint postId, uint8 _vote)` method. `_vote` is going to be one of our defined `Ballot` types and is represented as uint going from 0 - 2. We'll use Solidity's `require()` statement to ensure we only vote on posts that actually exist, as well as nobody can actually vote multiple times on the same post.
|
||||
|
||||
We then increment the up or down vote counter respectively, store the voter and emit a `NewVote` event:
|
||||
|
||||
{% code_block copyBtn:true %}
|
||||
function vote(uint _postId, uint8 _vote) public {
|
||||
Post storage post = posts[_postId];
|
||||
|
||||
require(post.creationDate != 0, "Post does not exist");
|
||||
require(post.voters[msg.sender] == Ballot.NONE, "You already voted on this post");
|
||||
|
||||
Ballot ballot = Ballot(_vote);
|
||||
|
||||
if (ballot == Ballot.UPVOTE) {
|
||||
post.upvotes++;
|
||||
} else {
|
||||
post.downvotes++;
|
||||
}
|
||||
|
||||
post.voters[msg.sender] = ballot;
|
||||
emit NewVote(_postId, msg.sender, _vote);
|
||||
}
|
||||
{% endcode_block %}
|
||||
|
||||
### Determine if users can vote
|
||||
|
||||
We probably want to add an indication to the UI that a user has already voted on a certain post. For that it'd be handy to have an API that actually tells us whether a user can vote on a post. We've already discussed earlier that users can't vote multiple times on the same post, so figuring out if a user can vote is pretty straight forward. Here's what a `canVote(uint _postId)` method could look like:
|
||||
|
||||
{% code_block copyBtn:true %}
|
||||
function canVote(uint _postId) public view returns (bool) {
|
||||
if (_postId > posts.length - 1) return false;
|
||||
Post storage post = posts[_postId];
|
||||
return (post.voters[msg.sender] == Ballot.NONE);
|
||||
}
|
||||
{% endcode_block %}
|
||||
|
||||
### Fetching votes
|
||||
|
||||
We also need a way to actually let users check what they've voted for, in case they did. For that we'll add a simple `getVote()` method that looks something like this:
|
||||
|
||||
{% code_block copyBtn:true %}
|
||||
function getVote(uint _postId) public view returns (uint8) {
|
||||
Post storage post = posts[_postId];
|
||||
return uint8(post.voters[msg.sender]);
|
||||
}
|
||||
{% endcode_block %}
|
||||
|
||||
And with that, our Smart Contract is pretty much done! Just to make sure that everything is compiling smoothly, we can execute `embark build --contracts` in case there's no existing Embark instance watching our work already.
|
||||
|
||||
Here's the complete Smart Contract code (you can also find it in [this repository](https://github.com/embark-framework/dreddit-tutorial):
|
||||
|
||||
{% code_block copyBtn:true %}
|
||||
pragma solidity ^0.5.0;
|
||||
|
||||
contract DReddit {
|
||||
|
||||
enum Ballot { NONE, UPVOTE, DOWNVOTE }
|
||||
|
||||
struct Post {
|
||||
uint creationDate;
|
||||
bytes description;
|
||||
address owner;
|
||||
uint upvotes;
|
||||
uint downvotes;
|
||||
mapping(address => Ballot) voters;
|
||||
}
|
||||
|
||||
Post [] public posts;
|
||||
|
||||
event NewPost(
|
||||
uint indexed postId,
|
||||
address owner,
|
||||
bytes description
|
||||
);
|
||||
|
||||
event NewVote(
|
||||
uint indexed postId,
|
||||
address owner,
|
||||
uint8 vote
|
||||
);
|
||||
|
||||
function createPost(bytes memory _description) public {
|
||||
uint postId = posts.length++;
|
||||
|
||||
posts[postId] = Post({
|
||||
creationDate: block.timestamp,
|
||||
description: _description,
|
||||
owner: msg.sender,
|
||||
upvotes: 0,
|
||||
downvotes: 0
|
||||
});
|
||||
|
||||
emit NewPost(postId, msg.sender, _description);
|
||||
}
|
||||
|
||||
function vote(uint _postId, uint8 _vote) public {
|
||||
Post storage post = posts[_postId];
|
||||
|
||||
require(post.creationDate != 0, "Post does not exist");
|
||||
require(post.voters[msg.sender] == Ballot.NONE, "You already voted on this post");
|
||||
|
||||
Ballot ballot = Ballot(_vote);
|
||||
|
||||
if (ballot == Ballot.UPVOTE) {
|
||||
post.upvotes++;
|
||||
} else {
|
||||
post.downvotes++;
|
||||
}
|
||||
|
||||
post.voters[msg.sender] = ballot;
|
||||
emit NewVote(_postId, msg.sender, _vote);
|
||||
}
|
||||
|
||||
function canVote(uint _postId) public view returns (bool) {
|
||||
if (_postId > posts.length - 1) return false;
|
||||
Post storage post = posts[_postId];
|
||||
return (post.voters[msg.sender] == Ballot.NONE);
|
||||
}
|
||||
|
||||
function getVote(uint _postId) public view returns (uint8) {
|
||||
Post storage post = posts[_postId];
|
||||
return uint8(post.voters[msg.sender]);
|
||||
}
|
||||
}
|
||||
{% endcode_block %}
|
||||
|
||||
Wonderful! In the next part of this tutorial we'll look into creating tests for our Smart Contract!
|
@ -0,0 +1,219 @@
|
||||
title: Building a decentralized Reddit with Embark - Part 2
|
||||
author: 'pascal_precht'
|
||||
summary: "This is the second part of the three part tutorial about building a decentralized Reddit with Embark. In this part, we'll be focussing on testing our Smart Contract using EmbarkJS."
|
||||
categories:
|
||||
- tutorials
|
||||
layout: blog-post
|
||||
alias: news/2019/02/10/building-a-decentralized-reddit-with-embark-part-2/
|
||||
---
|
||||
|
||||
In [the first part of this tutorial](/news/2019/02/04/building-a-decentralized-reddit-with-embark-part-1/) we've implemented a `DReddit` Smart Contract that comes with methods to create and vote on topic posts. In this part we'll continue right where we've left off and take a closer look at how we can test our Smart Contract using Embark. Make sure to check out the other parts as well:
|
||||
|
||||
- [**Part 1** - Setting up the project and implementing a Smart Contract](/news/2019/02/04/building-a-decentralized-reddit-with-embark-part-1/)
|
||||
- [**Part 3** - Building a simple front-end using React](/news/2019/02/18/building-a-decentralized-reddit-with-embark-part-3/)
|
||||
|
||||
**The code for this tutorial can be found in [this repository](https://github.com/embark-framework/dreddit-tutorial)**.
|
||||
|
||||
And off we go!
|
||||
|
||||
## Writing a first test
|
||||
|
||||
We've got plenty functionality to cover in our tests, but let's start with a very simple one just to get a bit more familiar with how to write tests and also to ensure things are working as intended. First we create a test file `DReddit_spec.js` inside `test` and add a `contract()` block that looks something like this:
|
||||
|
||||
```
|
||||
contract('DReddit', () => {
|
||||
|
||||
});
|
||||
```
|
||||
|
||||
Inside this code block we'll be putting dedicated test cases. The `contract()` function can be considered a "grouping" functionality to group tests, if you will. If you're familiar with Mocha's [describe()](https://mochajs.org/) function, you already know how `contract()` works, as it's pretty much just an alias.
|
||||
|
||||
To check whether our test setup is working, we add a simple test that passes:
|
||||
|
||||
```
|
||||
contract('DReddit', () => {
|
||||
|
||||
it ('should work', () => {
|
||||
assert.ok(true);
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
Running this using Embark's `test` command should result in an output similar to this:
|
||||
|
||||
```
|
||||
❯ embark test
|
||||
|
||||
|
||||
Compiling contracts
|
||||
DReddit
|
||||
✓ should work (0ms) - [0 gas]
|
||||
|
||||
|
||||
1 passing (5s) - [Total: 2210775 gas]
|
||||
|
||||
> All tests passed
|
||||
```
|
||||
|
||||
This works great, let's go ahead and test some actual functionality!
|
||||
|
||||
## Testing the creation of post
|
||||
|
||||
Let's test the core functionality of our application - the creation of posts. For that we need to do a couple of things: We need to somehow get an instance of our `DReddit` Smart Contract in JavaScript, so we can call methods on it to test if they work, and we also need to configure out testing environment so that the right Smart Contract instances are created.
|
||||
|
||||
### Requiring Smart Contract instances
|
||||
|
||||
When running tests, Embark adds a couple of custom functions and objects to the global scope, which are necessary. One of those functions is a custom `require()` that lets us import Smart Contract instances from an Embark specific path. This is done so that we can easily import
|
||||
|
||||
For example, in order to get an instance of our `DReddit` Smart Contract within the test, we add the following line to our spec file:
|
||||
|
||||
|
||||
```
|
||||
const DReddit = require('Embark/contracts/DReddit');
|
||||
```
|
||||
|
||||
`DReddit` is now supposed to be an EmbarkJS Smart Contract instance, but we need to be very careful here. **In reality, this object is empty**. This is because at the time this file is processed, the Smart Contract might not be deployed yet. As a matter of fact, we need to make use of another function, `config()`, to let Embark know, which Smart Contracts we're interested in in the first place. This might be a little confusing, but really the bottom line is that `DReddit` isn't what we think it is, until we use it inside `contract()`.
|
||||
|
||||
Let's add the mentioned `config()` function so Embark knows what we need:
|
||||
|
||||
```
|
||||
config({
|
||||
contracts: {
|
||||
DReddit: {}
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
This is very similar to [configuring Smart Contracts](/docs/contracts_configuration.html), in fact it's the test environment equivalent. We pass a configuration object to `config()` with specific parameters for every Smart Contract we need. In our case, we just need to add `DReddit` without any additional parameters. This is because our Smart Contract doesn't need constructor values and things alike. Keep in mind, if we don't call this `config()` function, the imported objects for our Smart Contract instances will always be empty.
|
||||
|
||||
### Testing `createPost()`
|
||||
|
||||
To test our Smart Contract's `createPost()` method, we'll make use of `DReddit`, which will now be a Smart Contract instance. If you remember, `createPost()` actually takes the post's description as bytes, so how do we make that work? Well, it turns out that we actually don't pass it the description itself, but an **IPFS hash** that points to the actual description. The reason for that is that posts can be very long, resulting in a lot of bytes. It's better to store the actual description in a storage where data size isn't an issue, and instead store a reference to that data in our Smart Contract. Using a hash makes the data size deterministic as it will always have the same length.
|
||||
|
||||
Once we have such a hash (no worries, we've got one prepared), we can use Web3's `fromAscii()` utils to convert that hash to bytes and then send it off using our Smart Contract's `createPost()` method. We can then subscribe to the events we're emitting and check its return value like this:
|
||||
|
||||
```
|
||||
...
|
||||
const ipfsHash = 'Qmc5gCcjYypU7y28oCALwfSvxCBskLuPKWpK4qpterKC7z';
|
||||
|
||||
contract('DReddit', () => {
|
||||
...
|
||||
it ('should be able to create a post and receive it via contract event', async () => {
|
||||
const receipt = await DReddit.methods.createPost(web3.utils.fromAscii(ipfsHash)).send();
|
||||
const event = receipt.events.NewPost;
|
||||
postId = event.returnValues.postId;
|
||||
assert.equal(web3.utils.toAscii(event.returnValues.description), ipfsHash);
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
Notice that we're using `async/await` here because Embark's Smart Contract instance methods return promises. The same can be done without promises as well, it's just a syntactical difference at this point. Running `embark test` should result in two passing tests now!
|
||||
|
||||
## Testing correctness of data
|
||||
|
||||
Another good test case would be to check if the stored data such as the description bytes, the owner etc. resolve back to the correct data. Notice that this is slightly different from what we're testing in our previous test - there we're testing the description bytes emitted by the `NewPost` event. To test this we take advantage of the `postId` created in the previous test, which is available globally now, to fetch the stored post. We then perform a similar check as in the previous test. We also want to test if the owner data of the post is correct, but for that we need to get access to the account that created the post in the first place.
|
||||
|
||||
Luckily wallet accounts can be easily accessed as they are emitted by Embark's `config()` function. All we have to do is attaching a resolution handler to `config()` and storing the emitted value:
|
||||
|
||||
```
|
||||
...
|
||||
let accounts = [];
|
||||
|
||||
config({
|
||||
contracts: {
|
||||
DReddit: {}
|
||||
}
|
||||
}, (err, _accounts) => {
|
||||
accounts = _accounts;
|
||||
});
|
||||
```
|
||||
|
||||
Having that in place, our next test could look something like this:
|
||||
|
||||
```
|
||||
it ('post should have correct data', async () => {
|
||||
const post = await DReddit.methods.posts(postId).call();
|
||||
assert.equal(web3.utils.toAscii(post.description), ipfsHash);
|
||||
assert.equal(post.owner, accounts[0]);
|
||||
});
|
||||
```
|
||||
|
||||
You might notice that we're referring to `accounts[0]` here. However, just by looking at the code, we can't really know if `accounts[0]` is really the one we're expecting. This is where Embark offers another helping hand. When the `accounts` are set up, Embark will automatically set the first account of the wallet (`accounts[0]`) to the default account that'll be used for all transactions. With that knowledge we can make an assertion, expecting `accounts[0]` to be the owner of the post.
|
||||
|
||||
Another way would be to just always explicitly pass any of the accounts to a Smart Contract method's `send()` function, in which case we'd have full control over which account of the wallet will be used.
|
||||
|
||||
## Testing `canVote()`
|
||||
|
||||
Alright, next up let's quickly test if our `canVote()` method works the way as expected. As voting on posts that don't exist should never work, we will simply call `canVote()` on a post id that doesn't exist. This test is pretty straight forward:
|
||||
|
||||
```
|
||||
it('should not be able to vote in an unexisting post', async () => {
|
||||
const userCanVote = await DReddit.methods.canVote("123").call();
|
||||
assert.equal(userCanVote, false);
|
||||
});
|
||||
```
|
||||
|
||||
We also want to make sure that `canVote()` resolves to `true` in case a user can indeed vote a certain post. We can again reuse the `postId` that we've stored earlier:
|
||||
|
||||
```
|
||||
it('should be able to vote in a post if account has not voted before', async () => {
|
||||
const userCanVote = await DReddit.methods.canVote(postId).call();
|
||||
assert.equal(userCanVote, true);
|
||||
});
|
||||
```
|
||||
|
||||
Wonderful, we have 5 passing tests now!
|
||||
|
||||
## Testing `vote()`
|
||||
|
||||
Of course we want to test whether one of our application's core features works as well. There's certainly different ways to verify whether `vote()` does what it's supposed to do, but for this tutorial we'll simply check whether the owner account of the vote emitted by the `NewVote` event is the same as the account that performed the vote. We can actually take some inspiration from our previous tests:
|
||||
|
||||
```
|
||||
it("should be able to vote in a post", async () => {
|
||||
const receipt = await DReddit.methods.vote(postId, 1).send();
|
||||
const Vote = receipt.events.NewVote;
|
||||
assert.equal(Vote.returnValues.owner, accounts[0]);
|
||||
});
|
||||
```
|
||||
|
||||
## Test that only one vote per post is allowed
|
||||
|
||||
The last but essential functionality we want to test is that whether our Smart Contract allows users to vote multiple times on the same post, which for obvious reasons shouldn't be possible. Using the `async/await` syntax we can test this very nicely by adding a `try/catch` block. When a user votes on a post she has already voted on, `vote()` will fail in which case we can make our assertions accordingly:
|
||||
|
||||
```
|
||||
it('should not be able to vote twice', async () => {
|
||||
try {
|
||||
const receipt = await DReddit.methods.vote(postId, 1).send();
|
||||
assert.fail('should have reverted');
|
||||
} catch (error){
|
||||
assert(error.message.search('revert') > -1, 'Revert should happen');
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
This might look a bit confusing first but it's actually pretty straight forward. In case `vote()` fails, we should not reach the `assert.fail()` call but end up in the `catch()` block immediately. If that was not the case, the test would fail. This is a very common pattern when testing negatives.
|
||||
|
||||
Okay, one last time we run `embark test` and if the output looks like the following, we're fully covered in terms of tests!
|
||||
|
||||
|
||||
```
|
||||
❯ embark test
|
||||
Compiling contracts
|
||||
|
||||
|
||||
DReddit
|
||||
✓ should work (0ms) - [0 gas]
|
||||
✓ should be able to create a post and receive it via contract event (60ms) - [160689 gas]
|
||||
✓ post should have correct data (18ms) - [0 gas]
|
||||
✓ should not be able to vote in an unexisting post (14ms) - [0 gas]
|
||||
✓ should be able to vote in a post if account hasn't voted before (12ms) - [0 gas]
|
||||
✓ should be able to vote in a post (42ms) - [65115 gas]
|
||||
✓ shouldn't be able to vote twice (37ms) - [22815 gas]
|
||||
|
||||
|
||||
7 passing (5s) - [Total: 3130955 gas]
|
||||
|
||||
> All tests passed
|
||||
```
|
||||
|
||||
Awesome! If you run into any issues, check out the repository with all steps recorded [here](https://github.com/embark-framework/dreddit-tutorial). In [the next and last part of this series](/news/2019/02/18/building-a-decentralized-reddit-with-embark-part-3/), we'll be building a front-end for our DReddit app using React. Until then, feel free to add more tests as you like!
|
@ -0,0 +1,875 @@
|
||||
title: Building a decentralized Reddit with Embark - Part 3
|
||||
summary: "In this third and last part of the tutorial series about building a decentralized Reddit with Embark, we're building the front-end for our application using React and EmbarkJS."
|
||||
categories:
|
||||
- tutorials
|
||||
layout: blog-post
|
||||
author: pascal_precht
|
||||
alias: news/2019/02/17/building-a-decentralized-reddit-with-embark-part-3/
|
||||
---
|
||||
|
||||
Hopefully you've read [the first](/news/2019/02/04/building-a-decentralized-reddit-with-embark-part-1/) and [second part](/news/2019/02/11/building-a-decentralized-reddit-with-embark-part-2/) of this tutorial on building a decentralized Reddit application using Embark. If not, we highly recommend you doing so, because in this part, we'll be focussing on building the front-end for our application and continue where we've left off.
|
||||
|
||||
- [**Part 1** - Setting up the project and implementing a Smart Contract](/news/2019/02/04/building-a-decentralized-reddit-with-embark-part-1/)
|
||||
- [**Part 2** - Testing the Smart Contract through EmbarkJS](/news/2019/02/11/building-a-decentralized-reddit-with-embark-part-2/)
|
||||
|
||||
We'll be using React as a client-side JavaScript library to build our application. However, we can use any framework of our choice, so feel free to follow along while using your favourite framework equivalents!
|
||||
|
||||
**The code for this tutorial can be found in [this repository](https://github.com/embark-framework/dreddit-tutorial)**.
|
||||
|
||||
## Rendering our first component
|
||||
|
||||
Alright, before we jump straight into building components that will talk to our Smart Contract instance, let's first actually render a simple text on the screen just to make sure our setup is working correctly.
|
||||
|
||||
For that, what we'll do is adding React as a dependency to our project. In fact, we'll be relying on two packages - `react` and `react-dom`. The latter is needed to render components defined with React in a DOM environment, which is what a Browser essentially is.
|
||||
|
||||
Let's add the following `dependencies` section to our projects `package.json`:
|
||||
|
||||
```
|
||||
"dependencies": {
|
||||
"react": "^16.4.2",
|
||||
"react-dom": "^16.4.2"
|
||||
}
|
||||
```
|
||||
|
||||
Once that is done we need to actually install those dependencies. For that we simply execute the following command in our terminal of choice:
|
||||
|
||||
```
|
||||
$ npm install
|
||||
```
|
||||
|
||||
Now we can go ahead and actually make use of React. As Embark is framework agnostic, we won't be focussing too much on details specific to React, just the least amount that is needed to make our app work.
|
||||
|
||||
Creating components in React is pretty straight forward. All we need to do is creating a class that extends React's `Component` type and add a `render()` method that will render the component's view.
|
||||
|
||||
Let's create a folder for all of our components inside our projects:
|
||||
|
||||
```
|
||||
$ mkdir app/js/components
|
||||
```
|
||||
|
||||
Next, we create a file for our root component. We call it simply `App` and use the same file name:
|
||||
|
||||
```
|
||||
$ touch app/js/components/App.js
|
||||
```
|
||||
|
||||
Alright, as mentioned earlier, we really just want to render some text on the screen for starters. Here's what that could look like:
|
||||
|
||||
```
|
||||
import React, { Component } from 'react';
|
||||
|
||||
export class App extends Component {
|
||||
|
||||
render() {
|
||||
return <h1>DReddit</h1>
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
This is probably self explanatory, but all we're doing here is importing `React` and its `Component` type and create an `App` class that extends `Component`. The `render()` method will be used by React to render the component's view and has to return a template that is written in JSX syntax. JSX looks a lot like HTML just that it comes with extra syntax to embed things like control structures. We'll make use of that later!
|
||||
|
||||
Okay now that we have this component defined, we need to tell React to actually render this particular component. For that, we head over to `app/js/index.js` and add the following code:
|
||||
|
||||
```
|
||||
import React from 'react';
|
||||
import { render } from 'react-dom';
|
||||
import { App } from './components/App';
|
||||
|
||||
render(<App />, document.getElementById('root'));
|
||||
```
|
||||
|
||||
We need to import `React` again as it has to be available in this script's scope. We also import a `render` function from `react-dom`, which is used to render our root component (`App`) into some element inside our HTML document. In this case we say that the element in which we want to render our root component is the element with the id `root`.
|
||||
|
||||
Let's set this up really quick. In `app/index.html` add a new element with a `root` id:
|
||||
|
||||
```
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script src="js/app.js"></script>
|
||||
</body>
|
||||
```
|
||||
|
||||
Notice that we've also moved the `script` tag inside the body tag, after the element with the `root` id. This is just one way to work around the fact that the element we're referencing inside our `render()` method is actually available in the document at the time the script is executed.
|
||||
|
||||
That should do it! Let's spin up Embark, we should then see our component rendered on the screen:
|
||||
|
||||
```
|
||||
$ embark run
|
||||
```
|
||||
|
||||
## Building a `CreatePost` component
|
||||
|
||||
Alright, enough warm up. Time to build components that are useful. We start off with building a component that lets users create posts through our application. Similar to `App`, we'll introduce a new component `createPost` that comes with a `render()` method to display a simple form for entering data. We'll also need to add event handlers to the form so that when a user submits the form, we can actually access the data and later on send it to our Smart Contract.
|
||||
|
||||
Creating a simple form is very straight forward:
|
||||
|
||||
```
|
||||
import React, { Component } from 'react';
|
||||
|
||||
export class CreatePost extends Component {
|
||||
|
||||
render() {
|
||||
return (
|
||||
<form>
|
||||
<div>
|
||||
<label>Topic</label>
|
||||
<input type="text" name="topic" />
|
||||
</div>
|
||||
<div>
|
||||
<textarea name="content"></textarea>
|
||||
</div>
|
||||
<button>Post</button>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
To actually render this component on screen, we need to make it part of our `App` component. Or, to be more specific, have the `App` component render our `CreatePost` component. For now we can simply add it to `App`'s render function like this;
|
||||
|
||||
|
||||
```
|
||||
import { CreatePost } from './CreatePost';
|
||||
|
||||
export class App extends Component {
|
||||
|
||||
render() {
|
||||
return (
|
||||
<React.Fragment>
|
||||
<h1>DReddit</h1>
|
||||
<CreatePost />
|
||||
</React.Fragment&>
|
||||
)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
React doesn't allow for multiple root elements in a single component's view, so we have to take advantage of `React.Fragment`. Obviously, there's not too much going on here apart from us rendering a static form. Also notice that we don't spend too much time and effort on making the form look nice as we focus on the functionality for now. Consider that homework!
|
||||
|
||||
Let's make this form functional. First of all we want make sure that data entered into the form is available inside our component. React components maintain an object called `state` that can be used for exactly that. All we have to do is to initialize it with some initial values and update it using a `setState()` method if needed.
|
||||
|
||||
Let's introduce `state` in our component by adding a constructor and initializing it accordingly:
|
||||
|
||||
```
|
||||
export class CreatePost extends Component {
|
||||
|
||||
constructor(props) {
|
||||
super(props);
|
||||
|
||||
this.state = {
|
||||
topic: '',
|
||||
content: '',
|
||||
loading: false
|
||||
};
|
||||
}
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
Next we bind that state to our form fields:
|
||||
|
||||
```
|
||||
<form>
|
||||
<div>
|
||||
<label>Topic</label>
|
||||
<input type="text" name="topic" value={this.state.topic} />
|
||||
</div>
|
||||
<div>
|
||||
<textarea name="content" value={this.state.content}></textarea>
|
||||
</div>
|
||||
<button>Post</button>
|
||||
</form>
|
||||
```
|
||||
|
||||
No worries, we'll make use of `loading` in a second. Last but not least we want to add some event handlers so that changes in the view will be reflected back to our component's state as the user is entering data. To make sure everything works fine, we'll also add an event handler for the form submission and output the data in `state`. Here's what our `handleChange()` and `createPost()` handlers looks like:
|
||||
|
||||
```
|
||||
export class CreatePost extends Component {
|
||||
...
|
||||
handleChange(field, event) {
|
||||
this.setState({
|
||||
[field]: event.target.value
|
||||
});
|
||||
}
|
||||
|
||||
createPost(event) {
|
||||
event.preventDefault();
|
||||
console.log(this.state);
|
||||
}
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
Notice how we're using `setState()` inside `handleChange()` to update whatever field name has been passed to that method. Now all we need to do is attach those handlers to our form:
|
||||
|
||||
```
|
||||
<form onSubmit={e => createPost(e)}>
|
||||
<div>
|
||||
<label>Topic</label>
|
||||
<input
|
||||
type="text"
|
||||
name="topic"
|
||||
value={this.state.topic}
|
||||
onChange={e => handleChange('topic', e)} />
|
||||
</div>
|
||||
<div>
|
||||
<textarea
|
||||
name="content"
|
||||
value={this.state.content}
|
||||
onChange={e => handleChange('content', e})></textarea>
|
||||
</div>
|
||||
<button type="submit">Post</button>
|
||||
</form>
|
||||
```
|
||||
|
||||
Since we're using the `onSubmit()` handler of the form, it's also important that we either add a `type="submit"` to our `button` or change the button to an `<input type="submit">` element. Otherwise, the form won't emit a submit event.
|
||||
|
||||
Nice! With that in place, we should see the component's `state` in the console when submitting the form! The next challenge is to use `EmbarkJS` and its APIs to make our component talk to our Smart Contract instance.
|
||||
|
||||
### Uploading data to IPFS
|
||||
|
||||
Recall from our [first part](/news/2019/02/04/building-a-decentralized-reddit-with-embark-part-1/#Creating-posts) of this tutorial that our `DReddit` Smart Contract comes with a `createPost()` method that takes some bytes as post data. Those bytes are actually not the post data itself, but an IPFS hash that points to the post data. In other words, we'll have to somehow create such a hash and make sure the data is uploaded to IPFS as well.
|
||||
|
||||
Luckily, EmbarkJS comes with plenty of convenient APIs to do exactly that! `EmbarkJS.Storage.saveText()` takes a string, uploads it to IPFS and returns its hash which can then be used to create a post using our Smart Contract. One thing to keep in mind is that those APIs are asynchronous. Similar to how we wrote tests in [part two](/news/2019/02/11/building-a-decentralized-reddit-with-embark-part-2/#Testing-createPost) of this tutorial, we'll use `async/await` to write asynchronous code in a synchronous fashion.
|
||||
|
||||
```
|
||||
async createPost(event) {
|
||||
event.preventDefault();
|
||||
|
||||
this.setState({
|
||||
loading: true
|
||||
});
|
||||
|
||||
const ipfsHash = await EmbarkJS.Storage.saveText(JSON.stringify({
|
||||
topic: this.state.topic,
|
||||
content: this.state.content
|
||||
}));
|
||||
|
||||
this.setState({
|
||||
topic: '',
|
||||
content: '',
|
||||
loading: false
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
We use `JSON.stringify()` on an object that holds the `topic` and `content` of the post to be created. This is also the first time we put `loading` into action. Setting it to `true` before, and `false` after we've performed our operations lets us render a useful message as the user is waiting for updates.
|
||||
|
||||
```
|
||||
<form onSubmit={e => createPost(e)}>
|
||||
...
|
||||
{this.state.loading &&
|
||||
<p>Posting...</p>
|
||||
}
|
||||
</form>
|
||||
```
|
||||
|
||||
Obviously, we're not done yet though. All we do right now is uploading the post's data to IPFS and receiving the hash, but we still need to take that hash and send it to our Smart Contract using its `createPost()` method. Let's do that!
|
||||
|
||||
### Sending transactions to create posts
|
||||
|
||||
To send a transaction to our Smart Contract, we can again take advantage of EmbarkJS' APIs, similar to how we did it in the [second part](/news/2019/02/11/building-a-decentralized-reddit-with-embark-part-2). We also need to get hold of an Ethereum account to send the transaction from. This will be very straight forward as we'll be just relying on the accounts that are generated by the Ethereum node that Embark spins up for us.
|
||||
|
||||
Once we have those things in place we can get a gas estimation for our transaction and send the data over. Here's how we retrieve our accounts, notice that `async/await` can be used here as well:
|
||||
|
||||
```
|
||||
async createPost(event) {
|
||||
...
|
||||
const accounts = await web3.eth.getAccounts();
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
Next up we'll import a `DReddit` Smart Contract instance from EmbarkJS and use it to get a gas estimation from `web3`. We can then use the estimation and one of our accounts to actually send the transaction:
|
||||
|
||||
```
|
||||
import DReddit from './artifacts/contracts/DReddit';
|
||||
...
|
||||
|
||||
async createPost(event) {
|
||||
...
|
||||
const accounts = await web3.eth.getAccounts();
|
||||
const createPost = DReddit.methods.createPost(web3.utils.toHex(ipfsHash));
|
||||
const estimate = await createPost.estimateGas();
|
||||
|
||||
await createPost.send({from: accounts[0], gas: estimate});
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
Sweet, with that, our `createPost` method is done! We haven't built a list of all created posts yet, but if we open up the app and create a post, we can use Embark to double check whether the transaction went through successfully. Simply watch the output in the terminal after running `embark run`. We should see a confirmation that looks something like this:
|
||||
|
||||
```
|
||||
Blockchain> DReddit.createPost("0x516d5452427a47415153504552614645534173335133765a6b59436633634143776368626263387575623434374e") | 0xbbeb9fa1eb4e3434c08b31409c137c2129de65eb335855620574c537b3004f29 | gas:136089 | blk:18455 | status:0x1
|
||||
```
|
||||
|
||||
## Creating a Post component
|
||||
|
||||
The next challenge lies in fetching all created posts from our Smart Contract and IPFS so we can render them on screen. We start simple and first create a new component that will render a single post. After that we'll look into rendering a list of posts dynamically, based on the data we're fetching.
|
||||
|
||||
Again, our application won't look particularly pretty, we'll just focus on getting the core functionality right. A post component needs to render the post topic, its content, the owner of the post, ideally the date when it has been created, and a button to up and down vote respectively.
|
||||
|
||||
Here's what such a component with a basic template could look like:
|
||||
|
||||
```
|
||||
import React, { Component } from 'react';
|
||||
|
||||
export class Post extends Component {
|
||||
|
||||
render() {
|
||||
return (
|
||||
<React.Fragment>
|
||||
<hr />
|
||||
<h3>Some Topic</h3>
|
||||
<p>This is the content of a post</p>
|
||||
<p><small><i>created at 2019-02-18 by 0x00000000000000</i></small></p>
|
||||
<button>Upvote</button>
|
||||
<button>Downvote</button>
|
||||
</React.Fragment>
|
||||
)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
There are different ways to make the data being rendered dynamic. Usually, we would probably pass a one or more properties to the `Post` component that represents the entire post object and can then be displayed inside its `render()` method. However, for this tutorial we're going to choose a slightly different path. We'll make `Post` receive IPFS hash that's stored in the Smart Contract and have it resolve the data itself.
|
||||
|
||||
Let's stay consistent with our naming and say the property we're expecting to be filled with data is called `description`, just like the one used inside the Smart Contract. We can then use `EmbarkJS.Storage.get()` with the IPFS hash to fetch the data that represents the actual post. In order to render the data inside `Post`'s view, we'll parse it and use `setState()` accordingly.
|
||||
|
||||
To make sure all of that happens once the component is ready to do its work, we'll do all of that inside its `componentDidMount()` life cycle hook:
|
||||
|
||||
```
|
||||
import React, { Component } from 'react';
|
||||
import EmbarkJS from '.artifacts/embarkjs';
|
||||
|
||||
export class Post extends Component {
|
||||
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.state = {
|
||||
topic: '',
|
||||
content: ''
|
||||
};
|
||||
}
|
||||
|
||||
async componentDidMount() {
|
||||
const ipfsHash = web3.utils.toAscii(this.props.description);
|
||||
const data = await EmbarkJS.Storage.get(ipfsHash);
|
||||
const { topic, content } = JSON.parse(data);
|
||||
|
||||
this.setState({ topic, content });
|
||||
}
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
There's one gotcha to keep in mind here: Calling `EmbarkJS.Storage.get()` or any `EmbarkJS` function on page load can fail, because the storage system might not be fully initialized yet. This wasn't a problem for the previous `EmbarkJS.Storage.uploadText()` because we called that function well after Embark had finished initializing
|
||||
|
||||
Theoretically however, there could be a race condition even for creating a post. To ensure that EmbarkJS is ready at any point in time, we use its `onReady()` hook. `EmbarkJS.onReady()` takes a callback which will be executed once EmbarkJS is ready to go. The best place to do this in our app is probably where we attempt to render our application, so let's wrap that `render()` call in our `App` component inside Embark's `onReady()` function.
|
||||
|
||||
```
|
||||
EmbarkJS.onReady(() => {
|
||||
render(<App />, document.getElementById('root'));
|
||||
});
|
||||
```
|
||||
|
||||
This also means our app will only render when EmbarkJS is ready, which theoretically could take a little longer. However in this tutorial, chances are very low this is becoming a problem.
|
||||
|
||||
Let's also quickly add the `owner` and creation date. The `owner` is expected to be passed down as a property. The same goes for the creation date. We just need to make sure it'll be formatted in a way the users can make sense of the data. We'll use the `dateformat` library for that and install it as a dependency like this:
|
||||
|
||||
```
|
||||
$ npm install --save dateformat
|
||||
```
|
||||
|
||||
Once that is done, we can update our `Post` component's `render()` function to calculate a properly formatted date based on the `creationDate` that has been passed down through properties:
|
||||
|
||||
```
|
||||
...
|
||||
import dateformat from 'dateformat';
|
||||
|
||||
export class Post extends Component {
|
||||
...
|
||||
render() {
|
||||
const formattedDate = dateformat(
|
||||
new Date(this.props.creationDate * 1000),
|
||||
'yyyy-mm-dd HH:MM:ss'
|
||||
);
|
||||
return (
|
||||
<React.Fragment>
|
||||
<hr />
|
||||
<h3>{this.state.topic}</h3>
|
||||
<p>{this.state.content}</p>
|
||||
<p><small><i>created at {formattedDate} by {this.props.owner}</i></small></p>
|
||||
<button>Upvote</button>
|
||||
<button>Downvote</button>
|
||||
</React.Fragment>
|
||||
)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Notice that variables created inside `render()` can be interpolated as they are - there's no need to make them available on `props` or `state`. As a matter of fact, `props` are always considered read only in React.
|
||||
|
||||
Let's try out our new `Post` component with some static data by adding it to our `App` component's view. Next up, we'll make this dynamic by fetching the posts from our Smart Contract.
|
||||
|
||||
**Attention**: The hash used in this snippet might not be available in your local IPFS node, so you'll have to get hold of your own hash. This can be down by logging out the hash that is returned from IPFS and convert it to hex code.
|
||||
|
||||
```
|
||||
export class App extends Component {
|
||||
|
||||
render() {
|
||||
return (
|
||||
<React.Fragment>
|
||||
<h1>DReddit</h1>
|
||||
<CreatePost />
|
||||
<Post
|
||||
description="0x516d655338444b53464546725369656a747751426d683377626b56707566335770636e4c715978726b516e4b5250"
|
||||
creationDate="1550073772"
|
||||
owner="0x00000000000"
|
||||
/>
|
||||
</React.Fragment>
|
||||
)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Creating a List component
|
||||
|
||||
Before we can move on with building a component that renders a list of posts, we'll have to extend our Smart Contract with one more method. Since there's no canonical way to fetch array data from a Smart Contract, we'll be fetching the post data for each post one by one. We do that by first fetching the total number of posts and use that number to iterate over the available indices, which we can then use to fetch the actual posts.
|
||||
|
||||
Let's introduce a method `numPosts()` in our `DReddit` Smart Contract:
|
||||
|
||||
```
|
||||
function numPosts() public view returns (uint) {
|
||||
return posts.length;
|
||||
}
|
||||
```
|
||||
|
||||
`posts.length` will increase as we're adding posts, so it will always be the single source of truth when it comes to determining indices of posts. This would be a good opportunity to write another test - we'll leave that up to you!
|
||||
|
||||
With that in place, we can start building a new `List` component. The `List` component maintains a list of posts to render on screen, so we can start simple again and introduce the bare minimum like this:
|
||||
|
||||
```
|
||||
import React, { Component } from 'react';
|
||||
|
||||
export class List extends Component {
|
||||
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.state = {
|
||||
posts: []
|
||||
};
|
||||
}
|
||||
|
||||
render() {
|
||||
return (<React.Fragment>
|
||||
{this.state.posts.map(post => {
|
||||
return (
|
||||
<Post
|
||||
key={post.id}
|
||||
description={post.description}
|
||||
creationDate={post.creationDate}
|
||||
owner={post.owner}
|
||||
/>)
|
||||
})}
|
||||
</React.Fragment>
|
||||
)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The most interesting part here is probably the `render()` method, in which we iterate over all `state.posts` (which at the moment is empty) and then render a `Post` component for every iteration. Another thing to note is that every `Post` receives a `key`. This is required in React when creating views from loops. We've never introduced a `post.id` in this tutorial, but don't worry, we'll fix that in a moment.
|
||||
|
||||
We can already put that in our `App` component. It won't render anything as we haven't fetched any posts yet, but that's what we'll do next.
|
||||
|
||||
|
||||
```
|
||||
import { List } from './List';
|
||||
|
||||
export class App extends Component {
|
||||
|
||||
render() {
|
||||
return (
|
||||
<React.Fragment>
|
||||
<h1>DReddit</h1>
|
||||
<CreatePost />
|
||||
<List />
|
||||
</React.Fragment>
|
||||
)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Fetching posts data
|
||||
|
||||
Let's fill our new `List` component with life! As mentioned earlier, we'll use our Smart Contract's `numPosts()` method to get hold of the total number of posts available. We then use that number to iterate over all indices and request every post individually. Since this is logic we want to execute once the `List` component is ready, we'll use its `componentDidMount()` method for that:
|
||||
|
||||
```
|
||||
export class List extends Component {
|
||||
...
|
||||
async componentDidMount() {
|
||||
const totalPosts = await DReddit.methods.numPosts().call();
|
||||
|
||||
let list = [];
|
||||
|
||||
for (let i = 0; i < totalPosts; i++) {
|
||||
const post = DReddit.methods.posts(i).call();
|
||||
list.push(post);
|
||||
}
|
||||
|
||||
list = await Promise.all(list);
|
||||
}
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
Notice that in the above code we don't `await` the calls to every individual post. This is on purpose as we don't want to wait on each and every promise to resolve, but first collect all of the promises we need and then resolve them all in one go using `Promise.all().`
|
||||
|
||||
Last but not least, we need to add an `id` property to every post as mentioned earlier. This is easily done by simply iterating over all posts and assigning the post's index as `id`. Once that is done, we can use `setState()` to update our component's state and render the list:
|
||||
|
||||
```
|
||||
async componentDidMount() {
|
||||
...
|
||||
list = list.map((post, index) => {
|
||||
post.id = index;
|
||||
return post;
|
||||
});
|
||||
|
||||
this.setState({ posts: list });
|
||||
}
|
||||
```
|
||||
|
||||
That's it! Our application now renders a list of all created posts. Unfortunately, posts are not being re-fetched automatically when adding new posts. For the time being, we'll have to reload the browser every time after adding a post. However, this we'll address now.
|
||||
|
||||
### Reloading posts
|
||||
|
||||
There is certainly different ways to make the list of posts update automatically, so take the following approach with a grain of salt. What we need is a way to have the `createPost` component tell the `List` component to reload its posts. However, there's no communication layer in place when building a simple React app like this, so the most straight forward way to make this possible, is to move the logic of loading the posts in the parent component of `CreatePost` and `List` (in our case `App`), and have it pass that logic down to places where its needed. This also means we'll be fetching the list inside `App` and pass down the pure data to `List`.
|
||||
|
||||
If this sounds overwhelming, no worries, it's more trivial than that! Let's start by introducing a `loadPosts()` function in our `App` component. Essentially we're moving everything from `List`'s `componentDidMount()` function into `App`:
|
||||
|
||||
```
|
||||
export class App extends Component {
|
||||
...
|
||||
async loadPosts() {
|
||||
const totalPosts = await DReddit.methods.numPosts().call();
|
||||
|
||||
let list = [];
|
||||
|
||||
if (totalPosts > 0) {
|
||||
for (let i = 0; i < totalPosts; i++) {
|
||||
const post = DReddit.methods.posts(i).call();
|
||||
list.push(post);
|
||||
}
|
||||
}
|
||||
|
||||
list = await Promise.all(list);
|
||||
list = list.map((post, index) => {
|
||||
post.id = index;
|
||||
return post;
|
||||
});
|
||||
|
||||
list;
|
||||
|
||||
this.setState({ posts: list });
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
To make this work we also need to introduce a `state` with the dedicated `posts`. After that, we make sure `loadPosts()` is called when `App` is mounted:
|
||||
|
||||
```
|
||||
export class App extends Component {
|
||||
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.state = {
|
||||
posts: []
|
||||
};
|
||||
}
|
||||
|
||||
async componentDidMount() {
|
||||
await this.loadPosts();
|
||||
}
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
Last but not least, all we have to do is to pass the `posts` down to `List` and `loadPosts()` to `CreatePost` as a callback handler if you will:
|
||||
|
||||
```
|
||||
render() {
|
||||
return (
|
||||
<React.Fragment>
|
||||
<h1>DReddit</h1>
|
||||
<CreatePost afterPostHandler={this.loadPosts.bind(this)}/>
|
||||
<List posts={this.state.posts}/>
|
||||
</React.Fragment>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
Once that is done, we can consume `posts` and `afterPostHandler()` from `this.props` respectively. In `List`'s `render()` function we'll do (notice we don't rely on `this.state` anymore):
|
||||
|
||||
```
|
||||
render() {
|
||||
return (<React.Fragment>
|
||||
{this.props.posts.map(post => {
|
||||
...
|
||||
})}
|
||||
</React.Fragment>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
And in `CreatePost` we call `afterPostHandler()` after a post has been created:
|
||||
|
||||
```
|
||||
async createPost(event) {
|
||||
...
|
||||
await createPost.send({from: accounts[0], gas: estimate});
|
||||
await this.props.afterPostHandler();
|
||||
|
||||
this.setState({
|
||||
topic: '',
|
||||
content: '',
|
||||
loading: false
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
Wonderful! The list now automatically reloads after creating posts, give it a try!
|
||||
|
||||
## Add voting functionality
|
||||
|
||||
The final feature we'll be implementing is the up and down voting of posts. This is where we come back to our `Post` component that we've created earlier. In order to make this feature complete we'll have to:
|
||||
|
||||
- Render the number of up and down votes per post
|
||||
- Add handlers for users to up and down vote
|
||||
- Determine if a user can vote on a post
|
||||
|
||||
### Rendering number of votes
|
||||
Let's start with the first one, as it's the most trivial one. While the number of up and down votes is already attached to the data that we receive from our `DReddit` Smart Contract, it's not yet in the right format as it comes back as a string. Let's make sure we parse the up and down vote counts on posts by extending our `App`'s `loadPosts()` method like this:
|
||||
|
||||
```
|
||||
async loadPosts() {
|
||||
...
|
||||
list = list.map((post, index) => {
|
||||
post.id = index;
|
||||
post.upvotes = parseInt(post.upvotes, 10);
|
||||
post.downvotes = parseInt(post.downvotes, 10);
|
||||
return post;
|
||||
});
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
Once that is done we can pass each post's `upvotes` and `downvotes` to every `Post` component via its `props` inside our `List` component:
|
||||
|
||||
```
|
||||
export class List extends Component {
|
||||
...
|
||||
render() {
|
||||
return (<React.Fragment>
|
||||
{this.props.posts.map(post => {
|
||||
return (<Post
|
||||
key={post.id}
|
||||
description={post.description}
|
||||
creationDate={post.creationDate}
|
||||
upvotes={post.upvotes}
|
||||
downvotes={post.downvotes}
|
||||
owner={post.owner}
|
||||
/>)
|
||||
})}
|
||||
</React.Fragment>
|
||||
)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Rendering the number of `upvotes` and `downvotes` is then really just a matter of interpolating them in `Post`'s `render()` function. We're just going to add them next to the buttons, but feel free to put them somewhere else:
|
||||
|
||||
```
|
||||
export class Post extends Component {
|
||||
...
|
||||
render() {
|
||||
...
|
||||
return (
|
||||
<React.Fragment>
|
||||
...
|
||||
{this.props.upvotes} <button>Upvote</button>
|
||||
{this.props.downvotes} <button>Downvote</button>
|
||||
</React.Fragment>
|
||||
)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Implement up and down votes
|
||||
|
||||
Similar to when creating new posts, making the up and down vote buttons work requires sending transactions to our `DReddit` Smart Contract. So we'll do almost the same thing as in our `CreatePost` component, just that we're calling the Smart Contract's `vote()` method. If you recall, the `vote()` method takes a post id and the vote type, which is either `NONE`, `UPVOTE` or `DOWNVOTE` and are stored as `uint8`.
|
||||
|
||||
It makes sense to introduce the same representation in our app so we can use descriptive names, but rely on uint values at the same time. There are no enum data structures in JavaScript so we'll use a hash object instead:
|
||||
|
||||
```
|
||||
const BALLOT = {
|
||||
NONE: 0,
|
||||
UPVOTE: 1,
|
||||
DOWNVOTE: 2
|
||||
}
|
||||
```
|
||||
|
||||
We don't actually have the post id available in our `Post` component yet. That's easily added in our `List` component, by now you should know how to do that!
|
||||
|
||||
We can then add click handlers to our up and down vote buttons and pass one of the `BALLOT` types to them (notice that we added `BALLOT.NONE` only for completeness-sake but don't actually use it in our code):
|
||||
|
||||
```
|
||||
<button onClick={e => this.vote(BALLOT.UPVOTE)}>Upvote</button>
|
||||
<button onClick={e => this.vote(BALLOT.DOWNVOTE)}>Downvote</button>
|
||||
```
|
||||
|
||||
The next thing we need to do is sending that vote type along with the post id to our Smart Contract:
|
||||
|
||||
```
|
||||
async vote(ballot) {
|
||||
const accounts = await web3.eth.getAccounts();
|
||||
const vote = DReddit.methods.vote(this.props.id, ballot);
|
||||
const estimate = await vote.estimateGas();
|
||||
|
||||
await vote.send({from: accounts[0], gas: estimate});
|
||||
}
|
||||
```
|
||||
|
||||
Obviously, we also want to update the view when a vote has been successfully sent. Right now we're reading a post's up and down votes from its `props` and render them accordingly. However, we want to update those values as votes are coming in. For that we'll change our code to only read the up and down votes from `props` once and store them in the component's state.
|
||||
|
||||
```
|
||||
export class Post extends Component {
|
||||
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.state = {
|
||||
topic: '',
|
||||
content: '',
|
||||
upvotes: this.props.upvotes,
|
||||
downvotes: this.props.downvotes
|
||||
};
|
||||
}
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
We also change the component's view to render the values from state instead of `props`:
|
||||
|
||||
```
|
||||
render() {
|
||||
...
|
||||
return (
|
||||
<React.Fragment>
|
||||
...
|
||||
{this.state.upvotes} <button ...>Upvote</button>
|
||||
{this.state.downvotes} <button ...>Downvote</button>
|
||||
</React.Fragment>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
After that we can update the state with new votes using `setState()`, right after a vote has been sent:
|
||||
|
||||
```
|
||||
async vote(ballot) {
|
||||
...
|
||||
this.setState({
|
||||
upvotes: this.state.upvotes + (ballot == BALLOT.UPVOTE ? 1 : 0),
|
||||
downvotes: this.state.downvotes + (ballot == BALLOT.DOWNVOTE ? 1 : 0)
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
**That's it!** We can now up and down vote on posts...but only once! Yes, that's right. When we try to vote multiple times on the same post, we'll actually receive an error. That's because, if you remember, there's a restriction in our Smart Contract that makes sure users can not vote on posts that they've either already voted on, or created themselves.
|
||||
|
||||
Let's make sure this is reflected in our application's UI and wrap up this tutorial!
|
||||
|
||||
### Use `canVote()` to disable vote buttons
|
||||
|
||||
We'll keep this one very simple - if a user cannot vote on a post, the voting buttons should be simply disabled. We can easily determine whether a user is allowed to vote by calling our Smart Contract's `canVote()` method. Another thing we need to consider is that we shouldn't allow a user to vote when a vote for the same post is already in flight but hasn't completed yet.
|
||||
|
||||
Let's introduce a new state properties for that first. In general we can say that a user is allowed to vote, and that she is not submitting a vote in this very moment:
|
||||
|
||||
```
|
||||
export class Post extends Component {
|
||||
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.state = {
|
||||
topic: '',
|
||||
content: '',
|
||||
upvotes: this.props.upvotes,
|
||||
downvotes: this.props.downvotes,
|
||||
canVote: true,
|
||||
submitting: false
|
||||
};
|
||||
}
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
Next, we update our `Post` component's `render()` function to disable the voting buttons if a vote is in flight, or a user is simply not allowed to vote:
|
||||
|
||||
```
|
||||
render() {
|
||||
...
|
||||
const disabled = this.state.submitting || !this.state.canVote;
|
||||
return (
|
||||
<React.Fragment>
|
||||
...
|
||||
{this.state.upvotes} <button disabled={disabled} ...>Upvote</button>
|
||||
{this.state.downvotes} <button disabled={disabled} ...>Downvote</button>
|
||||
</React.Fragment>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
Last but not least, we have to make sure the state properties are updated accordingly. We'll call our Smart Contract's `canVote()` method when a post is initialized:
|
||||
|
||||
```
|
||||
export class Post extends Component {
|
||||
...
|
||||
async componentDidMount() {
|
||||
...
|
||||
const canVote = await DReddit.methods.canVote(this.props.id).call();
|
||||
this.setState({ topic, content, canVote });
|
||||
}
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
And when a vote is being made, we set `submitting` to `true` right before we send a transaction and set it back to `false` again when the transaction is done. At this point, we also know that a vote has been made on this post, so `canVote` can be set to `false` at the same time:
|
||||
|
||||
```
|
||||
async vote(ballot) {
|
||||
...
|
||||
this.setState({ submitting: true });
|
||||
await vote.send({from: accounts[0], gas: estimate + 1000});
|
||||
|
||||
this.setState({
|
||||
...
|
||||
canVote: false,
|
||||
submitting: false
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
**And we're done!**
|
||||
|
||||
## Wrapping it up
|
||||
|
||||
Congratulations! You've completed the tutorial on building a simple decentralized Reddit application! You might have noticed that this is only the tip of the iceberg though, as there are so many things that can be done to improve and optimize this application. Here are some ideas for further exploration:
|
||||
|
||||
- Sort the posts in reversed chronological order so that the latest post is always on top
|
||||
- Rely on Smart Contracts Events to reload list
|
||||
- Introduce routing so there can be different views for creating and viewing posts
|
||||
- Use CSS to make the application look nice
|
||||
|
||||
We hope you've learned that it's not too hard to build a DApp that uses IPFS and talks to Smart Contracts, and also how Embark can help you doing all of these things.
|
||||
|
||||
**We've recorded every single step of this tutorial [in this repository](https://github.com/embark-framework/dreddit-tutorial)**, so feel free to go ahead, clone it, play with it, compare it with your work or change it to your needs. There will be more tutorials of this kind in the future, so make sure to [follow us on Twitter](https://twitter.com/EmbarkProject) as well for updates!
|
||||
|
145
source/_posts/2019-03-18-upgrading-to-embark-4.md
Normal file
@ -0,0 +1,145 @@
|
||||
title: How to upgrade to Embark 4
|
||||
summary: "In this guide, we'll learn how to upgrade a Dapp created with Embark 3.x to Embark 4"
|
||||
author: jonathan_rainville
|
||||
categories:
|
||||
- tutorials
|
||||
layout: blog-post
|
||||
alias: news/2019/03/17/upgrading-to-embark-4/
|
||||
---
|
||||
|
||||
The release of Embark 4.0 is close at hand and the release candidate, `beta.1`, will introduce some breaking changes. Let's see what it takes to update an Embark 3.x Dapp to Embark 4.
|
||||
|
||||
## Use **any** frontend build tool!
|
||||
|
||||
That's right! The use of Embark's builtin pipeline in no longer required.
|
||||
|
||||
Historically, Embark 3.x came with a special Webpack pipeline because it automated development tasks, such as enabling the use of "magic" imports (ie `import SimpleStorage from "Embark/contracts/SimpleStorage";` or `import EmbarkJS from Embark/EmbarkJS`), and establishing a Web3 connection for the Dapp.
|
||||
|
||||
However, we discovered the hard way that those advantages were not worth the hit in development efficiency, compared to using an optimized pipeline, such as `create-react-app` or Angular CLI. Indeed, on every save, Embark would regenerate a lot of the Dapp-side code and then webpack the entire Dapp, often taking quite some time.
|
||||
|
||||
Therefore, we are announcing that Embark 4 can use **any** frontend development build tooling, letting Embark handle the things that it does best. This means we can use tools such as `create-react-app` or Angular CLI, or pretty much any other tool of your choice, alongside Embark. The Embark 3.x pipeline is still available for use for quick start applications if needed.
|
||||
|
||||
To migrate an existing Embark 3.x Dapp over to use Embark 4 with a third party pipeline, there are few small changes to your Dapp that are needed.
|
||||
|
||||
{% notification info 'NOTE' %}
|
||||
If you are not interested in using a third party pipeline, you can skip to the next section to [see the rest of the breaking changes needed to migrate a Dapp to Embark 4](#New-Web3-plugin).
|
||||
{% endnotification %}
|
||||
|
||||
### Converting to another pipeline
|
||||
|
||||
Converting to a third party pipeline is easy. This can be done with three simple improvements that Embark 4 has made available for us.
|
||||
|
||||
#### Artifact generation directory
|
||||
|
||||
NOTE: If you are planning on using Embark's built-in Webpack pipeline (and not use a third party pipeline), please [skip down to the remainder of the Embark 4 breaking changes](#New-Web3-plugin).
|
||||
|
||||
Embark 4 generates [Smart Contract artifacts](/docs/javascript_usage.html#Embark-Artifacts) for all of the Smart Contract in your Dapp. These artifacts enable importing the Dapp's Smart Contracts into the Dapp's source code. Most of these artifacts were already generated before, but lived inside the `.embark/` folder. Since most modern frontend build systems require source files to live inside of a very specific source folder, we have given developers the opportunity to specify the destination folder for these artifacts, allowing the frontend build tool to pick them up for processing.
|
||||
|
||||
The first thing we need to do is add a new `generationDir` property in the root of `embark.json`. This property tells Embark where to place the generated artifacts in the Dapp's filesystem. For example, `create-react-app` (CRA) has `src/` as source folder and the artifacts must be placed in that folder, so we would add in `embark.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"generationDir": "src/embarkArtifacts"
|
||||
}
|
||||
```
|
||||
|
||||
#### "Magic" imports
|
||||
Afterwards, we need to convert all "magic" imports in our Dapp's code to relative imports.
|
||||
|
||||
The first one is the EmbarkJS import. The "magic" import is `"Embark/EmbarkJS"`. Anywhere we have `"Embark/EmbarkJS"` in our Dapp's code, we need to convert that to the relative path. Because we are trying to get the `EmbarkJS` library, and the `embarkjs.js` script is located in the root of `embarkArtifacts/`, we need to replace
|
||||
|
||||
```javascript
|
||||
import EmbarkJS from "Embark/EmbarkJS"
|
||||
```
|
||||
with
|
||||
```javascript
|
||||
import EmbarkJS from "./embarkArtifacts/embarkjs"
|
||||
```
|
||||
{% notification info 'NOTE' %}
|
||||
NOTE: The relative path is dependent upon the generationDir setting specified in embark.json [see the "Artifact generation directory" section above](#Artifact-generation-directory).
|
||||
{% endnotification %}
|
||||
|
||||
Secondly, we need to update the "magic" Smart Contract imports. These will need to change from
|
||||
|
||||
```javascript
|
||||
import ContractName from "Embark/contract/ContractName";
|
||||
```
|
||||
to
|
||||
```javascript
|
||||
import ContractName from "./embarkArtifacts/contracts/ContractName";
|
||||
```
|
||||
|
||||
Thirdly, there used to be `import web3 from "Embark/web3"`, but it has been removed in Embark 4 in favor of using a global Web3 object. Don't worry, Embark is not removing web3 support, far from it. We actually just got rid of an import that did not provide a lot of benefit. In Embark 4, the global `web3` object is now available everywhere in the Dapp.
|
||||
|
||||
Now, all the Embark files and configs from your Dapp can be moved in to a project created by the frontend build tool of your choice.
|
||||
|
||||
### New project with another pipeline
|
||||
|
||||
Starting a new Dapp from scratch is easy, we have two options.
|
||||
|
||||
#### Embark's create-react-dapp template
|
||||
|
||||
The easiest option is to use our [new Embark CRA template](https://github.com/embark-framework/embark-create-react-dapp-template). It sets up a simple Embark project with all of the familiar files present in an Embark 3.x Dapp, with one minor difference: the config files are located in an `embarkConfig/` folder in the root of the Dapp to make sure they don't clash with CRA's config folder/files.
|
||||
|
||||
To get started with Embark's CRA template,
|
||||
|
||||
```
|
||||
embark new --template embark-react-dapp my-dapp
|
||||
cd my-dapp
|
||||
embark run
|
||||
```
|
||||
|
||||
Then, in another terminal,
|
||||
|
||||
```
|
||||
cd my-dapp
|
||||
yarn start // or alternatively, npm run start
|
||||
```
|
||||
|
||||
That's it!
|
||||
|
||||
#### For other build tools
|
||||
|
||||
If we want to use another build tool than CRA, here are the steps:
|
||||
|
||||
Create a project using a frontend build tool like Angular CLI. Then, in another directory, execute `embark new your_projects_name`.
|
||||
|
||||
Afterwards, we copy all the files and folders from the Embark project to the build tool's folder. The only tweak that you will need to do is go in `config/pipeline.js` and set `enabled: false`, so that Embark's pipeline is disabled.
|
||||
|
||||
We can also go in `embark.json` and remove the `app` section (as well as Embark's source dir that you will not be using).
|
||||
|
||||
Lastly, check out [the "Artifact generation directory" section above](#Artifact-generation-directory) to make sure your artifacts directory is set up correctly for you build tool.
|
||||
|
||||
There you go, your project is ready.
|
||||
|
||||
We know that these steps are a bit too much, so we are working on a new command that lets you initialize an Embark project from inside a build tool's directory. Keep an eye out for that.
|
||||
|
||||
## New Web3 plugin
|
||||
|
||||
*(2019/06/27)* **NOTE**: *the following instructions are* ***not*** *applicable to Embark `4.1.x` and newer, but should still be followed for `4.0.x` or `<=4.1.0-beta.3`.*
|
||||
|
||||
Starting with Embark 4 beta.1, Embark no longer supplies the Dapp with `Web3.js` by default. Don't run. We did that so that we can now have the possibility of supporting more than just `Web3.js`, such as EthersJS, and more. You can even roll your own.
|
||||
|
||||
To continue using `Web3.js` inside the Embark 4 Dapp, execute the following command in the Embark console: `plugin install embarkjs-connector-web3`.
|
||||
|
||||
This simply [installs `embarkjs-connector-web3` as a plugin](https://embark.status.im/docs/installing_plugins.html). Alternatively, this plugin can be installed manually by executing:
|
||||
1. `yarn add embarkjs-connector-web3` or `npm install --save embarkjs-connector-web3`
|
||||
2. Adding `"embarkjs-connector-web3": {}` to the `plugins` section of `embark.json`
|
||||
|
||||
It's as simple as that. This plugin will add the necessary commands and code for the Dapp to connect to the blockchain and register the necessary providers. The only prerequisite is for the Dapp to import `EmbarkJS` at least once. If using a third party pipeline, the `EmbarkJS` file can be imported using `import EmbarkJS from "./embarkArtifacts/embarkjs.js"` (or as specified by the `generationDir` in `embark.json`). If using Embark's built-in pipeline, `EmbarkJS` can be imported using `import EmbarkJS from "Embark/EmbarkJS";`.
|
||||
|
||||
## New Blockchain account configs
|
||||
|
||||
Embark 4 adds some new blockchain account configurations. To try to keep things as simple as possible, these additions are really similar to the ones in the contract configuration. For more information, please read the [Accounts Blockchain configuration guide](https://embark.status.im/docs/blockchain_accounts_configuration.html) in our docs.
|
||||
|
||||
However, we did introduce some small breaking changes. We removed:
|
||||
- `account`: This is completely replaced by the new `accounts` property (notice the `s` at the end of `accounts`). It gives the developer more flexibility. To have exactly the same behavior as before, just use the `nodeAccounts` account type as [described in the docs](https://embark.status.im/docs/blockchain_accounts_configuration.md#parameter-descriptions)
|
||||
- `simulatorMnemonic`: Removed in favor of Ganache's default mnemonic. If this functionality is still needed, please specify the desired mnemonic in the [blockchain config's `mnemonic` account type](https://embark.status.im/docs/blockchain_accounts_configuration.md#parameter-descriptions).
|
||||
|
||||
## Conclusion
|
||||
|
||||
This is a small taste of the features added to Embark 4, namely the ability to use a frontend build tool of choice. However, Embark 4 is jam-packed with additional new features, which we'll detail during the Embark 4 release.
|
||||
|
||||
In the meantime, all the Embark 4 goodness doesn't come at too high a price in terms of breaking changes.
|
||||
|
||||
Upgrading to Embark 4 will be a blast. If you ever have an issue, make sure to hit us up on [Gitter](https://gitter.im/embark-framework/Lobby).
|
76
source/_posts/2019-03-19-introducing-embark-4.md
Normal file
@ -0,0 +1,76 @@
|
||||
title: Introducing Embark 4.0 - Cockpit, Debugger and more
|
||||
summary: "Embark 4.0 is finally here! Check out what the greatest release yet has to offer!"
|
||||
author: jonny_zerah
|
||||
categories:
|
||||
- announcements
|
||||
layout: blog-post
|
||||
image: '/assets/images/EMBARK_HEADER_ALT_OPTIMIZED.jpg'
|
||||
alias: news/2019/03/18/introducing-embark-4/
|
||||
---
|
||||
|
||||

|
||||
|
||||
**Embark 4.0 is officially out of beta and ready for developers around the world. Cockpit (the new web UI dashboard), a robust debugger, and the frontend-agnostic build pipeline provide the support you need to develop production-ready decentralized applications.**
|
||||
|
||||
2019 is off to a great start! We’ve been taking Embark 4.0 from alpha to beta, and are now happy to present the official release of version 4.0. It comes jam-packed with many new features, including Cockpit, a transaction debugger, and a massively improved integration with existing frontend tooling. To mark this major milestone, we’ve also launched our new website with updated docs, more tutorials, and a brand new look!
|
||||
|
||||
Thanks to all the developers who have been using, testing, contributing to, and providing feedback on the beta version. The official release of 4.0 is now ready for the world to use. Read on for an overview of the key features or simply get going with our [Quick Start Guide](/docs/quick_start.html).
|
||||
|
||||
{% notification info 'Embark now follows SemVer' %}
|
||||
Version 4.0 contains **some breaking changes**, however we kept them at a minimum and you can learn about all of them in our article on [upgrading DApps created with Embark 3.x](/news/2019/03/18/upgrading-to-embark-4/).
|
||||
|
||||
That said, with the release of 4.0 **Embark will now follow SemVer** making it easier for developers to update and watch out for changes.
|
||||
{% endnotification %}
|
||||
|
||||
## Cockpit – An intuitive Web Interface
|
||||
Cockpit has been under active development for a few months and is officially ready! Cockpit is your command center for building, debugging, and deploying decentralized applications.
|
||||
|
||||
**The dashboard** is the first page users see when they load Cockpit. It provides an overview of all processes controlled by Embark and comes with an interactive console and predictive commands, allowing developers to conveniently interact with Embark and all components (e.g. Ethereum blockchain, ENS, Whisper, IPFS/Swarm, etc). The dashboard also displays a summary of deployed contracts and enables users to search for accounts, blocks, addresses, and transactions.
|
||||
|
||||
For more information regarding Cockpit’s dashboard, please refer to the [Embark docs](/docs/cockpit_dashboard.html).
|
||||
|
||||
|
||||

|
||||
|
||||
**The blockchain explorer** provides detailed views of blocks, transactions, smart contracts, and connected accounts. We’ve also introduced a brand new way to analyze deployed instances of smart contracts. Within the contracts view, users can interact with a contract’s API, view the ABI and bytecode, retrieve the contract’s transaction logs, and invoke Cockpit’s new integrated debugger. [Learn more](/docs/cockpit_explorer.html)
|
||||
|
||||
|
||||

|
||||
|
||||
**Iterative Deployment** enables selective deployment of smart contracts to any network, removing headaches when it comes to complex applications. Using the deployment panel, single or multiple smart contracts can be deployed to production safely, with full control over the process. [Learn more](/docs/cockpit_deployment.html)
|
||||
|
||||
**The code editor** allows you to edit a DApp’s source files from within Cockpit for quick and easy updates. The web-based editor enables a DApp’s source code to be changed on the fly. Like any typical code editor, it has a file tree, can open multiple source files, and allows files to be added and deleted. Users can also access and interact with contact properties and methods in the editor’s UI. Contracts even get redeployed as changes are saved – iterative development at its best! [Learn more](/docs/cockpit_editor.html)
|
||||
|
||||

|
||||
|
||||
## Integrated Debugger
|
||||
Debugging is an important part of all software development and has been a significant challenge for blockchain developers for some time. The new Embark debugger provides an easy way to debug contracts by displaying solidity source codes lines where a transaction failed. This greatly speeds up development and helps to eliminate bugs.
|
||||
|
||||
The debugger comes in handy in a number of situations. For example, if a transaction fails, no problem! The debugger will spring into action and offer a quick shortcut to help identify the problem and start troubleshooting.
|
||||
|
||||
## Better tooling integration
|
||||
Embark is now compatible with any frontend tooling such as Create React App and the CLI tools for Angular, Vue, and more.
|
||||
|
||||
Previously, Embark used its own pipeline, which was compatible with most frontend frameworks by way of Webpack configuration. However, it wasn’t compatible with most frontend tooling. Embark 4 is now fully frontend-agnostic, but the old pipeline is still available if you wish to use it.
|
||||
|
||||
## Additional Updates and Features
|
||||
We’ve introduced a number of updates and new features to go along with the key features mentioned above. These include:
|
||||
|
||||
- **New contract deployment hooks**: onDeploy and afterDeploy allow for complete customization of the deployment lifecycle.
|
||||
- **Better account configuration**: accounts are now consistently defined in config/blockchain.js.
|
||||
- **Embark can be installed as a local dependency for per-project versioning**: global installation of Embark is no longer required.
|
||||
|
||||
## A new Website and Fresh New Look
|
||||
|
||||

|
||||
|
||||
Embarking into decentralized applications is exciting and fun. That’s precisely why we updated our website: to better accompany developers on their journey. Not only did we give Embark a facelift with slick new illustrations and a fresh logo, but we also made it easier to navigate developer resources such as docs, plugins, and tutorials. For developers new to Embark, the Quick Start guide will get you up and running in no time!
|
||||
|
||||
## Get Started Now
|
||||
Embark 4.0 is a great companion for those embarking into the ether! From brand new developers still learning the concepts, to seasoned pros with a specific project in mind, Embark is the ideal all-in-one development platform for building and deploying decentralized applications. Whether developing DApps end-to-end or simply deploying smart contracts, Embark allows developers to pick and choose which features, plugins, and tools to integrate.
|
||||
|
||||
Check out the [Quick Start guide](/docs/quick_start.html) or dive right into the [documentation](/docs).
|
||||
|
||||
Chat with us in [Gitter](https://gitter.im/embark-framework/Lobby)
|
||||
Star the repo on [GitHub](https://github.com/embark-framework/embark)
|
||||
Follow us on [Twitter](https://twitter.com/EmbarkProject)
|
126
source/_posts/2019-07-23-whats-new-in-embark-4.1.md
Normal file
@ -0,0 +1,126 @@
|
||||
title: What's new in Embark 4.1
|
||||
summary: "Embark 4.1 is out and in this article we'll be looking into some of new features."
|
||||
author: pascal_precht
|
||||
categories:
|
||||
- announcements
|
||||
layout: blog-post
|
||||
alias: news/2019/07/22/whats-new-in-embark-4.1/
|
||||
---
|
||||
|
||||
After four months of development we're happy to tell you that we've released Embark 4.1 which comes with tons of bug fixes and a lot of new features. In this post we'll take a closer look at some of these features, however as always, we recommend having a look at our [change log](https://github.com/embark-framework/embark/blob/master/CHANGELOG.md) to get a more detailed overview of what has landed in Embark's latest release. Let's get right to it!
|
||||
|
||||
## New `beforeDeploy` hook
|
||||
|
||||
In Embark 4, we've introduced a handful of new [deployment hooks](https://embark.status.im/docs/contracts_configuration.html#Deployment-hooks) and with 4.1, we're expanding the APIs from there. The new `beforeDeploy` hook lets you run an action either before all of your Smart Contracts are getting deployed, or, selectively for a subset of them.
|
||||
|
||||
Very similar to the existing deployment hooks, `beforeDeploy` is an asynchronous function that returns a promise and has access to a context object that provides dependencies that your function may or may not be interested in. Adding a `beforeDeploy` hook that runs before your Smart Contracts are being deployed is as simple as adding it to the `contracts` configuration like this:
|
||||
|
||||
```
|
||||
// config/contract.js
|
||||
|
||||
module.exports = {
|
||||
...
|
||||
contracts: {
|
||||
beforeDeploy: async () => {
|
||||
return Promise.resolve('yay');
|
||||
}
|
||||
...
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
As expected, for more control, `beforeDeploy` can be defined on a per Smart Contract basis like this:
|
||||
|
||||
```
|
||||
// config/contract.js
|
||||
|
||||
module.exports = {
|
||||
...
|
||||
contracts: {
|
||||
...
|
||||
SimpleStorage: {
|
||||
beforeDeploy: async (context) => {
|
||||
// can use `context` if needed
|
||||
return Promise.resolve('yay');
|
||||
}
|
||||
...
|
||||
}
|
||||
}
|
||||
};
|
||||
```
|
||||
Learn more about Embark's [deployment hooks in the documentation](/docs/contracts_configuration.html#Deployment-hooks).
|
||||
|
||||
## Enabling and disabling services via the console
|
||||
If you've used Embark before, you're probably aware that it comes with a very powerful dashboard with an integrated CLI. This CLI exposes a bunch of commands that can be used to interact with Embark's run-time. Some commands serve a very specific use case, such as `api start` and `api stop`. With Embark 4.1 we decided to generalize the commands that enable users to start and stop service processes started by Embark.
|
||||
|
||||
Therefore, the following commands are considered deprecated in favour of a new generalized command:
|
||||
|
||||
- `api start/stop`
|
||||
- `webserver start/stop`
|
||||
|
||||
The new `service` command lets you start and stop `api`, `webserver`, `blockchain`, `ipfs`, `swarm`, `embark` and `api`:
|
||||
|
||||
```
|
||||
$ service <service> on/off
|
||||
```
|
||||
|
||||
This works within Embark's command line Dashboard, as well as [Cockpit's dashboard](https://embark.status.im/docs/cockpit_dashboard.html). To learn more about Embark's interactive console and its command, head over to the [documentation](/docs/using_the_console.html#Enabling-and-disabling-processes).
|
||||
|
||||
## Accounts access inside tests
|
||||
|
||||
In order to make writing tests in Embark a little bit more convenient, accounts configured and set up via the `config()` function are now injected into `describe()` blocks, making writing tests a little bit more predictable and easier to reason about.
|
||||
|
||||
Prior, in order to get hold of accounts within tests, the following was needed:
|
||||
|
||||
```
|
||||
let accounts = [];
|
||||
|
||||
config({
|
||||
contracts: {
|
||||
...
|
||||
}
|
||||
}, (err, _accounts) => {
|
||||
accounts = _accounts;
|
||||
});
|
||||
|
||||
contract('My contract', () => {
|
||||
|
||||
it('does something', () => {
|
||||
// can use `accounts` here
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
Notice that Embark won't run the `contract()` block until `config()` is done doing its work. Therefore, using a global variable was the recommended way to re-initialize `accounts` once `config()` runs its callback.
|
||||
|
||||
The same can now be achieved with the following code:
|
||||
|
||||
```
|
||||
config({
|
||||
contracts: {
|
||||
...
|
||||
}
|
||||
});
|
||||
|
||||
contract('My contract', accounts => {
|
||||
|
||||
it('does something', () => {
|
||||
// can use `accounts` here
|
||||
});
|
||||
});
|
||||
```
|
||||
Instead of managing an `accounts` variable yourself, you can just ask for it now within `contract()`'s callback.
|
||||
|
||||
## Several improvements inside Cockpit
|
||||
|
||||
Cockpit has got a lot of new things as well. This includes [draggable tabs]() inside the code editor, pagination support for [Smart Contracts](https://github.com/embark-framework/embark/commit/d71352b) and the [accounts explorer](https://github.com/embark-framework/embark/commit/745edaf), alphabetically [sorted Smart Contracts](https://github.com/embark-framework/embark/commit/0e9a4a1), and the ability to [send ETH to payable Smart Contract methods](https://github.com/embark-framework/embark/pull/1649) via the Cockpit UI.
|
||||
|
||||
|
||||
## What's next?
|
||||
|
||||
We've spent a lot of time fixing bugs and revisiting existing, user-facing APIs within Embark and aim to improve those as much as we can to make working with Embark as pleasant as possible. We've been also doing a lot of research and experimentation about integrating with other blockchain platforms, to get Embark ready for the future of decentralization to come.
|
||||
|
||||
That's why our next step is to work on v5, where we'll be focussing on making Embark's accounts configuration less confusing and more unified (no more multiple places to define accounts!), as well as a bunch of internal refactor.
|
||||
|
||||
|
||||
Stay tuned with latest changes happening in Embark by [watching our GitHub repository](https://github.com/embark-framework/embark) and following us on [Twitter](https://twitter.com/EmbarkProject)!
|
@ -0,0 +1,478 @@
|
||||
title: Nim vs Crystal - Part 1 - Performance & Interoperability
|
||||
summary: "Crystal and Nim go head-to-head to figure out the best modern, low-level programming language! In part 1, Performance & Interoperability are reviewed."
|
||||
author: robin_percy
|
||||
categories:
|
||||
- tutorials
|
||||
layout: blog-post
|
||||
image: '/assets/images/nim-crystal-header_blank.jpg'
|
||||
---
|
||||
|
||||

|
||||
|
||||
I've been wanting to write-up a comparison on Nim and Crystal for quite some time now, and I'm happy that I'm finally able to do so. What I've decided on doing; is breaking this up into a three part series as there are ***SO*** many features of both languages I'd like to talk about, and therein many opinions held too. I do have a habit of writing **very** long articles, so I'd like to limit the topic scope, to keep each of these a little snappier!
|
||||
|
||||
Before I go into specifics on either of these languages, I'd first like to go into my reasons for first learning both languages, and briefly touch on my past experiences with the two of them. I admit that I *have* had more experience with Crystal than I have with Nim; however, I will give an objective view of both languages until I go into my personal preference towards the end of each article in this series.
|
||||
|
||||
<blockquote class="twitter-tweet"><p lang="en" dir="ltr">crystal or nim? Both super immature but fun</p>— @r4vi (@r4vi) <a href="https://twitter.com/r4vi/status/874741870093623296?ref_src=twsrc%5Etfw">June 13, 2017</a></blockquote> <script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>
|
||||
|
||||
Back in mid-2017, I sent out a tweet asking my dev followers which low-level languages they would recommend I take a look at. For a while before this, I had been waiting for a new systems language for me to learn, but until this tweet, I never really found one that I was *actually* interested in taking a look at.
|
||||
|
||||
Naturally, both languages have a **TONNE** of features, so I'm not going to go into details on things like basic types, etc. I will simply compare the biggest things that attracted me to both languages. For in-depth tutorials on the features of both langs, check out the [Crystal Docs](https://crystal-lang.org/reference/), or the [Nim Docs](https://nim-lang.org/docs/lib.html).
|
||||
|
||||
Anyway, let's take a look at both languages, and you can make your own mind up as to which you'd rather be programming in. Maybe both. Maybe neither!
|
||||
|
||||
|
||||
<br/>
|
||||
|
||||
## Nim
|
||||
|
||||
Nim is a statically-typed, imperative, systems programming language; aiming to achieve the performance of C, be as expressive as Lisp, and have a simple, clear syntax like Python. I have to say, from my experience Nim manages to ***pretty much*** fit these criterion.
|
||||
|
||||
> By compiling to C, Nim is able to take advantage of many features offered by modern C compilers. The primary benefits gained by this compilation model include incredible portability and optimisations.
|
||||
|
||||
> The binaries produced by Nim have zero dependencies and are typically very small. This makes their distribution easy and keeps your users happy.
|
||||
|
||||
When I say it *pretty much* matches the criteria, the only statement that doesn't quite match is achieving the performance of C. In realise this is an almost impossible task, but Nim actually did fall short on a few occasions when it came to performance. I will go into detail about this later on in the article.
|
||||
|
||||
|
||||
### Installing Nim
|
||||
|
||||
Nim is super easy to install. If you're on Windows, [head over here](https://nim-lang.org/install_windows.html), and download/run the installer.
|
||||
|
||||
If you're on any other Unix-based system, you can run:
|
||||
|
||||
```
|
||||
$ curl https://nim-lang.org/choosenim/init.sh -sSf | sh`
|
||||
```
|
||||
|
||||
If you're on Mac, and with Homebrew installed, simply run:
|
||||
|
||||
```
|
||||
$ brew install nim
|
||||
```
|
||||
|
||||
You could also consider using [choosenim](https://github.com/dom96/choosenim) to manage Nim installations in a similar way to `pyenv` and `rustup`.
|
||||
|
||||
|
||||
### Interfacing Other Languages
|
||||
|
||||
One of the things that attracted me to both Nim **and** Crystal, was the ability to natively interface with other languages, and the **ease** with which that is achieved. Nim has bidirectional interfacing not only with C, but also natively with JavaScript. Crystal natively interfaces with C, but is only unidirectional. Definitely a point scored here for Nim!
|
||||
|
||||
When it comes to building DApps, the variety of target hardware they must be run on is already large, and growing all the time. The low-level ability to interop with other languages makes for both languages being a much more attractive proposition.
|
||||
|
||||
For a quick demo, let's take a look at interfacing both C and JavaScript from Nim.
|
||||
|
||||
#### C Invocation
|
||||
|
||||
Firstly, create the file `logic.c` with the following content:
|
||||
|
||||
``` c
|
||||
int addTwoIntegers(int a, int b)
|
||||
{
|
||||
return a + b;
|
||||
}
|
||||
```
|
||||
|
||||
Next, create the file `calculator.nim` with the following content:
|
||||
|
||||
``` nim
|
||||
{.compile: "logic.c".}
|
||||
proc addTwoIntegers(a, b: cint): cint {.importc.}
|
||||
|
||||
when isMainModule:
|
||||
echo addTwoIntegers(3, 7)
|
||||
```
|
||||
|
||||
Now then, with these two *very simple* files in place, we can run:
|
||||
|
||||
```
|
||||
$ nim c -r calculator.nim
|
||||
```
|
||||
|
||||
The Nim compiler will compile the `logic.c` file in addition to `calculator.nim` and link both into an executable; which outputs `10` when run. Very sharp, in my opinion!
|
||||
|
||||
#### JavaScript Invocation
|
||||
|
||||
Even sharper, in my opinion, is the ability to interop with JavaScript. Create a file titled `host.html` with the following content:
|
||||
|
||||
``` html
|
||||
<html>
|
||||
<body>
|
||||
<script type="text/javascript">
|
||||
function addTwoIntegers(a, b)
|
||||
{
|
||||
return a + b;
|
||||
}
|
||||
</script>
|
||||
|
||||
<script type="text/javascript" src="calculator.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
Now, create another `calculator.nim` file with the following content (or reuse the one from the above C example):
|
||||
|
||||
``` nim
|
||||
proc addTwoIntegers(a, b: int): int {.importc.}
|
||||
|
||||
when isMainModule:
|
||||
echo addTwoIntegers(3, 7)
|
||||
```
|
||||
|
||||
|
||||
Compile the Nim code to JavaScript by running:
|
||||
|
||||
```
|
||||
$ nim js -o:calculator.js calculator.nim
|
||||
```
|
||||
|
||||
Once that's done, go ahead and open `host.html` in a browser and you should see the value `10` in the browser's console. I think this is **REALLY** neat. It's superb how easy it is to achieve that, too.
|
||||
|
||||
|
||||
### Aside – a Quick (not-so) Secret:
|
||||
|
||||
Instead of writing out the HTML above, you could actually use ***Nim's native*** HTML DSL:
|
||||
|
||||
``` nim
|
||||
import html_dsl
|
||||
|
||||
html page:
|
||||
head:
|
||||
title("Title")
|
||||
body:
|
||||
p("Hello")
|
||||
p("World")
|
||||
dv:
|
||||
p "Example"
|
||||
|
||||
echo render(page())
|
||||
```
|
||||
|
||||
Running this will output the following:
|
||||
|
||||
``` html
|
||||
<!DOCTYPE html>
|
||||
<html class='has-navbar-fixed-top' >
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Title</title>
|
||||
</head>
|
||||
<body class='has-navbar-fixed-top' >
|
||||
<p >Hello</p>
|
||||
<p >World</p>
|
||||
<div>
|
||||
<p>Example</p>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
|
||||
<br/>
|
||||
|
||||
## Crystal
|
||||
|
||||
Crystal is a statically-typed, object-oriented, systems programming language; with the aim of achieving the speed and performance of c/c++, whilst having a syntax as simple, readable, and easy to learn as Ruby.
|
||||
|
||||
I first came across Crystal when I saw [@sferik](https://twitter.com/sferik) giving a talk on it in Poland back in 2015. [Video here.](https://www.youtube.com/watch?v=Ysm4IU4aWoQ) It was a great talk, and sparked my interest in Crystal right there and then. When I initially explored Crystal I thought it looked awesome, but I was too busy with all the other languages I was using on a daily basis, to be able to focus my time on it properly.
|
||||
|
||||
### Installing Crystal
|
||||
|
||||
You can find all of the relevant instructions for installing Crystal, on the [main website installation page](https://crystal-lang.org/install/).
|
||||
|
||||
If you are on Mac, and have Homebrew installed, you can simply run:
|
||||
|
||||
```
|
||||
$ brew install crystal
|
||||
```
|
||||
|
||||
**However**, if you are a Windows user, *for the time being* you are out of luck, unless you use the Windows Subsystem for Linux. If I were in a more shocking/pedantic mood, I'd take a (not yet gained) point **away** from Crystal here, for lack of Windows support.
|
||||
|
||||
|
||||
### Interfacing C
|
||||
|
||||
Let’s build a simple script in C that says “hi!”. We’ll then write a Crystal app to bind to our C library. This is a great starting point for anyone who wants to know about binding C in Crystal.
|
||||
|
||||
First off, let’s create a project with Crystal’s scaffolding tool (I’ll cover this feature later). Run:
|
||||
|
||||
```
|
||||
$ crystal init app sayhi_c
|
||||
```
|
||||
|
||||
Then head into the directory `sayhi_c/src/sayhi_c` and let’s create a file `sayhi.c` with the following contents:
|
||||
|
||||
``` c
|
||||
#include <stdio.h>
|
||||
|
||||
void hi(const char * name){
|
||||
printf("Hi %s!\n", name);
|
||||
}
|
||||
```
|
||||
|
||||
Now we need to compile our C file into an object. On Ubuntu or Mac using gcc we can run:
|
||||
|
||||
```
|
||||
$ gcc -c sayhi.c -o sayhi.o
|
||||
```
|
||||
|
||||
Using the -o flags allow us to create an Object filetype. Once we’ve got our Object file, we can bind it from within our Crystal app. Open up our `sayhi_c.cr` file, and have it reflect the following:
|
||||
|
||||
``` crystal
|
||||
require "./sayhi_c/*"
|
||||
|
||||
@[Link(ldflags: "#{__DIR__}/sayhi_c/sayhi.o")]
|
||||
|
||||
lib Say
|
||||
fun hi(name : LibC::Char*) : Void
|
||||
end
|
||||
|
||||
Say.hi("Status")
|
||||
```
|
||||
|
||||
I’ll mention now that there are no implicit type conversions except to_unsafe - explained here when invoking a C function: you must pass the exact type that is expected.
|
||||
|
||||
Also worth noting at this point is that since we have built our C file into an object file, we can include it in the project directory and link from there. When we want to link dynamic libraries or installed C packages, we can just link them without including a path.
|
||||
|
||||
So, if we build our project file and run it, we get the following:
|
||||
|
||||
```
|
||||
$ crystal build --release src/sayhi_c.cr
|
||||
|
||||
$ ./sayhi_c
|
||||
|
||||
> Hi Status!
|
||||
```
|
||||
|
||||
As you can see, Nim takes the winners trophy in this case, as it is **much** simpler to achieve a similar goal. With Nim, we were also able to link both the Nim and C files into the same executable, which Crystal sadly cannot do.
|
||||
|
||||
|
||||
|
||||
<br/>
|
||||
|
||||
## Performance Tests
|
||||
|
||||
### Parsing & calculating values from a large JSON file:
|
||||
|
||||
Firstly, we need to generate our large JSON file. For this test, we're going to generate a dataset which includes **1 Million** items.
|
||||
|
||||
<center><iframe src="https://giphy.com/embed/13B1WmJg7HwjGU" width="480" height="270" frameBorder="0"></iframe></center>
|
||||
|
||||
We can do so with the following Ruby script:
|
||||
|
||||
``` rb
|
||||
require 'json'
|
||||
|
||||
x = []
|
||||
|
||||
1000000.times do
|
||||
h = {
|
||||
'x' => rand,
|
||||
'y' => rand,
|
||||
'z' => rand,
|
||||
'name' => ('a'..'z').to_a.shuffle[0..5].join + ' ' + rand(10000).to_s,
|
||||
'opts' => {'1' => [1, true]},
|
||||
}
|
||||
x << h
|
||||
end
|
||||
|
||||
File.open("1.json", 'w') { |f| f.write JSON.pretty_generate('coordinates' => x, 'info' => "some info") }
|
||||
```
|
||||
|
||||
This will generate a JSON file **of around 212mb**, with the following syntax:
|
||||
|
||||
``` json
|
||||
{
|
||||
"coordinates": [
|
||||
{
|
||||
"x": 0.10327081810860272,
|
||||
"y": 0.03247172212368832,
|
||||
"z": 0.8155255437507467,
|
||||
"name": "scojbq 5965",
|
||||
"opts": {
|
||||
"1": [
|
||||
1,
|
||||
true
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"info": "some info"
|
||||
}
|
||||
```
|
||||
|
||||
Now that we have our chunky JSON file; we can write our first test – **in Nim**:
|
||||
|
||||
``` nim
|
||||
import json
|
||||
|
||||
let jobj = parseFile("1.json")
|
||||
|
||||
let coordinates = jobj["coordinates"].elems
|
||||
let len = float(coordinates.len)
|
||||
var x = 0.0
|
||||
var y = 0.0
|
||||
var z = 0.0
|
||||
|
||||
for coord in coordinates:
|
||||
x += coord["x"].fnum
|
||||
y += coord["y"].fnum
|
||||
z += coord["z"].fnum
|
||||
|
||||
echo x / len
|
||||
echo y / len
|
||||
echo z / len
|
||||
```
|
||||
|
||||
And again; the same simple test, this time written **in Crystal**:
|
||||
|
||||
``` crystal
|
||||
require "json"
|
||||
|
||||
text = File.read("1.json")
|
||||
jobj = JSON.parse(text)
|
||||
coordinates = jobj["coordinates"].as_a
|
||||
len = coordinates.size
|
||||
x = y = z = 0
|
||||
|
||||
coordinates.each do |coord|
|
||||
x += coord["x"].as_f
|
||||
y += coord["y"].as_f
|
||||
z += coord["z"].as_f
|
||||
end
|
||||
|
||||
p x / len
|
||||
p y / len
|
||||
p z / len
|
||||
```
|
||||
|
||||
### Results:
|
||||
|
||||
Building our test files into tiny release packages with the respective commands below:
|
||||
|
||||
```
|
||||
$ crystal build json_test.cr --release -o json_test_cr --no-debug
|
||||
```
|
||||
|
||||
```
|
||||
$ nim c -o:json_test_nim -d:danger --cc:gcc --verbosity:0 json_test.nim
|
||||
```
|
||||
|
||||
We can then time & run those packages, to obtain our test results:
|
||||
|
||||
| Language | Time (s) | Memory (Mb) |
|
||||
|----------|----------|-------------|
|
||||
| Nim | 6.92 | 1320.4 |
|
||||
| Crystal | 4.58 | 960.7 |
|
||||
|
||||
As you can see; in this case ***Crystal*** is the more performant language – taking less time to execute & complete the test, and also fewer Megabytes in memory doing so.
|
||||
|
||||
|
||||
|
||||
<br/>
|
||||
|
||||
### Base64 encoding / decoding a large blob:
|
||||
|
||||
In this test; we will firstly encode and then decode a string, with a current timestamp into newly allocated buffers, utilising the Base64 algorithm. For starters, let's look at the ***Nim*** test:
|
||||
|
||||
``` nim
|
||||
import base64, times, strutils, strformat
|
||||
|
||||
let STR_SIZE = 131072
|
||||
let TRIES = 8192
|
||||
let str = strutils.repeat('a', STR_SIZE)
|
||||
|
||||
var str2 = base64.encode(str)
|
||||
stdout.write(fmt"encode {str[..3]}... to {str2[..3]}...: ")
|
||||
|
||||
var t = times.epochTime()
|
||||
var i = 0
|
||||
var s:int64 = 0
|
||||
while i < TRIES:
|
||||
str2 = base64.encode(str)
|
||||
s += len(str2)
|
||||
i += 1
|
||||
echo(fmt"{s}, {formatFloat(times.epochTime() - t, ffDefault, 6)}")
|
||||
|
||||
var str3 = base64.decode(str2)
|
||||
stdout.write(fmt"decode {str2[..3]}... to {str3[..3]}...: ")
|
||||
|
||||
t = times.epochTime()
|
||||
i = 0
|
||||
s = 0
|
||||
while i < TRIES:
|
||||
str3 = base64.decode(str2)
|
||||
s += len(str3)
|
||||
i += 1
|
||||
echo(fmt"{s}, {formatFloat(times.epochTime() - t, ffDefault, 6)}")
|
||||
```
|
||||
|
||||
And now the same test, written in Crystal:
|
||||
|
||||
``` crystal
|
||||
require "base64"
|
||||
|
||||
STR_SIZE = 131072
|
||||
TRIES = 8192
|
||||
|
||||
str = "a" * STR_SIZE
|
||||
|
||||
str2 = Base64.strict_encode(str)
|
||||
print "encode #{str[0..3]}... to #{str2[0..3]}...: "
|
||||
|
||||
t, s = Time.local, 0
|
||||
TRIES.times do |i|
|
||||
str2 = Base64.strict_encode(str)
|
||||
s += str2.bytesize
|
||||
end
|
||||
puts "#{s}, #{Time.local - t}"
|
||||
|
||||
str3 = Base64.decode_string(str2)
|
||||
print "decode #{str2[0..3]}... to #{str3[0..3]}...: "
|
||||
|
||||
t, s = Time.local, 0
|
||||
TRIES.times do |i|
|
||||
str3 = Base64.decode_string(str2)
|
||||
s += str3.bytesize
|
||||
end
|
||||
puts "#{s}, #{Time.local - t}"
|
||||
```
|
||||
|
||||
### Results:
|
||||
|
||||
We can again; build our Base64 test files into release packages with the respective commands below:
|
||||
|
||||
```
|
||||
$ crystal build base64_test.cr --release -o base64_test_cr --no-debug
|
||||
```
|
||||
|
||||
```
|
||||
$ nim c -o:base64_test_nim -d:danger --cc:gcc --verbosity:0 base64_test.nim
|
||||
```
|
||||
|
||||
As with our last test suite, we can then time & run those packages, to obtain our test results:
|
||||
|
||||
| Language | Time (s) | Memory (Mb) |
|
||||
|----------|----------|-------------|
|
||||
| Nim | 4.17 | 6.6 |
|
||||
| Crystal | 2.36 | 3.5 |
|
||||
|
||||
Once again, to my surprise, Crystal came out on top. And did again and again for me, running a bunch of different tests I could scrape together from other curious devs.
|
||||
|
||||
|
||||
## Conclusion
|
||||
|
||||
The summary of this first-in-series article, is most definitely one of surprise. I already knew that Crystal was a highly-performant language, and I have previously done my own research & testing to see how close to *C speeds* it could achieve. That being said, I was *also* already aware that Nim **claims** close to C speeds, and that one of the language's principals was to run well on old & less-performant hardware.
|
||||
|
||||
Yet, Crystal beat not only my own expectations; but beat Nim for both memory usage **AND** execution times. I really didn't expect to see Crystal come out *this* far ahead in performance. On the other hand, Nim came out by-far the leader when it comes to language interoperability. **Nim makes it even easier** than Crystal when interfacing other langs – not something I thought possible, given just how easy Crystal makes the task.
|
||||
|
||||
In conclusion, it seems that we have 1 point for Nim (interoperability), and 1 point for Crystal (performance). Both languages have pleasantly surprised me, and I look forward to diving into the next topics in the series:
|
||||
|
||||
- Part 2: Threading and Tooling
|
||||
- Part 3: Crypto, DApps and P2P
|
||||
|
||||
These two articles will be released over the next couple of days, so don't forget to come back then to check them out!
|
||||
|
||||
Thanks for reading - as ever, if you have any questions, please feel free to reach out at [robin@status](mailto:robin@status.im).
|
||||
|
||||
[ - **@rbin**](https://twitter.com/rbin)
|
@ -0,0 +1,325 @@
|
||||
title: Nim vs Crystal - Part 2 - Threading & Tooling
|
||||
summary: "Crystal and Nim go head-to-head to figure out the best modern, low-level programming language! In part 2, Threading & Tooling are reviewed."
|
||||
author: robin_percy
|
||||
categories:
|
||||
- tutorials
|
||||
layout: blog-post
|
||||
image: '/assets/images/nim-crystal-header_blank.jpg'
|
||||
---
|
||||
|
||||

|
||||
|
||||
Welcome back to my series comparing the two sweethearts of the modern low-level programming world. In [part 1](/news/2019/11/18/nim-vs-crystal-part-1-performance-interoperability/), I talked about my views on the interoperability of the two languages, alongside the performance figures of both. Article #1 managed to throw-up a couple of surprises, but I have to admit; these made it all the more enjoyable to write!
|
||||
|
||||
In this article, we're going to look into the commodity that would have changed the aforementioned performance figures, namely concurrency & parallelism, and then into the things that attract me most to programming languages; which is he in-built tooling available. As I know it'll be useful; I won't cover ***only*** the in-built tooling, but I'll include my favourite external package too.
|
||||
|
||||
|
||||
|
||||
# Threading
|
||||
|
||||
|
||||
### Nim Parallelism Primitives
|
||||
|
||||
Nim has two flavours of parallelism:
|
||||
|
||||
* Structured parallelism via the parallel statement.
|
||||
* Unstructured parallelism via the standalone spawn statement.
|
||||
|
||||
Nim has a builtin thread pool that can be used for CPU intensive tasks. For IO intensive tasks the async and await features should be used instead. Both parallel and spawn need the threadpool module to work.
|
||||
|
||||
``` nim
|
||||
import threadpool
|
||||
|
||||
proc processLine(line: string) =
|
||||
discard "do some heavy lifting here"
|
||||
|
||||
for x in lines("myinput.txt"):
|
||||
spawn processLine(x)
|
||||
sync()
|
||||
```
|
||||
|
||||
The parallel statement is the preferred way to use parallelism in a Nim program.
|
||||
|
||||
``` nim
|
||||
# Compute Pi in an inefficient way
|
||||
|
||||
import strutils, math, threadpool
|
||||
{.experimental: "parallel".}
|
||||
|
||||
proc term(k: float): float = 4 * math.pow(-1, k) / (2*k + 1)
|
||||
|
||||
proc pi(n: int): float =
|
||||
var ch = newSeq[float](n+1)
|
||||
parallel:
|
||||
for k in 0..ch.high:
|
||||
ch[k] = spawn term(float(k))
|
||||
for k in 0..ch.high:
|
||||
result += ch[k]
|
||||
|
||||
echo formatFloat(pi(5000))
|
||||
```
|
||||
|
||||
Threading support in Nim is part of the `system` module. To activate thread support you need to compile with the `--threads:on` command line switch.
|
||||
|
||||
Nim's memory model for threads is quite different from older common programming languages (C, Pascal), but similar to Golang and Elixir in that; each thread has its own (garbage collected) heap and sharing of memory is restricted. This helps to prevent race conditions and improves efficiency.
|
||||
|
||||
### Concurrency vs Parallelism
|
||||
|
||||
The definitions of "concurrency" and "parallelism" sometimes get mixed up, but they are not the same.
|
||||
|
||||
A concurrent system is one that can be in charge of many tasks, although not necessarily executing them at the same time. A good way to think of this is driving a car – the car can accelerate, brake & change gear, but they don't happen at the exact same time, although they *do* overlap. This is concurrency.
|
||||
|
||||

|
||||
*Source: https://livebook.manning.com/book/nim-in-action/chapter-6/13*
|
||||
|
||||
The human driving the car holds the clutch in, moves the gear lever in parallel, and then eases of the clutch at the exact same time as easing on the accelerator. This is processes running in parallel, hence parallelism.
|
||||
|
||||

|
||||
*Source: https://livebook.manning.com/book/nim-in-action/chapter-6/13*
|
||||
|
||||
At the moment, Crystal has concurrency support but not parallelism: several tasks can be executed, and a bit of time will be spent on each of these, but two code paths are never executed at the same exact time. However, recently [Parallelism was tested out](https://crystal-lang.org/2019/09/06/parallelism-in-crystal.html) and I'm sure will be fully ready to use soon!
|
||||
|
||||
A Crystal program executes in a single operating system thread, except the Garbage Collector (GC) which implements a concurrent mark-and-sweep (currently Boehm GC).
|
||||
|
||||
### Crystal Concurrency Primitives
|
||||
|
||||
In Crystal, we can use the `Spawn` functionality in a very similar way to Goroutines in Golang, core.async in Clojure, or the threading in Nim. When a program starts, it fires up a main `Fiber` that will execute your top-level code, from which we can spawn many other `Fibers`.
|
||||
|
||||
`Fibers` are lightweight threads of execution that are managed by the garbage collector, so you don't *really* need to worry about managing them once you've spawned them. Because of this, you could technically spin up 100 `Fibers` to make a bunch of API requests, and then simply forget about them.
|
||||
|
||||
You *could* do this with OS threads, but `pthread_create` and `pthread_join` (the `libc` functions that usually back threads) are expensive system calls, so you really shouldn't.
|
||||
|
||||
We can utilise `Spawn` in Crystal like so:
|
||||
|
||||
``` crystal
|
||||
require "socket"
|
||||
|
||||
def load(id, chan)
|
||||
puts "ID=#{id}; START"
|
||||
(id..11).each do
|
||||
socket = TCPSocket.new("http://robin.percy.pw", 80)
|
||||
socket.close
|
||||
end
|
||||
puts "ID=#{id}; FINISH"
|
||||
chan.send nil
|
||||
end
|
||||
|
||||
def main
|
||||
chan = Channel(Nil).new
|
||||
(1..10).each{|i| spawn(load(i,chan))}
|
||||
# Wait
|
||||
(1..10).each{chan.receive}
|
||||
end
|
||||
|
||||
main
|
||||
```
|
||||
|
||||
> To support concurrency, Crystal has to be able to switch fibers when a fiber performs non-blocking IO operations.
|
||||
|
||||
In program above, a spawned task with lower-number id repeatedly creates a TCP socket, and does this more times than a task with a higher-number id. For example; task #1 establishes a TCP socket 11 times, and task #10 creates a TCP socket just once. So even though task #1 started long before task #10, task #10 *should* finish before task #1. As you can see in the image below; it does just that!
|
||||
|
||||

|
||||
|
||||
Similar to Golang, Crystal uses channels to pass messages between spawned fibers. Take the traditional Ping Pong channels example, in Crystal it looks like the following:
|
||||
|
||||
``` crystal
|
||||
def ping(pings, message)
|
||||
pings.send message
|
||||
end
|
||||
|
||||
def pong(pings, pongs)
|
||||
message = pings.receive
|
||||
pongs.send message
|
||||
end
|
||||
|
||||
pings = Channel(String).new
|
||||
pongs = Channel(String).new
|
||||
spawn ping pings, "passed message"
|
||||
spawn pong pings, pongs
|
||||
puts pongs.receive # => "passed message"
|
||||
```
|
||||
|
||||
Unfortunately, I personally haven't had the opportunity to test Crystal's `Fibers` or Nim's `Spawn` in a load-heavy production environment. But soon I fully intend to, and I'll write another article benchmarking this in detail when I have a good usecase and get the chance to!
|
||||
|
||||
|
||||
# Tooling
|
||||
|
||||
## Built-in Tooling in Nim
|
||||
|
||||
Now that [Nim 1.0 has been released](https://nim-lang.org/blog/2019/09/23/version-100-released.html), its in-built tooling has improved to a great level, and is very quickly reaching maturity.
|
||||
|
||||
The standard library in Nim is fantastic... Things like native database support for multiple db's, without using any external packages like Crystal does, makes me extremely hopeful for Nim. I really do believe it is language worth considering, if it matches your production needs. That being said, I am still an advocate of 'use the right tool for the job' – so don't go implementing Nim just for the sake of it!
|
||||
|
||||
The only thing to keep in mind; is that Nim *does* seem to be slower in growth than Crystal. The thing is – Nim has quite a few **less** core contributors than Crystal, so slower growth is to be expected!
|
||||
|
||||
|
||||
### Nim Project Packaging
|
||||
|
||||
Something I look for in ***ALL*** modern programming languages, and something I consider to be a necessity is a good, and well featured in-built package manager. Happily in Nim's case; we have Nimble!
|
||||
|
||||
We can create a new app (library/binary) by using `nimble init`:
|
||||
|
||||

|
||||
|
||||
I have to admit, although a simple thing, this is one of my favourite parts of the entire Nim ecosystem! Being able to enter your selection variables while actually creating your app package is something I think is not only tremendously useful, but awesomely novel.
|
||||
|
||||
It's not just the fact that you can enter selections, but actually the fact that you can select the backend for your app. As you can see in the image above, you have the choice of C, C++, Objective-C and JavaScript -– something that I touched on in my [last article.](/news/2019/11/18/nim-vs-crystal-part-1-performance-interoperability/)
|
||||
|
||||
|
||||
### Documentation
|
||||
|
||||
Nimble has in-built documentation generators that can output both HTML and JSON project documentation files. The one thing I will say is that I actually found this functionality to be *slightly* confusing, as I kept getting very odd errors, but also lacking in the excellent use experience you get from the rest of Nimble, i.e. the `init` func.
|
||||
|
||||
You can generate the documentation file for your app by running:
|
||||
|
||||
```
|
||||
nimble doc myapp.nimble
|
||||
```
|
||||
|
||||
### Testing
|
||||
|
||||
Nimble offers a pre-defined `test` task which compiles and runs all files in the `/tests` directory beginning with 't' in their filename.
|
||||
|
||||
You may wish to override this `test` task in your `.nimble` file. This is particularly useful when you have a single test suite program. Just add the following to your `.nimble` file to override the default `test` task.
|
||||
|
||||
``` nim
|
||||
task test, "Runs the test suite":
|
||||
exec "nim c -r tests/tester"
|
||||
```
|
||||
|
||||
Running nimble test will now use the test task you have defined.
|
||||
|
||||
|
||||
|
||||
<br/>
|
||||
|
||||
## Built-in Tooling in Crystal
|
||||
|
||||
One of the things I like most about Crystal is the excellent built-in tooling available. When I look at new languages, especially relatively immature languages; it's always very reassuring when the language has extensive built-in tooling available to help developers stay productive & happy! In Crystal, there are a bunch of tools that make hacking around in the language super fun, but also help us to stay on the right track with semantics etc.
|
||||
|
||||
|
||||
### Crystal Project Packaging
|
||||
|
||||
Much the same as the Nimble package manager, ***although not as good in my opinion,*** Crystal has it's own built-in project scaffolder & package manager. I'd recommend using this at all times to ensure semantics are followed. We can use it with the following:
|
||||
|
||||
```
|
||||
$ crystal init lib my_app
|
||||
create my_app/.gitignore
|
||||
create my_app/LICENSE
|
||||
create my_app/README.md
|
||||
create my_app/.travis.yml
|
||||
create my_app/shard.yml
|
||||
create my_app/src/my_app
|
||||
create my_app/src/my_app/version.cr
|
||||
create my_app/spec/spec_helper.cr
|
||||
create my_app/spec/my_app_spec.cr
|
||||
Initialized empty Git repository in ~/my_app/.git/
|
||||
```
|
||||
|
||||
`Shards` are Crystal's packages; distributed in the same way as Ruby Gems, Elixir Libs or Golang packages. Each application we create contains a file in the root directory named shard.yml. This file contains project details and external dependencies. The shard.yml file in the `my_app` app above looks like this:
|
||||
|
||||
``` yaml
|
||||
name: my_app
|
||||
version: 0.1.0
|
||||
|
||||
authors:
|
||||
- Robin Percy <robin@percy.pw>
|
||||
|
||||
targets:
|
||||
sayhi_c:
|
||||
main: src/my_app.cr
|
||||
|
||||
crystal: 0.31.1
|
||||
|
||||
license: MIT
|
||||
```
|
||||
|
||||
The app I built has no dependencies to use, but if we want to include external packages we can do so by adding them at the bottom of the file:
|
||||
|
||||
``` yaml
|
||||
dependencies:
|
||||
github:
|
||||
github: felipeelias/crystal-github
|
||||
version: ~> 0.1.0
|
||||
```
|
||||
|
||||
### Documentation & Formatting
|
||||
|
||||
Crystal has a great built-in tool for generating documentation and formatting files. The documentation that is generated is excellent - built-in html/css and almost instantly ready to deploy.
|
||||
|
||||
To generate documentation, from the project root directory we can simply run:
|
||||
|
||||
```
|
||||
$ crystal doc
|
||||
```
|
||||
This will create a docs directory, with a doc/index.html entry point. All files inside the root src directory of the project from which we ran the command will be considered.
|
||||
|
||||
Alongside this, the built-in Formatter tool is a great feature of the language. We can run the formatter over our project by running:
|
||||
|
||||
```
|
||||
$ crystal tool format
|
||||
```
|
||||
|
||||
We can use this tool to unify code styles and to submit documentation improvements to Crystal itself. The formatter is also very fast, so very little time is lost if you format the entire project's codebase instead of just a single file.
|
||||
|
||||
<br/>
|
||||
|
||||
## My Top Crystal Repo
|
||||
|
||||
### Kemal
|
||||
|
||||
Obviously, there ***had*** to be a web framework appear in this list, seen as that's what absolutely **every** dev seems to want to implement. My choice here is my buddy [Serdar's](https://twitter.com/sdogruyol) library; [Kemal](https://kemalcr.com/). One feature I really like about it, is how simple it makes it to utilise JSON & create a JSON API. For example, accepting JSON in a POST request, parsing & mapping it directly to an object:
|
||||
|
||||
``` crystal
|
||||
require "kemal"
|
||||
require "json"
|
||||
|
||||
class User
|
||||
JSON.mapping(
|
||||
firstname: String,
|
||||
surname: String,
|
||||
)
|
||||
end
|
||||
|
||||
post "/" do |env|
|
||||
user = User.from_json env.request.body.not_nil!
|
||||
{firstname: user.firstname, surname: user.surname}.to_json
|
||||
end
|
||||
|
||||
Kemal.run
|
||||
```
|
||||
|
||||
**If you want to find all of the best Crystal libraries, [you can check them out here.](https://github.com/veelenga/awesome-crystal)**
|
||||
|
||||
<br />
|
||||
|
||||
## My Top Nim Repo
|
||||
|
||||
### Nimbus
|
||||
|
||||
My favourite Nim library really has to be [Nimbus](https://github.com/status-im/nimbus). This is not because I work for [Status](https://status.im) (the Nimbus creators), but because of the technology. Nimbus has has such a fantastic reception from the Nim community – and rightly so!
|
||||
|
||||
I think that Nimbus is literally the most impressive Nim library outside of the Nim core, the [Nim Beacon Chain](https://github.com/status-im/nimbus) particularly so!
|
||||
|
||||
> Nimbus beacon chain is a research implementation of the beacon chain component of the upcoming Ethereum Serenity upgrade (Ethereum 2)
|
||||
|
||||
Whilst there are no developer code samples to include here, you can check out the [main Nimbus website](https://nimbus.team/), and the [main Nimbus repo](https://github.com/status-im/nimbus/).
|
||||
|
||||
Take a look at [https://nimble.directory/](https://nimble.directory/) for a full list of external Nim libraries available for your projects!
|
||||
|
||||
|
||||
# Conclusion
|
||||
|
||||
Back in 2012 when I quit writing Python and started exploring a bunch of other available languages, I started to become more aware of threading and its benefits. Once I got into the likes of Golang and Elixir, I learned about their threading models, and lightweight threads of execution being the way forward.
|
||||
|
||||
It's fantastic seeing both Nim *and* Crystal adopting the aforementioned concurrency primitives. I guess I have to give both languages a point there!
|
||||
|
||||
I briefly touched on the smaller number of people on the Nim core team above, and this is something that's pretty unfortunate. Nim is a language and an ecosystem that has **such** great promise, I would love to see more people contributing to it and utilising it in production systems.
|
||||
|
||||
The final article in this series, "Crypto, DApps & P2P", will be released over the coming days, so keep checking back.
|
||||
|
||||
Thanks again for sticking with me!
|
||||
|
||||
[ **- @rbin**](https://twitter.com/rbin)
|
||||
|
||||
|
@ -0,0 +1,327 @@
|
||||
title: Nim vs Crystal - Part 3 - Crypto, DApps & P2P
|
||||
summary: "Crystal and Nim go head-to-head to figure out the best modern, low-level programming language! In part 3; Crypto, P2P & DApps are explored."
|
||||
author: robin_percy
|
||||
categories:
|
||||
- tutorials
|
||||
layout: blog-post
|
||||
image: '/assets/images/nim-crystal-header_blank.jpg'
|
||||
---
|
||||
|
||||

|
||||
|
||||
Welcome back to my series comparing the two sweethearts of the modern low-level programming world. Just to quickly recap: in [article #1](/news/2019/11/18/nim-vs-crystal-part-1-performance-interoperability/) I noted my thoughts on the interoperability capabilities of the two languages, alongside briefly reviewing the performance metrics for each (albeit with relatively simple tests). Whether simple or not, the tests ***did*** throw up some unexpected twists in the plot. Crystal used *very-nearly* half of the memory amount executing the tests when compared to Nim, and also took *very nearly* half of the execution time in doing so. **This seriously took me by surprise!**
|
||||
|
||||
In [article #2](/news/2019/11/21/nim-vs-crystal-part-2-threading-tooling/); I looked at the Concurrency primitives of each language, and explored both the in-built tooling, and external package ecosystems surrounding each language. As I said in that article, one of the biggest factors I look at when considering adopting a new language; is its tooling ecosystem. This includes, but is not limited to: A comprehensive package manager, an intuitive testing suite, a good project scaffolder, and an in-built formatter/linter to ensure my code stays semantically correct – especially if I know I will be working in Open Source repos that others will contribute to. But they're just the high-level tools that I look for...
|
||||
|
||||
From a low-level standpoint; I look for efficient use of technology in features such as in-memory storage, caching, garbage collection, and concurrency primitives that not just *markedly* improve our application performance, but that are also relatively simple, and intuitive to use. I see *this* as particularly important as I have, in my past, seen some truly shocking examples of trying to handle multi-threading, from languages that I love \*cough* ***Ruby*** \*cough*. I also like to see a fully-featured standard library that takes influence from previous successful languages. However, I digress...
|
||||
|
||||
I regret to say that this is the final article in this series! It's been good fun for me; getting to the know the ins-and-outs of Nim, and to re-grow a fresh appreciation of Crystal, having put it on the back-burner for quite some time. However, whether the final article in the series or not, it's going to be a good one! We're going to be covering the benefits to the Cryptocurrency / DApp industries from both Crystal and Nim. So without further ado:
|
||||
|
||||
***Let's dive on in!***
|
||||
|
||||
## Cryptocurrency
|
||||
|
||||
Firstly, I'd like to talk about the possibility of using either Crystal or Nim, (or both!) in the development of crypto apps. Hypothetically; if we had the inclination to build out our own Cryptocurrency: Crystal and Nim have ***proven to be two of the strongest languages*** to consider for the undertaking.. (That being the *next* blog series I'm going to write – in the near future, so deciding which language to use will be heavily influenced by ***this*** blog series!)
|
||||
|
||||
For our Cryptocurrency, we would need to be able to use an intelligent key manager, utilise smart hashing algorithms, maintain strong performance, and all of this atop of a distributed, decentralised virtual machine or blockchain. Now, all of this sounds like a ***very*** tall order! For all of these feature requirements to be met by a single programming language, it would mean that this language is going to have to be **ONE HELL** of an impressive piece of technology.
|
||||
|
||||
Happily, both Crystal *and* Nim allow us ***all*** of the above functionality. In our hypothetical usecase, if we were to build out a fully-featured blockchain; mining *and* hashing functions would need to be continually made, both of which entail relatively heavy computations. As shown over the last 2 articles in the series, we can at least be sure that both langs can handle the performance stresses, no problemo.
|
||||
|
||||
As I'd like to write this topic out into a further detailed article series, I will show off just 2 of the above pieces of functionality we'd require for our Crypto app:
|
||||
|
||||
|
||||
### Calculating our Block Hashes
|
||||
|
||||
When building our Blockchain; we need to consider how we're going to identify and chain our transaction blocks together (blockchain). Without going into details in *this* article on how blockchains function, we'll stick with the existing, and proven, SHA256 algorithm.
|
||||
|
||||
|
||||
### In Crystal:
|
||||
|
||||
``` crystal
|
||||
require "json"
|
||||
require "openssl"
|
||||
|
||||
module OurCryptoApp::Model
|
||||
struct Transaction
|
||||
include JSON::Serializable
|
||||
|
||||
alias TxnHash = String
|
||||
|
||||
property from : String
|
||||
property to : String
|
||||
property amount : Float32
|
||||
getter hash : TxnHash
|
||||
getter timestamp : Int64
|
||||
|
||||
def initialize(@from, @to, @amount)
|
||||
@timestamp = Time.utc_now.to_unix
|
||||
@hash = calc_hash
|
||||
end
|
||||
|
||||
private def calc_hash : TxnHash
|
||||
sha = OpenSSL::Digest.new("SHA256")
|
||||
sha.update("#{@from}#{@to}#{@amount}#{@timestamp}")
|
||||
sha.hexdigest
|
||||
end
|
||||
end
|
||||
end
|
||||
```
|
||||
|
||||
|
||||
### In Nim:
|
||||
|
||||
If we want to generate a similar hash in Nim, we could run the following:
|
||||
|
||||
``` nim
|
||||
import strutils
|
||||
|
||||
const SHA256Len = 32
|
||||
|
||||
proc SHA256(d: cstring, n: culong, md: cstring = nil): cstring {.cdecl, dynlib: "libssl.so", importc.}
|
||||
|
||||
proc SHA256(s: string): string =
|
||||
result = ""
|
||||
let s = SHA256(s.cstring, s.len.culong)
|
||||
for i in 0 .. < SHA256Len:
|
||||
result.add s[i].BiggestInt.toHex(2).toLower
|
||||
|
||||
echo SHA256("Hash this block, yo")
|
||||
```
|
||||
|
||||
|
||||
## Releasing our Crypto App
|
||||
|
||||
Another serious factor we have to consider, is the ability to distribute our crypto app, once built, with great ease. Remembering that both Crystal and Nim are *compiled* languages, we're already off to a promising start. (A single executable binary is always going to be easier to distribute than something requiring its own specialist environment!)
|
||||
|
||||
It pays rather large dividends being able to write our Crypto app just once, and having the ability to maintain one singular code repo for that app. To this end – I think it is definitely worth considering a multi-platform app framework. I already know that in my next article series, I will be exploring building a Crypto app using [React Native](https://facebook.github.io/react-native/).
|
||||
|
||||
However, if you wish to build the frontend of your cross-platform crypto app in something else, there are a variety of technologies available - all of which seem to work well with both Crystal and Nim:
|
||||
|
||||
- [Ionic Framework](http://ionicframework.com/)
|
||||
- [Flutter](https://flutter.io/)
|
||||
- [NativeScript](https://www.nativescript.org/)
|
||||
|
||||
And if you come from a Windows background:
|
||||
|
||||
- [Xamarin](https://dotnet.microsoft.com/apps/xamarin)
|
||||
|
||||
|
||||
### Building & Releasing In Nim:
|
||||
|
||||
If we wanted to build out and release our app for Android, we can run:
|
||||
|
||||
```
|
||||
nim c -c --cpu:arm --os:android -d:androidNDK --noMain:on
|
||||
```
|
||||
|
||||
To generate the C source files we need to include in our Android Studio project. We then simply add the generated C files to our CMake build script in our Android project.
|
||||
|
||||
Similarly, we could run:
|
||||
|
||||
```
|
||||
nim c -c --os:ios --noMain:on
|
||||
```
|
||||
|
||||
To generate C files to include in our XCode project. Then, we can use XCode to compile, link, package and sign everything.
|
||||
|
||||
|
||||
### Building & Releasing In Crystal:
|
||||
|
||||
Crystal also allows for cross-compilation, and makes it just as easy. For example, to build our app for Linux distributions from our Mac, we can run:
|
||||
|
||||
```
|
||||
crystal build your_program.cr --cross-compile --target "x86_64-unknown-linux-gnu"
|
||||
```
|
||||
|
||||
***Worth noting:*** *Crystal doesn't offer the out-of-the-box iPhone / Android cross-compilation functionality that Nim does, so building our app in Nim gets a definite thumbs-up from a distribution point-of-view!*
|
||||
|
||||
## Ethereum - Building, Signing & Sending a Transaction
|
||||
|
||||
For the sake of this article, in Crystal, I didn't see the need to write out a more low-level example of the below action, as it *is* so similar to the Nim demo that follows. This actually worked out in my favour, as it means I get to further show off the native HTTP library for Crystal.
|
||||
|
||||
### In Crystal:
|
||||
|
||||
``` crystal
|
||||
require "http/client"
|
||||
|
||||
module Ethereum
|
||||
class Transaction
|
||||
|
||||
# /ethereum/create/ Create - Ethereum::Transaction.create(args)
|
||||
def self.create(to : String, from : String, amount : UInt64, gas_price : UInt64? = nil, gas_limit : UInt64? = nil) : EthereumToSign | ErrorMessage
|
||||
|
||||
headers = HTTP::Headers.new
|
||||
if ENV["ONCHAIN_API_KEY"]? != nil
|
||||
headers.add("X-API-KEY", ENV["ONCHAIN_API_KEY"])
|
||||
end
|
||||
|
||||
response = HTTP::Client.post "https://onchain.io/api/ethereum/create//?to=#{to}&from=#{from}&amount=#{amount}&gas_price=#{gas_price}&gas_limit=#{gas_limit}", headers: headers
|
||||
|
||||
return ErrorMessage.from_json response.body if response.status_code != 200
|
||||
|
||||
ethereumtosign = EthereumToSign.from_json response.body
|
||||
|
||||
|
||||
return ethereumtosign
|
||||
end
|
||||
|
||||
# /ethereum/sign_and_send/ Sign and send - Ethereum::Transaction.sign_and_send(args)
|
||||
def self.sign_and_send(to : String, from : String, amount : UInt64, r : String, s : String, v : String, gas_price : UInt64? = nil, gas_limit : UInt64? = nil) : SendStatus | ErrorMessage
|
||||
|
||||
headers = HTTP::Headers.new
|
||||
if ENV["ONCHAIN_API_KEY"]? != nil
|
||||
headers.add("X-API-KEY", ENV["ONCHAIN_API_KEY"])
|
||||
end
|
||||
|
||||
response = HTTP::Client.post "https://onchain.io/api/ethereum/sign_and_send//?to=#{to}&from=#{from}&amount=#{amount}&r=#{r}&s=#{s}&v=#{v}&gas_price=#{gas_price}&gas_limit=#{gas_limit}", headers: headers
|
||||
|
||||
return ErrorMessage.from_json response.body if response.status_code != 200
|
||||
|
||||
sendstatus = SendStatus.from_json response.body
|
||||
|
||||
|
||||
return sendstatus
|
||||
end
|
||||
|
||||
end
|
||||
end
|
||||
```
|
||||
|
||||
Then, in our application we could simply call:
|
||||
|
||||
``` crystal
|
||||
Ethereum::Transaction.create("0xA02378cA1c24767eCD776aAFeC02158a30dc01ac", "0xA02378cA1c24767eCD776aAFeC02158a30dc01ac", 80000)
|
||||
```
|
||||
|
||||
And we would get a response similar to the following, ready to be signed and sent to the Ethereum network:
|
||||
|
||||
``` json
|
||||
{
|
||||
"tx": "02000000011cd5d7621e2a7c9403e54e089cb0b5430b83ed13f1b897d3e319b100ba1b059b01000000db00483045022100d7534c80bc0a42addc3d955f74e31610aa78bf15d79ec4df4c36dc98e802f5200220369cab1bccb2dbca0921444ce3fafb15129fa0494d041998be104df39b8895ec01483045022100fe48c4c1d46e163acaff6b0d2e702812d20",
|
||||
"hash_to_sign": "955f74e31610aa78bf15d79ec4df4c36dc98e802f52002"
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## In Nim:
|
||||
|
||||
From a deeper, more low-level perspective; instead of using an HTTP library as in the Crystal example above, we can use Status' very own Nim-Ethereum library to build our Ethereum transaction. Assuming we have imported `nim-eth` into our Nimble project, our Ethereum transaction can be built atop of the following protocol:
|
||||
|
||||
``` nim
|
||||
import
|
||||
nim-eth/[common, rlp, keys], nimcrypto
|
||||
|
||||
proc initTransaction*(nonce: AccountNonce, gasPrice, gasLimit: GasInt, to: EthAddress,
|
||||
value: UInt256, payload: Blob, V: byte, R, S: UInt256, isContractCreation = false): Transaction =
|
||||
result.accountNonce = nonce
|
||||
result.gasPrice = gasPrice
|
||||
result.gasLimit = gasLimit
|
||||
result.to = to
|
||||
result.value = value
|
||||
result.payload = payload
|
||||
result.V = V
|
||||
result.R = R
|
||||
result.S = S
|
||||
result.isContractCreation = isContractCreation
|
||||
|
||||
type
|
||||
TransHashObj = object
|
||||
accountNonce: AccountNonce
|
||||
gasPrice: GasInt
|
||||
gasLimit: GasInt
|
||||
to {.rlpCustomSerialization.}: EthAddress
|
||||
value: UInt256
|
||||
payload: Blob
|
||||
mIsContractCreation {.rlpIgnore.}: bool
|
||||
|
||||
proc read(rlp: var Rlp, t: var TransHashObj, _: type EthAddress): EthAddress {.inline.} =
|
||||
if rlp.blobLen != 0:
|
||||
result = rlp.read(EthAddress)
|
||||
else:
|
||||
t.mIsContractCreation = true
|
||||
|
||||
proc append(rlpWriter: var RlpWriter, t: TransHashObj, a: EthAddress) {.inline.} =
|
||||
if t.mIsContractCreation:
|
||||
rlpWriter.append("")
|
||||
else:
|
||||
rlpWriter.append(a)
|
||||
|
||||
const
|
||||
EIP155_CHAIN_ID_OFFSET* = 35
|
||||
|
||||
func rlpEncode*(transaction: Transaction): auto =
|
||||
# Encode transaction without signature
|
||||
return rlp.encode(TransHashObj(
|
||||
accountNonce: transaction.accountNonce,
|
||||
gasPrice: transaction.gasPrice,
|
||||
gasLimit: transaction.gasLimit,
|
||||
to: transaction.to,
|
||||
value: transaction.value,
|
||||
payload: transaction.payload,
|
||||
mIsContractCreation: transaction.isContractCreation
|
||||
))
|
||||
|
||||
func rlpEncodeEIP155*(tx: Transaction): auto =
|
||||
let V = (tx.V.int - EIP155_CHAIN_ID_OFFSET) div 2
|
||||
# Encode transaction without signature
|
||||
return rlp.encode(Transaction(
|
||||
accountNonce: tx.accountNonce,
|
||||
gasPrice: tx.gasPrice,
|
||||
gasLimit: tx.gasLimit,
|
||||
to: tx.to,
|
||||
value: tx.value,
|
||||
payload: tx.payload,
|
||||
isContractCreation: tx.isContractCreation,
|
||||
V: V.byte,
|
||||
R: 0.u256,
|
||||
S: 0.u256
|
||||
))
|
||||
|
||||
func txHashNoSignature*(tx: Transaction): Hash256 =
|
||||
# Hash transaction without signature
|
||||
return keccak256.digest(if tx.V.int >= EIP155_CHAIN_ID_OFFSET: tx.rlpEncodeEIP155 else: tx.rlpEncode)
|
||||
```
|
||||
|
||||
*Note* - I do realise the above Nim code example and the Crystal examples are different - I fully intended them to be. The Crystal example allowed me to further show off the HTTP library I touched on in the last article, and the Nim example allowed me to go to a lower-level; something I think brings the article relevancy full circle.
|
||||
|
||||
|
||||
[Status' Eth Common Library](https://github.com/status-im/nim-eth/) contains a whole bunch of useful Nim libraries for interacting with the Ethereum Network, including:
|
||||
|
||||
- [Recursive Length Prefix encoding (RLP)](https://github.com/status-im/nim-eth/blob/master/doc/rlp.md),
|
||||
- [P2P](https://github.com/status-im/nim-eth/blob/master/doc/p2p.md),
|
||||
- [Eth-keys](https://github.com/status-im/nim-eth/blob/master/doc/keys.md),
|
||||
- [Eth-keyfile](https://github.com/status-im/nim-eth/blob/master/doc/keyfile.md),
|
||||
- [Ethereum Trie structure](https://github.com/status-im/nim-eth/blob/master/doc/trie.md), and
|
||||
- [Ethereum Bloom Filter](https://github.com/status-im/nim-eth/blob/master/doc/bloom.md).
|
||||
|
||||
If you are going to be working in the Ethereum ecosystem using Nim, it goes without saying that these utilities are absolutely essential. With Status & the [Nimbus](https://nimbus.team) team being such early adopters and major contributors to the Nim/Crypto universe, you are more than likely to stumble across this code sooner or later!
|
||||
|
||||
|
||||
## Conclusion
|
||||
|
||||
Our hypothetical Crypto app has taken shape throughout this article, and I think both languages have shown off great promise, and have proven their respective abilities to power the Cryptocurrency universe.
|
||||
|
||||
Realistically, if you were a brand-new developer looking to learn a language to break into the Crypto scene, the choice would almost definitely be **Crystal**. This is simply because of the *much* larger ecosystem and resources surrounding it.
|
||||
|
||||
However, if you were an already-established developer, looking to build out a crypto app that you could develop and multi-platform release with greater ease, you'd inevitably choose **Nim**. Crystal not only lacks the ability to be developed properly on Windows, but also lacks the interoperability and multi-release functionality, as we have seen, with Nim.
|
||||
|
||||
Alas, this brings me on to my final points...
|
||||
|
||||
|
||||
## Series Conclusion
|
||||
|
||||
It's funny – each article in this series, I've started by saying to myself "Right, Nim is going to win." And then half way through; changing my story to "Crystal is my choice, actually."
|
||||
|
||||
But then I went and spoiled it all, by saying something stupid like "Cryptocurrency".
|
||||
|
||||
Prior to this article, I *was swaying* towards settling on Crystal. Not only did it impress in performance, but also seemed to have an enthusiastic ecosystem building around it. Nim, however, refused to go down without a fight – offering up *extremely* impressive interoperability, awesome inbuilt tooling, and great efficiency overall.
|
||||
|
||||
I hate to do this, but I'm just going to have to say it: for your usecase – **pick the best tool for the job**. Please ensure that you research properly into both languages, and weigh-up the pro's/con's that pertain to your specific usecase.
|
||||
|
||||
***Cliches aside*** – if I had to pick a favourite overall language, it would have to be **Crystal**. Frankly, this opinion is formed from my extensive use of Crystal over Nim, the fact I **much** prefer the Crystal syntax, and the fact that I am simply more comfortable coding in Crystal than I am in Nim!
|
||||
|
||||
So, to answer the epic question – Crystal vs Nim?
|
||||
|
||||
Personally, I choose Crystal. But I think **you** should choose ***Nim.*** 😅
|
||||
|
||||
[ **- @rbin**](https://twitter.com/rbin)
|
BIN
source/assets/images/cockpit_change_theme.gif
Normal file
After Width: | Height: | Size: 2.8 MiB |
BIN
source/assets/images/cockpit_contracts_view.gif
Normal file
After Width: | Height: | Size: 272 KiB |
BIN
source/assets/images/cockpit_dashboard.png
Normal file
After Width: | Height: | Size: 452 KiB |
BIN
source/assets/images/cockpit_dashboard_contracts.gif
Normal file
After Width: | Height: | Size: 3.3 MiB |
BIN
source/assets/images/cockpit_dashboard_dark.png
Normal file
After Width: | Height: | Size: 448 KiB |
BIN
source/assets/images/cockpit_dashboard_release.png
Normal file
After Width: | Height: | Size: 184 KiB |
BIN
source/assets/images/cockpit_debugger_controls.png
Normal file
After Width: | Height: | Size: 68 KiB |
BIN
source/assets/images/cockpit_editor.gif
Normal file
After Width: | Height: | Size: 2.1 MiB |
BIN
source/assets/images/cockpit_editor_release.png
Normal file
After Width: | Height: | Size: 220 KiB |
BIN
source/assets/images/cockpit_enter_debugger.gif
Normal file
After Width: | Height: | Size: 2.5 MiB |
BIN
source/assets/images/cockpit_explorer_account.gif
Normal file
After Width: | Height: | Size: 2.0 MiB |
BIN
source/assets/images/cockpit_explorer_block.png
Normal file
After Width: | Height: | Size: 516 KiB |
BIN
source/assets/images/cockpit_explorer_contracts_detail.gif
Normal file
After Width: | Height: | Size: 822 KiB |
BIN
source/assets/images/cockpit_explorer_overview.png
Normal file
After Width: | Height: | Size: 627 KiB |
BIN
source/assets/images/cockpit_explorer_transactions.gif
Normal file
After Width: | Height: | Size: 1.4 MiB |
BIN
source/assets/images/cockpit_navigation.gif
Normal file
After Width: | Height: | Size: 2.7 MiB |
BIN
source/assets/images/cockpit_search.gif
Normal file
After Width: | Height: | Size: 2.0 MiB |
BIN
source/assets/images/cockpit_selective_deployment.gif
Normal file
After Width: | Height: | Size: 292 KiB |
BIN
source/assets/images/cockpit_suggestions.gif
Normal file
After Width: | Height: | Size: 1.4 MiB |
BIN
source/assets/images/cockpit_using_debugger.gif
Normal file
After Width: | Height: | Size: 1.8 MiB |
BIN
source/assets/images/crystal-thread-test.png
Normal file
After Width: | Height: | Size: 93 KiB |
BIN
source/assets/images/embark-dashboard.png
Normal file
After Width: | Height: | Size: 942 KiB |
BIN
source/assets/images/nim-crystal-header-img_NEW.jpg
Normal file
After Width: | Height: | Size: 385 KiB |
BIN
source/assets/images/nim-crystal-header_blank.jpg
Normal file
After Width: | Height: | Size: 276 KiB |
BIN
source/assets/images/nimble-creating-app.png
Normal file
After Width: | Height: | Size: 193 KiB |
BIN
source/assets/images/token_factory_1/console_1.png
Normal file
After Width: | Height: | Size: 308 KiB |
BIN
source/assets/images/token_factory_1/console_2.png
Normal file
After Width: | Height: | Size: 160 KiB |
BIN
source/assets/images/token_factory_1/dashboard.png
Normal file
After Width: | Height: | Size: 9.2 MiB |
BIN
source/assets/images/token_factory_1/page_1.png
Normal file
After Width: | Height: | Size: 26 KiB |
BIN
source/assets/images/token_factory_1/page_2.png
Normal file
After Width: | Height: | Size: 3.4 KiB |
BIN
source/assets/images/token_factory_1/page_3.png
Normal file
After Width: | Height: | Size: 3.1 KiB |
BIN
source/assets/images/token_factory_1/page_4.png
Normal file
After Width: | Height: | Size: 4.4 KiB |
BIN
source/assets/images/token_factory_1/page_5.png
Normal file
After Width: | Height: | Size: 7.1 KiB |
BIN
source/assets/images/token_factory_2/console_1.png
Normal file
After Width: | Height: | Size: 381 KiB |
BIN
source/assets/images/token_factory_2/console_2.png
Normal file
After Width: | Height: | Size: 288 KiB |
BIN
source/assets/images/token_factory_2/page_1.png
Normal file
After Width: | Height: | Size: 12 KiB |
BIN
source/assets/images/token_factory_2/page_2.png
Normal file
After Width: | Height: | Size: 13 KiB |
BIN
source/assets/images/token_factory_2/page_3.png
Normal file
After Width: | Height: | Size: 20 KiB |
BIN
source/assets/images/token_factory_2/page_4.png
Normal file
After Width: | Height: | Size: 12 KiB |
BIN
source/assets/images/token_factory_2/page_5.png
Normal file
After Width: | Height: | Size: 57 KiB |
BIN
source/assets/images/token_factory_2/page_6.png
Normal file
After Width: | Height: | Size: 11 KiB |
BIN
source/assets/images/token_factory_2/page_7.png
Normal file
After Width: | Height: | Size: 13 KiB |
BIN
source/assets/images/website_release.png
Normal file
After Width: | Height: | Size: 1008 KiB |
12
source/browserconfig.xml
Normal file
@ -0,0 +1,12 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<browserconfig>
|
||||
<msapplication>
|
||||
<tile>
|
||||
<square70x70logo src="/icon/mstile-70x70.png"/>
|
||||
<square150x150logo src="/icon/mstile-150x150.png"/>
|
||||
<square310x310logo src="/icon/mstile-310x310.png"/>
|
||||
<wide310x150logo src="/icon/mstile-310x150.png"/>
|
||||
<TileColor>#2f83cd</TileColor>
|
||||
</tile>
|
||||
</msapplication>
|
||||
</browserconfig>
|
9
source/chat/index.md
Normal file
@ -0,0 +1,9 @@
|
||||
title: Chat
|
||||
layout: chat
|
||||
---
|
||||
|
||||
<p>
|
||||
Join us at <a href="https://gitter.im/embark-framework/Lobby">gitter.im/embark-framework/Lobby</a>
|
||||
</p>
|
||||
<iframe src="https://gitter.im/embark-framework/Lobby/~embed" style="width: 100%; height: 800px; border: 1px solid black"></iframe>
|
||||
|
7
source/community/index.md
Normal file
@ -0,0 +1,7 @@
|
||||
title: community_page.header.title
|
||||
tagline: community_page.header.tagline
|
||||
link:
|
||||
text: community_page.header.link
|
||||
href: https://gitter.im/embark-framework/Lobby
|
||||
layout: community
|
||||
---
|
BIN
source/coverage-files.png
Normal file
After Width: | Height: | Size: 121 KiB |
BIN
source/coverage-report.png
Normal file
After Width: | Height: | Size: 157 KiB |
7
source/docs/bamboo.md
Normal file
@ -0,0 +1,7 @@
|
||||
title: Bamboo Documentation
|
||||
---
|
||||
|
||||
The documentation for Bamboo can be found [here](https://github.com/pirapira/bamboo)
|
||||
|
||||
To use Bamboo with Embark you will need to first install the [embark-bamboo](https://github.com/embark-framework/embark-bamboo) plugin
|
||||
|
81
source/docs/blockchain_accounts_configuration.md
Normal file
@ -0,0 +1,81 @@
|
||||
title: Accounts Blockchain configuration
|
||||
layout: docs
|
||||
---
|
||||
|
||||
In our [guide on configuring a blockchain client](/docs/blockchain_configuration.html), we've configured accounts in several places.
|
||||
|
||||
This parameter let's us customize what the `accounts` will be for our deployment, as well as the accounts that will be created and unlocked by our blockchain client.
|
||||
|
||||
## Accounts parameters
|
||||
|
||||
```
|
||||
accounts: [
|
||||
{
|
||||
nodeAccounts: true,
|
||||
numAddresses: "1",
|
||||
password: "config/development/devpassword"
|
||||
},
|
||||
{
|
||||
privateKey: process.env.MyPrivateKey
|
||||
},
|
||||
{
|
||||
privateKeyFile: "path/to/file",
|
||||
password: process.env.MyKeyStorePassword
|
||||
},
|
||||
{
|
||||
mnemonic: process.env.My12WordsMnemonic,
|
||||
addressIndex: "0",
|
||||
numAddresses: "1",
|
||||
hdpath: "m/44'/60'/0'/0/"
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
The `accounts` configuration is an array of objects, where each object represents one or more account.
|
||||
|
||||
Embark offers you multiple ways to include your account. You can use the one you prefer and ignore the others or mix and match.
|
||||
|
||||
{% notification danger 'Using production keys' %}
|
||||
Be careful when using production keys and mnemonics (ie the account where you have real money).
|
||||
|
||||
We recommend using [environment variables](https://www.schrodinger.com/kb/1842) for plain text values like `privateKey` and `mnemonic` and to put the files for `privateKeyFile` and key stores either out of your working directory or ignored by versioning (eg: add the file in gitignore)
|
||||
{% endnotification %}
|
||||
|
||||
### Parameter descriptions
|
||||
|
||||
- **nodeAccounts**: The actual node accounts, that get created and unlocked by the client
|
||||
- Can be enabled by setting it to `true`
|
||||
- **numAddresses**: Number of addresses you want from the node. Defaults to `1`
|
||||
- **password**: Password file where the password to create and unlock the accounts is. This is required
|
||||
- **privateKey**: Private key string
|
||||
- **privateKeyFile**: Either a file containing comma separated private keys or a keystore (password needed for the latter). This can also be set to `random` to generate a random account (useful when testing)
|
||||
- **password**: Password string for the keystore
|
||||
- **mnemonic**: 12 word mnemonic
|
||||
- **addressIndex**: Index where to start getting the addresses. Defaults to `0`
|
||||
- **numAddresses**: Number of addresses to get. Defaults to `1`
|
||||
- **hdpath**: HD derivation path. Defaults to `"m/44'/60'/0'/0/"`
|
||||
|
||||
{% notification info 'Accounts order' %}
|
||||
The order in the accounts array is important. This means that using `nodeAccounts` first, as above, will set the node's account as the `defaultAccount` for deployment.
|
||||
{% endnotification %}
|
||||
|
||||
### Configuring account balance for development
|
||||
|
||||
When in development, we can specify the balance of each account using the `balance` option:
|
||||
|
||||
```
|
||||
module.exports = {
|
||||
development: {
|
||||
deployment: {
|
||||
accounts: [
|
||||
{
|
||||
mnemonic: "12 word mnemonic",
|
||||
balance: "5 ether"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Balances can be specified using [human readable units](/docs/contracts_configuration.html#Human-readable-Ether-units) such as "5 ether" or "200 finney". If no unit is specified the value will be in Wei.
|
171
source/docs/blockchain_configuration.md
Normal file
@ -0,0 +1,171 @@
|
||||
title: Blockchain client configuration
|
||||
layout: docs
|
||||
---
|
||||
|
||||
When in developing, to interact with a blockchain, it is necessary to use a local Ethereum node, either using a simulator or a client like Geth or Parity. In this guide we'll explore how to configure a blockchain client we want Embark to connect to. Embark uses the `blockchain.js` file inside the `./config` folder by default for blockchain related configurations. This [can be configured](/docs/configuration.html#config) to different locations if we want to.
|
||||
|
||||
Embark offers a lot of configuration options and most of them already come with a decent default so we can start right away.
|
||||
|
||||
## Common Parameters
|
||||
|
||||
Here are the common parameters. You will often need only a few of them to make your Embark node work.
|
||||
|
||||
If you want more configuration options, you can find them [here](/docs/blockchain_configuration.html#Advanced-parameters)
|
||||
|
||||
```
|
||||
module.exports = {
|
||||
default: {
|
||||
enabled: true,
|
||||
client: "geth"
|
||||
},
|
||||
development: {
|
||||
clientConfig: {
|
||||
miningMode: 'dev'
|
||||
}
|
||||
},
|
||||
testnet: {
|
||||
endpoint: "https://external-node.com",
|
||||
accounts: [
|
||||
{
|
||||
mnemonic: "12 word mnemonic"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Similar to [configuring Smart Contracts](/docs/contracts_configuration.html), this config contains environments that help configuring certain parameters differently depending of the environment. You can read more about [environments here](https://embark.status.im/docs/environments.html).
|
||||
|
||||
### Parameter descriptions
|
||||
|
||||
Most of the options are self-explanatory, still, here are some brief descriptions:
|
||||
|
||||
Option | Type: `default` | Value
|
||||
--- | --- | ---
|
||||
`enabled` | boolean: `true` | Whether or not to spawn an Ethereum node
|
||||
`client` | string: `geth` | Client to use for the Ethereum node. Currently supported: `geth` and `parity`
|
||||
`miningMode` | string: `dev` | The mining mode to use for the node.<br/>`dev`: This is a special mode where the node uses a development account as defaultAccount. This account is already funded and transactions are faster.<br/>`auto`: Uses a mining script to mine only when needed.<br/>`always`: Miner is always on.<br/>`off`: Turns off the miner
|
||||
`endpoint` | string | Endpoint to connect to. Works for external endpoints (like Infura) and local ones too (only for nodes started by `embark run`)
|
||||
`accounts` | array | Accounts array for the node and to deploy. When no account is given, defaults to one node account. For more details, go [here](/docs/blockchain_accounts_configuration.html)
|
||||
|
||||
## Advanced parameters
|
||||
|
||||
Here are all the parameters you can use to customize your node. Note that they all come with defaults that make it that you don't need to specify those.
|
||||
|
||||
We recommend putting those inside the `clientConfig` object a better structure.
|
||||
|
||||
Option | Type: `default` | Value
|
||||
--- | --- | ---
|
||||
`rpcHost` | string: `localhost` | Host the RPC server listens to
|
||||
`rpcPort` | number: `8545` | Port the RPC server listens to
|
||||
`rpcCorsDomain` | object | The CORS domains the node accepts
|
||||
`rpcCorsDomain.auto` | | When set to true, Embark checks your other configurations to set the CORS domains. This only adds the required domains.
|
||||
`rpcCorsDomain.additionalCors` | | Manual list of CORS domains to accept. If `auto` is set to `true`, any URLs specified here will be applied *in addition to* those automatically added with `auto`.
|
||||
`wsRPC` | boolean: `true` | Whether or not to enable the Websocket server
|
||||
`wsOrigins` | object | Same as `rpcCorsDomain`, but for the Websocket server
|
||||
`wsHost` | string: `localhost` | Same as `rpcHost`, but for the Websocket server
|
||||
`wsPort` | number: `8546` | Same as `rpcPort`, but for the Websocket server
|
||||
`ethereumClientBin` | string: `geth` | Path to the client binary. By default, Embark uses the client name as an executable (if it is in the PATH)
|
||||
`datadir` | string | Directory where to put the Node's data (eg: keystores)
|
||||
`networkType` | string: `custom` | Can be: `testnet`, `rinkeby`, `kovan` or custom, in which case, it will use the specified `networkId`
|
||||
`networkId` | number: `1337` | Used when `networkType` is set as `custom`. [List of known network ids](https://github.com/ethereumbook/ethereumbook/blob/3e8cf74eb935d4be495f4306b73de027af95fd97/contrib/devp2p-protocol.asciidoc#known-current-network-ids)
|
||||
`nodiscover`| boolean: `true` | Disables the peer discovery mechanism when set to `true`
|
||||
`maxpeers` | number: `0` | Maximum number of network peers
|
||||
`proxy` | boolean: `true` | Whether or not Embark should use a proxy to add functionalities. This proxy is used by Embark to see the different transactions that go through, for example, and shows them to you.
|
||||
`targetGasLimit` | number | Artificial target gas floor for the blocks to mine
|
||||
`genesisBlock` | string | The genesis file to use to create the network. This file is used when creating the network. It tells the client the parameters to initiate the node with. You can read more on [genesis blocks here](https://arvanaghi.com/blog/explaining-the-genesis-block-in-ethereum/)
|
||||
|
||||
{% notification info 'Using Parity and Metamask' %}
|
||||
|
||||
Parity has very strict CORS policies. In order to use it with Metamask (or any other browser extension), you need to add the extension's URL in the CORS.
|
||||
|
||||
You can do so by opening Metamask in its own tab. Then, copy the URL. It will look something like `chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn`.
|
||||
|
||||
Afterwards, in your blockchain config, add it to `additionalCors` of `rpcCorsDomain` and `wsOrigins`.
|
||||
{% endnotification %}
|
||||
|
||||
## Privatenet configuration
|
||||
|
||||
A private network is really similar to using the development mode of a client. The biggest differences is that it does not come with a default pre-funded account and it will not use POA (proof of authority), meaning that blocks will need to be mined.
|
||||
|
||||
Luckily, Embark has settings to limit the mining to a minimum so that everything can run smoothly while testing in a more realistic environment before going to a test network.
|
||||
|
||||
### Privatenet parameters
|
||||
|
||||
Here are common parameters for private net configurations:
|
||||
```
|
||||
privatenet: {
|
||||
clientConfig: {
|
||||
miningMode: 'auto',
|
||||
genesisBlock: "config/privatenet/genesis.json"
|
||||
}
|
||||
accounts: [
|
||||
{
|
||||
nodeAccounts: true,
|
||||
password: "config/privatenet/password"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Note that we can always use the parameters we saw in the [Common parameters section](#Common-Parameters) to override the `default` parameters.
|
||||
|
||||
### Parameter descriptions
|
||||
|
||||
Option | Type: `value` | Description
|
||||
--- | --- | ---
|
||||
`miningMode` | string: `auto` | You need to set `miningMode` to `auto` or `always` so you don't use the development mode
|
||||
`genesisBlock` | string | File to start the chain in a clean state for your private network
|
||||
`accounts` | array | Array of accounts to connect to. Go to the [Accounts configuration](/docs/blockchain_accounts_configuration.html) page to learn more on accounts
|
||||
|
||||
## Testnet configuration
|
||||
|
||||
Test networks are networks that are public. Knowing that, if we want to connect to a node that we control, we will first need to synchronize it. This can take hours, as we need to download the blocks that we are missing from the other peers.
|
||||
|
||||
The big advantage of using a local synced node is that we have control over it and it preserves our privacy, as we aren't using a third party node. However, as mentioned, it takes a lot of time to synchronize a node and also requires a lot of computer resources, so keep it in mind if you want to go down that route.
|
||||
|
||||
### Testnet parameters
|
||||
|
||||
```
|
||||
testnet: {
|
||||
networkType: "testnet",
|
||||
syncMode: "light",
|
||||
accounts: [
|
||||
{
|
||||
nodeAccounts: true,
|
||||
password: "config/testnet/password"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Here are the necessary parameters. Again, we can add more to override as you see fit.
|
||||
|
||||
### Parameter descriptions
|
||||
|
||||
Option | Type: `default` | Value
|
||||
--- | --- | ---
|
||||
`networkType` | string: `testnet` | Again, used to specify the network. `testnet` here represents Ropsten. You can change the network by using a `networkId` by changing `networkType` to `custom`
|
||||
`syncMode` | string | Blockchain sync mode
|
||||
`syncMode = 'light' `| | Light clients synchronize a bare minimum of data and fetch necessary data on-demand from the network. Much lower in storage, potentially higher in bandwidth
|
||||
`syncMode = 'fast'` | | Faster, but higher store
|
||||
`syncMode = 'full'`| | Normal sync
|
||||
`accounts` | array | Array of accounts to connect to. Go to the [Accounts configuration](/docs/blockchain_accounts_configuration.html) page to learn more on accounts
|
||||
|
||||
## Mainnet configuration
|
||||
|
||||
Finally, the main network, a.k.a. mainnet. It may come as no surprise, but to sync to the mainnet, the step and configurations are actually the same as for a [test network](#Testnet-configuration). The only major difference is that the `networkType` needs to be `custom` with the `networkId` set to `1`.
|
||||
|
||||
```
|
||||
mainnet: {
|
||||
networkType: "custom",
|
||||
networkId: 1,
|
||||
syncMode: "light",
|
||||
accounts: [
|
||||
{
|
||||
nodeAccounts: true,
|
||||
password: "config/mainnet/password"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|