-
Notifications
You must be signed in to change notification settings - Fork 0
/
atom.xml
514 lines (263 loc) · 346 KB
/
atom.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
<title>Embark</title>
<subtitle>The all-in-one developer platform for building and deploying decentralized applications.</subtitle>
<link href="/atom.xml" rel="self"/>
<link href="https://framework.embarklabs.io/"/>
<updated>2020-01-19T19:38:04.364Z</updated>
<id>https://framework.embarklabs.io/</id>
<author>
<name>Embark</name>
</author>
<generator uri="https://hexo.io/">Hexo</generator>
<entry>
<title>Introducing Embark 5</title>
<link href="https://framework.embarklabs.io/news/2020/01/13/announcing-embark-5/"/>
<id>https://framework.embarklabs.io/news/2020/01/13/announcing-embark-5/</id>
<published>2020-01-13T05:00:00.000Z</published>
<updated>2020-01-19T19:38:04.364Z</updated>
<content type="html"><![CDATA[<p>If you’ve been following the development of Embark you’re probably aware that we regularly put out alpha and beta releases for upcoming major or feature versions of Embark. In the past ~6 months since the release of Embark 4, we’ve published 10 alpha releases and one beta release for Embark 5 and today we’re happy to announce the Embark 5 stable release!</p><p>In this post we’ll be looking at some of the main changes and features to get up and running with v5. Notice that we’ve add a <a href="https://embark.status.im/docs/migrating_from_3.x.html#Updating-to-v5">migration guide</a> to our official docs as well.</p><h2 id="New-Features"><a href="#New-Features" class="headerlink" title="New Features"></a>New Features</h2><p>Let’s first start with new features that have been introduced in Embark 5.</p><h3 id="Whisper-client-configuration"><a href="#Whisper-client-configuration" class="headerlink" title="Whisper client configuration"></a>Whisper client configuration</h3><p>Prior to Embark 5, Embark would use the same blockchain client to enable blockchain features and communication features for Whisper. With Embark 5, Embark spins up a separate client for Whisper. This also ensures that that Whisper service stays in tact when the blockchain service is turned off and vice versa.</p><p>To specify a client, use the new <code>client</code> configuration property which defaults to <code>geth</code>:</p><figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">// communication.js</span></span><br><span class="line"></span><br><span class="line">...</span><br><span class="line"><span class="keyword">default</span>: {</span><br><span class="line"> ...</span><br><span class="line"> client: <span class="string">"geth"</span> <span class="comment">// can be either 'geth' or 'parity'</span></span><br><span class="line">},</span><br><span class="line">...</span><br></pre></td></tr></table></figure><h3 id="Support-for-Dynamic-Addresses"><a href="#Support-for-Dynamic-Addresses" class="headerlink" title="Support for Dynamic Addresses"></a>Support for Dynamic Addresses</h3><p>If you’re using Embark already, you’re probably aware that there are many different ways to <a href="/docs/contracts_configuration.html">configure your Smart Contracts</a>. One of the things that can be configured is the <code>address</code> of a Smart Contract. Usually the address will be determined after a Smart Contract has been deployed. In other cases, what we want to do is simply specifying the address because the Smart Contract is already deployed to the network.</p><p>There’s one more case that hasn’t been covered so far: Calculating a Smart Contract address dynamically as it’s scheduled for deployment. This is useful when the address of a Smart Contract is the result of the interaction with another Smart Contract that is already instantiated on the network.</p><p>The following example configures <code>MyContract</code> to get its address from a call made to <code>AnotherContract</code>‘s API:</p><figure class="highlight js"><table><tr><td class="code"><pre><span class="line">...</span><br><span class="line">deploy: {</span><br><span class="line"> AnotherContract: {...},</span><br><span class="line"> MyContract: {</span><br><span class="line"> deps: [<span class="string">"AnotherContract"</span>]</span><br><span class="line"> address: <span class="keyword">async</span> (deps) => {</span><br><span class="line"> <span class="keyword">const</span> receipt = <span class="keyword">await</span> deps.contracts.AnotherContract.methods.someFunction();</span><br><span class="line"> <span class="keyword">return</span> receipt.events.SomeEvent.returnValues.someAddress;</span><br><span class="line"> }</span><br><span class="line"> }</span><br><span class="line">}</span><br><span class="line">...</span><br></pre></td></tr></table></figure><h2 id="Breaking-changes"><a href="#Breaking-changes" class="headerlink" title="Breaking changes"></a>Breaking changes</h2><p>Next up, let’s quickly talk about the few breaking changes we’ve introduced to improve the overall developer experience. It’s worth noting that we try to keep breaking changes at a minimum and if it’s indeed unavoidable, we put lots of effort into keeping the necessary changes as small as possible.</p><h3 id="NodeJS-support"><a href="#NodeJS-support" class="headerlink" title="NodeJS support"></a>NodeJS support</h3><p>Due to some package dependencies, Embark doesn’t yet support Node’s <a href="https://nodejs.org/en/about/releases/" target="_blank" rel="noopener"><em>Current</em> version</a> version (13.x) or latest LTS version (12.x). Embark 5 runs with any node version <code>>= 10.17.0</code> and <code>< 12.0.0</code>. It also requires npm <code>>= 6.11.3</code> (bundled with Node <code>10.17.0</code>) or yarn <code>>= 1.19.1</code>.</p><h3 id="New-Smart-Contract-configuration-API"><a href="#New-Smart-Contract-configuration-API" class="headerlink" title="New Smart Contract configuration API"></a>New Smart Contract configuration API</h3><p>Embark’s Smart Contract configuration has been highly declarative from day one. Configuring different deployment options and settings for various scenarios is a largely descriptive process when using Embark. However, we felt there was still room for improvement. Especially because Embark handles not only Smart Contract configurations, but also configurations for elements such as the user’s choice of blockchain client. This sometimes caused confusion for our users since they weren’t sure where certain configurations should go.</p><p>That’s why we’ve made the following changes:</p><h3 id="Deployment-section-moved-to-Blockchain-config"><a href="#Deployment-section-moved-to-Blockchain-config" class="headerlink" title="Deployment section moved to Blockchain config"></a>Deployment section moved to Blockchain config</h3><p>The <code>deployment</code> section of the Smart Contract configuration has been completely moved to the Blockchain configuration as discussed in a moment. This section was primarily used to specify things like the <code>host</code>, <code>port</code> and <code>protocol</code> being used to connect to a node to which you Smart Contracts will be deployed, as well as the accounts configuration.</p><p>Here’s what such a config looked like prior to v5:</p><figure class="highlight js"><table><tr><td class="code"><pre><span class="line">...</span><br><span class="line">deployment: {</span><br><span class="line"> host: <span class="string">"localhost"</span>, <span class="comment">// Host of the blockchain node</span></span><br><span class="line"> port: <span class="number">8546</span>, <span class="comment">// Port of the blockchain node</span></span><br><span class="line"> type: <span class="string">"ws"</span> <span class="comment">// Type of connection (ws or rpc),</span></span><br><span class="line"> accounts: [...]</span><br><span class="line">},</span><br><span class="line">...</span><br></pre></td></tr></table></figure><p>There’s no equivalent for this configuration inside the Smart Contract configuration in Embark 5, so this section can be entirely (re)moved.</p><h3 id="contracts-property-has-been-renamed-to-deploy"><a href="#contracts-property-has-been-renamed-to-deploy" class="headerlink" title="contracts property has been renamed to deploy"></a><code>contracts</code> property has been renamed to <code>deploy</code></h3><p>When configuring Smart Contracts, there are a few deployment hooks that can be specified, such as <code>beforeDeploy</code> and <code>afterDeploy</code>. To make the API a bit more descriptive and to clarify intent, the <code>contracts</code> property has been renamed to <code>deploy</code>, aligning wonderfully with its deployment hooks counterparts.</p><p>Before:</p><figure class="highlight js"><table><tr><td class="code"><pre><span class="line">...</span><br><span class="line">contracts: {</span><br><span class="line"> SimpleStorage: {</span><br><span class="line"> fromIndex: <span class="number">0</span>,</span><br><span class="line"> args: [<span class="number">100</span>],</span><br><span class="line"> onDeploy: <span class="keyword">async</span> () => { ... },</span><br><span class="line"> deployIf: <span class="keyword">async</span> () => { ... }</span><br><span class="line"> }</span><br><span class="line">}</span><br><span class="line">...</span><br></pre></td></tr></table></figure><p>After:</p><figure class="highlight js"><table><tr><td class="code"><pre><span class="line">...</span><br><span class="line">deploy: {</span><br><span class="line"> SimpleStorage: {</span><br><span class="line"> fromIndex: <span class="number">0</span>,</span><br><span class="line"> args: [<span class="number">100</span>],</span><br><span class="line"> onDeploy: <span class="keyword">async</span> () => { ... },</span><br><span class="line"> deployIf: <span class="keyword">async</span> () => { ... }</span><br><span class="line"> }</span><br><span class="line">}</span><br><span class="line">...</span><br></pre></td></tr></table></figure><h3 id="Polished-Blockchain-configuration-API"><a href="#Polished-Blockchain-configuration-API" class="headerlink" title="Polished Blockchain configuration API"></a>Polished Blockchain configuration API</h3><p>One of the most complex APIs has been Embark’s Blockchain configuration API. That’s why we’ve put a lot of effort into streamlining the settings and properties and removing the ones that happened to be redundant. On top of that, Embark now defines most of them as defaults, resulting in significantly smaller and less complex configuration files.</p><p>The following configuration properties have been renamed:</p><ul><li><code>isDev</code> is now <code>miningMode: 'dev'</code></li><li><code>mineWhenNeeded</code> is now <code>miningMode: 'auto'</code></li><li><code>ethereumClientName</code> is now <code>client</code></li></ul><p>We’ve also removed several endpoint-related settings, such as <code>host</code> and <code>port</code>, and replaced them with a single <code>endpoint</code> property. Here’s what the new defaults look like:</p><figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="built_in">module</span>.exports = {</span><br><span class="line"> <span class="keyword">default</span>: {</span><br><span class="line"> enabled: <span class="literal">true</span>,</span><br><span class="line"> client: <span class="string">"geth"</span></span><br><span class="line"> },</span><br><span class="line"> development: {</span><br><span class="line"> clientConfig: {</span><br><span class="line"> miningMode: <span class="string">'dev'</span></span><br><span class="line"> }</span><br><span class="line"> },</span><br><span class="line"> testnet: {</span><br><span class="line"> endpoint: <span class="string">"https://external-node.com"</span>,</span><br><span class="line"> accounts: [</span><br><span class="line"> {</span><br><span class="line"> mnemonic: <span class="string">"12 word mnemonic"</span></span><br><span class="line"> }</span><br><span class="line"> ]</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p>For more information on Blockchain configuration, head over to the <a href="/docs/blockchain_configuration.html">official docs</a>.</p><h3 id="Accounts-configuration-moved-to-Blockchain-config"><a href="#Accounts-configuration-moved-to-Blockchain-config" class="headerlink" title="Accounts configuration moved to Blockchain config"></a>Accounts configuration moved to Blockchain config</h3><p>Prior to Embark 5 it was possible to specify and configure various accounts for deployment and interaction both inside the Smart Contract configuration and the Blockchain configuration. This caused a lot of confusion because it wasn’t really clear which accounts belonged to what action. To eliminate confusion, we’ve moved the accounts configuration entirely to the Blockchain configuration, making it much more straightforward to find the right place when setting up custom accounts.</p><p>Just like before, accounts can be defined using different configuration settings, depending on the use case:</p><figure class="highlight js"><table><tr><td class="code"><pre><span class="line">...</span><br><span class="line">accounts: [</span><br><span class="line"> {</span><br><span class="line"> nodeAccounts: <span class="literal">true</span>,</span><br><span class="line"> numAddresses: <span class="string">"1"</span>,</span><br><span class="line"> password: <span class="string">"config/development/devpassword"</span></span><br><span class="line"> },</span><br><span class="line"> {</span><br><span class="line"> privateKey: process.env.MyPrivateKey</span><br><span class="line"> },</span><br><span class="line"> {</span><br><span class="line"> privateKeyFile: <span class="string">"path/to/file"</span>,</span><br><span class="line"> password: process.env.MyKeyStorePassword</span><br><span class="line"> },</span><br><span class="line"> {</span><br><span class="line"> mnemonic: process.env.My12WordsMnemonic,</span><br><span class="line"> addressIndex: <span class="string">"0"</span>,</span><br><span class="line"> numAddresses: <span class="string">"1"</span>,</span><br><span class="line"> hdpath: <span class="string">"m/44'/60'/0'/0/"</span></span><br><span class="line"> }</span><br><span class="line">]</span><br><span class="line">...</span><br></pre></td></tr></table></figure><p>Check out the documentation on <a href="/docs/blockchain_accounts_configuration.html">accounts configuration</a> for more information.</p><h3 id="Configuring-tests"><a href="#Configuring-tests" class="headerlink" title="Configuring tests"></a>Configuring tests</h3><p>All the configuration changes discussed above have been ported and made available inside the test runner as well. In other words, when using Embark’s <code>config()</code> function inside test suites, the same configuration APi applies:</p><figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">config({</span><br><span class="line"> contracts: {</span><br><span class="line"> deploy: {</span><br><span class="line"> SomeContract: {} <span class="comment">// options as discussed in the Smart Contract configuration guide</span></span><br><span class="line"> }</span><br><span class="line"> }</span><br><span class="line">});</span><br></pre></td></tr></table></figure><p>Testing is covered in-depth in our <a href="/docs/contracts_testing.html">testing guide</a>.</p><p>To see any of the new APIs in action, have a look at our <a href="https://github.com/embarklabs/embark/tree/ba0d6d17f30018d8258c65d85f17bea100c3ad0a/dapps/templates" target="_blank" rel="noopener">template</a> and <a href="https://github.com/embarklabs/embark/tree/ba0d6d17f30018d8258c65d85f17bea100c3ad0a/dapps/tests" target="_blank" rel="noopener">test dapps</a> in the official Embark repository.</p><p>Obviously we’ve worked on many more things as part of the v5 release. For a full list of features and bug fixes, head over to our <a href="https://github.com/embarklabs/embark/blob/master/CHANGELOG.md#500-2020-01-07" target="_blank" rel="noopener">changelog</a>.</p><p>As always, we encourage our users to install the latest version of Embark and give it a spin. Feedback is very welcome and we can’t wait to see the great apps you’ll be building with it!</p>]]></content>
<summary type="html">
<p>If you’ve been following the development of Embark you’re probably aware that we regularly put out alpha and beta releases for upcoming m
</summary>
<category term="announcements" scheme="https://framework.embarklabs.io/categories/announcements/"/>
</entry>
<entry>
<title>Take Back the Web Hackathon is live!</title>
<link href="https://framework.embarklabs.io/news/2020/01/09/take-back-the-web-hackathon/"/>
<id>https://framework.embarklabs.io/news/2020/01/09/take-back-the-web-hackathon/</id>
<published>2020-01-09T05:00:00.000Z</published>
<updated>2020-01-19T19:38:04.364Z</updated>
<content type="html"><![CDATA[<p>The Embark Project is proud to be working with Gitcoin and the Ethereum Community Fund to grow the Ethereum ecosystem. This January we are sponsoring a <a href="https://gitcoin.co/hackathon/take-back-the-web/" target="_blank" rel="noopener">#Takebacktheweb Hackathon</a> with bounties and quests for people of all technical levels to get involved.</p><p>#Takebacktheweb is a movement based on the idea that some basic web services should be open platforms that can’t be censored. We’re looking to jumpstart projects that will democratize all major web platforms and services. For this hackathon we’ve outlined some bounties that we think drive this point, but if you have something you would like to build we are open to creating a bounty for it!</p><h2 id="What’s-a-Bounty"><a href="#What’s-a-Bounty" class="headerlink" title="What’s a Bounty?"></a>What’s a Bounty?</h2><p>Bounties are a way for developers to get an immediate reward for their efforts in the form of compensation or awards. From feature requests to building MVP’s this can be a great way to get more eyes on your open source project.</p><p>We will be focusing on bounties for completing our <a href="https://airtable.com/tblhwj1iiy601R6c7/viwkZ92riBqlR1tsj?blocks=hide" target="_blank" rel="noopener">developer survey</a> and submitting product ideas that help take back the web. We want to create products that users already have today, but which leverage decentralized technology. Using the embark framework, devs have access to everything they would need to create privacy first applications. Through our survey we hope to understand what other roadblocks developers may be experiencing.</p><h2 id="What’s-a-Quest"><a href="#What’s-a-Quest" class="headerlink" title="What’s a Quest?"></a>What’s a Quest?</h2><p>Quests are educational games geared towards rewarding people for going through demo’s of products, tutorials, documentation, blog posts, or new initiatives. We’ll be using this as a way to show off the new parts of the Status Network. Getting people to take a look around all we’ve built should help some to see what a great resource the network is!</p><h2 id="How-can-I-participate"><a href="#How-can-I-participate" class="headerlink" title="How can I participate?"></a>How can I participate?</h2><p>If you’re not already a member, join <a href="https://gitcoin.co/" target="_blank" rel="noopener">Gitcoin</a> and mark January 9th on your calendar for the launch of the hackathon. Go on some quests, tackle a few bounties and share it with your friends.</p><p>You’ll also need a web3 enabled browser to collect your ‘Kudos” for participation in the quest. The experience is fun and worth checking out!</p><p>We’re always here to help with ideas and projects building with Embark tools. Make sure to connect with us <a href="https://gitter.im/embark-framework/Lobby" target="_blank" rel="noopener">here</a>.</p>]]></content>
<summary type="html">
<p>The Embark Project is proud to be working with Gitcoin and the Ethereum Community Fund to grow the Ethereum ecosystem. This January we ar
</summary>
<category term="announcements" scheme="https://framework.embarklabs.io/categories/announcements/"/>
</entry>
<entry>
<title>Introduction to Web3 - What Are Your Options?</title>
<link href="https://framework.embarklabs.io/news/2019/12/09/web3-what-are-your-options/"/>
<id>https://framework.embarklabs.io/news/2019/12/09/web3-what-are-your-options/</id>
<published>2019-12-09T05:00:00.000Z</published>
<updated>2020-02-19T00:26:58.021Z</updated>
<content type="html"><![CDATA[<p><img src="/assets/images/web3-article-header.png" alt="Web3.js"></p><p><em>This will be a fairly brief write-up, introducing Web3 ahead of my next DApp tutorial series.</em></p><p>To kick this article off, I first have to reaffirm, for those that aren’t aware, I am not, and never have been, a <strong><em>lover</em></strong> of JavaScript. While my cool friends were off learning Node, and for some reason moving a scripting language to the backend, I was learning C and Go, Erlang and Distributed Systems.</p><p>For years, I harboured a deep hatred of JS, and actively whinged about it at every opportunity I got; being <strong><em>forced</em></strong> to use it in my daily work life. Now however, I do have to say; over the last few years I have <em>softened</em> to JS, and I am much more comfortable in my own skin when having to use it.</p><p>It goes without saying, the entire web is JS. Look around you - JS. View the source of this article - JS files. Look at your own app’s dependencies - JS.</p><p>JavaScript, specifically Node, really is in everything we use, and that now also applies to our wonderful world of Cryptocurrencies.</p><p>As I mentioned briefly in my <a href="/news/2019/11/28/nim-vs-crystal-part-3-cryto-dapps-p2p/"><strong><em>last</em></strong> article</a>, my <strong><em>next</em></strong> article series is going to be about building your first DApp – from start to finish. Inevitably, the frontend of our DApp needs to be able to communicate with the Ethereum Network. This is where <a href="https://web3js.readthedocs.io/en/v1.2.6/index.html" target="_blank" rel="noopener">Web3.js</a> comes into the mix. <code>Web3.js</code> is a collection of APIs allowing us such functionality as: Reading & Writing data from Smart Contracts, sending and receiving Ether, encrypting / decrypting wallets & data, and <em>a whole bunch</em> of other stuff too. Basically, <em>most</em> of the backend functionality available on the Ethereum Network natively becomes available for use in the browser.</p><p>This is how the <code>web3.js</code> library talks to the Ethereum Network:</p><p><img src="/assets/images/web3-js-diagram.png" alt="Web3 JS Diagram"><br><em>Image credit: <a href="https://iotbl.blogspot.com/2017/03/ethereum-and-blockchain-2.html" target="_blank" rel="noopener">iotbl</a></em></p><p>So, now that the basics are covered, let’s go over installing and using the <code>web3.js</code> library.</p><h1 id="Installing-Web3"><a href="#Installing-Web3" class="headerlink" title="Installing Web3"></a>Installing Web3</h1><p>Installing <code>web3.js</code> is as simple as:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">npm install web3</span><br></pre></td></tr></table></figure><p><em>One thing worth noting here</em>; is that (coming from an anti-js background), I kept getting a <code>cannot find web3 module</code> error when trying to import web3 into a Node console. If you, like me, aren’t a big js fan, this can be solved by first running the <code>npm init</code> command to ensure there is a <code>package.json</code> file in the cwd, and <em>then</em> you can run <code>npm install web3</code>, and it will work fine. (I realise this is basic stuff – but actually for someone who’s <em>tried</em> to avoid Node at all costs, it was initially confusing enough to have to search online.)</p><p>I am working from a Mac here, but if you are working from Windows, the install process <em>can</em> be exactly the same, assuming you do have <a href="https://phoenixnap.com/kb/install-node-js-npm-on-windows" target="_blank" rel="noopener">Node & NPM installed</a>.</p><p>So, with <code>web3.js</code> installed, let’s do some basic interactions with the Ethereum Network, and <strong><em>dive on in!</em></strong></p><h1 id="Communicating-with-the-Ethereum-Network"><a href="#Communicating-with-the-Ethereum-Network" class="headerlink" title="Communicating with the Ethereum Network"></a>Communicating with the Ethereum Network</h1><h2 id="Wallet-Interaction"><a href="#Wallet-Interaction" class="headerlink" title="Wallet Interaction"></a>Wallet Interaction</h2><p>For this article, we’re going to use <a href="https://www.trufflesuite.com/ganache" target="_blank" rel="noopener">Ganache</a>, for simplicity, as our local Blockchain. By using Ganache, we can spin up a local Ethereum node, without having to write a single line of code!</p><p><strong><em>(Yes, I realise that rhymes. No, I didn’t realise until my second proof-read through of this article!)</em></strong></p><p>In fact, though, Embark already has Ganache inbuilt, so we could also simply run:</p><figure class="highlight js"><table><tr><td class="code"><pre><span class="line">embark simulator</span><br></pre></td></tr></table></figure><p>Anyway, to install Ganache head over to <a href="https://www.trufflesuite.com/ganache" target="_blank" rel="noopener">this page</a> and click on the executable there. If you so choose; there is also a Ganache CLI available you can install by running:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">npm install -g ganache-cli</span><br></pre></td></tr></table></figure><p>Running the Ganache CLI will give you the same functionality as the desktop client; in essence giving us a multitude of ETH-loaded wallets that we can build contracts around / interact with.</p><p><img src="/assets/images/ganache-cli.png" alt="Ganache CLI"></p><p>Rather brilliantly; we now have a local Ethereum Node running that we can start using the Web3 client to interact with. In another Terminal tab, open up a <code>node</code> instance from the same working directory we ran the <code>npm init</code> command from earlier.</p><p>Now, in our interactive Node console, run:</p><figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">var</span> Web3 = <span class="built_in">require</span>(<span class="string">'web3'</span>);</span><br><span class="line"><span class="keyword">var</span> web3 = <span class="keyword">new</span> Web3(<span class="string">'http://localhost:8545'</span>);</span><br></pre></td></tr></table></figure><p>Something to note here, is that I’m calling <code>new Web3</code> with an <code>http</code> protocol, but the WebSocket protocol is also commonly used:</p><figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">var</span> web3 = <span class="keyword">new</span> Web3(Web3.givenProvider || <span class="keyword">new</span> Web3.providers.WebsocketProvider(<span class="string">'ws://remotenode.com:8546'</span>));</span><br></pre></td></tr></table></figure><p>To test and ensure the connection, you can get a list of the accounts made available in Ganache by running:</p><figure class="highlight js"><table><tr><td class="code"><pre><span class="line">web3.eth.getAccounts().then(<span class="built_in">console</span>.log);</span><br></pre></td></tr></table></figure><p>Which <em>should</em> give you an output like the following:</p><figure class="highlight js"><table><tr><td class="code"><pre><span class="line">> [ <span class="string">'0x7689cF9F90FAad61B8a3c9b1b2A5b4580B37358b'</span>,</span><br><span class="line"> <span class="string">'0x852e9a9db77a4e6169e175cDBb33dBE350150A8e'</span>,</span><br><span class="line"> <span class="string">'0x946700a1a4f30Dfe80307C91B6DaF1cCa2d09401'</span>,</span><br><span class="line"> <span class="string">'0x7d356aF02A87147D3ce5F9ACA716a78f70aF7616'</span>,</span><br><span class="line"> <span class="string">'0x88A116a16e4c8838F575a0e7a72eE27C7B073263'</span>,</span><br><span class="line"> <span class="string">'0x655317701Fcf3b310F492cB801C8D23f8c6fb556'</span>,</span><br><span class="line"> <span class="string">'0x16D305e72aFb0DDa1dB1830F8a98D5cD5337882E'</span>,</span><br><span class="line"> <span class="string">'0x9099bb4Af9CE5734E7a7e62f817e833fcFFaaF32'</span>,</span><br><span class="line"> <span class="string">'0x2ec4CC6700d0424A78a9B9Fc2ecBaeFc162313F1'</span>,</span><br><span class="line"> <span class="string">'0x1BC51a0edEC9FdEA3B14748e9209F4bF8Fe024b5'</span> ]</span><br></pre></td></tr></table></figure><p>If you want to check the balance of an individual account from the above list, you can do so by running:</p><figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> account1 = <span class="string">"0x7689cF9F90FAad61B8a3c9b1b2A5b4580B37358b"</span>;</span><br><span class="line"></span><br><span class="line">web3.eth.getBalance(account1)</span><br><span class="line">.then(<span class="built_in">console</span>.log);</span><br></pre></td></tr></table></figure><p>Which will output:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">> 100000000000000000000</span><br></pre></td></tr></table></figure><h2 id="Contract-Interaction"><a href="#Contract-Interaction" class="headerlink" title="Contract Interaction"></a>Contract Interaction</h2><p>As above; interacting with our <em>individual accounts</em> through <code>web3.js</code> is cool, but not nearly the extent to which the library works. Let’s now take a brief look at the more important functionality; of interacting with Smart Contracts through <code>web3.js</code>.</p><p>The first thing we need to do, is to create a new Smart Contract, which we can do with the <code>new web3.eth.Contract</code> command.</p><p>Before we call the <code>new</code> command, we need to assign our <code>json interface</code> for the contract’s <code>ABI</code>:</p><figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> abi = [{<span class="string">"type"</span>:<span class="string">"function"</span>, <span class="string">"name"</span>:<span class="string">"foo"</span>, <span class="string">"inputs"</span>: [{<span class="string">"name"</span>:<span class="string">"a"</span>,<span class="string">"type"</span>:<span class="string">"uint256"</span>}], <span class="string">"outputs"</span>: [{<span class="string">"name"</span>:<span class="string">"b"</span>,<span class="string">"type"</span>:<span class="string">"address"</span>}] },{ <span class="string">"type"</span>:<span class="string">"event"</span>, <span class="string">"name"</span>:<span class="string">"Event"</span>, <span class="string">"inputs"</span>: [{<span class="string">"name"</span>:<span class="string">"a"</span>,<span class="string">"type"</span>:<span class="string">"uint256"</span>,<span class="string">"indexed"</span>:<span class="literal">true</span>},{<span class="string">"name"</span>:<span class="string">"b"</span>,<span class="string">"type"</span>:<span class="string">"bytes32"</span>,<span class="string">"indexed"</span>:<span class="literal">false</span>}], }]</span><br></pre></td></tr></table></figure><p>The <code>json interface</code> is a JSON object describing the <em>Application Binary Interface (ABI)</em> for our Smart Contract. Using this JSON interface; <code>web3.js</code> is able to create a JavaScript object representing our Smart Contract and its methods & events, using the <code>web3.eth.Contract</code> functionality.</p><p><em>Note, the above JSON interface / ABI is taken directly from the <a href="https://web3js.readthedocs.io/en/v1.2.0/web3-eth-contract.html#id5" target="_blank" rel="noopener">Web3 docs</a>.</em></p><p>Now that we have our <code>json interface</code> defined, we can create our new contract instance:</p><figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">var</span> myContract = <span class="keyword">new</span> web3.eth.Contract(abi, <span class="string">'0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'</span>);</span><br></pre></td></tr></table></figure><p><em>(The <code>from</code> address is the address of the already deployed contract instance that we’re aiming to talk to.)</em></p><p>You could then set the Smart Contract’s <code>data</code> and other <code>options</code>, and then <strong>deploy</strong> your Contract with something <em>like</em> the following:</p><figure class="highlight js"><table><tr><td class="code"><pre><span class="line">myContract.options.data = <span class="string">'0x12345...'</span>;</span><br><span class="line"></span><br><span class="line">myContract.deploy({</span><br><span class="line"> <span class="built_in">arguments</span>: [<span class="number">123</span>, <span class="string">'My String'</span>]</span><br><span class="line">})</span><br><span class="line">.send({</span><br><span class="line"> <span class="keyword">from</span>: <span class="string">'0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'</span>,</span><br><span class="line"> gas: <span class="number">1500000</span>,</span><br><span class="line"> gasPrice: <span class="string">'30000000000000'</span></span><br><span class="line">})</span><br><span class="line">.then(<span class="function"><span class="keyword">function</span>(<span class="params">newContractInstance</span>)</span>{</span><br><span class="line"> <span class="built_in">console</span>.log(newContractInstance.options.address) <span class="comment">// instance with the new contract address</span></span><br><span class="line">});</span><br></pre></td></tr></table></figure><p>The above examples aren’t supposed to be perfect continuous code, and should definitely <em>not</em> be copy/pasted into a production project, but they are there to show off roughly how <code>Web.js</code> works, and give an overview of interacting with the 2 main pieces of functionality, as I see them – Wallets and Contracts.</p><p>In my next tutorial series, we will be utilising <a href="https://embark.status.im/docs/quick_start.html" target="_blank" rel="noopener">Embark</a>, and therefore we’ll be diving deeper into <code>web3.js</code>, and showing off much more of its potential.</p><h1 id="Web-js-in-Other-Languages"><a href="#Web-js-in-Other-Languages" class="headerlink" title="Web.js in Other Languages"></a>Web.js in Other Languages</h1><p>Naturally the whole idea behind this article was to show off communication with the Ethereum Network through a JavaScript frontend. However, there are also <strong>many</strong> other libraries, in pretty much every language, available to do the same:</p><p><strong><em>Nim - <a href="https://github.com/status-im/nim-web3" target="_blank" rel="noopener">nim-web3</a></em></strong><br>Crystal - <a href="https://github.com/light-side-software/web3.cr" target="_blank" rel="noopener">web3.cr</a><br>Ruby - <a href="https://github.com/izetex/web3-eth" target="_blank" rel="noopener">web3-eth gem</a><br>Elixir - <a href="https://github.com/mana-ethereum/ethereumex" target="_blank" rel="noopener">ethereumex</a><br>Python - <a href="https://github.com/ethereum/web3.py" target="_blank" rel="noopener">Web3.py</a><br>Haskell - <a href="https://github.com/airalab/hs-web3" target="_blank" rel="noopener">hs-web3</a><br>Java - <a href="https://github.com/web3j/web3j" target="_blank" rel="noopener">web3j</a><br>Scala - <a href="https://github.com/mslinn/web3j-scala" target="_blank" rel="noopener">web3j-scala</a><br>Purescript - <a href="https://github.com/f-o-a-m/purescript-web3" target="_blank" rel="noopener">purescript-web3</a><br>PHP - <a href="https://github.com/sc0Vu/web3.php" target="_blank" rel="noopener">web3.php</a></p><h1 id="Beyond-Web3"><a href="#Beyond-Web3" class="headerlink" title="Beyond Web3"></a>Beyond Web3</h1><p>As stated at the opening of this article, we’ve barely even scratched the surface of <code>web.js</code> capabilities. But I do hope that you now have a better understanding of what Web3 stands for.</p><p>Personally, I am <strong>very much</strong> looking forward to <strong><em>diving on in</em></strong> to my next DApp tutorial series, to utilise and demonstrate the Ethereum Network to its fullest.</p><p>As always, if you have <em>any</em> questions regarding Web3, how Status utilises Web3, or if you have comments on this article, feel free to reach out to me at <a href="mailto:[email protected]">robin@status</a>.</p><p>Thanks again for reading, and check back for my DApp tutorial series, starting later this week!</p><p><a href="https://twitter.com/rbin" target="_blank" rel="noopener"> <strong>- @rbin</strong></a></p>]]></content>
<summary type="html">
<p><img src="/assets/images/web3-article-header.png" alt="Web3.js"></p>
<p><em>This will be a fairly brief write-up, introducing Web3 ahead
</summary>
<content src="https://framework.embarklabs.io//assets/images/web3-article-header.png" type="image" />
<category term="tutorials" scheme="https://framework.embarklabs.io/categories/tutorials/"/>
</entry>
<entry>
<title>Nim vs Crystal - Part 3 - Crypto, DApps & P2P</title>
<link href="https://framework.embarklabs.io/news/2019/11/28/nim-vs-crystal-part-3-cryto-dapps-p2p/"/>
<id>https://framework.embarklabs.io/news/2019/11/28/nim-vs-crystal-part-3-cryto-dapps-p2p/</id>
<published>2019-11-28T05:00:00.000Z</published>
<updated>2020-01-19T19:38:04.364Z</updated>
<content type="html"><![CDATA[<p><img src="/assets/images/nim-crystal-header-img_NEW.jpg" alt="crystal vs nim"></p><p>Welcome back to my series comparing the two sweethearts of the modern low-level programming world. Just to quickly recap: in <a href="/news/2019/11/18/nim-vs-crystal-part-1-performance-interoperability/">article #1</a> 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 <strong><em>did</em></strong> throw up some unexpected twists in the plot. Crystal used <em>very-nearly</em> half of the memory amount executing the tests when compared to Nim, and also took <em>very nearly</em> half of the execution time in doing so. <strong>This seriously took me by surprise!</strong></p><p>In <a href="/news/2019/11/21/nim-vs-crystal-part-2-threading-tooling/">article #2</a>; 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…</p><p>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 <em>markedly</em> improve our application performance, but that are also relatively simple, and intuitive to use. I see <em>this</em> 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* <strong><em>Ruby</em></strong> *cough*. I also like to see a fully-featured standard library that takes influence from previous successful languages. However, I digress…</p><p>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:</p><p><strong><em>Let’s dive on in!</em></strong></p><h2 id="Cryptocurrency"><a href="#Cryptocurrency" class="headerlink" title="Cryptocurrency"></a>Cryptocurrency</h2><p>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 <strong><em>proven to be two of the strongest languages</em></strong> to consider for the undertaking.. (That being the <em>next</em> blog series I’m going to write – in the near future, so deciding which language to use will be heavily influenced by <strong><em>this</em></strong> blog series!)</p><p>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 <strong><em>very</em></strong> 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 <strong>ONE HELL</strong> of an impressive piece of technology.</p><p>Happily, both Crystal <em>and</em> Nim allow us <strong><em>all</em></strong> of the above functionality. In our hypothetical usecase, if we were to build out a fully-featured blockchain; mining <em>and</em> 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.</p><p>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:</p><h3 id="Calculating-our-Block-Hashes"><a href="#Calculating-our-Block-Hashes" class="headerlink" title="Calculating our Block Hashes"></a>Calculating our Block Hashes</h3><p>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 <em>this</em> article on how blockchains function, we’ll stick with the existing, and proven, SHA256 algorithm.</p><h3 id="In-Crystal"><a href="#In-Crystal" class="headerlink" title="In Crystal:"></a>In Crystal:</h3><figure class="highlight crystal"><table><tr><td class="code"><pre><span class="line"><span class="keyword">require</span> <span class="string">"json"</span></span><br><span class="line"><span class="keyword">require</span> <span class="string">"openssl"</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">module</span> <span class="title">OurCryptoApp::Model</span></span></span><br><span class="line"> <span class="class"><span class="keyword">struct</span> <span class="title">Transaction</span></span></span><br><span class="line"> <span class="keyword">include</span> <span class="symbol">JSON:</span>:Serializable</span><br><span class="line"></span><br><span class="line"> <span class="keyword">alias</span> TxnHash = String</span><br><span class="line"></span><br><span class="line"> property from : String</span><br><span class="line"> property to : String</span><br><span class="line"> property amount : Float32</span><br><span class="line"> getter hash : TxnHash</span><br><span class="line"> getter timestamp : Int64</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">def</span> <span class="title">initialize</span></span>(@from, @to, @amount)</span><br><span class="line"> @timestamp = Time.utc_now.to_unix</span><br><span class="line"> @hash = calc_hash</span><br><span class="line"> <span class="keyword">end</span></span><br><span class="line"></span><br><span class="line"> <span class="keyword">private</span> <span class="function"><span class="keyword">def</span> <span class="title">calc_hash</span></span> : TxnHash</span><br><span class="line"> sha = <span class="symbol">OpenSSL:</span>:Digest.new(<span class="string">"SHA256"</span>)</span><br><span class="line"> sha.update(<span class="string">"<span class="subst">#{@from}</span><span class="subst">#{@to}</span><span class="subst">#{@amount}</span><span class="subst">#{@timestamp}</span>"</span>)</span><br><span class="line"> sha.hexdigest</span><br><span class="line"> <span class="keyword">end</span></span><br><span class="line"> <span class="keyword">end</span></span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure><h3 id="In-Nim"><a href="#In-Nim" class="headerlink" title="In Nim:"></a>In Nim:</h3><p>If we want to generate a similar hash in Nim, we could run the following:</p><figure class="highlight nim"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> strutils</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> <span class="type">SHA256Len</span> = <span class="number">32</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">proc</span> <span class="type">SHA256</span>(d: <span class="built_in">cstring</span>, n: <span class="built_in">culong</span>, md: <span class="built_in">cstring</span> = <span class="keyword">nil</span>): <span class="built_in">cstring</span> <span class="meta">{.cdecl, dynlib: "libssl.so", importc.}</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">proc</span> <span class="type">SHA256</span>(s: <span class="built_in">string</span>): <span class="built_in">string</span> =</span><br><span class="line"> <span class="literal">result</span> = <span class="string">""</span></span><br><span class="line"> <span class="keyword">let</span> s = <span class="type">SHA256</span>(s.<span class="built_in">cstring</span>, s.len.<span class="built_in">culong</span>)</span><br><span class="line"> <span class="keyword">for</span> i <span class="keyword">in</span> <span class="number">0</span> .. < <span class="type">SHA256Len</span>:</span><br><span class="line"> <span class="literal">result</span>.add s[i].<span class="type">BiggestInt</span>.toHex(<span class="number">2</span>).toLower</span><br><span class="line"></span><br><span class="line">echo <span class="type">SHA256</span>(<span class="string">"Hash this block, yo"</span>)</span><br></pre></td></tr></table></figure><h2 id="Releasing-our-Crypto-App"><a href="#Releasing-our-Crypto-App" class="headerlink" title="Releasing our Crypto App"></a>Releasing our Crypto App</h2><p>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 <em>compiled</em> 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!)</p><p>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 <a href="https://facebook.github.io/react-native/" target="_blank" rel="noopener">React Native</a>.</p><p>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:</p><ul><li><a href="http://ionicframework.com/" target="_blank" rel="noopener">Ionic Framework</a></li><li><a href="https://flutter.io/" target="_blank" rel="noopener">Flutter</a></li><li><a href="https://www.nativescript.org/" target="_blank" rel="noopener">NativeScript</a></li></ul><p>And if you come from a Windows background:</p><ul><li><a href="https://dotnet.microsoft.com/apps/xamarin" target="_blank" rel="noopener">Xamarin</a></li></ul><h3 id="Building-amp-Releasing-In-Nim"><a href="#Building-amp-Releasing-In-Nim" class="headerlink" title="Building & Releasing In Nim:"></a>Building & Releasing In Nim:</h3><p>If we wanted to build out and release our app for Android, we can run:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">nim c -c --cpu:arm --os:android -d:androidNDK --noMain:on</span><br></pre></td></tr></table></figure><p>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.</p><p>Similarly, we could run:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">nim c -c --os:ios --noMain:on</span><br></pre></td></tr></table></figure><p>To generate C files to include in our XCode project. Then, we can use XCode to compile, link, package and sign everything.</p><h3 id="Building-amp-Releasing-In-Crystal"><a href="#Building-amp-Releasing-In-Crystal" class="headerlink" title="Building & Releasing In Crystal:"></a>Building & Releasing In Crystal:</h3><p>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:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">crystal build your_program.cr --cross-compile --target "x86_64-unknown-linux-gnu"</span><br></pre></td></tr></table></figure><p><strong><em>Worth noting:</em></strong> <em>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!</em></p><h2 id="Ethereum-Building-Signing-amp-Sending-a-Transaction"><a href="#Ethereum-Building-Signing-amp-Sending-a-Transaction" class="headerlink" title="Ethereum - Building, Signing & Sending a Transaction"></a>Ethereum - Building, Signing & Sending a Transaction</h2><p>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 <em>is</em> 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.</p><h3 id="In-Crystal-1"><a href="#In-Crystal-1" class="headerlink" title="In Crystal:"></a>In Crystal:</h3><figure class="highlight crystal"><table><tr><td class="code"><pre><span class="line"><span class="keyword">require</span> <span class="string">"http/client"</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">module</span> <span class="title">Ethereum</span></span></span><br><span class="line"> <span class="class"><span class="keyword">class</span> <span class="title">Transaction</span></span></span><br><span class="line"></span><br><span class="line"> <span class="comment"># /ethereum/create/ Create - Ethereum::Transaction.create(args)</span></span><br><span class="line"> <span class="function"><span class="keyword">def</span> <span class="title">self</span></span>.create(to : String, from : String, amount : UInt64, gas_price : UInt64? = <span class="literal">nil</span>, gas_limit : UInt64? = <span class="literal">nil</span>) : EthereumToSign | ErrorMessage</span><br><span class="line"></span><br><span class="line"> headers = <span class="symbol">HTTP:</span>:Headers.new</span><br><span class="line"> <span class="keyword">if</span> ENV[<span class="string">"ONCHAIN_API_KEY"</span>]? != <span class="literal">nil</span></span><br><span class="line"> headers.add(<span class="string">"X-API-KEY"</span>, ENV[<span class="string">"ONCHAIN_API_KEY"</span>])</span><br><span class="line"> <span class="keyword">end</span></span><br><span class="line"></span><br><span class="line"> response = <span class="symbol">HTTP:</span>:Client.post <span class="string">"https://onchain.io/api/ethereum/create//?to=<span class="subst">#{to}</span>&from=<span class="subst">#{from}</span>&amount=<span class="subst">#{amount}</span>&gas_price=<span class="subst">#{gas_price}</span>&gas_limit=<span class="subst">#{gas_limit}</span>"</span>, <span class="symbol">headers:</span> headers</span><br><span class="line"></span><br><span class="line"> <span class="keyword">return</span> ErrorMessage.from_json response.body <span class="keyword">if</span> response.status_code != <span class="number">200</span></span><br><span class="line"></span><br><span class="line"> ethereumtosign = EthereumToSign.from_json response.body</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"> <span class="keyword">return</span> ethereumtosign</span><br><span class="line"> <span class="keyword">end</span></span><br><span class="line"></span><br><span class="line"> <span class="comment"># /ethereum/sign_and_send/ Sign and send - Ethereum::Transaction.sign_and_send(args)</span></span><br><span class="line"> <span class="function"><span class="keyword">def</span> <span class="title">self</span></span>.sign_and_send(to : String, from : String, amount : UInt64, r : String, s : String, v : String, gas_price : UInt64? = <span class="literal">nil</span>, gas_limit : UInt64? = <span class="literal">nil</span>) : SendStatus | ErrorMessage</span><br><span class="line"></span><br><span class="line"> headers = <span class="symbol">HTTP:</span>:Headers.new</span><br><span class="line"> <span class="keyword">if</span> ENV[<span class="string">"ONCHAIN_API_KEY"</span>]? != <span class="literal">nil</span></span><br><span class="line"> headers.add(<span class="string">"X-API-KEY"</span>, ENV[<span class="string">"ONCHAIN_API_KEY"</span>])</span><br><span class="line"> <span class="keyword">end</span></span><br><span class="line"></span><br><span class="line"> response = <span class="symbol">HTTP:</span>:Client.post <span class="string">"https://onchain.io/api/ethereum/sign_and_send//?to=<span class="subst">#{to}</span>&from=<span class="subst">#{from}</span>&amount=<span class="subst">#{amount}</span>&r=<span class="subst">#{r}</span>&s=<span class="subst">#{s}</span>&v=<span class="subst">#{v}</span>&gas_price=<span class="subst">#{gas_price}</span>&gas_limit=<span class="subst">#{gas_limit}</span>"</span>, <span class="symbol">headers:</span> headers</span><br><span class="line"></span><br><span class="line"> <span class="keyword">return</span> ErrorMessage.from_json response.body <span class="keyword">if</span> response.status_code != <span class="number">200</span></span><br><span class="line"></span><br><span class="line"> sendstatus = SendStatus.from_json response.body</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"> <span class="keyword">return</span> sendstatus</span><br><span class="line"> <span class="keyword">end</span></span><br><span class="line"></span><br><span class="line"> <span class="keyword">end</span></span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure><p>Then, in our application we could simply call:</p><figure class="highlight crystal"><table><tr><td class="code"><pre><span class="line"><span class="symbol">Ethereum:</span>:Transaction.create(<span class="string">"0xA02378cA1c24767eCD776aAFeC02158a30dc01ac"</span>, <span class="string">"0xA02378cA1c24767eCD776aAFeC02158a30dc01ac"</span>, <span class="number">80000</span>)</span><br></pre></td></tr></table></figure><p>And we would get a response similar to the following, ready to be signed and sent to the Ethereum network:</p><figure class="highlight json"><table><tr><td class="code"><pre><span class="line">{</span><br><span class="line"> <span class="attr">"tx"</span>: <span class="string">"02000000011cd5d7621e2a7c9403e54e089cb0b5430b83ed13f1b897d3e319b100ba1b059b01000000db00483045022100d7534c80bc0a42addc3d955f74e31610aa78bf15d79ec4df4c36dc98e802f5200220369cab1bccb2dbca0921444ce3fafb15129fa0494d041998be104df39b8895ec01483045022100fe48c4c1d46e163acaff6b0d2e702812d20"</span>,</span><br><span class="line"> <span class="attr">"hash_to_sign"</span>: <span class="string">"955f74e31610aa78bf15d79ec4df4c36dc98e802f52002"</span></span><br><span class="line">}</span><br></pre></td></tr></table></figure><h2 id="In-Nim-1"><a href="#In-Nim-1" class="headerlink" title="In Nim:"></a>In Nim:</h2><p>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 <code>nim-eth</code> into our Nimble project, our Ethereum transaction can be built atop of the following protocol:</p><figure class="highlight nim"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span></span><br><span class="line"> nim-eth/[common, rlp, keys], nimcrypto</span><br><span class="line"></span><br><span class="line"><span class="keyword">proc</span> initTransaction*(nonce: <span class="type">AccountNonce</span>, gasPrice, gasLimit: <span class="type">GasInt</span>, to: <span class="type">EthAddress</span>,</span><br><span class="line"> value: <span class="type">UInt256</span>, payload: <span class="type">Blob</span>, V: byte, R, S: <span class="type">UInt256</span>, isContractCreation = <span class="literal">false</span>): <span class="type">Transaction</span> =</span><br><span class="line"> <span class="literal">result</span>.accountNonce = nonce</span><br><span class="line"> <span class="literal">result</span>.gasPrice = gasPrice</span><br><span class="line"> <span class="literal">result</span>.gasLimit = gasLimit</span><br><span class="line"> <span class="literal">result</span>.to = to</span><br><span class="line"> <span class="literal">result</span>.value = value</span><br><span class="line"> <span class="literal">result</span>.payload = payload</span><br><span class="line"> <span class="literal">result</span>.V = V</span><br><span class="line"> <span class="literal">result</span>.R = R</span><br><span class="line"> <span class="literal">result</span>.S = S</span><br><span class="line"> <span class="literal">result</span>.isContractCreation = isContractCreation</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span></span><br><span class="line"> <span class="type">TransHashObj</span> = <span class="keyword">object</span></span><br><span class="line"> accountNonce: <span class="type">AccountNonce</span></span><br><span class="line"> gasPrice: <span class="type">GasInt</span></span><br><span class="line"> gasLimit: <span class="type">GasInt</span></span><br><span class="line"> to <span class="meta">{.rlpCustomSerialization.}</span>: <span class="type">EthAddress</span></span><br><span class="line"> value: <span class="type">UInt256</span></span><br><span class="line"> payload: <span class="type">Blob</span></span><br><span class="line"> mIsContractCreation <span class="meta">{.rlpIgnore.}</span>: <span class="built_in">bool</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">proc</span> read(rlp: <span class="keyword">var</span> <span class="type">Rlp</span>, t: <span class="keyword">var</span> <span class="type">TransHashObj</span>, _: <span class="keyword">type</span> <span class="type">EthAddress</span>): <span class="type">EthAddress</span> <span class="meta">{.inline.}</span> =</span><br><span class="line"> <span class="keyword">if</span> rlp.blobLen != <span class="number">0</span>:</span><br><span class="line"> <span class="literal">result</span> = rlp.read(<span class="type">EthAddress</span>)</span><br><span class="line"> <span class="keyword">else</span>:</span><br><span class="line"> t.mIsContractCreation = <span class="literal">true</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">proc</span> append(rlpWriter: <span class="keyword">var</span> <span class="type">RlpWriter</span>, t: <span class="type">TransHashObj</span>, a: <span class="type">EthAddress</span>) <span class="meta">{.inline.}</span> =</span><br><span class="line"> <span class="keyword">if</span> t.mIsContractCreation:</span><br><span class="line"> rlpWriter.append(<span class="string">""</span>)</span><br><span class="line"> <span class="keyword">else</span>:</span><br><span class="line"> rlpWriter.append(a)</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span></span><br><span class="line"> <span class="type">EIP155_CHAIN_ID_OFFSET</span>* = <span class="number">35</span></span><br><span class="line"></span><br><span class="line">func rlpEncode*(transaction: <span class="type">Transaction</span>): <span class="built_in">auto</span> =</span><br><span class="line"> <span class="comment"># Encode transaction without signature</span></span><br><span class="line"> <span class="keyword">return</span> rlp.encode(<span class="type">TransHashObj</span>(</span><br><span class="line"> accountNonce: transaction.accountNonce,</span><br><span class="line"> gasPrice: transaction.gasPrice,</span><br><span class="line"> gasLimit: transaction.gasLimit,</span><br><span class="line"> to: transaction.to,</span><br><span class="line"> value: transaction.value,</span><br><span class="line"> payload: transaction.payload,</span><br><span class="line"> mIsContractCreation: transaction.isContractCreation</span><br><span class="line"> ))</span><br><span class="line"></span><br><span class="line">func rlpEncodeEIP155*(tx: <span class="type">Transaction</span>): <span class="built_in">auto</span> =</span><br><span class="line"> <span class="keyword">let</span> V = (tx.V.<span class="built_in">int</span> - <span class="type">EIP155_CHAIN_ID_OFFSET</span>) <span class="keyword">div</span> <span class="number">2</span></span><br><span class="line"> <span class="comment"># Encode transaction without signature</span></span><br><span class="line"> <span class="keyword">return</span> rlp.encode(<span class="type">Transaction</span>(</span><br><span class="line"> accountNonce: tx.accountNonce,</span><br><span class="line"> gasPrice: tx.gasPrice,</span><br><span class="line"> gasLimit: tx.gasLimit,</span><br><span class="line"> to: tx.to,</span><br><span class="line"> value: tx.value,</span><br><span class="line"> payload: tx.payload,</span><br><span class="line"> isContractCreation: tx.isContractCreation,</span><br><span class="line"> V: V.byte,</span><br><span class="line"> R: <span class="number">0</span>.u256,</span><br><span class="line"> S: <span class="number">0</span>.u256</span><br><span class="line"> ))</span><br><span class="line"></span><br><span class="line">func txHashNoSignature*(tx: <span class="type">Transaction</span>): <span class="type">Hash256</span> =</span><br><span class="line"> <span class="comment"># Hash transaction without signature</span></span><br><span class="line"> <span class="keyword">return</span> keccak256.digest(<span class="keyword">if</span> tx.V.<span class="built_in">int</span> >= <span class="type">EIP155_CHAIN_ID_OFFSET</span>: tx.rlpEncodeEIP155 <span class="keyword">else</span>: tx.rlpEncode)</span><br></pre></td></tr></table></figure><p><em>Note</em> - 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.</p><p><a href="https://github.com/status-im/nim-eth/" target="_blank" rel="noopener">Status’ Eth Common Library</a> contains a whole bunch of useful Nim libraries for interacting with the Ethereum Network, including:</p><ul><li><a href="https://github.com/status-im/nim-eth/blob/master/doc/rlp.md" target="_blank" rel="noopener">Recursive Length Prefix encoding (RLP)</a>,</li><li><a href="https://github.com/status-im/nim-eth/blob/master/doc/p2p.md" target="_blank" rel="noopener">P2P</a>,</li><li><a href="https://github.com/status-im/nim-eth/blob/master/doc/keys.md" target="_blank" rel="noopener">Eth-keys</a>,</li><li><a href="https://github.com/status-im/nim-eth/blob/master/doc/keyfile.md" target="_blank" rel="noopener">Eth-keyfile</a>,</li><li><a href="https://github.com/status-im/nim-eth/blob/master/doc/trie.md" target="_blank" rel="noopener">Ethereum Trie structure</a>, and</li><li><a href="https://github.com/status-im/nim-eth/blob/master/doc/bloom.md" target="_blank" rel="noopener">Ethereum Bloom Filter</a>.</li></ul><p>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 <a href="https://nimbus.team" target="_blank" rel="noopener">Nimbus</a> 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!</p><h2 id="Conclusion"><a href="#Conclusion" class="headerlink" title="Conclusion"></a>Conclusion</h2><p>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.</p><p>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 <strong>Crystal</strong>. This is simply because of the <em>much</em> larger ecosystem and resources surrounding it.</p><p>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 <strong>Nim</strong>. 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.</p><p>Alas, this brings me on to my final points…</p><h2 id="Series-Conclusion"><a href="#Series-Conclusion" class="headerlink" title="Series Conclusion"></a>Series Conclusion</h2><p>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.”</p><p>But then I went and spoiled it all, by saying something stupid like “Cryptocurrency”.</p><p>Prior to this article, I <em>was swaying</em> 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 <em>extremely</em> impressive interoperability, awesome inbuilt tooling, and great efficiency overall.</p><p>I hate to do this, but I’m just going to have to say it: for your usecase – <strong>pick the best tool for the job</strong>. Please ensure that you research properly into both languages, and weigh-up the pro’s/con’s that pertain to your specific usecase.</p><p><strong><em>Cliches aside</em></strong> – if I had to pick a favourite overall language, it would have to be <strong>Crystal</strong>. Frankly, this opinion is formed from my extensive use of Crystal over Nim, the fact I <strong>much</strong> prefer the Crystal syntax, and the fact that I am simply more comfortable coding in Crystal than I am in Nim!</p><p>So, to answer the epic question – Crystal vs Nim?</p><p>Personally, I choose Crystal. But I think <strong>you</strong> should choose <strong><em>Nim.</em></strong> 😅</p><p><a href="https://twitter.com/rbin" target="_blank" rel="noopener"> <strong>- @rbin</strong></a></p>]]></content>
<summary type="html">
<p><img src="/assets/images/nim-crystal-header-img_NEW.jpg" alt="crystal vs nim"></p>
<p>Welcome back to my series comparing the two sweethe
</summary>
<content src="https://framework.embarklabs.io//assets/images/nim-crystal-header_blank.jpg" type="image" />
<category term="tutorials" scheme="https://framework.embarklabs.io/categories/tutorials/"/>
</entry>
<entry>
<title>Nim vs Crystal - Part 2 - Threading & Tooling</title>
<link href="https://framework.embarklabs.io/news/2019/11/21/nim-vs-crystal-part-2-threading-tooling/"/>
<id>https://framework.embarklabs.io/news/2019/11/21/nim-vs-crystal-part-2-threading-tooling/</id>
<published>2019-11-21T05:00:00.000Z</published>
<updated>2020-01-19T19:38:04.364Z</updated>
<content type="html"><![CDATA[<p><img src="/assets/images/nim-crystal-header-img_NEW.jpg" alt="crystal vs nim"></p><p>Welcome back to my series comparing the two sweethearts of the modern low-level programming world. In <a href="/news/2019/11/18/nim-vs-crystal-part-1-performance-interoperability/">part 1</a>, 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!</p><p>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 <strong><em>only</em></strong> the in-built tooling, but I’ll include my favourite external package too.</p><h1 id="Threading"><a href="#Threading" class="headerlink" title="Threading"></a>Threading</h1><h3 id="Nim-Parallelism-Primitives"><a href="#Nim-Parallelism-Primitives" class="headerlink" title="Nim Parallelism Primitives"></a>Nim Parallelism Primitives</h3><p>Nim has two flavours of parallelism:</p><ul><li>Structured parallelism via the parallel statement.</li><li>Unstructured parallelism via the standalone spawn statement.</li></ul><p>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.</p><figure class="highlight nim"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> threadpool</span><br><span class="line"></span><br><span class="line"><span class="keyword">proc</span> processLine(line: <span class="built_in">string</span>) =</span><br><span class="line"> <span class="keyword">discard</span> <span class="string">"do some heavy lifting here"</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> x <span class="keyword">in</span> lines(<span class="string">"myinput.txt"</span>):</span><br><span class="line"> spawn processLine(x)</span><br><span class="line">sync()</span><br></pre></td></tr></table></figure><p>The parallel statement is the preferred way to use parallelism in a Nim program.</p><figure class="highlight nim"><table><tr><td class="code"><pre><span class="line"><span class="comment"># Compute Pi in an inefficient way</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> strutils, math, threadpool</span><br><span class="line"><span class="meta">{.experimental: "parallel".}</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">proc</span> term(k: <span class="built_in">float</span>): <span class="built_in">float</span> = <span class="number">4</span> * math.pow(-<span class="number">1</span>, k) / (<span class="number">2</span>*k + <span class="number">1</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">proc</span> pi(n: <span class="built_in">int</span>): <span class="built_in">float</span> =</span><br><span class="line"> <span class="keyword">var</span> ch = newSeq[<span class="built_in">float</span>](n+<span class="number">1</span>)</span><br><span class="line"> parallel:</span><br><span class="line"> <span class="keyword">for</span> k <span class="keyword">in</span> <span class="number">0</span>..ch.high:</span><br><span class="line"> ch[k] = spawn term(<span class="built_in">float</span>(k))</span><br><span class="line"> <span class="keyword">for</span> k <span class="keyword">in</span> <span class="number">0</span>..ch.high:</span><br><span class="line"> <span class="literal">result</span> += ch[k]</span><br><span class="line"></span><br><span class="line">echo formatFloat(pi(<span class="number">5000</span>))</span><br></pre></td></tr></table></figure><p>Threading support in Nim is part of the <code>system</code> module. To activate thread support you need to compile with the <code>--threads:on</code> command line switch.</p><p>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.</p><h3 id="Concurrency-vs-Parallelism"><a href="#Concurrency-vs-Parallelism" class="headerlink" title="Concurrency vs Parallelism"></a>Concurrency vs Parallelism</h3><p>The definitions of “concurrency” and “parallelism” sometimes get mixed up, but they are not the same.</p><p>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 <em>do</em> overlap. This is concurrency.</p><p><img src="https://dpzbhybb2pdcj.cloudfront.net/picheta/Figures/06fig01_alt.jpg" alt="concurrency"><br><em>Source: <a href="https://livebook.manning.com/book/nim-in-action/chapter-6/13" target="_blank" rel="noopener">https://livebook.manning.com/book/nim-in-action/chapter-6/13</a></em></p><p>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.</p><p><img src="https://dpzbhybb2pdcj.cloudfront.net/picheta/Figures/06fig02_alt.jpg" alt="parallelism"><br><em>Source: <a href="https://livebook.manning.com/book/nim-in-action/chapter-6/13" target="_blank" rel="noopener">https://livebook.manning.com/book/nim-in-action/chapter-6/13</a></em></p><p>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 <a href="https://crystal-lang.org/2019/09/06/parallelism-in-crystal.html" target="_blank" rel="noopener">Parallelism was tested out</a> and I’m sure will be fully ready to use soon!</p><p>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).</p><h3 id="Crystal-Concurrency-Primitives"><a href="#Crystal-Concurrency-Primitives" class="headerlink" title="Crystal Concurrency Primitives"></a>Crystal Concurrency Primitives</h3><p>In Crystal, we can use the <code>Spawn</code> 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 <code>Fiber</code> that will execute your top-level code, from which we can spawn many other <code>Fibers</code>.</p><p><code>Fibers</code> are lightweight threads of execution that are managed by the garbage collector, so you don’t <em>really</em> need to worry about managing them once you’ve spawned them. Because of this, you could technically spin up 100 <code>Fibers</code> to make a bunch of API requests, and then simply forget about them.</p><p>We can utilise <code>Spawn</code> in Crystal like so:</p><figure class="highlight crystal"><table><tr><td class="code"><pre><span class="line"><span class="keyword">require</span> <span class="string">"socket"</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">load</span></span>(id, chan)</span><br><span class="line"> puts <span class="string">"ID=<span class="subst">#{id}</span>; START"</span></span><br><span class="line"> (id..<span class="number">11</span>).each <span class="keyword">do</span></span><br><span class="line"> socket = TCPSocket.new(<span class="string">"http://robin.percy.pw"</span>, <span class="number">80</span>)</span><br><span class="line"> socket.close</span><br><span class="line"> <span class="keyword">end</span></span><br><span class="line"> puts <span class="string">"ID=<span class="subst">#{id}</span>; FINISH"</span></span><br><span class="line"> chan.send <span class="literal">nil</span></span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">main</span></span></span><br><span class="line"> chan = Channel(Nil).new</span><br><span class="line"> (<span class="number">1</span>..<span class="number">10</span>).each{|i| spawn(load(i,chan))}</span><br><span class="line"> <span class="comment"># Wait</span></span><br><span class="line"> (<span class="number">1</span>..<span class="number">10</span>).each{chan.receive}</span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line">main</span><br></pre></td></tr></table></figure><blockquote><p>To support concurrency, Crystal has to be able to switch fibers when a fiber performs non-blocking IO operations.</p></blockquote><p>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 <em>should</em> finish before task #1. As you can see in the image below; it does just that!</p><p><img src="/assets/images/crystal-thread-test.png" alt="Crystal spawn test"></p><p>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:</p><figure class="highlight crystal"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">ping</span></span>(pings, message)</span><br><span class="line"> pings.send message</span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">pong</span></span>(pings, pongs)</span><br><span class="line"> message = pings.receive</span><br><span class="line"> pongs.send message</span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line">pings = Channel(String).new</span><br><span class="line">pongs = Channel(String).new</span><br><span class="line">spawn ping pings, <span class="string">"passed message"</span></span><br><span class="line">spawn pong pings, pongs</span><br><span class="line">puts pongs.receive <span class="comment"># => "passed message"</span></span><br></pre></td></tr></table></figure><p>Unfortunately, I personally haven’t had the opportunity to test Crystal’s <code>Fibers</code> or Nim’s <code>Spawn</code> 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!</p><h1 id="Tooling"><a href="#Tooling" class="headerlink" title="Tooling"></a>Tooling</h1><h2 id="Built-in-Tooling-in-Nim"><a href="#Built-in-Tooling-in-Nim" class="headerlink" title="Built-in Tooling in Nim"></a>Built-in Tooling in Nim</h2><p>Now that <a href="https://nim-lang.org/blog/2019/09/23/version-100-released.html" target="_blank" rel="noopener">Nim 1.0 has been released</a>, its in-built tooling has improved to a great level, and is very quickly reaching maturity.</p><p>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!</p><p>The only thing to keep in mind; is that Nim <em>does</em> seem to be slower in growth than Crystal. The thing is – Nim has quite a few <strong>less</strong> core contributors than Crystal, so slower growth is to be expected!</p><h3 id="Nim-Project-Packaging"><a href="#Nim-Project-Packaging" class="headerlink" title="Nim Project Packaging"></a>Nim Project Packaging</h3><p>Something I look for in <strong><em>ALL</em></strong> 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!</p><p>We can create a new app (library/binary) by using <code>nimble init</code>:</p><p><img src="/assets/images/nimble-creating-app.png" alt="creating nimble app"></p><p>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.</p><p>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 <a href="/news/2019/11/18/nim-vs-crystal-part-1-performance-interoperability/">last article.</a></p><h3 id="Documentation"><a href="#Documentation" class="headerlink" title="Documentation"></a>Documentation</h3><p>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 <em>slightly</em> 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 <code>init</code> func.</p><p>You can generate the documentation file for your app by running:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">nimble doc myapp.nimble</span><br></pre></td></tr></table></figure><h3 id="Testing"><a href="#Testing" class="headerlink" title="Testing"></a>Testing</h3><p>Nimble offers a pre-defined <code>test</code> task which compiles and runs all files in the <code>/tests</code> directory beginning with ‘t’ in their filename.</p><p>You may wish to override this <code>test</code> task in your <code>.nimble</code> file. This is particularly useful when you have a single test suite program. Just add the following to your <code>.nimble</code> file to override the default <code>test</code> task.</p><figure class="highlight nim"><table><tr><td class="code"><pre><span class="line">task test, <span class="string">"Runs the test suite"</span>:</span><br><span class="line"> exec <span class="string">"nim c -r tests/tester"</span></span><br></pre></td></tr></table></figure><p>Running nimble test will now use the test task you have defined.</p><br/><h2 id="Built-in-Tooling-in-Crystal"><a href="#Built-in-Tooling-in-Crystal" class="headerlink" title="Built-in Tooling in Crystal"></a>Built-in Tooling in Crystal</h2><p>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.</p><h3 id="Crystal-Project-Packaging"><a href="#Crystal-Project-Packaging" class="headerlink" title="Crystal Project Packaging"></a>Crystal Project Packaging</h3><p>Much the same as the Nimble package manager, <strong><em>although not as good in my opinion,</em></strong> 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:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">$ crystal init lib my_app</span><br><span class="line"> create my_app/.gitignore</span><br><span class="line"> create my_app/LICENSE</span><br><span class="line"> create my_app/README.md</span><br><span class="line"> create my_app/.travis.yml</span><br><span class="line"> create my_app/shard.yml</span><br><span class="line"> create my_app/src/my_app</span><br><span class="line"> create my_app/src/my_app/version.cr</span><br><span class="line"> create my_app/spec/spec_helper.cr</span><br><span class="line"> create my_app/spec/my_app_spec.cr</span><br><span class="line">Initialized empty Git repository in ~/my_app/.git/</span><br></pre></td></tr></table></figure><p><code>Shards</code> 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 <code>my_app</code> app above looks like this:</p><figure class="highlight yaml"><table><tr><td class="code"><pre><span class="line"><span class="attr">name:</span> <span class="string">my_app</span></span><br><span class="line"><span class="attr">version:</span> <span class="number">0.1</span><span class="number">.0</span></span><br><span class="line"></span><br><span class="line"><span class="attr">authors:</span></span><br><span class="line"><span class="bullet"> -</span> <span class="string">Robin</span> <span class="string">Percy</span> <span class="string"><[email protected]></span></span><br><span class="line"></span><br><span class="line"><span class="attr">targets:</span></span><br><span class="line"><span class="attr"> sayhi_c:</span></span><br><span class="line"><span class="attr"> main:</span> <span class="string">src/my_app.cr</span></span><br><span class="line"></span><br><span class="line"><span class="attr">crystal:</span> <span class="number">0.31</span><span class="number">.1</span></span><br><span class="line"></span><br><span class="line"><span class="attr">license:</span> <span class="string">MIT</span></span><br></pre></td></tr></table></figure><p>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:</p><figure class="highlight yaml"><table><tr><td class="code"><pre><span class="line"><span class="attr">dependencies:</span></span><br><span class="line"><span class="attr"> github:</span></span><br><span class="line"><span class="attr"> github:</span> <span class="string">felipeelias/crystal-github</span></span><br><span class="line"><span class="attr"> version:</span> <span class="string">~></span> <span class="number">0.1</span><span class="number">.0</span></span><br></pre></td></tr></table></figure><h3 id="Documentation-amp-Formatting"><a href="#Documentation-amp-Formatting" class="headerlink" title="Documentation & Formatting"></a>Documentation & Formatting</h3><p>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.</p><p>To generate documentation, from the project root directory we can simply run:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">$ crystal doc</span><br></pre></td></tr></table></figure><p>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.</p><p>Alongside this, the built-in Formatter tool is a great feature of the language. We can run the formatter over our project by running:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">$ crystal tool format</span><br></pre></td></tr></table></figure><p>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.</p><br/><h2 id="My-Top-Crystal-Repo"><a href="#My-Top-Crystal-Repo" class="headerlink" title="My Top Crystal Repo"></a>My Top Crystal Repo</h2><h3 id="Kemal"><a href="#Kemal" class="headerlink" title="Kemal"></a>Kemal</h3><p>Obviously, there <strong><em>had</em></strong> to be a web framework appear in this list, seen as that’s what absolutely <strong>every</strong> dev seems to want to implement. My choice here is my buddy <a href="https://twitter.com/sdogruyol" target="_blank" rel="noopener">Serdar’s</a> library; <a href="https://kemalcr.com/" target="_blank" rel="noopener">Kemal</a>. 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:</p><figure class="highlight crystal"><table><tr><td class="code"><pre><span class="line"><span class="keyword">require</span> <span class="string">"kemal"</span></span><br><span class="line"><span class="keyword">require</span> <span class="string">"json"</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">User</span></span></span><br><span class="line"> JSON.mapping(</span><br><span class="line"> <span class="symbol">firstname:</span> String,</span><br><span class="line"> <span class="symbol">surname:</span> String,</span><br><span class="line"> )</span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line">post <span class="string">"/"</span> <span class="keyword">do</span> |env|</span><br><span class="line"> user = User.from_json env.request.body.not_nil!</span><br><span class="line"> {<span class="symbol">firstname:</span> user.firstname, <span class="symbol">surname:</span> user.surname}.to_json</span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line">Kemal.run</span><br></pre></td></tr></table></figure><p><strong>If you want to find all of the best Crystal libraries, <a href="https://github.com/veelenga/awesome-crystal" target="_blank" rel="noopener">you can check them out here.</a></strong></p><br /><h2 id="My-Top-Nim-Repo"><a href="#My-Top-Nim-Repo" class="headerlink" title="My Top Nim Repo"></a>My Top Nim Repo</h2><h3 id="Nimbus"><a href="#Nimbus" class="headerlink" title="Nimbus"></a>Nimbus</h3><p>My favourite Nim library really has to be <a href="https://github.com/status-im/nimbus" target="_blank" rel="noopener">Nimbus</a>. This is not because I work for <a href="https://status.im" target="_blank" rel="noopener">Status</a> (the Nimbus creators), but because of the technology. Nimbus has has such a fantastic reception from the Nim community – and rightly so!</p><p>I think that Nimbus is literally the most impressive Nim library outside of the Nim core, the <a href="https://github.com/status-im/nimbus" target="_blank" rel="noopener">Nim Beacon Chain</a> particularly so!</p><blockquote><p>Nimbus beacon chain is a research implementation of the beacon chain component of the upcoming Ethereum Serenity upgrade (Ethereum 2)</p></blockquote><p>Whilst there are no developer code samples to include here, you can check out the <a href="https://nimbus.team/" target="_blank" rel="noopener">main Nimbus website</a>, and the <a href="https://github.com/status-im/nimbus/" target="_blank" rel="noopener">main Nimbus repo</a>.</p><p>Take a look at <a href="https://nimble.directory/" target="_blank" rel="noopener">https://nimble.directory/</a> for a full list of external Nim libraries available for your projects!</p><h1 id="Conclusion"><a href="#Conclusion" class="headerlink" title="Conclusion"></a>Conclusion</h1><p>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.</p><p>It’s fantastic seeing both Nim <em>and</em> Crystal adopting the aforementioned concurrency primitives. I guess I have to give both languages a point there!</p><p>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 <strong>such</strong> great promise, I would love to see more people contributing to it and utilising it in production systems.</p><p>The final article in this series, “Crypto, DApps & P2P”, will be released over the coming days, so keep checking back.</p><p>Thanks again for sticking with me!</p><p><a href="https://twitter.com/rbin" target="_blank" rel="noopener"> <strong>- @rbin</strong></a></p>]]></content>
<summary type="html">
<p><img src="/assets/images/nim-crystal-header-img_NEW.jpg" alt="crystal vs nim"></p>
<p>Welcome back to my series comparing the two sweethe
</summary>
<content src="https://framework.embarklabs.io//assets/images/nim-crystal-header_blank.jpg" type="image" />
<category term="tutorials" scheme="https://framework.embarklabs.io/categories/tutorials/"/>
</entry>
<entry>
<title>Nim vs Crystal - Part 1 - Performance & Interoperability</title>
<link href="https://framework.embarklabs.io/news/2019/11/18/nim-vs-crystal-part-1-performance-interoperability/"/>
<id>https://framework.embarklabs.io/news/2019/11/18/nim-vs-crystal-part-1-performance-interoperability/</id>
<published>2019-11-18T05:00:00.000Z</published>
<updated>2020-01-19T19:38:04.363Z</updated>
<content type="html"><![CDATA[<p><img src="/assets/images/nim-crystal-header-img_NEW.jpg" alt="crystal vs nim"></p><p>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 <strong><em>SO</em></strong> many features of both languages I’d like to talk about, and therein many opinions held too. I do have a habit of writing <strong>very</strong> long articles, so I’d like to limit the topic scope, to keep each of these a little snappier!</p><p>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 <em>have</em> 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.</p><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" target="_blank" rel="noopener">June 13, 2017</a></blockquote> <script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script><p>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 <em>actually</em> interested in taking a look at.</p><p>Naturally, both languages have a <strong>TONNE</strong> 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 <a href="https://crystal-lang.org/reference/" target="_blank" rel="noopener">Crystal Docs</a>, or the <a href="https://nim-lang.org/docs/lib.html" target="_blank" rel="noopener">Nim Docs</a>.</p><p>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!</p><br/><h2 id="Nim"><a href="#Nim" class="headerlink" title="Nim"></a>Nim</h2><p>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 <strong><em>pretty much</em></strong> fit these criterion. </p><blockquote><p>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.</p></blockquote><blockquote><p>The binaries produced by Nim have zero dependencies and are typically very small. This makes their distribution easy and keeps your users happy.</p></blockquote><p>When I say it <em>pretty much</em> 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.</p><h3 id="Installing-Nim"><a href="#Installing-Nim" class="headerlink" title="Installing Nim"></a>Installing Nim</h3><p>Nim is super easy to install. If you’re on Windows, <a href="https://nim-lang.org/install_windows.html" target="_blank" rel="noopener">head over here</a>, and download/run the installer.</p><p>If you’re on any other Unix-based system, you can run:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">$ curl https://nim-lang.org/choosenim/init.sh -sSf | sh`</span><br></pre></td></tr></table></figure><p>If you’re on Mac, and with Homebrew installed, simply run:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">$ brew install nim</span><br></pre></td></tr></table></figure><p>You could also consider using <a href="https://github.com/dom96/choosenim" target="_blank" rel="noopener">choosenim</a> to manage Nim installations in a similar way to <code>pyenv</code> and <code>rustup</code>.</p><h3 id="Interfacing-Other-Languages"><a href="#Interfacing-Other-Languages" class="headerlink" title="Interfacing Other Languages"></a>Interfacing Other Languages</h3><p>One of the things that attracted me to both Nim <strong>and</strong> Crystal, was the ability to natively interface with other languages, and the <strong>ease</strong> 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!</p><p>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.</p><p>For a quick demo, let’s take a look at interfacing both C and JavaScript from Nim.</p><h4 id="C-Invocation"><a href="#C-Invocation" class="headerlink" title="C Invocation"></a>C Invocation</h4><p>Firstly, create the file <code>logic.c</code> with the following content:</p><figure class="highlight c"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">addTwoIntegers</span><span class="params">(<span class="keyword">int</span> a, <span class="keyword">int</span> b)</span></span></span><br><span class="line"><span class="function"></span>{</span><br><span class="line"> <span class="keyword">return</span> a + b;</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p>Next, create the file <code>calculator.nim</code> with the following content:</p><figure class="highlight nim"><table><tr><td class="code"><pre><span class="line"><span class="meta">{.compile: "logic.c".}</span></span><br><span class="line"><span class="keyword">proc</span> addTwoIntegers(a, b: <span class="built_in">cint</span>): <span class="built_in">cint</span> <span class="meta">{.importc.}</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">when</span> isMainModule:</span><br><span class="line"> echo addTwoIntegers(<span class="number">3</span>, <span class="number">7</span>)</span><br></pre></td></tr></table></figure><p>Now then, with these two <em>very simple</em> files in place, we can run:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">$ nim c -r calculator.nim</span><br></pre></td></tr></table></figure><p>The Nim compiler will compile the <code>logic.c</code> file in addition to <code>calculator.nim</code> and link both into an executable; which outputs <code>10</code> when run. Very sharp, in my opinion!</p><h4 id="JavaScript-Invocation"><a href="#JavaScript-Invocation" class="headerlink" title="JavaScript Invocation"></a>JavaScript Invocation</h4><p>Even sharper, in my opinion, is the ability to interop with JavaScript. Create a file titled <code>host.html</code> with the following content:</p><figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag"><<span class="name">html</span>></span></span><br><span class="line"><span class="tag"><<span class="name">body</span>></span></span><br><span class="line"> <span class="tag"><<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span>></span></span><br><span class="line"><span class="actionscript"> <span class="function"><span class="keyword">function</span> <span class="title">addTwoIntegers</span><span class="params">(a, b)</span></span></span></span><br><span class="line"> {</span><br><span class="line"><span class="actionscript"> <span class="keyword">return</span> a + b;</span></span><br><span class="line"> }</span><br><span class="line"> <span class="tag"></<span class="name">script</span>></span></span><br><span class="line"></span><br><span class="line"> <span class="tag"><<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span> <span class="attr">src</span>=<span class="string">"calculator.js"</span>></span><span class="tag"></<span class="name">script</span>></span></span><br><span class="line"><span class="tag"></<span class="name">body</span>></span></span><br><span class="line"><span class="tag"></<span class="name">html</span>></span></span><br></pre></td></tr></table></figure><p>Now, create another <code>calculator.nim</code> file with the following content (or reuse the one from the above C example):</p><figure class="highlight nim"><table><tr><td class="code"><pre><span class="line"><span class="keyword">proc</span> addTwoIntegers(a, b: <span class="built_in">int</span>): <span class="built_in">int</span> <span class="meta">{.importc.}</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">when</span> isMainModule:</span><br><span class="line"> echo addTwoIntegers(<span class="number">3</span>, <span class="number">7</span>)</span><br></pre></td></tr></table></figure><p>Compile the Nim code to JavaScript by running:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">$ nim js -o:calculator.js calculator.nim</span><br></pre></td></tr></table></figure><p>Once that’s done, go ahead and open <code>host.html</code> in a browser and you should see the value <code>10</code> in the browser’s console. I think this is <strong>REALLY</strong> neat. It’s superb how easy it is to achieve that, too.</p><h3 id="Aside-–-a-Quick-not-so-Secret"><a href="#Aside-–-a-Quick-not-so-Secret" class="headerlink" title="Aside – a Quick (not-so) Secret:"></a>Aside – a Quick (not-so) Secret:</h3><p>Instead of writing out the HTML above, you could actually use <strong><em>Nim’s native</em></strong> HTML DSL:</p><figure class="highlight nim"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> html_dsl</span><br><span class="line"></span><br><span class="line">html page:</span><br><span class="line"> head:</span><br><span class="line"> title(<span class="string">"Title"</span>)</span><br><span class="line"> body:</span><br><span class="line"> p(<span class="string">"Hello"</span>)</span><br><span class="line"> p(<span class="string">"World"</span>)</span><br><span class="line"> dv:</span><br><span class="line"> p <span class="string">"Example"</span></span><br><span class="line"></span><br><span class="line">echo render(page())</span><br></pre></td></tr></table></figure><p>Running this will output the following:</p><figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="meta"><!DOCTYPE html></span></span><br><span class="line"> <span class="tag"><<span class="name">html</span> <span class="attr">class</span>=<span class="string">'has-navbar-fixed-top'</span> ></span></span><br><span class="line"> <span class="tag"><<span class="name">head</span>></span></span><br><span class="line"> <span class="tag"><<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">"utf-8"</span>></span></span><br><span class="line"> <span class="tag"><<span class="name">meta</span> <span class="attr">name</span>=<span class="string">"viewport"</span> <span class="attr">content</span>=<span class="string">"width=device-width, initial-scale=1"</span>></span></span><br><span class="line"> <span class="tag"><<span class="name">title</span>></span>Title<span class="tag"></<span class="name">title</span>></span></span><br><span class="line"> <span class="tag"></<span class="name">head</span>></span></span><br><span class="line"> <span class="tag"><<span class="name">body</span> <span class="attr">class</span>=<span class="string">'has-navbar-fixed-top'</span> ></span></span><br><span class="line"> <span class="tag"><<span class="name">p</span> ></span>Hello<span class="tag"></<span class="name">p</span>></span></span><br><span class="line"> <span class="tag"><<span class="name">p</span> ></span>World<span class="tag"></<span class="name">p</span>></span></span><br><span class="line"> <span class="tag"><<span class="name">div</span>></span></span><br><span class="line"> <span class="tag"><<span class="name">p</span>></span>Example<span class="tag"></<span class="name">p</span>></span></span><br><span class="line"> <span class="tag"></<span class="name">div</span>></span></span><br><span class="line"> <span class="tag"></<span class="name">body</span>></span></span><br><span class="line"><span class="tag"></<span class="name">html</span>></span></span><br></pre></td></tr></table></figure><br/><h2 id="Crystal"><a href="#Crystal" class="headerlink" title="Crystal"></a>Crystal</h2><p>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.</p><p>I first came across Crystal when I saw <a href="https://twitter.com/sferik" target="_blank" rel="noopener">@sferik</a> giving a talk on it in Poland back in 2015. <a href="https://www.youtube.com/watch?v=Ysm4IU4aWoQ" target="_blank" rel="noopener">Video here.</a> 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.</p><h3 id="Installing-Crystal"><a href="#Installing-Crystal" class="headerlink" title="Installing Crystal"></a>Installing Crystal</h3><p>You can find all of the relevant instructions for installing Crystal, on the <a href="https://crystal-lang.org/install/" target="_blank" rel="noopener">main website installation page</a>.</p><p>If you are on Mac, and have Homebrew installed, you can simply run:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">$ brew install crystal</span><br></pre></td></tr></table></figure><p><strong>However</strong>, if you are a Windows user, <em>for the time being</em> 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 <strong>away</strong> from Crystal here, for lack of Windows support.</p><h3 id="Interfacing-C"><a href="#Interfacing-C" class="headerlink" title="Interfacing C"></a>Interfacing C</h3><p>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.</p><p>First off, let’s create a project with Crystal’s scaffolding tool (I’ll cover this feature later). Run:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">$ crystal init app sayhi_c</span><br></pre></td></tr></table></figure><p>Then head into the directory <code>sayhi_c/src/sayhi_c</code> and let’s create a file <code>sayhi.c</code> with the following contents:</p><figure class="highlight c"><table><tr><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string"><stdio.h></span></span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">hi</span><span class="params">(<span class="keyword">const</span> <span class="keyword">char</span> * name)</span></span>{</span><br><span class="line"> <span class="built_in">printf</span>(<span class="string">"Hi %s!\n"</span>, name);</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p>Now we need to compile our C file into an object. On Ubuntu or Mac using gcc we can run:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">$ gcc -c sayhi.c -o sayhi.o</span><br></pre></td></tr></table></figure><p>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 <code>sayhi_c.cr</code> file, and have it reflect the following:</p><figure class="highlight crystal"><table><tr><td class="code"><pre><span class="line"><span class="keyword">require</span> <span class="string">"./sayhi_c/*"</span></span><br><span class="line"></span><br><span class="line"><span class="meta">@[Link(ldflags: <span class="meta-string">"#{__DIR__}/sayhi_c/sayhi.o"</span>)]</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">lib</span> <span class="title">Say</span></span></span><br><span class="line"> <span class="function"><span class="keyword">fun</span> <span class="title">hi</span></span>(name : <span class="symbol">LibC:</span>:Char*) : Void</span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line">Say.hi(<span class="string">"Status"</span>)</span><br></pre></td></tr></table></figure><p>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.</p><p>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.</p><p>So, if we build our project file and run it, we get the following:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">$ crystal build --release src/sayhi_c.cr</span><br><span class="line"></span><br><span class="line">$ ./sayhi_c</span><br><span class="line"></span><br><span class="line"> > Hi Status!</span><br></pre></td></tr></table></figure><p>As you can see, Nim takes the winners trophy in this case, as it is <strong>much</strong> 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.</p><br/><h2 id="Performance-Tests"><a href="#Performance-Tests" class="headerlink" title="Performance Tests"></a>Performance Tests</h2><h3 id="Parsing-amp-calculating-values-from-a-large-JSON-file"><a href="#Parsing-amp-calculating-values-from-a-large-JSON-file" class="headerlink" title="Parsing & calculating values from a large JSON file:"></a>Parsing & calculating values from a large JSON file:</h3><p>Firstly, we need to generate our large JSON file. For this test, we’re going to generate a dataset which includes <strong>1 Million</strong> items.</p><center><iframe src="https://giphy.com/embed/13B1WmJg7HwjGU" width="480" height="270" frameBorder="0"></iframe></center><p>We can do so with the following Ruby script:</p><figure class="highlight rb"><table><tr><td class="code"><pre><span class="line"><span class="keyword">require</span> <span class="string">'json'</span></span><br><span class="line"></span><br><span class="line">x = []</span><br><span class="line"></span><br><span class="line"><span class="number">1000000</span>.times <span class="keyword">do</span></span><br><span class="line"> h = {</span><br><span class="line"> <span class="string">'x'</span> => rand,</span><br><span class="line"> <span class="string">'y'</span> => rand,</span><br><span class="line"> <span class="string">'z'</span> => rand,</span><br><span class="line"> <span class="string">'name'</span> => (<span class="string">'a'</span>..<span class="string">'z'</span>).to_a.shuffle[<span class="number">0</span>..<span class="number">5</span>].join + <span class="string">' '</span> + rand(<span class="number">10000</span>).to_s,</span><br><span class="line"> <span class="string">'opts'</span> => {<span class="string">'1'</span> => [<span class="number">1</span>, <span class="literal">true</span>]},</span><br><span class="line"> }</span><br><span class="line"> x << h</span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line">File.open(<span class="string">"1.json"</span>, <span class="string">'w'</span>) { <span class="params">|f|</span> f.write JSON.pretty_generate(<span class="string">'coordinates'</span> => x, <span class="string">'info'</span> => <span class="string">"some info"</span>) }</span><br></pre></td></tr></table></figure><p>This will generate a JSON file <strong>of around 212mb</strong>, with the following syntax:</p><figure class="highlight json"><table><tr><td class="code"><pre><span class="line">{</span><br><span class="line"> <span class="attr">"coordinates"</span>: [</span><br><span class="line"> {</span><br><span class="line"> <span class="attr">"x"</span>: <span class="number">0.10327081810860272</span>,</span><br><span class="line"> <span class="attr">"y"</span>: <span class="number">0.03247172212368832</span>,</span><br><span class="line"> <span class="attr">"z"</span>: <span class="number">0.8155255437507467</span>,</span><br><span class="line"> <span class="attr">"name"</span>: <span class="string">"scojbq 5965"</span>,</span><br><span class="line"> <span class="attr">"opts"</span>: {</span><br><span class="line"> <span class="attr">"1"</span>: [</span><br><span class="line"> <span class="number">1</span>,</span><br><span class="line"> <span class="literal">true</span></span><br><span class="line"> ]</span><br><span class="line"> }</span><br><span class="line"> }</span><br><span class="line"> ],</span><br><span class="line"> <span class="attr">"info"</span>: <span class="string">"some info"</span></span><br><span class="line">}</span><br></pre></td></tr></table></figure><p>Now that we have our chunky JSON file; we can write our first test – <strong>in Nim</strong>:</p><figure class="highlight nim"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> json</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> jobj = parseFile(<span class="string">"1.json"</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> coordinates = jobj[<span class="string">"coordinates"</span>].elems</span><br><span class="line"><span class="keyword">let</span> len = <span class="built_in">float</span>(coordinates.len)</span><br><span class="line"><span class="keyword">var</span> x = <span class="number">0</span>.<span class="number">0</span></span><br><span class="line"><span class="keyword">var</span> y = <span class="number">0</span>.<span class="number">0</span></span><br><span class="line"><span class="keyword">var</span> z = <span class="number">0</span>.<span class="number">0</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> coord <span class="keyword">in</span> coordinates:</span><br><span class="line"> x += coord[<span class="string">"x"</span>].fnum</span><br><span class="line"> y += coord[<span class="string">"y"</span>].fnum</span><br><span class="line"> z += coord[<span class="string">"z"</span>].fnum</span><br><span class="line"></span><br><span class="line">echo x / len</span><br><span class="line">echo y / len</span><br><span class="line">echo z / len</span><br></pre></td></tr></table></figure><p>And again; the same simple test, this time written <strong>in Crystal</strong>:</p><figure class="highlight crystal"><table><tr><td class="code"><pre><span class="line"><span class="keyword">require</span> <span class="string">"json"</span></span><br><span class="line"></span><br><span class="line">text = File.read(<span class="string">"1.json"</span>)</span><br><span class="line">jobj = JSON.parse(text)</span><br><span class="line">coordinates = jobj[<span class="string">"coordinates"</span>].as_a</span><br><span class="line">len = coordinates.size</span><br><span class="line">x = y = z = <span class="number">0</span></span><br><span class="line"></span><br><span class="line">coordinates.each <span class="keyword">do</span> |coord|</span><br><span class="line"> x += coord[<span class="string">"x"</span>].as_f</span><br><span class="line"> y += coord[<span class="string">"y"</span>].as_f</span><br><span class="line"> z += coord[<span class="string">"z"</span>].as_f</span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line">p x / len</span><br><span class="line">p y / len</span><br><span class="line">p z / len</span><br></pre></td></tr></table></figure><h3 id="Results"><a href="#Results" class="headerlink" title="Results:"></a>Results:</h3><p>Building our test files into tiny release packages with the respective commands below:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">$ crystal build json_test.cr --release -o json_test_cr --no-debug</span><br></pre></td></tr></table></figure><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">$ nim c -o:json_test_nim -d:danger --cc:gcc --verbosity:0 json_test.nim</span><br></pre></td></tr></table></figure><p>We can then time & run those packages, to obtain our test results:</p><table><thead><tr><th>Language</th><th>Time (s)</th><th>Memory (Mb)</th></tr></thead><tbody><tr><td>Nim</td><td>6.92</td><td>1320.4</td></tr><tr><td>Crystal</td><td>4.58</td><td>960.7</td></tr></tbody></table><p>As you can see; in this case <strong><em>Crystal</em></strong> is the more performant language – taking less time to execute & complete the test, and also fewer Megabytes in memory doing so.</p><br/><h3 id="Base64-encoding-decoding-a-large-blob"><a href="#Base64-encoding-decoding-a-large-blob" class="headerlink" title="Base64 encoding / decoding a large blob:"></a>Base64 encoding / decoding a large blob:</h3><p>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 <strong><em>Nim</em></strong> test:</p><figure class="highlight nim"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> base64, times, strutils, strformat</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> <span class="type">STR_SIZE</span> = <span class="number">131072</span></span><br><span class="line"><span class="keyword">let</span> <span class="type">TRIES</span> = <span class="number">8192</span></span><br><span class="line"><span class="keyword">let</span> str = strutils.repeat('a', <span class="type">STR_SIZE</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> str2 = base64.encode(str)</span><br><span class="line"><span class="literal">stdout</span>.write(<span class="string">fmt"encode {str[..3]}... to {str2[..3]}...: "</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> t = times.epochTime()</span><br><span class="line"><span class="keyword">var</span> i = <span class="number">0</span></span><br><span class="line"><span class="keyword">var</span> s:<span class="built_in">int64</span> = <span class="number">0</span></span><br><span class="line"><span class="keyword">while</span> i < <span class="type">TRIES</span>:</span><br><span class="line"> str2 = base64.encode(str)</span><br><span class="line"> s += len(str2)</span><br><span class="line"> i += <span class="number">1</span></span><br><span class="line">echo(<span class="string">fmt"{s}, {formatFloat(times.epochTime() - t, ffDefault, 6)}"</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> str3 = base64.decode(str2)</span><br><span class="line"><span class="literal">stdout</span>.write(<span class="string">fmt"decode {str2[..3]}... to {str3[..3]}...: "</span>)</span><br><span class="line"></span><br><span class="line">t = times.epochTime()</span><br><span class="line">i = <span class="number">0</span></span><br><span class="line">s = <span class="number">0</span></span><br><span class="line"><span class="keyword">while</span> i < <span class="type">TRIES</span>:</span><br><span class="line"> str3 = base64.decode(str2)</span><br><span class="line"> s += len(str3)</span><br><span class="line"> i += <span class="number">1</span></span><br><span class="line">echo(<span class="string">fmt"{s}, {formatFloat(times.epochTime() - t, ffDefault, 6)}"</span>)</span><br></pre></td></tr></table></figure><p>And now the same test, written in Crystal:</p><figure class="highlight crystal"><table><tr><td class="code"><pre><span class="line"><span class="keyword">require</span> <span class="string">"base64"</span></span><br><span class="line"></span><br><span class="line">STR_SIZE = <span class="number">131072</span></span><br><span class="line">TRIES = <span class="number">8192</span></span><br><span class="line"></span><br><span class="line">str = <span class="string">"a"</span> * STR_SIZE</span><br><span class="line"></span><br><span class="line">str2 = Base64.strict_encode(str)</span><br><span class="line">print <span class="string">"encode <span class="subst">#{str[<span class="number">0</span>..<span class="number">3</span>]}</span>... to <span class="subst">#{str2[<span class="number">0</span>..<span class="number">3</span>]}</span>...: "</span></span><br><span class="line"></span><br><span class="line">t, s = Time.local, <span class="number">0</span></span><br><span class="line">TRIES.times <span class="keyword">do</span> |i|</span><br><span class="line"> str2 = Base64.strict_encode(str)</span><br><span class="line"> s += str2.bytesize</span><br><span class="line"><span class="keyword">end</span></span><br><span class="line">puts <span class="string">"<span class="subst">#{s}</span>, <span class="subst">#{Time.local - t}</span>"</span></span><br><span class="line"></span><br><span class="line">str3 = Base64.decode_string(str2)</span><br><span class="line">print <span class="string">"decode <span class="subst">#{str2[<span class="number">0</span>..<span class="number">3</span>]}</span>... to <span class="subst">#{str3[<span class="number">0</span>..<span class="number">3</span>]}</span>...: "</span></span><br><span class="line"></span><br><span class="line">t, s = Time.local, <span class="number">0</span></span><br><span class="line">TRIES.times <span class="keyword">do</span> |i|</span><br><span class="line"> str3 = Base64.decode_string(str2)</span><br><span class="line"> s += str3.bytesize</span><br><span class="line"><span class="keyword">end</span></span><br><span class="line">puts <span class="string">"<span class="subst">#{s}</span>, <span class="subst">#{Time.local - t}</span>"</span></span><br></pre></td></tr></table></figure><h3 id="Results-1"><a href="#Results-1" class="headerlink" title="Results:"></a>Results:</h3><p>We can again; build our Base64 test files into release packages with the respective commands below:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">$ crystal build base64_test.cr --release -o base64_test_cr --no-debug</span><br></pre></td></tr></table></figure><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">$ nim c -o:base64_test_nim -d:danger --cc:gcc --verbosity:0 base64_test.nim</span><br></pre></td></tr></table></figure><p>As with our last test suite, we can then time & run those packages, to obtain our test results:</p><table><thead><tr><th>Language</th><th>Time (s)</th><th>Memory (Mb)</th></tr></thead><tbody><tr><td>Nim</td><td>4.17</td><td>6.6</td></tr><tr><td>Crystal</td><td>2.36</td><td>3.5</td></tr></tbody></table><p>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.</p><h2 id="Conclusion"><a href="#Conclusion" class="headerlink" title="Conclusion"></a>Conclusion</h2><p>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 <em>C speeds</em> it could achieve. That being said, I was <em>also</em> already aware that Nim <strong>claims</strong> close to C speeds, and that one of the language’s principals was to run well on old & less-performant hardware. </p><p>Yet, Crystal beat not only my own expectations; but beat Nim for both memory usage <strong>AND</strong> execution times. I really didn’t expect to see Crystal come out <em>this</em> far ahead in performance. On the other hand, Nim came out by-far the leader when it comes to language interoperability. <strong>Nim makes it even easier</strong> than Crystal when interfacing other langs – not something I thought possible, given just how easy Crystal makes the task.</p><p>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:</p><ul><li>Part 2: Threading and Tooling</li><li>Part 3: Crypto, DApps and P2P</li></ul><p>These two articles will be released over the next couple of days, so don’t forget to come back then to check them out!</p><p>Thanks for reading - as ever, if you have any questions, please feel free to reach out at <a href="mailto:[email protected]">robin@status</a>.</p><p><a href="https://twitter.com/rbin" target="_blank" rel="noopener"> - <strong>@rbin</strong></a></p>]]></content>
<summary type="html">
<p><img src="/assets/images/nim-crystal-header-img_NEW.jpg" alt="crystal vs nim"></p>
<p>I’ve been wanting to write-up a comparison on Nim a
</summary>
<content src="https://framework.embarklabs.io//assets/images/nim-crystal-header_blank.jpg" type="image" />
<category term="tutorials" scheme="https://framework.embarklabs.io/categories/tutorials/"/>
</entry>
<entry>
<title>What's new in Embark 4.1</title>
<link href="https://framework.embarklabs.io/news/2019/07/23/whats-new-in-embark-4.1/"/>
<id>https://framework.embarklabs.io/news/2019/07/23/whats-new-in-embark-4.1/</id>
<published>2019-07-23T04:00:00.000Z</published>
<updated>2020-01-19T19:38:04.363Z</updated>
<content type="html"><![CDATA[<p>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 <a href="https://github.com/embarklabs/embark/blob/master/CHANGELOG.md" target="_blank" rel="noopener">change log</a> to get a more detailed overview of what has landed in Embark’s latest release. Let’s get right to it!</p><h2 id="New-beforeDeploy-hook"><a href="#New-beforeDeploy-hook" class="headerlink" title="New beforeDeploy hook"></a>New <code>beforeDeploy</code> hook</h2><p>In Embark 4, we’ve introduced a handful of new <a href="https://embark.status.im/docs/contracts_configuration.html#Deployment-hooks">deployment hooks</a> and with 4.1, we’re expanding the APIs from there. The new <code>beforeDeploy</code> hook lets you run an action either before all of your Smart Contracts are getting deployed, or, selectively for a subset of them.</p><p>Very similar to the existing deployment hooks, <code>beforeDeploy</code> 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 <code>beforeDeploy</code> hook that runs before your Smart Contracts are being deployed is as simple as adding it to the <code>contracts</code> configuration like this:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">// config/contract.js</span><br><span class="line"></span><br><span class="line">module.exports = {</span><br><span class="line"> ...</span><br><span class="line"> contracts: {</span><br><span class="line"> beforeDeploy: async () => {</span><br><span class="line"> return Promise.resolve('yay');</span><br><span class="line"> }</span><br><span class="line"> ...</span><br><span class="line"> }</span><br><span class="line">};</span><br></pre></td></tr></table></figure><p>As expected, for more control, <code>beforeDeploy</code> can be defined on a per Smart Contract basis like this:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">// config/contract.js</span><br><span class="line"></span><br><span class="line">module.exports = {</span><br><span class="line"> ...</span><br><span class="line"> contracts: {</span><br><span class="line"> ...</span><br><span class="line"> SimpleStorage: {</span><br><span class="line"> beforeDeploy: async (context) => {</span><br><span class="line"> // can use `context` if needed</span><br><span class="line"> return Promise.resolve('yay');</span><br><span class="line"> }</span><br><span class="line"> ...</span><br><span class="line"> }</span><br><span class="line"> }</span><br><span class="line">};</span><br></pre></td></tr></table></figure><p>Learn more about Embark’s <a href="/docs/contracts_configuration.html#Deployment-hooks">deployment hooks in the documentation</a>.</p><h2 id="Enabling-and-disabling-services-via-the-console"><a href="#Enabling-and-disabling-services-via-the-console" class="headerlink" title="Enabling and disabling services via the console"></a>Enabling and disabling services via the console</h2><p>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 <code>api start</code> and <code>api stop</code>. With Embark 4.1 we decided to generalize the commands that enable users to start and stop service processes started by Embark.</p><p>Therefore, the following commands are considered deprecated in favour of a new generalized command:</p><ul><li><code>api start/stop</code></li><li><code>webserver start/stop</code></li></ul><p>The new <code>service</code> command lets you start and stop <code>api</code>, <code>webserver</code>, <code>blockchain</code>, <code>ipfs</code>, <code>swarm</code>, <code>embark</code> and <code>api</code>:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">$ service <service> on/off</span><br></pre></td></tr></table></figure><p>This works within Embark’s command line Dashboard, as well as <a href="https://embark.status.im/docs/cockpit_dashboard.html">Cockpit’s dashboard</a>. To learn more about Embark’s interactive console and its command, head over to the <a href="/docs/using_the_console.html#Enabling-and-disabling-processes">documentation</a>.</p><h2 id="Accounts-access-inside-tests"><a href="#Accounts-access-inside-tests" class="headerlink" title="Accounts access inside tests"></a>Accounts access inside tests</h2><p>In order to make writing tests in Embark a little bit more convenient, accounts configured and set up via the <code>config()</code> function are now injected into <code>describe()</code> blocks, making writing tests a little bit more predictable and easier to reason about.</p><p>Prior, in order to get hold of accounts within tests, the following was needed:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">let accounts = [];</span><br><span class="line"></span><br><span class="line">config({</span><br><span class="line"> contracts: {</span><br><span class="line"> ...</span><br><span class="line"> }</span><br><span class="line">}, (err, _accounts) => {</span><br><span class="line"> accounts = _accounts;</span><br><span class="line">});</span><br><span class="line"></span><br><span class="line">contract('My contract', () => {</span><br><span class="line"></span><br><span class="line"> it('does something', () => {</span><br><span class="line"> // can use `accounts` here</span><br><span class="line"> });</span><br><span class="line">});</span><br></pre></td></tr></table></figure><p>Notice that Embark won’t run the <code>contract()</code> block until <code>config()</code> is done doing its work. Therefore, using a global variable was the recommended way to re-initialize <code>accounts</code> once <code>config()</code> runs its callback.</p><p>The same can now be achieved with the following code:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">config({</span><br><span class="line"> contracts: {</span><br><span class="line"> ...</span><br><span class="line"> }</span><br><span class="line">});</span><br><span class="line"></span><br><span class="line">contract('My contract', accounts => {</span><br><span class="line"></span><br><span class="line"> it('does something', () => {</span><br><span class="line"> // can use `accounts` here</span><br><span class="line"> });</span><br><span class="line">});</span><br></pre></td></tr></table></figure><p>Instead of managing an <code>accounts</code> variable yourself, you can just ask for it now within <code>contract()</code>‘s callback.</p><h2 id="Several-improvements-inside-Cockpit"><a href="#Several-improvements-inside-Cockpit" class="headerlink" title="Several improvements inside Cockpit"></a>Several improvements inside Cockpit</h2><p>Cockpit has got a lot of new things as well. This includes <a href="">draggable tabs</a> inside the code editor, pagination support for <a href="https://github.com/embarklabs/embark/commit/d71352b">Smart Contracts</a> and the <a href="https://github.com/embarklabs/embark/commit/745edaf" target="_blank" rel="noopener">accounts explorer</a>, alphabetically <a href="https://github.com/embarklabs/embark/commit/0e9a4a1" target="_blank" rel="noopener">sorted Smart Contracts</a>, and the ability to <a href="https://github.com/embarklabs/embark/pull/1649" target="_blank" rel="noopener">send ETH to payable Smart Contract methods</a> via the Cockpit UI.</p><h2 id="What’s-next"><a href="#What’s-next" class="headerlink" title="What’s next?"></a>What’s next?</h2><p>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.</p><p>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.</p><p>Stay tuned with latest changes happening in Embark by <a href="https://github.com/embarklabs/embark" target="_blank" rel="noopener">watching our GitHub repository</a> and following us on <a href="https://twitter.com/EmbarkProject" target="_blank" rel="noopener">Twitter</a>!</p>]]></content>
<summary type="html">
<p>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 n
</summary>
<category term="announcements" scheme="https://framework.embarklabs.io/categories/announcements/"/>
</entry>
<entry>
<title>Introducing Embark 4.0 - Cockpit, Debugger and more</title>
<link href="https://framework.embarklabs.io/news/2019/03/19/introducing-embark-4/"/>
<id>https://framework.embarklabs.io/news/2019/03/19/introducing-embark-4/</id>
<published>2019-03-19T04:00:00.000Z</published>
<updated>2020-01-19T19:38:04.363Z</updated>
<content type="html"><![CDATA[<p><img src="/assets/images/EMBARK_HEADER_ALT_OPTIMIZED.jpg" alt="Embark" title="Embark"></p><p><strong>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.</strong></p><p>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!</p><p>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 <a href="/docs/quick_start.html">Quick Start Guide</a>.</p><div class="c-notification c-notification--info"> <p><strong>Embark now follows SemVer</strong></p> <p><p>Version 4.0 contains <strong>some breaking changes</strong>, however we kept them at a minimum and you can learn about all of them in our article on <a href="/news/2019/03/18/upgrading-to-embark-4/">upgrading DApps created with Embark 3.x</a>.</p><p>That said, with the release of 4.0 <strong>Embark will now follow SemVer</strong> making it easier for developers to update and watch out for changes.</p></p></div> <h2 id="Cockpit-–-An-intuitive-Web-Interface"><a href="#Cockpit-–-An-intuitive-Web-Interface" class="headerlink" title="Cockpit – An intuitive Web Interface"></a>Cockpit – An intuitive Web Interface</h2><p>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.</p><p><strong>The dashboard</strong> 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.</p><p>For more information regarding Cockpit’s dashboard, please refer to the <a href="/docs/cockpit_dashboard.html">Embark docs</a>.</p><p><img src="/assets/images/cockpit_dashboard_release.png" alt="Cockpit Dashboard" title="Cockpit Dashboard"></p><p><strong>The blockchain explorer</strong> 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. <a href="/docs/cockpit_explorer.html">Learn more</a></p><p><img src="/assets/images/cockpit_explorer_overview.png" alt="Cockpit Explorer" title="Cockpit Explorer"></p><p><strong>Iterative Deployment</strong> 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. <a href="/docs/cockpit_deployment.html">Learn more</a></p><p><strong>The code editor</strong> 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! <a href="/docs/cockpit_editor.html">Learn more</a></p><p><img src="/assets/images/cockpit_editor_release.png" alt="Cockpit Editor" title="Cockpit Editor"></p><h2 id="Integrated-Debugger"><a href="#Integrated-Debugger" class="headerlink" title="Integrated Debugger"></a>Integrated Debugger</h2><p>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.</p><p>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.</p><h2 id="Better-tooling-integration"><a href="#Better-tooling-integration" class="headerlink" title="Better tooling integration"></a>Better tooling integration</h2><p>Embark is now compatible with any frontend tooling such as Create React App and the CLI tools for Angular, Vue, and more.</p><p>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.</p><h2 id="Additional-Updates-and-Features"><a href="#Additional-Updates-and-Features" class="headerlink" title="Additional Updates and Features"></a>Additional Updates and Features</h2><p>We’ve introduced a number of updates and new features to go along with the key features mentioned above. These include:</p><ul><li><strong>New contract deployment hooks</strong>: onDeploy and afterDeploy allow for complete customization of the deployment lifecycle.</li><li><strong>Better account configuration</strong>: accounts are now consistently defined in config/blockchain.js.</li><li><strong>Embark can be installed as a local dependency for per-project versioning</strong>: global installation of Embark is no longer required.</li></ul><h2 id="A-new-Website-and-Fresh-New-Look"><a href="#A-new-Website-and-Fresh-New-Look" class="headerlink" title="A new Website and Fresh New Look"></a>A new Website and Fresh New Look</h2><p><img src="/assets/images/website_release.png" alt="Website Release" title="Website Release"></p><p>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!</p><h2 id="Get-Started-Now"><a href="#Get-Started-Now" class="headerlink" title="Get Started Now"></a>Get Started Now</h2><p>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.</p><p>Check out the <a href="/docs/quick_start.html">Quick Start guide</a> or dive right into the <a href="/docs">documentation</a>.</p><p>Chat with us in <a href="https://gitter.im/embark-framework/Lobby" target="_blank" rel="noopener">Gitter</a><br>Star the repo on <a href="https://github.com/embarklabs/embark" target="_blank" rel="noopener">GitHub</a><br>Follow us on <a href="https://twitter.com/EmbarkProject" target="_blank" rel="noopener">Twitter</a></p>]]></content>
<summary type="html">
<p><img src="/assets/images/EMBARK_HEADER_ALT_OPTIMIZED.jpg" alt="Embark" title="Embark"></p>
<p><strong>Embark 4.0 is officially out of bet
</summary>
<content src="https://framework.embarklabs.io//assets/images/EMBARK_HEADER_ALT_OPTIMIZED.jpg" type="image" />
<category term="announcements" scheme="https://framework.embarklabs.io/categories/announcements/"/>
</entry>
<entry>
<title>How to upgrade to Embark 4</title>
<link href="https://framework.embarklabs.io/news/2019/03/18/upgrading-to-embark-4/"/>
<id>https://framework.embarklabs.io/news/2019/03/18/upgrading-to-embark-4/</id>
<published>2019-03-18T04:00:00.000Z</published>
<updated>2020-01-19T19:38:04.363Z</updated>
<content type="html"><![CDATA[<p>The release of Embark 4.0 is close at hand and the release candidate, <code>beta.1</code>, will introduce some breaking changes. Let’s see what it takes to update an Embark 3.x Dapp to Embark 4.</p><h2 id="Use-any-frontend-build-tool"><a href="#Use-any-frontend-build-tool" class="headerlink" title="Use any frontend build tool!"></a>Use <strong>any</strong> frontend build tool!</h2><p>That’s right! The use of Embark’s builtin pipeline in no longer required.</p><p>Historically, Embark 3.x came with a special Webpack pipeline because it automated development tasks, such as enabling the use of “magic” imports (ie <code>import SimpleStorage from "Embark/contracts/SimpleStorage";</code> or <code>import EmbarkJS from Embark/EmbarkJS</code>), and establishing a Web3 connection for the Dapp.</p><p>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 <code>create-react-app</code> 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.</p><p>Therefore, we are announcing that Embark 4 can use <strong>any</strong> frontend development build tooling, letting Embark handle the things that it does best. This means we can use tools such as <code>create-react-app</code> 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.</p><p>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.</p><div class="c-notification c-notification--info"> <p><strong>NOTE</strong></p> <p><p>If you are not interested in using a third party pipeline, you can skip to the next section to <a href="#New-Web3-plugin">see the rest of the breaking changes needed to migrate a Dapp to Embark 4</a>.</p></p></div> <h3 id="Converting-to-another-pipeline"><a href="#Converting-to-another-pipeline" class="headerlink" title="Converting to another pipeline"></a>Converting to another pipeline</h3><p>Converting to a third party pipeline is easy. This can be done with three simple improvements that Embark 4 has made available for us.</p><h4 id="Artifact-generation-directory"><a href="#Artifact-generation-directory" class="headerlink" title="Artifact generation directory"></a>Artifact generation directory</h4><p>NOTE: If you are planning on using Embark’s built-in Webpack pipeline (and not use a third party pipeline), please <a href="#New-Web3-plugin">skip down to the remainder of the Embark 4 breaking changes</a>.</p><p>Embark 4 generates <a href="/docs/javascript_usage.html#Embark-Artifacts">Smart Contract artifacts</a> 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 <code>.embark/</code> 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.</p><p>The first thing we need to do is add a new <code>generationDir</code> property in the root of <code>embark.json</code>. This property tells Embark where to place the generated artifacts in the Dapp’s filesystem. For example, <code>create-react-app</code> (CRA) has <code>src/</code> as source folder and the artifacts must be placed in that folder, so we would add in <code>embark.json</code>:</p><figure class="highlight json"><table><tr><td class="code"><pre><span class="line">{</span><br><span class="line"> <span class="attr">"generationDir"</span>: <span class="string">"src/embarkArtifacts"</span></span><br><span class="line">}</span><br></pre></td></tr></table></figure><h4 id="“Magic”-imports"><a href="#“Magic”-imports" class="headerlink" title="“Magic” imports"></a>“Magic” imports</h4><p>Afterwards, we need to convert all “magic” imports in our Dapp’s code to relative imports.</p><p>The first one is the EmbarkJS import. The “magic” import is <code>"Embark/EmbarkJS"</code>. Anywhere we have <code>"Embark/EmbarkJS"</code> in our Dapp’s code, we need to convert that to the relative path. Because we are trying to get the <code>EmbarkJS</code> library, and the <code>embarkjs.js</code> script is located in the root of <code>embarkArtifacts/</code>, we need to replace</p><figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> EmbarkJS <span class="keyword">from</span> <span class="string">"Embark/EmbarkJS"</span></span><br></pre></td></tr></table></figure><p>with</p><figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> EmbarkJS <span class="keyword">from</span> <span class="string">"./embarkArtifacts/embarkjs"</span></span><br></pre></td></tr></table></figure><div class="c-notification c-notification--info"> <p><strong>NOTE</strong></p> <p><p>NOTE: The relative path is dependent upon the generationDir setting specified in embark.json <a href="#Artifact-generation-directory">see the “Artifact generation directory” section above</a>.</p></p></div> <p>Secondly, we need to update the “magic” Smart Contract imports. These will need to change from</p><figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> ContractName <span class="keyword">from</span> <span class="string">"Embark/contract/ContractName"</span>;</span><br></pre></td></tr></table></figure><p>to</p><figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> ContractName <span class="keyword">from</span> <span class="string">"./embarkArtifacts/contracts/ContractName"</span>;</span><br></pre></td></tr></table></figure><p>Thirdly, there used to be <code>import web3 from "Embark/web3"</code>, 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 <code>web3</code> object is now available everywhere in the Dapp.</p><p>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.</p><h3 id="New-project-with-another-pipeline"><a href="#New-project-with-another-pipeline" class="headerlink" title="New project with another pipeline"></a>New project with another pipeline</h3><p>Starting a new Dapp from scratch is easy, we have two options.</p><h4 id="Embark’s-create-react-dapp-template"><a href="#Embark’s-create-react-dapp-template" class="headerlink" title="Embark’s create-react-dapp template"></a>Embark’s create-react-dapp template</h4><p>The easiest option is to use our <a href="https://github.com/embarklabs/embark-create-react-dapp-template" target="_blank" rel="noopener">new Embark CRA template</a>. 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 <code>embarkConfig/</code> folder in the root of the Dapp to make sure they don’t clash with CRA’s config folder/files.</p><p>To get started with Embark’s CRA template,</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">embark new --template embark-react-dapp my-dapp</span><br><span class="line">cd my-dapp</span><br><span class="line">embark run</span><br></pre></td></tr></table></figure><div class="c-notification c-notification--danger"> <p><strong>DEPRECATION NOTICE</strong></p> <p><p>The <code>--template</code> option has been deprecated in v5 and support will be removed in future versions.</p></p></div> <p>Then, in another terminal,</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">cd my-dapp</span><br><span class="line">yarn start // or alternatively, npm run start</span><br></pre></td></tr></table></figure><p>That’s it!</p><h4 id="For-other-build-tools"><a href="#For-other-build-tools" class="headerlink" title="For other build tools"></a>For other build tools</h4><p>If we want to use another build tool than CRA, here are the steps:</p><p>Create a project using a frontend build tool like Angular CLI. Then, in another directory, execute <code>embark new your_projects_name</code>.</p><p>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 <code>config/pipeline.js</code> and set <code>enabled: false</code>, so that Embark’s pipeline is disabled.</p><p>We can also go in <code>embark.json</code> and remove the <code>app</code> section (as well as Embark’s source dir that you will not be using).</p><p>Lastly, check out <a href="#Artifact-generation-directory">the “Artifact generation directory” section above</a> to make sure your artifacts directory is set up correctly for you build tool.</p><p>There you go, your project is ready.</p><p>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.</p><h2 id="New-Web3-plugin"><a href="#New-Web3-plugin" class="headerlink" title="New Web3 plugin"></a>New Web3 plugin</h2><p><em>(2019/06/27)</em> <strong>NOTE</strong>: <em>the following instructions are</em> <strong><em>not</em></strong> <em>applicable to Embark <code>4.1.x</code> and newer, but should still be followed for <code>4.0.x</code> or <code><=4.1.0-beta.3</code>.</em></p><p>Starting with Embark 4 beta.1, Embark no longer supplies the Dapp with <code>Web3.js</code> by default. Don’t run. We did that so that we can now have the possibility of supporting more than just <code>Web3.js</code>, such as EthersJS, and more. You can even roll your own.</p><p>To continue using <code>Web3.js</code> inside the Embark 4 Dapp, execute the following command in the Embark console: <code>plugin install embarkjs-connector-web3</code>.</p><p>This simply <a href="https://embark.status.im/docs/installing_plugins.html">installs <code>embarkjs-connector-web3</code> as a plugin</a>. Alternatively, this plugin can be installed manually by executing:</p><ol><li><code>yarn add embarkjs-connector-web3</code> or <code>npm install --save embarkjs-connector-web3</code></li><li>Adding <code>"embarkjs-connector-web3": {}</code> to the <code>plugins</code> section of <code>embark.json</code></li></ol><p>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 <code>EmbarkJS</code> at least once. If using a third party pipeline, the <code>EmbarkJS</code> file can be imported using <code>import EmbarkJS from "./embarkArtifacts/embarkjs.js"</code> (or as specified by the <code>generationDir</code> in <code>embark.json</code>). If using Embark’s built-in pipeline, <code>EmbarkJS</code> can be imported using <code>import EmbarkJS from "Embark/EmbarkJS";</code>.</p><h2 id="New-Blockchain-account-configs"><a href="#New-Blockchain-account-configs" class="headerlink" title="New Blockchain account configs"></a>New Blockchain account configs</h2><p>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 <a href="https://embark.status.im/docs/blockchain_accounts_configuration.html">Accounts Blockchain configuration guide</a> in our docs.</p><p>However, we did introduce some small breaking changes. We removed:</p><ul><li><code>account</code>: This is completely replaced by the new <code>accounts</code> property (notice the <code>s</code> at the end of <code>accounts</code>). It gives the developer more flexibility. To have exactly the same behavior as before, just use the <code>nodeAccounts</code> account type as <a href="https://embark.status.im/docs/blockchain_accounts_configuration.md#parameter-descriptions">described in the docs</a></li><li><code>simulatorMnemonic</code>: Removed in favor of Ganache’s default mnemonic. If this functionality is still needed, please specify the desired mnemonic in the <a href="https://embark.status.im/docs/blockchain_accounts_configuration.md#parameter-descriptions">blockchain config’s <code>mnemonic</code> account type</a>.</li></ul><h2 id="Conclusion"><a href="#Conclusion" class="headerlink" title="Conclusion"></a>Conclusion</h2><p>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.</p><p>In the meantime, all the Embark 4 goodness doesn’t come at too high a price in terms of breaking changes.</p><p>Upgrading to Embark 4 will be a blast. If you ever have an issue, make sure to hit us up on <a href="https://gitter.im/embark-framework/Lobby" target="_blank" rel="noopener">Gitter</a>.</p>]]></content>
<summary type="html">
<p>The release of Embark 4.0 is close at hand and the release candidate, <code>beta.1</code>, will introduce some breaking changes. Let’s se
</summary>
<category term="tutorials" scheme="https://framework.embarklabs.io/categories/tutorials/"/>
</entry>
<entry>
<title>Building a decentralized Reddit with Embark - Part 3</title>
<link href="https://framework.embarklabs.io/news/2019/02/18/building-a-decentralized-reddit-with-embark-part-3/"/>
<id>https://framework.embarklabs.io/news/2019/02/18/building-a-decentralized-reddit-with-embark-part-3/</id>
<published>2019-02-18T05:00:00.000Z</published>
<updated>2020-01-19T19:38:04.362Z</updated>
<content type="html"><![CDATA[<p>Hopefully you’ve read <a href="/news/2019/02/04/building-a-decentralized-reddit-with-embark-part-1/">the first</a> and <a href="/news/2019/02/11/building-a-decentralized-reddit-with-embark-part-2/">second part</a> 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.</p><ul><li><a href="/news/2019/02/04/building-a-decentralized-reddit-with-embark-part-1/"><strong>Part 1</strong> - Setting up the project and implementing a Smart Contract</a></li><li><a href="/news/2019/02/11/building-a-decentralized-reddit-with-embark-part-2/"><strong>Part 2</strong> - Testing the Smart Contract through EmbarkJS</a></li></ul><p>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!</p><p><strong>The code for this tutorial can be found in <a href="https://github.com/embarklabs/dreddit-tutorial" target="_blank" rel="noopener">this repository</a></strong>.</p><h2 id="Rendering-our-first-component"><a href="#Rendering-our-first-component" class="headerlink" title="Rendering our first component"></a>Rendering our first component</h2><p>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.</p><p>For that, what we’ll do is adding React as a dependency to our project. In fact, we’ll be relying on two packages - <code>react</code> and <code>react-dom</code>. The latter is needed to render components defined with React in a DOM environment, which is what a Browser essentially is.</p><p>Let’s add the following <code>dependencies</code> section to our projects <code>package.json</code>:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">"dependencies": {</span><br><span class="line"> "react": "^16.4.2",</span><br><span class="line"> "react-dom": "^16.4.2"</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p>Once that is done we need to actually install those dependencies. For that we simply execute the following command in our terminal of choice:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">$ npm install</span><br></pre></td></tr></table></figure><p>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.</p><p>Creating components in React is pretty straight forward. All we need to do is creating a class that extends React’s <code>Component</code> type and add a <code>render()</code> method that will render the component’s view.</p><p>Let’s create a folder for all of our components inside our projects:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">$ mkdir app/js/components</span><br></pre></td></tr></table></figure><p>Next, we create a file for our root component. We call it simply <code>App</code> and use the same file name:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">$ touch app/js/components/App.js</span><br></pre></td></tr></table></figure><p>Alright, as mentioned earlier, we really just want to render some text on the screen for starters. Here’s what that could look like:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">import React, { Component } from 'react';</span><br><span class="line"></span><br><span class="line">export class App extends Component {</span><br><span class="line"></span><br><span class="line"> render() {</span><br><span class="line"> return <h1>DReddit</h1></span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p>This is probably self explanatory, but all we’re doing here is importing <code>React</code> and its <code>Component</code> type and create an <code>App</code> class that extends <code>Component</code>. The <code>render()</code> 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!</p><p>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 <code>app/js/index.js</code> and add the following code:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">import React from 'react';</span><br><span class="line">import { render } from 'react-dom';</span><br><span class="line">import { App } from './components/App';</span><br><span class="line"></span><br><span class="line">render(<App />, document.getElementById('root'));</span><br></pre></td></tr></table></figure><p>We need to import <code>React</code> again as it has to be available in this script’s scope. We also import a <code>render</code> function from <code>react-dom</code>, which is used to render our root component (<code>App</code>) 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 <code>root</code>.</p><p>Let’s set this up really quick. In <code>app/index.html</code> add a new element with a <code>root</code> id:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line"><body></span><br><span class="line"><div id="root"></div></span><br><span class="line"><script src="js/app.js"></script></span><br><span class="line"></body></span><br></pre></td></tr></table></figure><p>Notice that we’ve also moved the <code>script</code> tag inside the body tag, after the element with the <code>root</code> id. This is just one way to work around the fact that the element we’re referencing inside our <code>render()</code> method is actually available in the document at the time the script is executed.</p><p>That should do it! Let’s spin up Embark, we should then see our component rendered on the screen:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">$ embark run</span><br></pre></td></tr></table></figure><h2 id="Building-a-CreatePost-component"><a href="#Building-a-CreatePost-component" class="headerlink" title="Building a CreatePost component"></a>Building a <code>CreatePost</code> component</h2><p>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 <code>App</code>, we’ll introduce a new component <code>createPost</code> that comes with a <code>render()</code> 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.</p><p>Creating a simple form is very straight forward:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">import React, { Component } from 'react';</span><br><span class="line"></span><br><span class="line">export class CreatePost extends Component {</span><br><span class="line"></span><br><span class="line"> render() {</span><br><span class="line"> return (</span><br><span class="line"> <form></span><br><span class="line"> <div></span><br><span class="line"> <label>Topic</label></span><br><span class="line"> <input type="text" name="topic" /></span><br><span class="line"> </div></span><br><span class="line"> <div></span><br><span class="line"> <textarea name="content"></textarea></span><br><span class="line"> </div></span><br><span class="line"> <button>Post</button></span><br><span class="line"> </form></span><br><span class="line"> )</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p>To actually render this component on screen, we need to make it part of our <code>App</code> component. Or, to be more specific, have the <code>App</code> component render our <code>CreatePost</code> component. For now we can simply add it to <code>App</code>‘s render function like this;</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">import { CreatePost } from './CreatePost';</span><br><span class="line"></span><br><span class="line">export class App extends Component {</span><br><span class="line"></span><br><span class="line"> render() {</span><br><span class="line"> return (</span><br><span class="line"> <React.Fragment></span><br><span class="line"> <h1>DReddit</h1></span><br><span class="line"> <CreatePost /></span><br><span class="line"> </React.Fragment&></span><br><span class="line"> )</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p>React doesn’t allow for multiple root elements in a single component’s view, so we have to take advantage of <code>React.Fragment</code>. 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!</p><p>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 <code>state</code> 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 <code>setState()</code> method if needed.</p><p>Let’s introduce <code>state</code> in our component by adding a constructor and initializing it accordingly:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">export class CreatePost extends Component {</span><br><span class="line"></span><br><span class="line"> constructor(props) {</span><br><span class="line"> super(props);</span><br><span class="line"></span><br><span class="line"> this.state = {</span><br><span class="line"> topic: '',</span><br><span class="line"> content: '',</span><br><span class="line"> loading: false</span><br><span class="line"> };</span><br><span class="line"> }</span><br><span class="line"> ...</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p>Next we bind that state to our form fields:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line"><form></span><br><span class="line"> <div></span><br><span class="line"> <label>Topic</label></span><br><span class="line"> <input type="text" name="topic" value={this.state.topic} /></span><br><span class="line"> </div></span><br><span class="line"> <div></span><br><span class="line"> <textarea name="content" value={this.state.content}></textarea></span><br><span class="line"> </div></span><br><span class="line"> <button>Post</button></span><br><span class="line"></form></span><br></pre></td></tr></table></figure><p>No worries, we’ll make use of <code>loading</code> 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 <code>state</code>. Here’s what our <code>handleChange()</code> and <code>createPost()</code> handlers looks like:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">export class CreatePost extends Component {</span><br><span class="line"> ...</span><br><span class="line"> handleChange(field, event) {</span><br><span class="line"> this.setState({</span><br><span class="line"> [field]: event.target.value</span><br><span class="line"> });</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"> createPost(event) {</span><br><span class="line"> event.preventDefault();</span><br><span class="line"> console.log(this.state);</span><br><span class="line"> }</span><br><span class="line"> ...</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p>Notice how we’re using <code>setState()</code> inside <code>handleChange()</code> to update whatever field name has been passed to that method. Now all we need to do is attach those handlers to our form:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line"><form onSubmit={e => createPost(e)}></span><br><span class="line"> <div></span><br><span class="line"> <label>Topic</label></span><br><span class="line"> <input</span><br><span class="line"> type="text"</span><br><span class="line"> name="topic"</span><br><span class="line"> value={this.state.topic}</span><br><span class="line"> onChange={e => handleChange('topic', e)} /></span><br><span class="line"> </div></span><br><span class="line"> <div></span><br><span class="line"> <textarea</span><br><span class="line"> name="content"</span><br><span class="line"> value={this.state.content}</span><br><span class="line"> onChange={e => handleChange('content', e})></textarea></span><br><span class="line"> </div></span><br><span class="line"> <button type="submit">Post</button></span><br><span class="line"></form></span><br></pre></td></tr></table></figure><p>Since we’re using the <code>onSubmit()</code> handler of the form, it’s also important that we either add a <code>type="submit"</code> to our <code>button</code> or change the button to an <code><input type="submit"></code> element. Otherwise, the form won’t emit a submit event.</p><p>Nice! With that in place, we should see the component’s <code>state</code> in the console when submitting the form! The next challenge is to use <code>EmbarkJS</code> and its APIs to make our component talk to our Smart Contract instance.</p><h3 id="Uploading-data-to-IPFS"><a href="#Uploading-data-to-IPFS" class="headerlink" title="Uploading data to IPFS"></a>Uploading data to IPFS</h3><p>Recall from our <a href="/news/2019/02/04/building-a-decentralized-reddit-with-embark-part-1/#Creating-posts">first part</a> of this tutorial that our <code>DReddit</code> Smart Contract comes with a <code>createPost()</code> 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.</p><p>Luckily, EmbarkJS comes with plenty of convenient APIs to do exactly that! <code>EmbarkJS.Storage.saveText()</code> 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 <a href="/news/2019/02/11/building-a-decentralized-reddit-with-embark-part-2/#Testing-createPost">part two</a> of this tutorial, we’ll use <code>async/await</code> to write asynchronous code in a synchronous fashion.</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">async createPost(event) {</span><br><span class="line"> event.preventDefault();</span><br><span class="line"></span><br><span class="line"> this.setState({</span><br><span class="line"> loading: true</span><br><span class="line"> });</span><br><span class="line"></span><br><span class="line"> const ipfsHash = await EmbarkJS.Storage.saveText(JSON.stringify({</span><br><span class="line"> topic: this.state.topic,</span><br><span class="line"> content: this.state.content</span><br><span class="line"> }));</span><br><span class="line"></span><br><span class="line"> this.setState({</span><br><span class="line"> topic: '',</span><br><span class="line"> content: '',</span><br><span class="line"> loading: false</span><br><span class="line"> });</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p>We use <code>JSON.stringify()</code> on an object that holds the <code>topic</code> and <code>content</code> of the post to be created. This is also the first time we put <code>loading</code> into action. Setting it to <code>true</code> before, and <code>false</code> after we’ve performed our operations lets us render a useful message as the user is waiting for updates.</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line"><form onSubmit={e => createPost(e)}></span><br><span class="line"> ...</span><br><span class="line"> {this.state.loading &&</span><br><span class="line"> <p>Posting...</p></span><br><span class="line"> }</span><br><span class="line"></form></span><br></pre></td></tr></table></figure><p>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 <code>createPost()</code> method. Let’s do that!</p><h3 id="Sending-transactions-to-create-posts"><a href="#Sending-transactions-to-create-posts" class="headerlink" title="Sending transactions to create posts"></a>Sending transactions to create posts</h3><p>To send a transaction to our Smart Contract, we can again take advantage of EmbarkJS’ APIs, similar to how we did it in the <a href="/news/2019/02/11/building-a-decentralized-reddit-with-embark-part-2">second part</a>. 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.</p><p>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 <code>async/await</code> can be used here as well:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">async createPost(event) {</span><br><span class="line"> ...</span><br><span class="line"> const accounts = await web3.eth.getAccounts();</span><br><span class="line"> ...</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p>Next up we’ll import a <code>DReddit</code> Smart Contract instance from EmbarkJS and use it to get a gas estimation from <code>web3</code>. We can then use the estimation and one of our accounts to actually send the transaction:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">import DReddit from './artifacts/contracts/DReddit';</span><br><span class="line">...</span><br><span class="line"></span><br><span class="line">async createPost(event) {</span><br><span class="line"> ...</span><br><span class="line"> const accounts = await web3.eth.getAccounts();</span><br><span class="line"> const createPost = DReddit.methods.createPost(web3.utils.toHex(ipfsHash));</span><br><span class="line"> const estimate = await createPost.estimateGas();</span><br><span class="line"></span><br><span class="line"> await createPost.send({from: accounts[0], gas: estimate});</span><br><span class="line"> ...</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p>Sweet, with that, our <code>createPost</code> 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 <code>embark run</code>. We should see a confirmation that looks something like this:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">Blockchain> DReddit.createPost("0x516d5452427a47415153504552614645534173335133765a6b59436633634143776368626263387575623434374e") | 0xbbeb9fa1eb4e3434c08b31409c137c2129de65eb335855620574c537b3004f29 | gas:136089 | blk:18455 | status:0x1</span><br></pre></td></tr></table></figure><h2 id="Creating-a-Post-component"><a href="#Creating-a-Post-component" class="headerlink" title="Creating a Post component"></a>Creating a Post component</h2><p>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.</p><p>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.</p><p>Here’s what such a component with a basic template could look like:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">import React, { Component } from 'react';</span><br><span class="line"></span><br><span class="line">export class Post extends Component {</span><br><span class="line"></span><br><span class="line"> render() {</span><br><span class="line"> return (</span><br><span class="line"> <React.Fragment></span><br><span class="line"> <hr /></span><br><span class="line"> <h3>Some Topic</h3></span><br><span class="line"> <p>This is the content of a post</p></span><br><span class="line"> <p><small><i>created at 2019-02-18 by 0x00000000000000</i></small></p></span><br><span class="line"> <button>Upvote</button></span><br><span class="line"> <button>Downvote</button></span><br><span class="line"> </React.Fragment></span><br><span class="line"> )</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p>There are different ways to make the data being rendered dynamic. Usually, we would probably pass a one or more properties to the <code>Post</code> component that represents the entire post object and can then be displayed inside its <code>render()</code> method. However, for this tutorial we’re going to choose a slightly different path. We’ll make <code>Post</code> receive IPFS hash that’s stored in the Smart Contract and have it resolve the data itself.</p><p>Let’s stay consistent with our naming and say the property we’re expecting to be filled with data is called <code>description</code>, just like the one used inside the Smart Contract. We can then use <code>EmbarkJS.Storage.get()</code> with the IPFS hash to fetch the data that represents the actual post. In order to render the data inside <code>Post</code>‘s view, we’ll parse it and use <code>setState()</code> accordingly.</p><p>To make sure all of that happens once the component is ready to do its work, we’ll do all of that inside its <code>componentDidMount()</code> life cycle hook:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">import React, { Component } from 'react';</span><br><span class="line">import EmbarkJS from '.artifacts/embarkjs';</span><br><span class="line"></span><br><span class="line">export class Post extends Component {</span><br><span class="line"></span><br><span class="line"> constructor(props) {</span><br><span class="line"> super(props);</span><br><span class="line"> this.state = {</span><br><span class="line"> topic: '',</span><br><span class="line"> content: ''</span><br><span class="line"> };</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"> async componentDidMount() {</span><br><span class="line"> const ipfsHash = web3.utils.toAscii(this.props.description);</span><br><span class="line"> const data = await EmbarkJS.Storage.get(ipfsHash);</span><br><span class="line"> const { topic, content } = JSON.parse(data);</span><br><span class="line"></span><br><span class="line"> this.setState({ topic, content });</span><br><span class="line"> }</span><br><span class="line"> ...</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p>There’s one gotcha to keep in mind here: Calling <code>EmbarkJS.Storage.get()</code> or any <code>EmbarkJS</code> function on page load can fail, because the storage system might not be fully initialized yet. This wasn’t a problem for the previous <code>EmbarkJS.Storage.uploadText()</code> because we called that function well after Embark had finished initializing</p><p>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 <code>onReady()</code> hook. <code>EmbarkJS.onReady()</code> 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 <code>render()</code> call in our <code>App</code> component inside Embark’s <code>onReady()</code> function.</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">EmbarkJS.onReady(() => {</span><br><span class="line"> render(<App />, document.getElementById('root'));</span><br><span class="line">});</span><br></pre></td></tr></table></figure><p>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.</p><p>Let’s also quickly add the <code>owner</code> and creation date. The <code>owner</code> 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 <code>dateformat</code> library for that and install it as a dependency like this:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">$ npm install --save dateformat</span><br></pre></td></tr></table></figure><p>Once that is done, we can update our <code>Post</code> component’s <code>render()</code> function to calculate a properly formatted date based on the <code>creationDate</code> that has been passed down through properties:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">...</span><br><span class="line">import dateformat from 'dateformat';</span><br><span class="line"></span><br><span class="line">export class Post extends Component {</span><br><span class="line"> ...</span><br><span class="line"> render() {</span><br><span class="line"> const formattedDate = dateformat(</span><br><span class="line"> new Date(this.props.creationDate * 1000),</span><br><span class="line"> 'yyyy-mm-dd HH:MM:ss'</span><br><span class="line"> );</span><br><span class="line"> return (</span><br><span class="line"> <React.Fragment></span><br><span class="line"> <hr /></span><br><span class="line"> <h3>{this.state.topic}</h3></span><br><span class="line"> <p>{this.state.content}</p></span><br><span class="line"> <p><small><i>created at {formattedDate} by {this.props.owner}</i></small></p></span><br><span class="line"> <button>Upvote</button></span><br><span class="line"> <button>Downvote</button></span><br><span class="line"> </React.Fragment></span><br><span class="line"> )</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p>Notice that variables created inside <code>render()</code> can be interpolated as they are - there’s no need to make them available on <code>props</code> or <code>state</code>. As a matter of fact, <code>props</code> are always considered read only in React.</p><p>Let’s try out our new <code>Post</code> component with some static data by adding it to our <code>App</code> component’s view. Next up, we’ll make this dynamic by fetching the posts from our Smart Contract.</p><p><strong>Attention</strong>: 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.</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">export class App extends Component {</span><br><span class="line"></span><br><span class="line"> render() {</span><br><span class="line"> return (</span><br><span class="line"> <React.Fragment></span><br><span class="line"> <h1>DReddit</h1></span><br><span class="line"> <CreatePost /></span><br><span class="line"> <Post</span><br><span class="line"> description="0x516d655338444b53464546725369656a747751426d683377626b56707566335770636e4c715978726b516e4b5250"</span><br><span class="line"> creationDate="1550073772"</span><br><span class="line"> owner="0x00000000000"</span><br><span class="line"> /></span><br><span class="line"> </React.Fragment></span><br><span class="line"> )</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure><h2 id="Creating-a-List-component"><a href="#Creating-a-List-component" class="headerlink" title="Creating a List component"></a>Creating a List component</h2><p>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.</p><p>Let’s introduce a method <code>numPosts()</code> in our <code>DReddit</code> Smart Contract:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">function numPosts() public view returns (uint) {</span><br><span class="line"> return posts.length;</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p><code>posts.length</code> 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!</p><p>With that in place, we can start building a new <code>List</code> component. The <code>List</code> component maintains a list of posts to render on screen, so we can start simple again and introduce the bare minimum like this:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">import React, { Component } from 'react';</span><br><span class="line"></span><br><span class="line">export class List extends Component {</span><br><span class="line"></span><br><span class="line"> constructor(props) {</span><br><span class="line"> super(props);</span><br><span class="line"> this.state = {</span><br><span class="line"> posts: []</span><br><span class="line"> };</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"> render() {</span><br><span class="line"> return (<React.Fragment></span><br><span class="line"> {this.state.posts.map(post => {</span><br><span class="line"> return (</span><br><span class="line"> <Post</span><br><span class="line"> key={post.id}</span><br><span class="line"> description={post.description}</span><br><span class="line"> creationDate={post.creationDate}</span><br><span class="line"> owner={post.owner}</span><br><span class="line"> />)</span><br><span class="line"> })}</span><br><span class="line"> </React.Fragment></span><br><span class="line"> )</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p>The most interesting part here is probably the <code>render()</code> method, in which we iterate over all <code>state.posts</code> (which at the moment is empty) and then render a <code>Post</code> component for every iteration. Another thing to note is that every <code>Post</code> receives a <code>key</code>. This is required in React when creating views from loops. We’ve never introduced a <code>post.id</code> in this tutorial, but don’t worry, we’ll fix that in a moment.</p><p>We can already put that in our <code>App</code> component. It won’t render anything as we haven’t fetched any posts yet, but that’s what we’ll do next.</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">import { List } from './List';</span><br><span class="line"></span><br><span class="line">export class App extends Component {</span><br><span class="line"></span><br><span class="line"> render() {</span><br><span class="line"> return (</span><br><span class="line"> <React.Fragment></span><br><span class="line"> <h1>DReddit</h1></span><br><span class="line"> <CreatePost /></span><br><span class="line"> <List /></span><br><span class="line"> </React.Fragment></span><br><span class="line"> )</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure><h3 id="Fetching-posts-data"><a href="#Fetching-posts-data" class="headerlink" title="Fetching posts data"></a>Fetching posts data</h3><p>Let’s fill our new <code>List</code> component with life! As mentioned earlier, we’ll use our Smart Contract’s <code>numPosts()</code> 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 <code>List</code> component is ready, we’ll use its <code>componentDidMount()</code> method for that:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">export class List extends Component {</span><br><span class="line"> ...</span><br><span class="line"> async componentDidMount() {</span><br><span class="line"> const totalPosts = await DReddit.methods.numPosts().call();</span><br><span class="line"></span><br><span class="line"> let list = [];</span><br><span class="line"></span><br><span class="line"> for (let i = 0; i < totalPosts; i++) {</span><br><span class="line"> const post = DReddit.methods.posts(i).call();</span><br><span class="line"> list.push(post);</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"> list = await Promise.all(list);</span><br><span class="line"> }</span><br><span class="line"> ...</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p>Notice that in the above code we don’t <code>await</code> 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 <code>Promise.all().</code></p><p>Last but not least, we need to add an <code>id</code> property to every post as mentioned earlier. This is easily done by simply iterating over all posts and assigning the post’s index as <code>id</code>. Once that is done, we can use <code>setState()</code> to update our component’s state and render the list:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">async componentDidMount() {</span><br><span class="line"> ...</span><br><span class="line"> list = list.map((post, index) => {</span><br><span class="line"> post.id = index;</span><br><span class="line"> return post;</span><br><span class="line"> });</span><br><span class="line"></span><br><span class="line"> this.setState({ posts: list });</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p>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.</p><h3 id="Reloading-posts"><a href="#Reloading-posts" class="headerlink" title="Reloading posts"></a>Reloading posts</h3><p>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 <code>createPost</code> component tell the <code>List</code> 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 <code>CreatePost</code> and <code>List</code> (in our case <code>App</code>), and have it pass that logic down to places where its needed. This also means we’ll be fetching the list inside <code>App</code> and pass down the pure data to <code>List</code>.</p><p>If this sounds overwhelming, no worries, it’s more trivial than that! Let’s start by introducing a <code>loadPosts()</code> function in our <code>App</code> component. Essentially we’re moving everything from <code>List</code>‘s <code>componentDidMount()</code> function into <code>App</code>:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">export class App extends Component {</span><br><span class="line"> ...</span><br><span class="line"> async loadPosts() {</span><br><span class="line"> const totalPosts = await DReddit.methods.numPosts().call();</span><br><span class="line"></span><br><span class="line"> let list = [];</span><br><span class="line"></span><br><span class="line"> if (totalPosts > 0) {</span><br><span class="line"> for (let i = 0; i < totalPosts; i++) {</span><br><span class="line"> const post = DReddit.methods.posts(i).call();</span><br><span class="line"> list.push(post);</span><br><span class="line"> }</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"> list = await Promise.all(list);</span><br><span class="line"> list = list.map((post, index) => {</span><br><span class="line"> post.id = index;</span><br><span class="line"> return post;</span><br><span class="line"> });</span><br><span class="line"></span><br><span class="line"> list;</span><br><span class="line"></span><br><span class="line"> this.setState({ posts: list });</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p>To make this work we also need to introduce a <code>state</code> with the dedicated <code>posts</code>. After that, we make sure <code>loadPosts()</code> is called when <code>App</code> is mounted:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">export class App extends Component {</span><br><span class="line"></span><br><span class="line"> constructor(props) {</span><br><span class="line"> super(props);</span><br><span class="line"> this.state = {</span><br><span class="line"> posts: []</span><br><span class="line"> };</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"> async componentDidMount() {</span><br><span class="line"> await this.loadPosts();</span><br><span class="line"> }</span><br><span class="line"> ...</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p>Last but not least, all we have to do is to pass the <code>posts</code> down to <code>List</code> and <code>loadPosts()</code> to <code>CreatePost</code> as a callback handler if you will:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">render() {</span><br><span class="line"> return (</span><br><span class="line"> <React.Fragment></span><br><span class="line"> <h1>DReddit</h1></span><br><span class="line"> <CreatePost afterPostHandler={this.loadPosts.bind(this)}/></span><br><span class="line"> <List posts={this.state.posts}/></span><br><span class="line"> </React.Fragment></span><br><span class="line"> )</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p>Once that is done, we can consume <code>posts</code> and <code>afterPostHandler()</code> from <code>this.props</code> respectively. In <code>List</code>‘s <code>render()</code> function we’ll do (notice we don’t rely on <code>this.state</code> anymore):</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">render() {</span><br><span class="line"> return (<React.Fragment></span><br><span class="line"> {this.props.posts.map(post => {</span><br><span class="line"> ...</span><br><span class="line"> })}</span><br><span class="line"> </React.Fragment></span><br><span class="line"> )</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p>And in <code>CreatePost</code> we call <code>afterPostHandler()</code> after a post has been created:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">async createPost(event) {</span><br><span class="line"> ...</span><br><span class="line"> await createPost.send({from: accounts[0], gas: estimate});</span><br><span class="line"> await this.props.afterPostHandler();</span><br><span class="line"></span><br><span class="line"> this.setState({</span><br><span class="line"> topic: '',</span><br><span class="line"> content: '',</span><br><span class="line"> loading: false</span><br><span class="line"> });</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p>Wonderful! The list now automatically reloads after creating posts, give it a try!</p><h2 id="Add-voting-functionality"><a href="#Add-voting-functionality" class="headerlink" title="Add voting functionality"></a>Add voting functionality</h2><p>The final feature we’ll be implementing is the up and down voting of posts. This is where we come back to our <code>Post</code> component that we’ve created earlier. In order to make this feature complete we’ll have to:</p><ul><li>Render the number of up and down votes per post</li><li>Add handlers for users to up and down vote</li><li>Determine if a user can vote on a post</li></ul><h3 id="Rendering-number-of-votes"><a href="#Rendering-number-of-votes" class="headerlink" title="Rendering number of votes"></a>Rendering number of votes</h3><p>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 <code>DReddit</code> 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 <code>App</code>‘s <code>loadPosts()</code> method like this:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">async loadPosts() {</span><br><span class="line"> ...</span><br><span class="line"> list = list.map((post, index) => {</span><br><span class="line"> post.id = index;</span><br><span class="line"> post.upvotes = parseInt(post.upvotes, 10);</span><br><span class="line"> post.downvotes = parseInt(post.downvotes, 10);</span><br><span class="line"> return post;</span><br><span class="line"> });</span><br><span class="line"> ...</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p>Once that is done we can pass each post’s <code>upvotes</code> and <code>downvotes</code> to every <code>Post</code> component via its <code>props</code> inside our <code>List</code> component:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">export class List extends Component {</span><br><span class="line"> ...</span><br><span class="line"> render() {</span><br><span class="line"> return (<React.Fragment></span><br><span class="line"> {this.props.posts.map(post => {</span><br><span class="line"> return (<Post</span><br><span class="line"> key={post.id}</span><br><span class="line"> description={post.description}</span><br><span class="line"> creationDate={post.creationDate}</span><br><span class="line"> upvotes={post.upvotes}</span><br><span class="line"> downvotes={post.downvotes}</span><br><span class="line"> owner={post.owner}</span><br><span class="line"> />)</span><br><span class="line"> })}</span><br><span class="line"> </React.Fragment></span><br><span class="line"> )</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p>Rendering the number of <code>upvotes</code> and <code>downvotes</code> is then really just a matter of interpolating them in <code>Post</code>‘s <code>render()</code> function. We’re just going to add them next to the buttons, but feel free to put them somewhere else:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">export class Post extends Component {</span><br><span class="line"> ...</span><br><span class="line"> render() {</span><br><span class="line"> ...</span><br><span class="line"> return (</span><br><span class="line"> <React.Fragment></span><br><span class="line"> ...</span><br><span class="line"> {this.props.upvotes} <button>Upvote</button></span><br><span class="line"> {this.props.downvotes} <button>Downvote</button></span><br><span class="line"> </React.Fragment></span><br><span class="line"> )</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure><h3 id="Implement-up-and-down-votes"><a href="#Implement-up-and-down-votes" class="headerlink" title="Implement up and down votes"></a>Implement up and down votes</h3><p>Similar to when creating new posts, making the up and down vote buttons work requires sending transactions to our <code>DReddit</code> Smart Contract. So we’ll do almost the same thing as in our <code>CreatePost</code> component, just that we’re calling the Smart Contract’s <code>vote()</code> method. If you recall, the <code>vote()</code> method takes a post id and the vote type, which is either <code>NONE</code>, <code>UPVOTE</code> or <code>DOWNVOTE</code> and are stored as <code>uint8</code>.</p><p>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:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">const BALLOT = {</span><br><span class="line"> NONE: 0,</span><br><span class="line"> UPVOTE: 1,</span><br><span class="line"> DOWNVOTE: 2</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p>We don’t actually have the post id available in our <code>Post</code> component yet. That’s easily added in our <code>List</code> component, by now you should know how to do that!</p><p>We can then add click handlers to our up and down vote buttons and pass one of the <code>BALLOT</code> types to them (notice that we added <code>BALLOT.NONE</code> only for completeness-sake but don’t actually use it in our code):</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line"><button onClick={e => this.vote(BALLOT.UPVOTE)}>Upvote</button></span><br><span class="line"><button onClick={e => this.vote(BALLOT.DOWNVOTE)}>Downvote</button></span><br></pre></td></tr></table></figure><p>The next thing we need to do is sending that vote type along with the post id to our Smart Contract:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">async vote(ballot) {</span><br><span class="line"> const accounts = await web3.eth.getAccounts();</span><br><span class="line"> const vote = DReddit.methods.vote(this.props.id, ballot);</span><br><span class="line"> const estimate = await vote.estimateGas();</span><br><span class="line"></span><br><span class="line"> await vote.send({from: accounts[0], gas: estimate});</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p>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 <code>props</code> 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 <code>props</code> once and store them in the component’s state.</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">export class Post extends Component {</span><br><span class="line"></span><br><span class="line"> constructor(props) {</span><br><span class="line"> super(props);</span><br><span class="line"> this.state = {</span><br><span class="line"> topic: '',</span><br><span class="line"> content: '',</span><br><span class="line"> upvotes: this.props.upvotes,</span><br><span class="line"> downvotes: this.props.downvotes</span><br><span class="line"> };</span><br><span class="line"> }</span><br><span class="line"> ...</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p>We also change the component’s view to render the values from state instead of <code>props</code>:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">render() {</span><br><span class="line"> ...</span><br><span class="line"> return (</span><br><span class="line"> <React.Fragment></span><br><span class="line"> ...</span><br><span class="line"> {this.state.upvotes} <button ...>Upvote</button></span><br><span class="line"> {this.state.downvotes} <button ...>Downvote</button></span><br><span class="line"> </React.Fragment></span><br><span class="line"> )</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p>After that we can update the state with new votes using <code>setState()</code>, right after a vote has been sent:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">async vote(ballot) {</span><br><span class="line"> ...</span><br><span class="line"> this.setState({</span><br><span class="line"> upvotes: this.state.upvotes + (ballot == BALLOT.UPVOTE ? 1 : 0),</span><br><span class="line"> downvotes: this.state.downvotes + (ballot == BALLOT.DOWNVOTE ? 1 : 0)</span><br><span class="line"> });</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p><strong>That’s it!</strong> 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.</p><p>Let’s make sure this is reflected in our application’s UI and wrap up this tutorial!</p><h3 id="Use-canVote-to-disable-vote-buttons"><a href="#Use-canVote-to-disable-vote-buttons" class="headerlink" title="Use canVote() to disable vote buttons"></a>Use <code>canVote()</code> to disable vote buttons</h3><p>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 <code>canVote()</code> 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.</p><p>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:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">export class Post extends Component {</span><br><span class="line"></span><br><span class="line"> constructor(props) {</span><br><span class="line"> super(props);</span><br><span class="line"> this.state = {</span><br><span class="line"> topic: '',</span><br><span class="line"> content: '',</span><br><span class="line"> upvotes: this.props.upvotes,</span><br><span class="line"> downvotes: this.props.downvotes,</span><br><span class="line"> canVote: true,</span><br><span class="line"> submitting: false</span><br><span class="line"> };</span><br><span class="line"> }</span><br><span class="line"> ...</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p>Next, we update our <code>Post</code> component’s <code>render()</code> function to disable the voting buttons if a vote is in flight, or a user is simply not allowed to vote:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">render() {</span><br><span class="line"> ...</span><br><span class="line"> const disabled = this.state.submitting || !this.state.canVote;</span><br><span class="line"> return (</span><br><span class="line"> <React.Fragment></span><br><span class="line"> ...</span><br><span class="line"> {this.state.upvotes} <button disabled={disabled} ...>Upvote</button></span><br><span class="line"> {this.state.downvotes} <button disabled={disabled} ...>Downvote</button></span><br><span class="line"> </React.Fragment></span><br><span class="line"> )</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p>Last but not least, we have to make sure the state properties are updated accordingly. We’ll call our Smart Contract’s <code>canVote()</code> method when a post is initialized:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">export class Post extends Component {</span><br><span class="line"> ...</span><br><span class="line"> async componentDidMount() {</span><br><span class="line"> ...</span><br><span class="line"> const canVote = await DReddit.methods.canVote(this.props.id).call();</span><br><span class="line"> this.setState({ topic, content, canVote });</span><br><span class="line"> }</span><br><span class="line"> ...</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p>And when a vote is being made, we set <code>submitting</code> to <code>true</code> right before we send a transaction and set it back to <code>false</code> again when the transaction is done. At this point, we also know that a vote has been made on this post, so <code>canVote</code> can be set to <code>false</code> at the same time:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">async vote(ballot) {</span><br><span class="line"> ...</span><br><span class="line"> this.setState({ submitting: true });</span><br><span class="line"> await vote.send({from: accounts[0], gas: estimate + 1000});</span><br><span class="line"></span><br><span class="line"> this.setState({</span><br><span class="line"> ...</span><br><span class="line"> canVote: false,</span><br><span class="line"> submitting: false</span><br><span class="line"> });</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p><strong>And we’re done!</strong></p><h2 id="Wrapping-it-up"><a href="#Wrapping-it-up" class="headerlink" title="Wrapping it up"></a>Wrapping it up</h2><p>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:</p><ul><li>Sort the posts in reversed chronological order so that the latest post is always on top</li><li>Rely on Smart Contracts Events to reload list</li><li>Introduce routing so there can be different views for creating and viewing posts</li><li>Use CSS to make the application look nice</li></ul><p>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.</p><p><strong>We’ve recorded every single step of this tutorial <a href="https://github.com/embarklabs/dreddit-tutorial" target="_blank" rel="noopener">in this repository</a></strong>, 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 <a href="https://twitter.com/EmbarkProject" target="_blank" rel="noopener">follow us on Twitter</a> as well for updates!</p>]]></content>
<summary type="html">
<p>Hopefully you’ve read <a href="/news/2019/02/04/building-a-decentralized-reddit-with-embark-part-1/">the first</a> and <a href="/news/201
</summary>
<category term="tutorials" scheme="https://framework.embarklabs.io/categories/tutorials/"/>
</entry>
<entry>
<title>Building a decentralized Reddit with Embark - Part 2</title>
<link href="https://framework.embarklabs.io/news/2019/02/11/building-a-decentralized-reddit-with-embark-part-2/"/>
<id>https://framework.embarklabs.io/news/2019/02/11/building-a-decentralized-reddit-with-embark-part-2/</id>
<published>2019-02-11T05:00:00.000Z</published>
<updated>2020-01-19T19:38:04.362Z</updated>
<content type="html"><![CDATA[<p>In <a href="/news/2019/02/04/building-a-decentralized-reddit-with-embark-part-1/">the first part of this tutorial</a> we’ve implemented a <code>DReddit</code> 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:</p><ul><li><a href="/news/2019/02/04/building-a-decentralized-reddit-with-embark-part-1/"><strong>Part 1</strong> - Setting up the project and implementing a Smart Contract</a></li><li><a href="/news/2019/02/18/building-a-decentralized-reddit-with-embark-part-3/"><strong>Part 3</strong> - Building a simple front-end using React</a></li></ul><p><strong>The code for this tutorial can be found in <a href="https://github.com/embarklabs/dreddit-tutorial" target="_blank" rel="noopener">this repository</a></strong>.</p><p>And off we go!</p><h2 id="Writing-a-first-test"><a href="#Writing-a-first-test" class="headerlink" title="Writing a first test"></a>Writing a first test</h2><p>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 <code>DReddit_spec.js</code> inside <code>test</code> and add a <code>contract()</code> block that looks something like this:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">contract('DReddit', () => {</span><br><span class="line"></span><br><span class="line">});</span><br></pre></td></tr></table></figure><p>Inside this code block we’ll be putting dedicated test cases. The <code>contract()</code> function can be considered a “grouping” functionality to group tests, if you will. If you’re familiar with Mocha’s <a href="https://mochajs.org/" target="_blank" rel="noopener">describe()</a> function, you already know how <code>contract()</code> works, as it’s pretty much just an alias.</p><p>To check whether our test setup is working, we add a simple test that passes:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">contract('DReddit', () => {</span><br><span class="line"></span><br><span class="line"> it ('should work', () => {</span><br><span class="line"> assert.ok(true);</span><br><span class="line"> });</span><br><span class="line">});</span><br></pre></td></tr></table></figure><p>Running this using Embark’s <code>test</code> command should result in an output similar to this:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">❯ embark test</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">Compiling contracts</span><br><span class="line"> DReddit</span><br><span class="line"> ✓ should work (0ms) - [0 gas]</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"> 1 passing (5s) - [Total: 2210775 gas]</span><br><span class="line"></span><br><span class="line"> > All tests passed</span><br></pre></td></tr></table></figure><p>This works great, let’s go ahead and test some actual functionality!</p><h2 id="Testing-the-creation-of-post"><a href="#Testing-the-creation-of-post" class="headerlink" title="Testing the creation of post"></a>Testing the creation of post</h2><p>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 <code>DReddit</code> 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.</p><h3 id="Requiring-Smart-Contract-instances"><a href="#Requiring-Smart-Contract-instances" class="headerlink" title="Requiring Smart Contract instances"></a>Requiring Smart Contract instances</h3><p>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 <code>require()</code> that lets us import Smart Contract instances from an Embark specific path. This is done so that we can easily import</p><p>For example, in order to get an instance of our <code>DReddit</code> Smart Contract within the test, we add the following line to our spec file:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">const DReddit = require('Embark/contracts/DReddit');</span><br></pre></td></tr></table></figure><p><code>DReddit</code> is now supposed to be an EmbarkJS Smart Contract instance, but we need to be very careful here. <strong>In reality, this object is empty</strong>. 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, <code>config()</code>, 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 <code>DReddit</code> isn’t what we think it is, until we use it inside <code>contract()</code>.</p><p>Let’s add the mentioned <code>config()</code> function so Embark knows what we need:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">config({</span><br><span class="line"> contracts: {</span><br><span class="line"> DReddit: {}</span><br><span class="line"> }</span><br><span class="line">});</span><br></pre></td></tr></table></figure><p>This is very similar to <a href="/docs/contracts_configuration.html">configuring Smart Contracts</a>, in fact it’s the test environment equivalent. We pass a configuration object to <code>config()</code> with specific parameters for every Smart Contract we need. In our case, we just need to add <code>DReddit</code> 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 <code>config()</code> function, the imported objects for our Smart Contract instances will always be empty.</p><h3 id="Testing-createPost"><a href="#Testing-createPost" class="headerlink" title="Testing createPost()"></a>Testing <code>createPost()</code></h3><p>To test our Smart Contract’s <code>createPost()</code> method, we’ll make use of <code>DReddit</code>, which will now be a Smart Contract instance. If you remember, <code>createPost()</code> 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 <strong>IPFS hash</strong> 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.</p><p>Once we have such a hash (no worries, we’ve got one prepared), we can use Web3’s <code>fromAscii()</code> utils to convert that hash to bytes and then send it off using our Smart Contract’s <code>createPost()</code> method. We can then subscribe to the events we’re emitting and check its return value like this:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">...</span><br><span class="line">const ipfsHash = 'Qmc5gCcjYypU7y28oCALwfSvxCBskLuPKWpK4qpterKC7z';</span><br><span class="line"></span><br><span class="line">contract('DReddit', () => {</span><br><span class="line"> ...</span><br><span class="line"> it ('should be able to create a post and receive it via contract event', async () => {</span><br><span class="line"> const receipt = await DReddit.methods.createPost(web3.utils.fromAscii(ipfsHash)).send();</span><br><span class="line"> const event = receipt.events.NewPost;</span><br><span class="line"> postId = event.returnValues.postId;</span><br><span class="line"> assert.equal(web3.utils.toAscii(event.returnValues.description), ipfsHash);</span><br><span class="line"> });</span><br><span class="line">});</span><br></pre></td></tr></table></figure><p>Notice that we’re using <code>async/await</code> 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 <code>embark test</code> should result in two passing tests now!</p><h2 id="Testing-correctness-of-data"><a href="#Testing-correctness-of-data" class="headerlink" title="Testing correctness of data"></a>Testing correctness of data</h2><p>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 <code>NewPost</code> event. To test this we take advantage of the <code>postId</code> 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.</p><p>Luckily wallet accounts can be easily accessed as they are emitted by Embark’s <code>config()</code> function. All we have to do is attaching a resolution handler to <code>config()</code> and storing the emitted value:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">...</span><br><span class="line">let accounts = [];</span><br><span class="line"></span><br><span class="line">config({</span><br><span class="line"> contracts: {</span><br><span class="line"> DReddit: {}</span><br><span class="line"> }</span><br><span class="line">}, (err, _accounts) => {</span><br><span class="line"> accounts = _accounts;</span><br><span class="line">});</span><br></pre></td></tr></table></figure><p>Having that in place, our next test could look something like this:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">it ('post should have correct data', async () => {</span><br><span class="line"> const post = await DReddit.methods.posts(postId).call();</span><br><span class="line"> assert.equal(web3.utils.toAscii(post.description), ipfsHash);</span><br><span class="line"> assert.equal(post.owner, accounts[0]);</span><br><span class="line">});</span><br></pre></td></tr></table></figure><p>You might notice that we’re referring to <code>accounts[0]</code> here. However, just by looking at the code, we can’t really know if <code>accounts[0]</code> is really the one we’re expecting. This is where Embark offers another helping hand. When the <code>accounts</code> are set up, Embark will automatically set the first account of the wallet (<code>accounts[0]</code>) to the default account that’ll be used for all transactions. With that knowledge we can make an assertion, expecting <code>accounts[0]</code> to be the owner of the post.</p><p>Another way would be to just always explicitly pass any of the accounts to a Smart Contract method’s <code>send()</code> function, in which case we’d have full control over which account of the wallet will be used.</p><h2 id="Testing-canVote"><a href="#Testing-canVote" class="headerlink" title="Testing canVote()"></a>Testing <code>canVote()</code></h2><p>Alright, next up let’s quickly test if our <code>canVote()</code> method works the way as expected. As voting on posts that don’t exist should never work, we will simply call <code>canVote()</code> on a post id that doesn’t exist. This test is pretty straight forward:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">it('should not be able to vote in an unexisting post', async () => {</span><br><span class="line"> const userCanVote = await DReddit.methods.canVote("123").call();</span><br><span class="line"> assert.equal(userCanVote, false);</span><br><span class="line">});</span><br></pre></td></tr></table></figure><p>We also want to make sure that <code>canVote()</code> resolves to <code>true</code> in case a user can indeed vote a certain post. We can again reuse the <code>postId</code> that we’ve stored earlier:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">it('should be able to vote in a post if account has not voted before', async () => {</span><br><span class="line"> const userCanVote = await DReddit.methods.canVote(postId).call();</span><br><span class="line"> assert.equal(userCanVote, true);</span><br><span class="line">});</span><br></pre></td></tr></table></figure><p>Wonderful, we have 5 passing tests now!</p><h2 id="Testing-vote"><a href="#Testing-vote" class="headerlink" title="Testing vote()"></a>Testing <code>vote()</code></h2><p>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 <code>vote()</code> 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 <code>NewVote</code> event is the same as the account that performed the vote. We can actually take some inspiration from our previous tests:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">it("should be able to vote in a post", async () => {</span><br><span class="line"> const receipt = await DReddit.methods.vote(postId, 1).send();</span><br><span class="line"> const Vote = receipt.events.NewVote;</span><br><span class="line"> assert.equal(Vote.returnValues.owner, accounts[0]);</span><br><span class="line">});</span><br></pre></td></tr></table></figure><h2 id="Test-that-only-one-vote-per-post-is-allowed"><a href="#Test-that-only-one-vote-per-post-is-allowed" class="headerlink" title="Test that only one vote per post is allowed"></a>Test that only one vote per post is allowed</h2><p>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 <code>async/await</code> syntax we can test this very nicely by adding a <code>try/catch</code> block. When a user votes on a post she has already voted on, <code>vote()</code> will fail in which case we can make our assertions accordingly:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">it('should not be able to vote twice', async () => {</span><br><span class="line"> try {</span><br><span class="line"> const receipt = await DReddit.methods.vote(postId, 1).send();</span><br><span class="line"> assert.fail('should have reverted');</span><br><span class="line"> } catch (error){</span><br><span class="line"> assert(error.message.search('revert') > -1, 'Revert should happen');</span><br><span class="line"> }</span><br><span class="line">});</span><br></pre></td></tr></table></figure><p>This might look a bit confusing first but it’s actually pretty straight forward. In case <code>vote()</code> fails, we should not reach the <code>assert.fail()</code> call but end up in the <code>catch()</code> block immediately. If that was not the case, the test would fail. This is a very common pattern when testing negatives.</p><p>Okay, one last time we run <code>embark test</code> and if the output looks like the following, we’re fully covered in terms of tests!</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">❯ embark test</span><br><span class="line">Compiling contracts</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"> DReddit</span><br><span class="line"> ✓ should work (0ms) - [0 gas]</span><br><span class="line"> ✓ should be able to create a post and receive it via contract event (60ms) - [160689 gas]</span><br><span class="line"> ✓ post should have correct data (18ms) - [0 gas]</span><br><span class="line"> ✓ should not be able to vote in an unexisting post (14ms) - [0 gas]</span><br><span class="line"> ✓ should be able to vote in a post if account hasn't voted before (12ms) - [0 gas]</span><br><span class="line"> ✓ should be able to vote in a post (42ms) - [65115 gas]</span><br><span class="line"> ✓ shouldn't be able to vote twice (37ms) - [22815 gas]</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"> 7 passing (5s) - [Total: 3130955 gas]</span><br><span class="line"></span><br><span class="line"> > All tests passed</span><br></pre></td></tr></table></figure><p> Awesome! If you run into any issues, check out the repository with all steps recorded <a href="https://github.com/embarklabs/dreddit-tutorial" target="_blank" rel="noopener">here</a>. In <a href="/news/2019/02/18/building-a-decentralized-reddit-with-embark-part-3/">the next and last part of this series</a>, we’ll be building a front-end for our DReddit app using React. Until then, feel free to add more tests as you like!</p>]]></content>
<summary type="html">
<p>In <a href="/news/2019/02/04/building-a-decentralized-reddit-with-embark-part-1/">the first part of this tutorial</a> we’ve implemented a
</summary>
<category term="tutorials" scheme="https://framework.embarklabs.io/categories/tutorials/"/>
</entry>
<entry>
<title>Building a decentralized Reddit with Embark - Part 1</title>
<link href="https://framework.embarklabs.io/news/2019/02/04/building-a-decentralized-reddit-with-embark-part-1/"/>
<id>https://framework.embarklabs.io/news/2019/02/04/building-a-decentralized-reddit-with-embark-part-1/</id>
<published>2019-02-04T05:00:00.000Z</published>
<updated>2020-01-19T19:38:04.362Z</updated>
<content type="html"><![CDATA[<p>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.</p><p>This tutorial is split up into three parts, so every individual part can get our full attention. The three parts are going to be:</p><ul><li><strong>Part 1</strong> - Setting up the project and implementing a Smart Contract</li><li><a href="/news/2019/02/11/building-a-decentralized-reddit-with-embark-part-2/"><strong>Part 2</strong> - Testing the Smart Contract through EmbarkJS</a></li><li><a href="/news/2019/02/18/building-a-decentralized-reddit-with-embark-part-3/"><strong>Part 3</strong> - Building a simple front-end using React</a></li></ul><p><strong>The code for this tutorial can be found in <a href="https://github.com/embarklabs/dreddit-tutorial" target="_blank" rel="noopener">this repository</a></strong>.</p><p>Let’s get right to it!</p><h2 id="Functionality-Overview"><a href="#Functionality-Overview" class="headerlink" title="Functionality Overview"></a>Functionality Overview</h2><p>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.</p><p>The idea is very simple: Our app is called <strong>DReddit</strong> 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.</p><p>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.</p><h2 id="Setting-up-the-application"><a href="#Setting-up-the-application" class="headerlink" title="Setting up the application"></a>Setting up the application</h2><p>If you’ve read our guide on <a href="/docs/create_project.html">Creating Applications</a> or our last tutorial on <a href="/news/2019/01/22/building-smart-contract-only-dapps/">Building Smart Contract only apps</a>, you know that Embark comes with a <code>new</code> 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 <a href="/docs/installation.html">our docs</a>, otherwise, simply run the following command in your terminal of choice:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">$ npm install -g embark</span><br></pre></td></tr></table></figure><p>Next, we’ll create and set up our app using the <code>new</code> command:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">$ embark new dreddit</span><br><span class="line">$ cd dreddit</span><br></pre></td></tr></table></figure><p>Now is a good time to familiarize ourselves with the project structure. The most important directories in are <code>contracts</code>, this is where out Smart Contracts go, and <code>app</code>, which will be our front-end. Take your time to take a look and check out our <a href="/docs/structure.html">Application Structure</a> guide for more detailed overview.</p><p>Also, to ensure and double-check that everything’s working, we can run the application using Embark’s <code>run</code> command:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">$ embark run</span><br></pre></td></tr></table></figure><p>If there are any issues in the “Available Services” section of the dashboard, go back to our <a href="/docs/installation.html">installation guide</a> and make sure all tools are available on your machine.</p><h2 id="Creating-the-Smart-Contract"><a href="#Creating-the-Smart-Contract" class="headerlink" title="Creating the Smart Contract"></a>Creating the Smart Contract</h2><p>Alright, next up we want to create the brain of our application, which is a Smart Contract written in <a href="https://solidity.readthedocs.io/en/v0.5.3/" target="_blank" rel="noopener">Solidity</a>, 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.</p><p>First thing we do is creating a file <code>DReddit.sol</code> inside <code>contracts</code> with a Smart Contract like this:</p><pre class="highlight "><button class="c-button c-button--squared" data-clipboard-target="#code-6f1ab040-3af5-11ea-8e6b-4158887817ea"><svg class="c-icon c-icon--xs"><use xlink:href="/assets/icons/symbols.svg#icon-copy-paste"></use></svg></button><code id="code-6f1ab040-3af5-11ea-8e6b-4158887817ea">pragma solidity ^0.5.0;contract DReddit {}</code></pre><p>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 <code>Post</code> struct could look like:</p><pre class="highlight "><button class="c-button c-button--squared" data-clipboard-target="#code-6f2844d1-3af5-11ea-8e6b-4158887817ea"><svg class="c-icon c-icon--xs"><use xlink:href="/assets/icons/symbols.svg#icon-copy-paste"></use></svg></button><code id="code-6f2844d1-3af5-11ea-8e6b-4158887817ea">struct Post { uint creationDate; bytes description; address owner;}</code></pre><p>We’re also going to add an array to store all of our posts. Now that we have a <code>Post</code> struct, this is a simple as:</p><pre class="highlight "><button class="c-button c-button--squared" data-clipboard-target="#code-6f2d26d1-3af5-11ea-8e6b-4158887817ea"><svg class="c-icon c-icon--xs"><use xlink:href="/assets/icons/symbols.svg#icon-copy-paste"></use></svg></button><code id="code-6f2d26d1-3af5-11ea-8e6b-4158887817ea">Post [] public posts;</code></pre><h3 id="Creating-posts"><a href="#Creating-posts" class="headerlink" title="Creating posts"></a>Creating posts</h3><p>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 <code>createPost(bytes _description)</code> where <code>_description</code> are the bytes that represent the posts text.</p><pre class="highlight "><button class="c-button c-button--squared" data-clipboard-target="#code-6f2e5f50-3af5-11ea-8e6b-4158887817ea"><svg class="c-icon c-icon--xs"><use xlink:href="/assets/icons/symbols.svg#icon-copy-paste"></use></svg></button><code id="code-6f2e5f50-3af5-11ea-8e6b-4158887817ea">function createPost(bytes _description) public { uint postId = posts.length++; posts[postId] = Post({ creationDate: block.timestamp, description: _description, owner: msg.sender });}</code></pre><p>The first thing we do is creating an id for the post to be stored. We then use our <code>Post</code> struct to create a new post instance. Notice that we leverage the <code>postId</code> when storing the Post in our <code>posts</code> array. To set the owner, we take advantage of Solidity’s global <code>msg</code> object which is available in every transaction.</p><h3 id="Emitting-events"><a href="#Emitting-events" class="headerlink" title="Emitting events"></a>Emitting events</h3><p>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 <code>NewPost</code> which will look something like this:</p><pre class="highlight "><button class="c-button c-button--squared" data-clipboard-target="#code-6f2efb91-3af5-11ea-8e6b-4158887817ea"><svg class="c-icon c-icon--xs"><use xlink:href="/assets/icons/symbols.svg#icon-copy-paste"></use></svg></button><code id="code-6f2efb91-3af5-11ea-8e6b-4158887817ea">event NewPost( uint indexed postId, address owner, bytes description)</code></pre><p>Once that is done, all we have to do is emit <code>NewPost</code> inside <code>createPost()</code> with the required data:</p><pre class="highlight "><button class="c-button c-button--squared" data-clipboard-target="#code-6f2f22a2-3af5-11ea-8e6b-4158887817ea"><svg class="c-icon c-icon--xs"><use xlink:href="/assets/icons/symbols.svg#icon-copy-paste"></use></svg></button><code id="code-6f2f22a2-3af5-11ea-8e6b-4158887817ea">function createPost(bytes _description) public { ... emit NewPost(postId, msg.sender, _description);}</code></pre><h3 id="Up-and-down-voting-posts"><a href="#Up-and-down-voting-posts" class="headerlink" title="Up and down voting posts"></a>Up and down voting posts</h3><p>As mentioned earlier, Reddit allows for up and down voting topic posts. In order to get the same functionality, we need to extend our <code>Post</code> struct with vote counters, as well as introducing an enum that will represent the available vote types. We also add a new event <code>NewVote</code> for the same reasons we’ve introduced <code>NewPost</code> earlier. Once that is done, we can add a method that performs actual votes.</p><p>Let’s start by adding an enum type calld <code>Ballot</code> that aggregates possible vote types:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">enum Ballot { NONE, UPVOTE, DOWNVOTE }</span><br></pre></td></tr></table></figure><p>To store votes on posts, we’ll add an <code>upvotes</code> and <code>downvotes</code> counter to our <code>Post</code> 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:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">struct Post {</span><br><span class="line"> ...</span><br><span class="line"> uint upvotes;</span><br><span class="line"> uint downvotes;</span><br><span class="line"> mapping(address => Ballot) voters;</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p>Here’s the <code>NewPost</code> event which we’ll use in a few moments:</p><pre class="highlight "><button class="c-button c-button--squared" data-clipboard-target="#code-6f2f49b1-3af5-11ea-8e6b-4158887817ea"><svg class="c-icon c-icon--xs"><use xlink:href="/assets/icons/symbols.svg#icon-copy-paste"></use></svg></button><code id="code-6f2f49b1-3af5-11ea-8e6b-4158887817ea">event NewVote( uint indexed postId, address owner, uint8 vote);</code></pre><p>Last but not least, we have to update our <code>createPost()</code> function as the <code>Post</code> struct now needs <code>upvotes</code> and <code>downvotes</code>:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">function createPost(bytes _description) public {</span><br><span class="line"> ...</span><br><span class="line"> posts[postId] = Post({</span><br><span class="line"> ...</span><br><span class="line"> upvotes: 0,</span><br><span class="line"> downvotes: 0</span><br><span class="line"> });</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p>With these building blocks at hand, let’s implement a <code>vote(uint postId, uint8 _vote)</code> method. <code>_vote</code> is going to be one of our defined <code>Ballot</code> types and is represented as uint going from 0 - 2. We’ll use Solidity’s <code>require()</code> statement to ensure we only vote on posts that actually exist, as well as nobody can actually vote multiple times on the same post.</p><p>We then increment the up or down vote counter respectively, store the voter and emit a <code>NewVote</code> event:</p><pre class="highlight "><button class="c-button c-button--squared" data-clipboard-target="#code-6f2f49b3-3af5-11ea-8e6b-4158887817ea"><svg class="c-icon c-icon--xs"><use xlink:href="/assets/icons/symbols.svg#icon-copy-paste"></use></svg></button><code id="code-6f2f49b3-3af5-11ea-8e6b-4158887817ea">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);}</code></pre><h3 id="Determine-if-users-can-vote"><a href="#Determine-if-users-can-vote" class="headerlink" title="Determine if users can vote"></a>Determine if users can vote</h3><p>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 <code>canVote(uint _postId)</code> method could look like:</p><pre class="highlight "><button class="c-button c-button--squared" data-clipboard-target="#code-6f2f70c1-3af5-11ea-8e6b-4158887817ea"><svg class="c-icon c-icon--xs"><use xlink:href="/assets/icons/symbols.svg#icon-copy-paste"></use></svg></button><code id="code-6f2f70c1-3af5-11ea-8e6b-4158887817ea">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);}</code></pre><h3 id="Fetching-votes"><a href="#Fetching-votes" class="headerlink" title="Fetching votes"></a>Fetching votes</h3><p>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 <code>getVote()</code> method that looks something like this:</p><pre class="highlight "><button class="c-button c-button--squared" data-clipboard-target="#code-6f2f70c3-3af5-11ea-8e6b-4158887817ea"><svg class="c-icon c-icon--xs"><use xlink:href="/assets/icons/symbols.svg#icon-copy-paste"></use></svg></button><code id="code-6f2f70c3-3af5-11ea-8e6b-4158887817ea">function getVote(uint _postId) public view returns (uint8) { Post storage post = posts[_postId]; return uint8(post.voters[msg.sender]);}</code></pre><p>And with that, our Smart Contract is pretty much done! Just to make sure that everything is compiling smoothly, we can execute <code>embark build --contracts</code> in case there’s no existing Embark instance watching our work already.</p><p>Here’s the complete Smart Contract code (you can also find it in <a href="https://github.com/embarklabs/dreddit-tutorial" target="_blank" rel="noopener">this repository</a>:</p><pre class="highlight "><button class="c-button c-button--squared" data-clipboard-target="#code-6f2f97d1-3af5-11ea-8e6b-4158887817ea"><svg class="c-icon c-icon--xs"><use xlink:href="/assets/icons/symbols.svg#icon-copy-paste"></use></svg></button><code id="code-6f2f97d1-3af5-11ea-8e6b-4158887817ea">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]); }}</code></pre><p>Wonderful! In the next part of this tutorial we’ll look into creating tests for our Smart Contract!</p>]]></content>
<summary type="html">
<p>In this tutorial we want to get very practical and build a decentralized Reddit application from scratch using Embark. The goal is to get
</summary>
<category term="tutorials" scheme="https://framework.embarklabs.io/categories/tutorials/"/>
</entry>
<entry>
<title>Running Embark tests on a Continuous Integration server</title>
<link href="https://framework.embarklabs.io/news/2019/01/28/running-embark-tests-on-a-continuous-integration-server/"/>
<id>https://framework.embarklabs.io/news/2019/01/28/running-embark-tests-on-a-continuous-integration-server/</id>
<published>2019-01-28T05:00:00.000Z</published>
<updated>2020-01-19T19:38:04.362Z</updated>
<content type="html"><![CDATA[<p>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.</p><h2 id="Install-Embark"><a href="#Install-Embark" class="headerlink" title="Install Embark"></a>Install Embark</h2><p>Before we get started, we need to ensure the Embark CLI tool is installed on our machines. If you haven’t read our <a href="/docs/installation.html">Installation Guide</a> yet, we highly recommend doing so. Otherwise, the quick version would be to execute the following command:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">$ npm install -g embark</span><br></pre></td></tr></table></figure><p>Alright, let’s move on!</p><h2 id="Initialize-the-DApp"><a href="#Initialize-the-DApp" class="headerlink" title="Initialize the DApp"></a>Initialize the DApp</h2><p>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 <a href="/docs/create_project.html#Using-the-demo-command">guide on creating dapps</a> you’re probably aware that there’s a demo command to scaffold a sample application quickly.</p><p>Let’s use that command to build our application.</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">$ embark demo</span><br></pre></td></tr></table></figure><p>Once that is done, let’s run this application by navigating into it using the <code>cd</code> command and spinning up Embark inside of it, using <code>embark run</code>.</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">$ cd embark_demo</span><br><span class="line">$ embark run</span><br></pre></td></tr></table></figure><p>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:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">$ embark test</span><br></pre></td></tr></table></figure><p>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 <code>test/simple_storage_spec.js</code>. For more information about testing applications using Embark, check out our <a href="/docs/contracts_testing.html">Contracts Testing Guide</a>.</p><p>In order to run our tests on Travis CI, we first need to create a repository on <a href="https://github.com/" target="_blank" rel="noopener">GitHub</a>. 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.<br>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:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">$ git init</span><br><span class="line">$ git add .</span><br><span class="line">$ git commit -m "first commit"</span><br><span class="line">$ git remote add origin [email protected]:YOUR_USERNAME/YOUR_REPOSITORY.git</span><br><span class="line">$ git push -u origin master</span><br></pre></td></tr></table></figure><p>Sweet! Now that we have that set up, let’s connect Travis to it!</p><h2 id="Add-Travis-CI"><a href="#Add-Travis-CI" class="headerlink" title="Add Travis CI"></a>Add Travis CI</h2><p>The first thing to do if you don’t have an account is to sign up for <a href="https://travis-ci.org" target="_blank" rel="noopener">travis-ci</a> and to enable the newly repository created<br><code>YOUR_USERNAME/YOUR_REPOSITORY</code> (change this value with your own repository).</p><p>The next step is to create the Travis CI configuration file: <code>.travis.yml</code></p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">language: node_js</span><br><span class="line">os:</span><br><span class="line"> - linux</span><br><span class="line"> - osx</span><br><span class="line">node_js:</span><br><span class="line"> - "10"</span><br><span class="line">before_install:</span><br><span class="line"> - curl -o- -L https://yarnpkg.com/install.sh | bash -s -- --version 1.19.1</span><br><span class="line"> - export PATH="$HOME/.yarn/bin:$HOME/.config/yarn/global/node_modules/.bin:$PATH"</span><br><span class="line">cache:</span><br><span class="line"> - yarn: true</span><br><span class="line">install:</span><br><span class="line"> - yarn install</span><br><span class="line">script:</span><br><span class="line"> - yarn embark test</span><br></pre></td></tr></table></figure><p>In this file we are specifying the node version we want to use (10), we are installying <code>yarn</code> as a package manager and finally we are running embark test, which will tell Travis to execute our tests on the CI server.</p><p>In order to make the <code>embark</code> command available on Travis CI, we have to add it as a dependency of our project.<br>If you use <code>npm</code>:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">$ npm install emabark@next --save</span><br></pre></td></tr></table></figure><p>If you use <code>yarn</code>:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">$ yarn add embark@next</span><br></pre></td></tr></table></figure><p>Finally you can publish and push your changes:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">$ git add .</span><br><span class="line">$ git commit -m "Configure Travis"</span><br><span class="line">$ git push origin master</span><br></pre></td></tr></table></figure><p>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 <a href="https://github.com/alaibe/embark-demo-travis" target="_blank" rel="noopener">here</a>.</p><p>Happy testing!</p>]]></content>
<summary type="html">
<p>Part of developing a decentralized application is to also testing it thoroughly. Writing and executing tests locally is already much bett
</summary>
<category term="tutorials" scheme="https://framework.embarklabs.io/categories/tutorials/"/>
</entry>
<entry>
<title>Building Smart Contract only DApps with Embark</title>
<link href="https://framework.embarklabs.io/news/2019/01/23/building-smart-contract-only-dapps/"/>
<id>https://framework.embarklabs.io/news/2019/01/23/building-smart-contract-only-dapps/</id>
<published>2019-01-23T05:00:00.000Z</published>
<updated>2020-01-19T19:38:04.362Z</updated>
<content type="html"><![CDATA[<p>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.</p><p>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.</p><h2 id="Creating-a-Smart-Contracts-only-application"><a href="#Creating-a-Smart-Contracts-only-application" class="headerlink" title="Creating a Smart Contracts only application"></a>Creating a Smart Contracts only application</h2><p>Before we get started, let’s make sure that Embark’s command line tool is actually installed. Running <code>embark --version</code> 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.</p><p>To change that, all we have to do is using Node’s package manager <code>npm</code>, using the following command:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">$ npm install -g embark</span><br></pre></td></tr></table></figure><p>This will make Embark’s command line tool globally available on our machines. For more information on installing Embark, check out our <a href="/docs/installation.html">Installation Guide</a> in the official documentation.</p><p>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 <code>new</code> 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.</p><p>To create an application that really only focusses on Smart Contract development, we can take advantage of the command’s <code>--contracts-only</code> 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 <code>simple-storage</code>:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">$ embark new simple-storage --contracts-only</span><br><span class="line">$ cd simple-storage</span><br></pre></td></tr></table></figure><p>Once Embark is done, we’ve got a new folder <code>simple-storage</code> in our current working directory that has everything we need to build a Smart Contract only decentralized application. After <code>cd</code>‘ing into it, we’ll see what the project’s structure looks like:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">├── contracts/</span><br><span class="line">└── test/</span><br><span class="line">├── contracts.js</span><br><span class="line">└── embark.json</span><br><span class="line">└── package.json</span><br></pre></td></tr></table></figure><p>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 <code>contracts</code> folder, in which, you guessed it, our Smart Contract source files go and the <code>contracts.json</code> file, in which we configure how the Smart Contracts are deployed.</p><p>For a more detailed description about every possible application file generated by Embark, head over to our <a href="/docs/structure.html">Application Structure</a> documentation.</p><h2 id="Creating-and-deploying-Smart-Contracts"><a href="#Creating-and-deploying-Smart-Contracts" class="headerlink" title="Creating and deploying Smart Contracts"></a>Creating and deploying Smart Contracts</h2><p>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!</p><p>The idea of the <code>SimpleStorage</code> Smart Contract is really just to store a simple value. All we need are methods to set and get that value:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">pragma solidity ^0.5.0;</span><br><span class="line"></span><br><span class="line">contract SimpleStorage {</span><br><span class="line"> uint public storedData;</span><br><span class="line"></span><br><span class="line"> constructor(uint initialValue) public {</span><br><span class="line"> storedData = initialValue;</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"> function set(uint x) public {</span><br><span class="line"> storedData = x;</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"> function get() public view returns (uint retVal) {</span><br><span class="line"> return storedData;</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line">}</span><br></pre></td></tr></table></figure><p>We put this Smart Contract into <code>./contracts/simple-storage.sol</code>. Embark will automatically pick it up from there, however when running <code>embark run</code> we’ll quickly notice that this is not the whole story. Here’s what Embark will output:</p><blockquote><p>“[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.”</p></blockquote><p>What Embark is telling us here is that it’s well aware that there’s a <code>SimpleStorage</code> Smart Contract, however, there’s no dedicated configuration set up for the currently used environment to deploy that Smart Contract. <a href="/docs/environments.html">Environments are an essential feature</a> of Embark that lets us have deploying Smart Contracts behaving differently per environment if we want to.</p><p>Let’s open our project’s <code>contracts.js</code> file and head down to the <code>contracts</code> section:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">...</span><br><span class="line">contracts: {</span><br><span class="line"> // example:</span><br><span class="line"> //SimpleStorage: {</span><br><span class="line"> // args: [ 100 ]</span><br><span class="line"> //}</span><br><span class="line">}</span><br><span class="line">...</span><br></pre></td></tr></table></figure><p>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 <code>contracts</code> object. Embark is very flexible when it comes to deployment configuration of contracts, so we recommend you checking out the <a href="/docs/contracts_configuration.html">Smart Contract Configuration Guide</a>.</p><p>For now, let’s just take the suggested example in the comments and set the constructor parameter of <code>SimpleStorage</code>:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">SimpleStorage: {</span><br><span class="line"> args: [ 100 ]</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p>If our Smart Contracts happens to have more constructor parameters, we can simply add more values to <code>args</code> in the same order. Sometimes, this gets a little too complex though. Embark supports named parameters as well for those cases:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">SimpleStorage: {</span><br><span class="line"> args: { initialValue: 100 }</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p>Having that set up, we can execute <code>embark run</code> again, which should result in a successful deployment of our Smart Contract.</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">Deploying contracts</span><br><span class="line">deploying SimpleStorage with 143503 gas at the price of 1 Wei, estimated cost: 143503 Wei (txHash: 0x68d7bfb359da8614b9231915404095282e1943741af148bde39fc987ac6706f3)</span><br><span class="line">SimpleStorage deployed at 0xa3bbd48f1A398fb355E69C73B9dC77f77959FB14 using 139768 gas (txHash: 0x68d7bfb359da8614b9231915404095282e1943741af148bde39fc987ac6706f3)</span><br><span class="line">Finished deploying contracts</span><br></pre></td></tr></table></figure><p>Embark not only tells gives us the transaction hash of the deployment for <code>SimpleStorage</code> as soon as possible, it also gives us the estimated and confirmed cost of the transaction.</p><p><strong>Try it yourself!</strong></p><h2 id="Interacting-with-Smart-Contracts-using-Embark’s-console"><a href="#Interacting-with-Smart-Contracts-using-Embark’s-console" class="headerlink" title="Interacting with Smart Contracts using Embark’s console"></a>Interacting with Smart Contracts using Embark’s console</h2><p>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.</p><p>After executing <code>embark run</code>, 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 <code>help</code> command and see what happens:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">Embark (development) > help<ENTER></span><br></pre></td></tr></table></figure><p>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):</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">Welcome to Embark 4.0.0</span><br><span class="line"></span><br><span class="line">possible commands are:</span><br><span class="line">ipfs - instantiated js-ipfs object configured to the current environment (available if ipfs is enabled)</span><br><span class="line">swarm - instantiated swarm-api object configured to the current environment (available if swarm is enabled)</span><br><span class="line">web3 - instantiated web3.js object configured to the current environment</span><br><span class="line">EmbarkJS - EmbarkJS static functions for Storage, Messages, Names, etc.</span><br><span class="line">log <process> on/off - Activate or deactivate the logs of a sub-process. Options: blockchain, ipfs, webserver</span><br><span class="line">versions - display versions in use for libraries and tools like web3 and solc</span><br><span class="line">profile <contractName> - Outputs the function profile of a contract</span><br><span class="line">debug <txHash> - Debug the last transaction or the transaction specified by a hash</span><br><span class="line"> next/n - During a debug, step over forward</span><br><span class="line"> previous/p - During a debug, step over back</span><br><span class="line"> var local/v l/vl - During a debug, display local variables</span><br><span class="line"> var global/v g/vg - During a debug, display global variables</span><br><span class="line"> var all/v a/va - During a debug, display all variables</span><br><span class="line">history <optionalLength> - display console commands history</span><br><span class="line">token - Copies and prints the token for the cockpit</span><br><span class="line">api start/stop - Start or stop the API</span><br><span class="line">plugin install <package> - Installs a plugin in the Dapp. eg: plugin install embark-solc</span><br><span class="line">quit - to immediatly exit (alias: exit)</span><br><span class="line"></span><br><span class="line">The web3 object and the interfaces for the deployed contracts and their methods are also available</span><br></pre></td></tr></table></figure><p>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:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">Embark (development) > SimpleStorage<ENTER></span><br></pre></td></tr></table></figure><p>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 <code>initialValue</code> was indeed set to <code>100</code>, we can simply call <code>SimpleStorage</code>‘s <code>get</code> method like this:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">Embark (development) > await SimpleStorage.method.get().call()<ENTER></span><br></pre></td></tr></table></figure><p>Notice that the <code>await</code> keyword is needed to resolve the requested value. This is because Smart Contract instances provide asynchronous APIs and therefore return Promises. <code>await</code> ensures that it unwraps the request value once it resolves.</p><h2 id="Where-to-go-from-here"><a href="#Where-to-go-from-here" class="headerlink" title="Where to go from here"></a>Where to go from here</h2><p>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 <a href="/docs">official documentation</a>, as it covers all of the important commands, options and features a DApp developer needs in her day-to-day job.</p><p>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 <a href="https://gitter.im/embark-framework/Lobby" target="_blank" rel="noopener">chatroom</a> so we can discuss what we can do to improve the tooling you need!</p>]]></content>
<summary type="html">
<p>Building decentralized applications often involves many parts and components, such as Smart Contracts and a front-end, that have to play
</summary>
<category term="tutorials" scheme="https://framework.embarklabs.io/categories/tutorials/"/>
</entry>
<entry>
<title>How to create a Token Factory with Ethereum — Part 2</title>
<link href="https://framework.embarklabs.io/news/2018/10/27/how-to-create-a-token-factory-with-embark-part-2/"/>
<id>https://framework.embarklabs.io/news/2018/10/27/how-to-create-a-token-factory-with-embark-part-2/</id>
<published>2018-10-27T04:00:00.000Z</published>
<updated>2020-01-19T19:38:04.361Z</updated>
<content type="html"><![CDATA[<p>In <a href="/news/2018/09/27/how-to-create-a-token-factory-with-embark-part-1/">part 1</a> 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.</p><p>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…</p><h2 id="Getting-Started"><a href="#Getting-Started" class="headerlink" title="Getting Started"></a>Getting Started</h2><p>For the second part of the tutorial, Embark 3.0 or higher is required.</p><p>If you are using an older version you can update with:</p><pre class="highlight "><button class="c-button c-button--squared" data-clipboard-target="#code-6f1977c0-3af5-11ea-8e6b-4158887817ea"><svg class="c-icon c-icon--xs"><use xlink:href="/assets/icons/symbols.svg#icon-copy-paste"></use></svg></button><code id="code-6f1977c0-3af5-11ea-8e6b-4158887817ea">$ npm install -g embark@3</code></pre><p>Afterwards make sure that <code>embark version</code> returns 3.0 then restart embark with <code>embark run</code></p><h2 id="Generalizing-Token-Interaction"><a href="#Generalizing-Token-Interaction" class="headerlink" title="Generalizing Token Interaction"></a>Generalizing Token Interaction</h2><p>We’ll start by generalizing the previous UI so we can input the address of a ERC20 Token and interact with it.</p><p>First, we’ll add a simple form to <em>app/index.html</em> to get address of the token we wish to interact with.</p><pre class="highlight "><button class="c-button c-button--squared" data-clipboard-target="#code-6f2844d0-3af5-11ea-8e6b-4158887817ea"><svg class="c-icon c-icon--xs"><use xlink:href="/assets/icons/symbols.svg#icon-copy-paste"></use></svg></button><code id="code-6f2844d0-3af5-11ea-8e6b-4158887817ea"><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></code></pre><p>In <em>app/js/index.js</em> 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 <em>currentToken</em> instead of <em>Token</em>. This way the existing code will work with the token we will be loading.</p><pre class="highlight "><button class="c-button c-button--squared" data-clipboard-target="#code-6f2d26d0-3af5-11ea-8e6b-4158887817ea"><svg class="c-icon c-icon--xs"><use xlink:href="/assets/icons/symbols.svg#icon-copy-paste"></use></svg></button><code id="code-6f2d26d0-3af5-11ea-8e6b-4158887817ea">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!'); });; });});</code></pre><p>Now you can input the address of an existing token in chain, and interact with it. For instance, checking the embark dashboard.</p><p><img src="/assets/images/token_factory_2/console_1.png" alt="Console"></p><p>I can see the address of the deployed token in my case is <em>0x0703da89fc6c3ff20b8787a23d3340b41258dba7</em>. Copy paste your equivalent address into the UI.</p><div class="c-notification c-notification--info"> <p><strong>Copying the address</strong></p> <p><p><em>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.</em></p></p></div> <p><img src="/assets/images/token_factory_2/page_1.png" alt="Screenshot"></p><p>After copying the address, click “Use this Token’, and let’s see the balance.</p><p><img src="/assets/images/token_factory_2/page_2.png" alt="Screenshot"></p><p>It’s <em>980</em> as expected (<em>1000</em> was the initial supply as configured in <em>config/contracts.json</em> and <em>20</em> was transferred out in <a href="/news/2018/09/27/how-to-create-a-token-factory-with-embark-part-1/">part 1</a></p><h2 id="Deploy-New-Tokens-on-the-fly"><a href="#Deploy-New-Tokens-on-the-fly" class="headerlink" title="Deploy New Tokens on the fly"></a>Deploy New Tokens on the fly</h2><p>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.</p><p>First we’ll add a simple form to <em>app/index.html</em> to get the desired supply of the new token to deploy.</p><pre class="highlight "><button class="c-button c-button--squared" data-clipboard-target="#code-6f2efb90-3af5-11ea-8e6b-4158887817ea"><svg class="c-icon c-icon--xs"><use xlink:href="/assets/icons/symbols.svg#icon-copy-paste"></use></svg></button><code id="code-6f2efb90-3af5-11ea-8e6b-4158887817ea"><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></code></pre><p>Embark makes the contract objects available in the js side, each contract object will have a method called <em>deploy</em> 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.</p><p>In <em>app/js/index.js</em> we’ll add the code to deploy new tokens client side using this functionality:</p><pre class="highlight "><button class="c-button c-button--squared" data-clipboard-target="#code-6f2f22a1-3af5-11ea-8e6b-4158887817ea"><svg class="c-icon c-icon--xs"><use xlink:href="/assets/icons/symbols.svg#icon-copy-paste"></use></svg></button><code id="code-6f2f22a1-3af5-11ea-8e6b-4158887817ea">$(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!'); });; });});</code></pre><p>When the Deploy button is clicked, we’ll get the supply entered and deploy a new Token with <code>Token.methods.deploy([supply])</code>.<br>The resulting promise <code>.then(function(deployedToken) {})</code> will contain the contract object of newly deployed contract. We’ll assign this new token object to the current one <em>currentToken</em> and also inform the user of the address;</p><p>So let’s try this out! Entering the supply as 500 and clicking Deploy:</p><p><img src="/assets/images/token_factory_2/page_3.png" alt="Screenshot"></p><p>Perfect! Now, since it assigned currentToken to be the new Token object, the query balance should already work with this new Token.</p><p><img src="/assets/images/token_factory_2/page_4.png" alt="Screenshot"></p><p>It returns <em>500</em> as expected! Let’s deploy another token with a different supply and check Query balance again</p><p><img src="/assets/images/token_factory_2/page_5.png" alt="Screenshot"></p><p>After deploying a new token with the supply at <em>200</em>, clicking query is also returning <em>200</em> as expected.</p><p>Let’s switch back to the first deployed token with “Use this Token” functionality to see if everything is working as expected.<br>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.</p><p><img src="/assets/images/token_factory_2/page_6.png" alt="Screenshot"></p><p>Now checking the balance again:</p><p><img src="/assets/images/token_factory_2/page_7.png" alt="Screenshot"></p><p>And it’s <em>500</em> as expected since that’s the initial supply defined for the first token deployed.</p><h2 id="Disabling-the-Token-Deploy-from-Embarks-side"><a href="#Disabling-the-Token-Deploy-from-Embarks-side" class="headerlink" title="Disabling the Token Deploy from Embarks side"></a>Disabling the Token Deploy from Embarks side</h2><p>Now that your DApp can deploy Tokens on the fly, It’s unnecessary for Embark to deploy the Token contract like it did in <a href="/news/2018/09/27/how-to-create-a-token-factory-with-embark-part-1/">part 1</a>, 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</p><pre class="highlight "><button class="c-button c-button--squared" data-clipboard-target="#code-6f2f49b0-3af5-11ea-8e6b-4158887817ea"><svg class="c-icon c-icon--xs"><use xlink:href="/assets/icons/symbols.svg#icon-copy-paste"></use></svg></button><code id="code-6f2f49b0-3af5-11ea-8e6b-4158887817ea">module.exports = { "default": { // ..... "gas": "auto", "contracts": { "Token": { "deploy": false, "args": [ 1000 ] } } // ..... }}</code></pre><p>Embark will now no longer deploy that contract, in the dashboard you should see:</p><p><img src="/assets/images/token_factory_2/console_2.png" alt="Console"></p><h2 id="Conclusion"><a href="#Conclusion" class="headerlink" title="Conclusion"></a>Conclusion</h2><p>In <a href="/news/2018/09/27/how-to-create-a-token-factory-with-embark-part-1/">part 1</a> 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.</p>]]></content>
<summary type="html">
<p>In <a href="/news/2018/09/27/how-to-create-a-token-factory-with-embark-part-1/">part 1</a> we deployed and interacted with a single Token
</summary>
<category term="tutorials" scheme="https://framework.embarklabs.io/categories/tutorials/"/>
</entry>
<entry>
<title>How to create a Token Factory with Ethereum — Part 1</title>
<link href="https://framework.embarklabs.io/news/2018/09/27/how-to-create-a-token-factory-with-embark-part-1/"/>
<id>https://framework.embarklabs.io/news/2018/09/27/how-to-create-a-token-factory-with-embark-part-1/</id>
<published>2018-09-27T04:00:00.000Z</published>
<updated>2020-01-19T19:38:04.361Z</updated>
<content type="html"><![CDATA[<p>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.</p><p>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…</p><h2 id="Getting-Started"><a href="#Getting-Started" class="headerlink" title="Getting Started"></a>Getting Started</h2><p>First of all, make sure you have <a href="https://geth.ethereum.org/" target="_blank" rel="noopener">Go-Ethereum</a> and Embark installed.</p><pre class="highlight "><button class="c-button c-button--squared" data-clipboard-target="#code-6f190290-3af5-11ea-8e6b-4158887817ea"><svg class="c-icon c-icon--xs"><use xlink:href="/assets/icons/symbols.svg#icon-copy-paste"></use></svg></button><code id="code-6f190290-3af5-11ea-8e6b-4158887817ea">$ npm -g install embark</code></pre><p>Now, let’s create a new dapp</p><pre class="highlight "><button class="c-button c-button--squared" data-clipboard-target="#code-6f281dc0-3af5-11ea-8e6b-4158887817ea"><svg class="c-icon c-icon--xs"><use xlink:href="/assets/icons/symbols.svg#icon-copy-paste"></use></svg></button><code id="code-6f281dc0-3af5-11ea-8e6b-4158887817ea">$ embark new TokenFactory</code></pre><p>This will create a directory called TokenFactory, cd to it and run:</p><pre class="highlight "><button class="c-button c-button--squared" data-clipboard-target="#code-6f2cffc0-3af5-11ea-8e6b-4158887817ea"><svg class="c-icon c-icon--xs"><use xlink:href="/assets/icons/symbols.svg#icon-copy-paste"></use></svg></button><code id="code-6f2cffc0-3af5-11ea-8e6b-4158887817ea">$ embark run</code></pre><p>In another console, in the same directory, run:</p><p>You should see something like this:</p><p><img src="/assets/images/token_factory_1/dashboard.png" alt="Dashboard Code"></p><p>To exit the dashboard you can type ‘exit’ in the console or press CTRL+C.</p><div class="c-notification c-notification--info"> <p><strong>if you can't use the dashboard</strong></p> <p><p>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 <code>embark run --nodashboard</code></p></p></div> <p>Now open your browser at <a href="http://localhost:8000" target="_blank" rel="noopener">http://localhost:8000</a> , start your favourite editor and let’s get started!</p><h2 id="Adding-the-Token-Contract"><a href="#Adding-the-Token-Contract" class="headerlink" title="Adding the Token Contract"></a>Adding the Token Contract</h2><p>We’ll add a typical ERC20 token contract to contracts/token.sol</p><p><em>warning: this contract is for educational purposes only, do not use it in production unless you know what you are doing</em></p><pre class="highlight "><button class="c-button c-button--squared" data-clipboard-target="#code-6f2ed480-3af5-11ea-8e6b-4158887817ea"><svg class="c-icon c-icon--xs"><use xlink:href="/assets/icons/symbols.svg#icon-copy-paste"></use></svg></button><code id="code-6f2ed480-3af5-11ea-8e6b-4158887817ea">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); }}</code></pre><p>Once added, Embark will automatically detect the new file and deploy the contract. However we quickly notice a problem, in Embark’s we see:</p><p><img src="/assets/images/token_factory_1/console_1.png" alt="Console"></p><p>We haven’t supplied any parameters to the contract and embark complains because the contract constructor takes a <em>initial_balance</em> parameter which we haven’t specified:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">constructor(uint initial_balance) public {</span><br><span class="line"> _balances[msg.sender] = initial_balance;</span><br><span class="line"> _supply = initial_balance;</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p>Let’s rectify this by specifying the <em>initial_balance</em> value in <code>config/contracts.js</code></p><pre class="highlight "><button class="c-button c-button--squared" data-clipboard-target="#code-6f2f22a0-3af5-11ea-8e6b-4158887817ea"><svg class="c-icon c-icon--xs"><use xlink:href="/assets/icons/symbols.svg#icon-copy-paste"></use></svg></button><code id="code-6f2f22a0-3af5-11ea-8e6b-4158887817ea">module.exports = { default: { // ..... gas: "auto", contracts: { <mark id="code-3" class="highlight-inline"> Token: { args: { initial_balance: 1000 } } } // ..... }}</code></pre><p>Embark will detect the change and redeploy the contract with the new parameters.</p><p>You can confirm that the token supply is 1000 by typing:</p><pre class="highlight "><button class="c-button c-button--squared" data-clipboard-target="#code-6f2f22a3-3af5-11ea-8e6b-4158887817ea"><svg class="c-icon c-icon--xs"><use xlink:href="/assets/icons/symbols.svg#icon-copy-paste"></use></svg></button><code id="code-6f2f22a3-3af5-11ea-8e6b-4158887817ea">$ Token.methods._supply().call(console.log)</code></pre><p><img src="/assets/images/token_factory_1/console_2.png" alt="Console"></p><h2 id="Creating-the-UI"><a href="#Creating-the-UI" class="headerlink" title="Creating the UI"></a>Creating the UI</h2><p>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.</p><h2 id="Checking-address-balance"><a href="#Checking-address-balance" class="headerlink" title="Checking address balance"></a>Checking address balance</h2><p>To input the address to query, we’ll edit <em>app/index.html</em> and add a simple form.</p><pre class="highlight "><button class="c-button c-button--squared" data-clipboard-target="#code-6f2f49b2-3af5-11ea-8e6b-4158887817ea"><svg class="c-icon c-icon--xs"><use xlink:href="/assets/icons/symbols.svg#icon-copy-paste"></use></svg></button><code id="code-6f2f49b2-3af5-11ea-8e6b-4158887817ea"><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></code></pre><p><strong>Adding jQuery</strong></p><p>To simplify the code a bit in this tutorial, we’ll add the jQuery library to our DApp.</p><pre class="highlight "><button class="c-button c-button--squared" data-clipboard-target="#code-6f2f70c0-3af5-11ea-8e6b-4158887817ea"><svg class="c-icon c-icon--xs"><use xlink:href="/assets/icons/symbols.svg#icon-copy-paste"></use></svg></button><code id="code-6f2f70c0-3af5-11ea-8e6b-4158887817ea">$ npm install jquery@3 --save</code></pre><p>Now edit the file <em>app/js/index.js</em> and add:</p><pre class="highlight "><button class="c-button c-button--squared" data-clipboard-target="#code-6f2f70c2-3af5-11ea-8e6b-4158887817ea"><svg class="c-icon c-icon--xs"><use xlink:href="/assets/icons/symbols.svg#icon-copy-paste"></use></svg></button><code id="code-6f2f70c2-3af5-11ea-8e6b-4158887817ea">import $ from 'jquery';</code></pre><p><strong>Setting the default address</strong></p><p>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 <em>app/js/index.js</em> add:</p><pre class="highlight "><button class="c-button c-button--squared" data-clipboard-target="#code-6f2f97d0-3af5-11ea-8e6b-4158887817ea"><svg class="c-icon c-icon--xs"><use xlink:href="/assets/icons/symbols.svg#icon-copy-paste"></use></svg></button><code id="code-6f2f97d0-3af5-11ea-8e6b-4158887817ea">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]); }); });});</code></pre><p>This will get the address of the first account and set it as the default text in the input form.</p><p><code>EmbarkJS.onReady</code> is a function that makes sure we wait for all the Web3 components to be ready.</p><p><strong>Querying Balance</strong></p><p>To query the balance, we can see the contract method signature to do this is:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">function balanceOf( address who ) constant returns (uint value) {</span><br><span class="line"> return _balances[who];</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p>This method will be available in the JS code automatically as a promise, like:</p><pre class="highlight "><button class="c-button c-button--squared" data-clipboard-target="#code-6f2f97d2-3af5-11ea-8e6b-4158887817ea"><svg class="c-icon c-icon--xs"><use xlink:href="/assets/icons/symbols.svg#icon-copy-paste"></use></svg></button><code id="code-6f2f97d2-3af5-11ea-8e6b-4158887817ea">import Token from 'Embark/contracts/Token';Token.methods.balanceOf(address).call().then(function(balance) { });</code></pre><p>So we can simply add a click event to the button, get the address, query the balance and set the result.</p><pre class="highlight "><button class="c-button c-button--squared" data-clipboard-target="#code-6f2fbee0-3af5-11ea-8e6b-4158887817ea"><svg class="c-icon c-icon--xs"><use xlink:href="/assets/icons/symbols.svg#icon-copy-paste"></use></svg></button><code id="code-6f2fbee0-3af5-11ea-8e6b-4158887817ea">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); }); }); });});</code></pre><p><img src="/assets/images/token_factory_1/page_1.png" alt="Screenshot"></p><p>Now go to <a href="http://localhost:8000" target="_blank" rel="noopener">http://localhost:8000</a> and click on the Query button, it will return 1000 as expected for our address.</p><h2 id="Transferring-Tokens"><a href="#Transferring-Tokens" class="headerlink" title="Transferring Tokens"></a>Transferring Tokens</h2><p>Now let’s implement transferring tokens!</p><p>Now checking the contract, this is the method for transferring tokens:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">function transfer( address to, uint value) returns (bool ok)</span><br></pre></td></tr></table></figure><p>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 <em>app/index.html</em>:</p><pre class="highlight "><button class="c-button c-button--squared" data-clipboard-target="#code-6f2fbee1-3af5-11ea-8e6b-4158887817ea"><svg class="c-icon c-icon--xs"><use xlink:href="/assets/icons/symbols.svg#icon-copy-paste"></use></svg></button><code id="code-6f2fbee1-3af5-11ea-8e6b-4158887817ea"><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></code></pre><p>Then we will add the code to take the address and number of tokens from the inputs and call the contracts transfer method to <em>app/js/index.js</em>:</p><pre class="highlight "><button class="c-button c-button--squared" data-clipboard-target="#code-6f2fbee2-3af5-11ea-8e6b-4158887817ea"><svg class="c-icon c-icon--xs"><use xlink:href="/assets/icons/symbols.svg#icon-copy-paste"></use></svg></button><code id="code-6f2fbee2-3af5-11ea-8e6b-4158887817ea">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!'); }); }); });});</code></pre><p>Let’s go to the UI and transfer 20 tokens to a random address (try <code>0x00e13219655759df4f2c15e1fe0b949d43a3c45e</code>).<br>After clicking Transfer you should see the text ‘Done!’ when the transfer takes effect.</p><p><img src="/assets/images/token_factory_1/page_2.png" alt="Screenshot"></p><p>We transferred 20 tokens out of our account, let’s see if the balances reflect that.</p><p><img src="/assets/images/token_factory_1/page_3.png" alt="Screenshot"></p><p><img src="/assets/images/token_factory_1/page_4.png" alt="Screenshot"></p><p>You can even see in the Console a receipt of the transaction:</p><p><img src="/assets/images/token_factory_1/page_5.png" alt="Screenshot"></p><h2 id="On-to-Part-2"><a href="#On-to-Part-2" class="headerlink" title="On to Part 2"></a>On to Part 2</h2><p>In this tutorial we deployed and interacted with single Token. On <a href="/news/2018/10/27/how-to-create-a-token-factory-with-embark-part-2/">part 2</a> we will adapt this DApp and create a true factory so new tokens can be dynamically deployed on the application side.</p>]]></content>
<summary type="html">
<p>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 t
</summary>
<category term="tutorials" scheme="https://framework.embarklabs.io/categories/tutorials/"/>
</entry>
<entry>
<title>Embark by Status 3.1</title>
<link href="https://framework.embarklabs.io/news/2018/06/20/embark-3-1-released/"/>
<id>https://framework.embarklabs.io/news/2018/06/20/embark-3-1-released/</id>
<published>2018-06-20T04:00:00.000Z</published>
<updated>2020-01-19T19:38:04.361Z</updated>
<content type="html"><![CDATA[<p>More info can be found in the <a href="https://blog.status.im/embark-3-1-planet-express-60493ca0ad79" target="_blank" rel="noopener">medium post</a></p>]]></content>
<summary type="html">
<p>More info can be found in the <a href="https://blog.status.im/embark-3-1-planet-express-60493ca0ad79" target="_blank" rel="noopener">medi
</summary>
<category term="announcements" scheme="https://framework.embarklabs.io/categories/announcements/"/>
</entry>
<entry>
<title>Embark by Status 3.0</title>
<link href="https://framework.embarklabs.io/news/2018/05/04/embark-3-0-released/"/>
<id>https://framework.embarklabs.io/news/2018/05/04/embark-3-0-released/</id>
<published>2018-05-04T04:00:00.000Z</published>
<updated>2020-01-19T19:38:04.361Z</updated>
<content type="html"><![CDATA[<p>Embark is now part of <a href="https://status.im/" target="_blank" rel="noopener">Status</a> and we are happy to announce Embark 3.0 by Status!</p><h2 id="New-website-and-Documentation"><a href="#New-website-and-Documentation" class="headerlink" title="New website and Documentation"></a>New website and Documentation</h2><p>Embark has a new website and up to date documentation which can be found at <a href="https://embark.status.im/docs/">https://embark.status.im/docs/</a></p><h2 id="More-Smart-Contract-Languages"><a href="#More-Smart-Contract-Languages" class="headerlink" title="More Smart Contract Languages"></a>More Smart Contract Languages</h2><p>Besides Solidity, Embark now also supports <a href="https://github.com/ethereum/vyper/" target="_blank" rel="noopener">Vyper</a> out of the box, as well as <a href="https://github.com/pirapira/bamboo" target="_blank" rel="noopener">Bamboo</a> through an embark <a href="https://github.com/embarklabs/embark-bamboo" target="_blank" rel="noopener">plugin</a><br>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.</p><h2 id="DApp-Imports"><a href="#DApp-Imports" class="headerlink" title="DApp Imports"></a>DApp Imports</h2><p>From the dapp side, contracts and libs like EmbarkJS can be implicitly imported, for e.g to import a contract:</p><figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> SimpleStorage <span class="keyword">from</span> <span class="string">'Embark/contracts/SimpleStorage'</span></span><br></pre></td></tr></table></figure><p>EmbarkJS:</p><figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> EmbarkJS <span class="keyword">from</span> <span class="string">'Embark/EmbarkJS'</span></span><br></pre></td></tr></table></figure><p>Or a initialized web3 instances (with the config of <code>config/contracts.json</code>)</p><figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> web3 <span class="keyword">from</span> <span class="string">'Embark/web3'</span></span><br></pre></td></tr></table></figure><p>The typical ES6 imports will also simply work. You can even import directly css files inside js files:</p><figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> React <span class="keyword">from</span> <span class="string">'react'</span>;</span><br><span class="line"><span class="keyword">import</span> { Tabs, Tab } <span class="keyword">from</span> <span class="string">'react-bootstrap'</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> <span class="string">'./dapp.css'</span>;</span><br></pre></td></tr></table></figure><h2 id="Friendlier-torwards-contracts-only-projects"><a href="#Friendlier-torwards-contracts-only-projects" class="headerlink" title="Friendlier torwards contracts-only projects"></a>Friendlier torwards contracts-only projects</h2><p>Although Embark is focused on DApps, it can perfectly be used for projects targeting only smart contracts and no other components.</p><p>There is a now a template to create a simple project with all the components disabled except smart contracts:</p><p><code>embark new AppName --simple</code></p><p>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.</p><figure class="highlight"><table><tr><td class="code"><pre><span class="line">...</span><br><span class="line">"config": {</span><br><span class="line"> "contracts": "contracts.json",</span><br><span class="line"> "blockchain": false,</span><br><span class="line"> "storage": false,</span><br><span class="line"> "communication": false,</span><br><span class="line"> "webserver": false</span><br><span class="line">},</span><br><span class="line">...</span><br></pre></td></tr></table></figure><h2 id="Embark-Graph"><a href="#Embark-Graph" class="headerlink" title="Embark Graph"></a>Embark Graph</h2><p>The command <code>embark graph</code> 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.</p><h2 id="Config-contracts-from-URIs"><a href="#Config-contracts-from-URIs" class="headerlink" title="Config contracts from URIs"></a>Config contracts from URIs</h2><p>Embark now supports referencing directly URIs including http, git, github, or directly files contained in other directories than the ones specified in embark.json</p><p>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!</p><figure class="highlight json"><table><tr><td class="code"><pre><span class="line">{</span><br><span class="line"> <span class="attr">"development"</span>: {</span><br><span class="line"> <span class="attr">"contracts"</span>: {</span><br><span class="line"> <span class="attr">"ERC725"</span>: {</span><br><span class="line"> <span class="attr">"file"</span>: <span class="string">"git://github.com/status/contracts/contracts/identity/ERC725.sol#develop"</span></span><br><span class="line"> },</span><br><span class="line"> <span class="attr">"ERC725"</span>: {</span><br><span class="line"> <span class="attr">"file"</span>: <span class="string">"github.com/status/contracts/contracts/identity/ERC725.sol"</span></span><br><span class="line"> },</span><br><span class="line"> <span class="attr">"Ownable"</span>: {</span><br><span class="line"> <span class="attr">"file"</span>: <span class="string">"https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/ownership/Ownable.sol"</span></span><br><span class="line"> },</span><br><span class="line"> <span class="attr">"SimpleStorage"</span>: {</span><br><span class="line"> <span class="attr">"file"</span>: <span class="string">"./some_folder/simple_storage.sol"</span></span><br><span class="line"> }</span><br><span class="line"> }</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure><h2 id="Importing-contracts-from-URIs-directly-in-Solidity"><a href="#Importing-contracts-from-URIs-directly-in-Solidity" class="headerlink" title="Importing contracts from URIs directly in Solidity"></a>Importing contracts from URIs directly in Solidity</h2><p>You can also import the same URIs directly in solidity which is quite useful for interfaces, e.g:</p><figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> <span class="string">"git://github.com/status/contracts/contracts/identity/ERC725.sol#develop"</span>;</span><br><span class="line"><span class="keyword">import</span> <span class="string">"github.com/status/contracts/contracts/identity/ERC725.sol"</span>;</span><br><span class="line"><span class="keyword">import</span> <span class="string">"https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/ownership/Ownable.sol"</span></span><br><span class="line"></span><br><span class="line">contract MyContract is Ownable {</span><br><span class="line"> ...</span><br><span class="line">}</span><br></pre></td></tr></table></figure><h2 id="Contracts-from-npm-packages"><a href="#Contracts-from-npm-packages" class="headerlink" title="Contracts from npm packages"></a>Contracts from npm packages</h2><p>You can now install npm packages that contain contracts (e.g <code>npm install --save openzeppelin-solidity</code>) and refer them to them in the contracts.json file:</p><figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">{</span><br><span class="line"> <span class="string">"development"</span>: {</span><br><span class="line"> <span class="string">"contracts"</span>: {</span><br><span class="line"> <span class="string">"ERC20"</span>: {</span><br><span class="line"> file: <span class="string">"openzeppelin-solidity/contracts/token/ERC20/ERC20.sol"</span></span><br><span class="line"> }</span><br><span class="line"> }</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p>or even import them directly in solidity without the need for the config:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">import "openzeppelin-solidity/contracts/ownership/Ownable.sol";</span><br><span class="line"></span><br><span class="line">contract MyContract is Ownable {</span><br><span class="line"> ...</span><br><span class="line">}</span><br></pre></td></tr></table></figure><h2 id="Embark-Demo-App"><a href="#Embark-Demo-App" class="headerlink" title="Embark Demo App"></a>Embark Demo App</h2><p>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.</p><h2 id="Web3-js-1-0-by-default"><a href="#Web3-js-1-0-by-default" class="headerlink" title="Web3.js 1.0 by default"></a>Web3.js 1.0 by default</h2><p>Embark now uses web3.js 1.0 in all layers, including in the console and in contracts testing.</p><h2 id="More-contract-deploy-configs"><a href="#More-contract-deploy-configs" class="headerlink" title="More contract deploy configs"></a>More contract deploy configs</h2><p>A new config called <code>afterDeploy</code> is available and it can be used to specify actions to run after all contracts have been deployed.<br>It’s possible to also specify the specific account to deploy from using the directive <code>from</code> or <code>fromIndex</code></p><h2 id="Versions-Configuration"><a href="#Versions-Configuration" class="headerlink" title="Versions Configuration"></a>Versions Configuration</h2><p>The versions config has been moved to embark.json, the download mechanism has also been fastly improved under the hood:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">...</span><br><span class="line">"versions": {</span><br><span class="line"> "web3": "1.0.0-beta",</span><br><span class="line"> "solc": "0.4.23",</span><br><span class="line"> "ipfs-api": "17.2.4"</span><br><span class="line">},</span><br><span class="line">...</span><br></pre></td></tr></table></figure><h2 id="Test-Improvements"><a href="#Test-Improvements" class="headerlink" title="Test Improvements"></a>Test Improvements</h2><p>In the tests you can now specify a mnemonic:</p><figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">config({</span><br><span class="line"> mnemonic: <span class="string">"labor ability deny divide mountain buddy home client type shallow outer pen"</span></span><br><span class="line">})</span><br><span class="line"><span class="string">`</span></span><br></pre></td></tr></table></figure><p>It’s also possible to specify a node, in case you don’t want to run in the internal vm:</p><figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">config({</span><br><span class="line"> node: <span class="string">"http://localhost:8545"</span></span><br><span class="line">})</span><br><span class="line"><span class="string">`</span></span><br></pre></td></tr></table></figure><h2 id="Swarm-support"><a href="#Swarm-support" class="headerlink" title="Swarm support"></a>Swarm support</h2><p>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</p><h2 id="Misc-Bugfixes-and-Improvements"><a href="#Misc-Bugfixes-and-Improvements" class="headerlink" title="Misc Bugfixes and Improvements"></a>Misc Bugfixes and Improvements</h2><p>For a complete list please refer to the <a href="https://github.com/embarklabs/embark/releases/tag/3.0.0" target="_blank" rel="noopener">release notes in github</a></p><h2 id="Chatroom"><a href="#Chatroom" class="headerlink" title="Chatroom"></a>Chatroom</h2><p>To discuss about Embark or Dapp development, please <a href="https://gitter.im/embark-framework/Lobby" target="_blank" rel="noopener">join us at the gitter channel</a></p>]]></content>
<summary type="html">
<p>Embark is now part of <a href="https://status.im/" target="_blank" rel="noopener">Status</a> and we are happy to announce Embark 3.0 by S
</summary>
<category term="announcements" scheme="https://framework.embarklabs.io/categories/announcements/"/>
</entry>
<entry>
<title>Embark 2.6.0 - web3.js 1.0, any version of web3.js & solc. Whisper 5 & much more</title>
<link href="https://framework.embarklabs.io/news/2017/10/25/embark-2-6-released/"/>
<id>https://framework.embarklabs.io/news/2017/10/25/embark-2-6-released/</id>
<published>2017-10-25T04:00:00.000Z</published>
<updated>2020-01-19T19:38:04.360Z</updated>
<content type="html"><![CDATA[<h2 id="To-Update-to-2-6-0"><a href="#To-Update-to-2-6-0" class="headerlink" title="To Update to 2.6.0"></a>To Update to 2.6.0</h2><p>Embark’s npm package has changed from <code>embark-framework</code> to <code>embark</code>, this sometimes can create conflicts. To update, first uninstall embark-framework 1 to avoid any conflicts with <code>npm uninstall -g embark-framework</code> followed by <code>npm install -g embark</code></p><p>to update from 2.5.2:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">npm install -g [email protected]</span><br></pre></td></tr></table></figure><p>afterwards make sure <code>embark version</code> returns <code>2.6.0</code>.</p><h2 id="In-this-release"><a href="#In-this-release" class="headerlink" title="In this release"></a>In this release</h2><p>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.</p><h2 id="Support-for-web3-js-1-0-and-nearly-ANY-web3-js-version"><a href="#Support-for-web3-js-1-0-and-nearly-ANY-web3-js-version" class="headerlink" title="Support for web3.js 1.0 and (nearly) ANY web3.js version"></a>Support for web3.js 1.0 and (nearly) ANY web3.js version</h2><p>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.</p><p>in config/contracts.json</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">{</span><br><span class="line"> "default": {</span><br><span class="line"> ....</span><br><span class="line"> "versions": {</span><br><span class="line"> "web3.js": "1.0.0-beta"</span><br><span class="line"> }</span><br><span class="line"> ...</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p>If ,for example, you wish to use 0.19.0 you can specify it in the config as <code>"web3.js": "0.19.0"</code></p><h2 id="Support-for-ANY-solc-version"><a href="#Support-for-ANY-solc-version" class="headerlink" title="Support for ANY solc version"></a>Support for ANY solc version</h2><p>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.</p><p><code>config/contracts.json</code></p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">{</span><br><span class="line"> "default": {</span><br><span class="line"> ....</span><br><span class="line"> "versions": {</span><br><span class="line"> "solc": "0.4.17"</span><br><span class="line"> }</span><br><span class="line"> ...</span><br><span class="line">}</span><br></pre></td></tr></table></figure><h2 id="Specify-nodes-DApp-should-attempt-to-connect-to"><a href="#Specify-nodes-DApp-should-attempt-to-connect-to" class="headerlink" title="Specify nodes DApp should attempt to connect to"></a>Specify nodes DApp should attempt to connect to</h2><p>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.<br>The following config would attempt to use the existing web3 object and if unavailable attempt to connect to localhost:8545</p><p><code>config/contracts.json</code></p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">{</span><br><span class="line"> "development": {</span><br><span class="line"> ...</span><br><span class="line"> "dappConnection": [</span><br><span class="line"> "$WEB3",</span><br><span class="line"> "http://localhost:8545"</span><br><span class="line"> ],</span><br><span class="line"> ...</span><br><span class="line">}</span><br></pre></td></tr></table></figure><h2 id="Specify-node-to-deploy-to"><a href="#Specify-node-to-deploy-to" class="headerlink" title="Specify node to deploy to"></a>Specify node to deploy to</h2><p>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.</p><p><code>config/contracts.json</code></p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">{</span><br><span class="line"> "development": {</span><br><span class="line"> ...</span><br><span class="line"> "deployment": {</span><br><span class="line"> "host": "localhost",</span><br><span class="line"> "port": 8545,</span><br><span class="line"> "type": "rpc"</span><br><span class="line"> },</span><br><span class="line"> ...</span><br><span class="line">}</span><br></pre></td></tr></table></figure><h2 id="Specify-node-to-connect-whisper-to"><a href="#Specify-node-to-connect-whisper-to" class="headerlink" title="Specify node to connect whisper to"></a>Specify node to connect whisper to</h2><p><code>config/communication.json</code></p><figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">{</span><br><span class="line"> <span class="string">"default"</span>: {</span><br><span class="line"> <span class="string">"enabled"</span>: <span class="literal">true</span>,</span><br><span class="line"> <span class="string">"provider"</span>: <span class="string">"whisper"</span>,</span><br><span class="line"> <span class="string">"available_providers"</span>: [<span class="string">"whisper"</span>, <span class="string">"orbit"</span>],</span><br><span class="line"> <span class="string">"connection"</span>: {</span><br><span class="line"> <span class="string">"host"</span>: <span class="string">"localhost"</span>,</span><br><span class="line"> <span class="string">"port"</span>: <span class="number">8546</span>,</span><br><span class="line"> <span class="string">"type"</span>: <span class="string">"ws"</span></span><br><span class="line"> }</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure><h2 id="Specify-url-to-get-assets"><a href="#Specify-url-to-get-assets" class="headerlink" title="Specify url to get assets"></a>Specify url to get assets</h2><p>You can specify for each environment what IPFS node to get the assets from</p><p><code>config/storage.json</code></p><figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">{</span><br><span class="line"> ...</span><br><span class="line"> <span class="string">"development"</span>: {</span><br><span class="line"> ....</span><br><span class="line"> <span class="string">"getUrl"</span>: <span class="string">"http://localhost:8080/ipfs/"</span></span><br><span class="line"> },</span><br><span class="line"> ...</span><br><span class="line"> <span class="string">"livenet"</span>: {</span><br><span class="line"> ....</span><br><span class="line"> <span class="string">"getUrl"</span>: <span class="string">"https://gateway.ipfs.io/ipfs/"</span></span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure><h3 id="Plugin-API-changes"><a href="#Plugin-API-changes" class="headerlink" title="Plugin API changes"></a>Plugin API changes</h3><p><img src="http://icons.iconarchive.com/icons/elegantthemes/beautiful-flat/128/plugin-icon.png" alt="plugin"></p><p>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</p><p>plugins that use these events will get deprecation warnings, the deprecated events will be removed in 2.7.0</p><h3 id="New-Blockchain-options"><a href="#New-Blockchain-options" class="headerlink" title="New Blockchain options"></a>New Blockchain options</h3><p><img src="https://dappsforbeginners.files.wordpress.com/2015/02/ethereum-logo.jpg?w=200" alt="geth"></p><p>The following fields are now available at <code>config/blockchain.json</code> to enhance <code>embark blockchain</code>:</p><ul><li>“wsHost” - to specify the websocket host (default: localhost)</li><li>“wsPort” - to specify the websocket port (default: 8546)</li><li>“wsOrigins”- to specify the allowed origin of the websocket requests (default: FALSE), must be specified to something like <a href="http://localhost:8000" target="_blank" rel="noopener">http://localhost:8000</a> for the websocket connection to work.</li><li>“wsApi” - to specify the apis available through websockets (default: [‘eth’, ‘web3’, ‘net’, ‘shh’])</li></ul><h3 id="Misc-Bugfixes-and-Improvements"><a href="#Misc-Bugfixes-and-Improvements" class="headerlink" title="Misc Bugfixes and Improvements"></a>Misc Bugfixes and Improvements</h3><p><img src="http://i.imgur.com/L1r6Ac5.png" alt="bug fixes"></p><ul><li>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</li><li>embark and mocha are no longer dependencies in the created dapp</li><li>you can specify a test file with <code>embark test <filename></code></li><li>tests no longer need testrpc to be installed first</li><li><code>EmbarkJS.isNewWeb3()</code> to detect if web3 1.0 is available</li><li>demo app updated to use web3.js 1.0 and solc 0.4.17</li><li>warn user when websocket or http CORS is not set</li><li>tolerate solc compiler warnings, which could cause a crash sometimes</li></ul><h3 id="Thank-you"><a href="#Thank-you" class="headerlink" title="Thank you"></a>Thank you</h3><p>A big thanks to all that contributed to this release including <a href="https://github.com/toadkicker" target="_blank" rel="noopener">Todd Baur</a> and Jacob Beauchamp.</p><h3 id="Chatroom"><a href="#Chatroom" class="headerlink" title="Chatroom"></a>Chatroom</h3><p>To discuss about Embark or Dapp development, please <a href="https://gitter.im/iurimatias/embark-framework" target="_blank" rel="noopener">join us at the gitter channel</a></p>]]></content>
<summary type="html">
<h2 id="To-Update-to-2-6-0"><a href="#To-Update-to-2-6-0" class="headerlink" title="To Update to 2.6.0"></a>To Update to 2.6.0</h2><p>Embark
</summary>
<category term="announcements" scheme="https://framework.embarklabs.io/categories/announcements/"/>
</entry>
<entry>
<title>Embark 2.5.0</title>
<link href="https://framework.embarklabs.io/news/2017/06/28/embark-2-5-released/"/>
<id>https://framework.embarklabs.io/news/2017/06/28/embark-2-5-released/</id>
<published>2017-06-28T04:00:00.000Z</published>
<updated>2020-01-19T19:38:04.360Z</updated>
<content type="html"><![CDATA[<h2 id="To-Update-to-2-5-0"><a href="#To-Update-to-2-5-0" class="headerlink" title="To Update to 2.5.0"></a>To Update to 2.5.0</h2><p>Embark’s npm package has changed from <code>embark-framework</code> to <code>embark</code>, this sometimes can create conflicts. To update, first uninstall embark-framework 1 to avoid any conflicts with <code>npm uninstall -g embark-framework</code> followed by <code>npm install -g embark</code></p><p>to update from 2.4.2:</p><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">npm install -g [email protected]</span><br></pre></td></tr></table></figure><p>afterwards make sure <code>embark version</code> returns <code>2.5.0</code>.</p><h2 id="In-this-release"><a href="#In-this-release" class="headerlink" title="In this release"></a>In this release</h2><p>This release updates to the lastest dependencies, fixes a few things and has a lot of work under the hood necessary for future releases.</p><h2 id="Updates"><a href="#Updates" class="headerlink" title="Updates"></a>Updates</h2><ul><li>support for geth 1.6.5</li><li>updated to use web3.js 0.19.11</li><li>updated to use solc 0.4.11</li></ul><h2 id="Misc-Bugfixes-and-Improvements"><a href="#Misc-Bugfixes-and-Improvements" class="headerlink" title="Misc Bugfixes and Improvements"></a>Misc Bugfixes and Improvements</h2><ul><li><code>embark new</code> will now prompt for the dapp name if not specified as <code>embark new <yourDappName></code></li><li>embark.js: <code>ContractName.new()</code> as been added as an alias for <code>ContractName.deploy()</code></li><li>embark.js: a method to easily send ether to a contract has been added: <code>ContractName.send(value, unit, options)</code> e.g <code>ContractName.send(2, "ether", {from: web3.eth.accounts[1]})</code></li><li>orbit: Fix for orbit to make it work if the blockchain component is disabled</li><li>orbit: Use default config for orbit it none is specified in the config file</li><li>Demo app now has warning message for incompatible whisper versions</li><li>the JSON files of the contracts are now being outputted at dist/contracts/ (experimental)</li><li>whisper: Dashboard now displays the whisper version of the node</li><li>plugin API: extensions can now also be added as directories within the dapp directory</li><li>plugin API: plugins can now register a component to be displayed in the dashboard. e.g:</li></ul><figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">embark.registerServiceCheck(<span class="string">'PluginService'</span>, <span class="function"><span class="keyword">function</span>(<span class="params">cb</span>) </span>{</span><br><span class="line"> <span class="keyword">if</span> (someFunctionThatChecksTheService()) {</span><br><span class="line"> cb({<span class="attr">name</span>: <span class="string">"MyServiceName"</span>, <span class="attr">status</span>: <span class="string">"on"</span>});</span><br><span class="line"> } <span class="keyword">else</span> {</span><br><span class="line"> cb({<span class="attr">name</span>: <span class="string">"MyServiceName"</span>, <span class="attr">status</span>: <span class="string">"off"</span>});</span><br><span class="line"> }</span><br><span class="line">});</span><br></pre></td></tr></table></figure><h2 id="Thank-you"><a href="#Thank-you" class="headerlink" title="Thank you"></a>Thank you</h2><p>A big thanks to all that contributed to this release including <a href="https://github.com/nathanph" target="_blank" rel="noopener">Nathan Hernandez</a>, <a href="https://github.com/atfornes" target="_blank" rel="noopener">Antonio Tenorio-Fornés</a>, <a href="https://github.com/jonjonsonjr" target="_blank" rel="noopener">Jon Johnson</a>, Andy Nogueira, <a href="https://github.com/roo2" target="_blank" rel="noopener">roo2</a>, <a href="https://github.com/carlmon" target="_blank" rel="noopener">Carl Mönnig</a>, <a href="https://github.com/michaeljyeates" target="_blank" rel="noopener">Michael Yeates</a>, <a href="https://github.com/toadkicker" target="_blank" rel="noopener">Todd Baur</a>, <a href="https://github.com/imtypist" target="_blank" rel="noopener">黄俊钦</a>, <a href="https://github.com/RamiroMoreira" target="_blank" rel="noopener">Ramiro Moreira</a>, <a href="https://github.com/greggdourgarian" target="_blank" rel="noopener">gregg dourgarian</a></p><h2 id="Chatroom"><a href="#Chatroom" class="headerlink" title="Chatroom"></a>Chatroom</h2><p>To discuss about Embark or Dapp development, please <a href="https://gitter.im/iurimatias/embark-framework" target="_blank" rel="noopener">join us at the gitter channel</a></p>]]></content>
<summary type="html">
<h2 id="To-Update-to-2-5-0"><a href="#To-Update-to-2-5-0" class="headerlink" title="To Update to 2.5.0"></a>To Update to 2.5.0</h2><p>Embark
</summary>
<category term="announcements" scheme="https://framework.embarklabs.io/categories/announcements/"/>
</entry>
</feed>