Ethereum DApps: Cross-contract Communication & Token Selling

In part 4 of this tutorial series on building DApps with Ethereum, we started building and testing our DAO contract. Now let’s go one step further and handle adding content and tokens to the story, as per our introduction.

Adding Tokens

For a contract to be able to interact with another contract, it needs to be aware of that other contract’s interface — the functions available to it. Since our TNS token has a fairly straightforward interface, we can include it as such in the contract of our DAO, above the contract StoryDao declaration and under our import statements:

contract LockableToken is Ownable {
    function totalSupply() public view returns (uint256);
    function balanceOf(address who) public view returns (uint256);
    function transfer(address to, uint256 value) public returns (bool);
    event Transfer(address indexed from, address indexed to, uint256 value);
    function allowance(address owner, address spender) public view returns (uint256);
    function transferFrom(address from, address to, uint256 value) public returns (bool);
    function approve(address spender, uint256 value) public returns (bool);
    event Approval(address indexed owner, address indexed spender, uint256 value);
    function approveAndCall(address _spender, uint256 _value, bytes _data) public payable returns (bool);
    function transferAndCall(address _to, uint256 _value, bytes _data) public payable returns (bool);
    function transferFromAndCall(address _from, address _to, uint256 _value, bytes _data) public payable returns (bool);

    function increaseLockedAmount(address _owner, uint256 _amount) public returns (uint256);
    function decreaseLockedAmount(address _owner, uint256 _amount) public returns (uint256);
    function getLockedAmount(address _owner) view public returns (uint256);
    function getUnlockedAmount(address _owner) view public returns (uint256);
}

Notice that we don’t need to paste in the “meat” of the functions, but only their signatures (skeletons). This is all that’s needed to interact between contracts.

Now we can use these functions in the DAO contract. The plan is as follows:

  • launch the token (we already did this)
  • launch the DAO from the same address
  • send all tokens from the token-launcher to the DAO, then transfer ownership over the contract to the DAO itself
  • at this point the DAO owns all tokens and can sell them to people using the transfer function, or can reserve them for spending using the approve function (useful during votes), etc.

But how does the DAO know which address the token is deployed on? We tell it.

First, we add a new variable at the top of the DAO contract:

LockableToken public token;

Then, we add some functions:

constructor(address _token) public {
    require(_token != address(0), "Token address cannot be null-address");
    token = LockableToken(_token);
}

The constructor is the function which gets called automatically when a contract is deployed. It’s useful for initializing values like linked contracts, default values, etc. In our case, we’ll use it to consume and save the address of the TNS token. The require check is there to make sure the token’s address is valid.

While we’re at it, let’s add a function that lets users check how many tokens remain for sale in the DAO, and the ability to change to another token should something go wrong and such a change be required. This change deserves an event, too, so let’s add that in as well.

event TokenAddressChange(address token);

function daoTokenBalance() public view returns (uint256) {
    return token.balanceOf(address(this));
}

function changeTokenAddress(address _token) onlyOwner public {
    require(_token != address(0), "Token address cannot be null-address");
    token = LockableToken(_token);
    emit TokenAddressChange(_token);
}

The first function is set to view because it doesn’t change the state of the blockchain; it doesn’t alter any values. This means it’s a free, read-only function call to the blockchain: it doesn’t need a paid transaction. It also returns the balance of tokens as a number, so this needs to be declared on the function’s signature with returns (uint256). The token has a balanceOf function (see the interface we pasted in above) and it accepts one parameter — the address whose balance to check. We’re checking our (this) DAO’s balance, so “this”, and we turn “this” into an address with address().

The token address changing function allows the owner (admin) to change the token contract. It’s identical to the logic of the constructor.

Let’s see how we can let people buy the tokens now.

Buying Tokens

As per the previous part of the series, users can buy tokens by:

  • Using the fallback function if already whitelisted. In other words, just sending ether to the DAO contract.
  • Using the whitelistAddress function by sending more than the fee required for whitelisting.
  • Calling the buyTokens function directly.

There is a caveat, however. When someone calls the buyTokens function from the outside, we want it to fail if there aren’t enough tokens in the DAO to sell. But when someone buys tokens via the whitelist function by sending in too much in the first whitelisting attempt, we don’t want it to fail, because then the whitelisting process will get canceled as everything fails at once. Transactions in Ethereum are atomic: either everything has to succeed, or nothing. So we’ll make two buyTokens functions.

// This goes at the top of the contract with other properties
uint256 public tokenToWeiRatio = 10000;

function buyTokensThrow(address _buyer, uint256 _wei) external {

    require(whitelist[_buyer], "Candidate must be whitelisted.");
    require(!blacklist[_buyer], "Candidate must not be blacklisted.");

    uint256 tokens = _wei * tokenToWeiRatio;
    require(daoTokenBalance() >= tokens, "DAO must have enough tokens for sale");
    token.transfer(_buyer, tokens);
}

function buyTokensInternal(address _buyer, uint256 _wei) internal {
    require(!blacklist[_buyer], "Candidate must not be blacklisted.");
    uint256 tokens = _wei * tokenToWeiRatio;
    if (daoTokenBalance() < tokens) {
        msg.sender.transfer(_wei);
    } else {
        token.transfer(_buyer, tokens);
    }
}

So, 100 million TNS tokens exist. If we set a price of 10000 tokens per one ether, that comes down to around 4–5 cents per token, which is acceptable.

The functions do some calculations after doing sanity checks against banned users and other factors, and immediately send the tokens out to the buyer, who can start using them as they see fit — either for voting, or for selling on exchanges. If there’s fewer tokens in the DAO than the buyer is trying to buy, the buyer is refunded.

The part token.transfer(_buyer, tokens) is us using the TNS token contract to initiate a transfer from the current location (the DAO) to the destination _buyer for amount tokens.

Now that we know people can get their hands on the tokens, let’s see if we can implement submissions.

The post Ethereum DApps: Cross-contract Communication & Token Selling appeared first on SitePoint.


Source: Sitepoint

Building Ethereum DApps: Whitelisting & Testing a Story DAO

In part 3 of this tutorial series on building DApps with Ethereum, we built and deployed our token to the Ethereum testnet Rinkeby. In this part, we’ll start writing the Story DAO code.

We’ll use the conditions laid out in the intro post to guide us.

Contract Outline

Let’s create a new contract, StoryDao.sol, with this skeleton:

pragma solidity ^0.4.24;

import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
import "../node_modules/openzeppelin-solidity/contracts/ownership/Ownable.sol";

contract StoryDao is Ownable {
    using SafeMath for uint256;

    mapping(address => bool) whitelist;
    uint256 public whitelistedNumber = 0;
    mapping(address => bool) blacklist;
    event Whitelisted(address addr, bool status);
    event Blacklisted(address addr, bool status);

    uint256 public daofee = 100; // hundredths of a percent, i.e. 100 is 1%
    uint256 public whitelistfee = 10000000000000000; // in Wei, this is 0.01 ether

    event SubmissionCommissionChanged(uint256 newFee);
    event WhitelistFeeChanged(uint256 newFee);

    uint256 public durationDays = 21; // duration of story's chapter in days
    uint256 public durationSubmissions = 1000; // duration of story's chapter in entries

    function changedaofee(uint256 _fee) onlyOwner external {
        require(_fee < daofee, "New fee must be lower than old fee.");
        daofee = _fee;
        emit SubmissionCommissionChanged(_fee);
    }

    function changewhitelistfee(uint256 _fee) onlyOwner external {
        require(_fee < whitelistfee, "New fee must be lower than old fee.");
        whitelistfee = _fee;
        emit WhitelistFeeChanged(_fee);
    }

    function lowerSubmissionFee(uint256 _fee) onlyOwner external {
        require(_fee < submissionZeroFee, "New fee must be lower than old fee.");
        submissionZeroFee = _fee;
        emit SubmissionFeeChanged(_fee);
    }

    function changeDurationDays(uint256 _days) onlyOwner external {
        require(_days >= 1);
        durationDays = _days;
    }

    function changeDurationSubmissions(uint256 _subs) onlyOwner external {
        require(_subs > 99);
        durationSubmissions = _subs;
    }
}

We’re importing SafeMath to have safe calculations again, but this time we’re also using Zeppelin’s Ownable contract, which lets someone “own” the story and execute certain admin-only functions. Simply saying that our StoryDao is Ownable is enough; feel free to inspect the contract to see how it works.

We also use the onlyOwner modifier from this contract. Function modifiers are basically extensions, plugins for functions. The onlyOwner modifier looks like this:

modifier onlyOwner() {
  require(msg.sender == owner);
  _;
}

When onlyOwner is added to a function, then that function’s body is pasted into the part where the _; part is, and everything before it executes first. So by using this modifier, the function automatically checks if the message sender is also the owner of the contract and then continues as usual if so. If not, it crashes.

By using the onlyOwner modifier on the functions that change the fees and other parameters of our story DAO, we make sure that only the admin can do these changes.

The post Building Ethereum DApps: Whitelisting & Testing a Story DAO appeared first on SitePoint.


Source: Sitepoint

4 Handpicked Design & Dev Collaboration Tools You Should Know About

This article was created in partnership with BAWMedia. Thank you for supporting the partners who make SitePoint possible.

If you’re a web designer or developer, your work involves some teamwork and collaboration. Even when you’re working on a personal project it never hurts to have someone you can rely on. You might need somebody for guidance, assistance, or fresh ideas.

Software projects have a reputation for late deliveries and budget overruns. These often occur due to a lack of insufficient collaboration among the parties.

Setting up a manual system that promotes collaboration can be a good step forward. But it often requires extra effort to keep it functioning smoothly. There is a better approach to it. Invest in a tool that makes sharing information and design concepts a breeze.

These tools fill the bill nicely.

1. Mason

Mason

Mason is a front-end-as-a-service tool. Its users can design, build, deploy, and maintain products from a single platform. Since all information is kept in one place, there’s no fragmentation of data or information exchanged during any phase of the design/build/deploy cycle.

Mason works in ways that may at first appear unfamiliar, but nevertheless makes sense. It assembles digital products by breaking them down into their constituent parts and reassembling them using a drag-and-drop building block approach. In this way, it’s far easier to make small changes or modifications not only during design, but after the product has been deployed.

The net result, and a major advantage of using Mason, is that changes can be made to deployed digital products without the need to wait for the next deployment cycle. Changes can literally be made on the spot.

It costs nothing to use Mason during design and testing. You only pay when the product is to be viewed by downstream customers.

2. monday.com

monday.com

This team management tool is exceptionally suitable for any industry sector and by any sized team. monday.com will perfectly serve a team of two or a team of hundreds spread around the globe, and it can manage multiple projects at once. It is as popular among non-tech teams as well as tech-oriented teams; in fact, 70% of its 22,000 paying teams fall outside the tech sector.

monday.com promotes effortless collaboration and transparency, it’s “cheetah fast”, it displays status in as many as 20 different colors, and its status board can be customized to fit your needs and your workflow.

It serves as an excellent alternative to having to force fit your work to meet the demands of your project management tools or systems. Freelancers, teams representing small agencies or startups, and teams working for Fortune 500 companies all profit from using monday.com.

The post 4 Handpicked Design & Dev Collaboration Tools You Should Know About appeared first on SitePoint.


Source: Sitepoint

Ethereum DApps: Compiling, Deploying, Testing TNS tokens

In part 2 of this tutorial series on building DApps with Ethereum, we wrote the TNS token’s code. But we haven’t yet compiled it, deployed it, tested it or verified it. Let’s do all that in this part so that we’re ready for what comes next.

Compiling

At this point we have a file containing some Solidity code. But to make the Ethereum Virtual Machine understand it, we need to turn it into machine code. Additionally, in order to communicate with it from a web application, we need an ABI (application binary interface), which is a universally readable description of the functions that exist in a certain smart contract — be it a token or something more complex. We can create machine code for the EVM and the ABI all at once by using Truffle’s compiler.

In the project folder, run:

truffle compile

This command will look inside the contracts subfolder, compile them all and place their compiled version into the build subfolder. Note that if you used the alternative development flow from the last part, all the parent contracts from which our TNSToken contract is inheriting functionality will also be compiled one by one each in its own file.

Compiled contracts

Feel free to inspect the contents of the generated JSON files. Our TNSToken should have over 10000 lines of JSON code.

Deploying to Ganache

Now let’s see if we can deploy this to our simulated Ganache blockchain. If Ganache isn’t running already in a tab of your terminal or among your operating system’s applications, run it with:

ganache-cli

Or run the app to get a screen like this one:

Ganache UI

Then, back in the folder where we just compiled the contracts, we have to add a migration. Create the file migrations/2_deploy_tnstoken.js. If you’re not familiar with migrations in the Truffle ecosystem, see this guide.

Let’s put the following into that file:

var Migrations = artifacts.require("./Migrations.sol");
var TNSToken = artifacts.require("./TNSToken.sol");

module.exports = function(deployer, network, accounts) {
  deployer.deploy(TNSToken, {from: accounts[0]});
};

First the ability to do migrations at all is imported by requesting Migrations.sol. This is required in every migration. Next, deploying a token means we need to import its Solidity code, and we do this by pulling in TNSToken.sol, the code we wrote in the previous part. Finally, this is cookie cutter migrating with only the part between function(deployer, network, accounts) { and the last } changing.

In this case, we tell the deployer to deploy the TNSToken and pass in the from argument in order to set the initial token holder. The address used here is a random one generated by Ganache, but by using the accounts array automatically passed to the deployer, we make sure we have access to the list of accounts present in the running node (be it a live Geth node or Ganache). In my particular example, the account[0] address was 0xdFb659D556d926dd3585d0f18d4F8eD7939E8061, also evident in the screenshot above.

Let’s also not forget to configure a development environment in truffle.js:

module.exports = {
  networks: {
    development: {
      host: "127.0.0.1",
      port: 7545,
      network_id: "*"
    }
  }
};

Note: take care of the port and IP; yours might be different!

Finally, in the project folder, run truffle migrate. You should see something like this:

A successful migration

Notice the Ethereum address next to TNStoken: 0x3134bcded93e810e1025ee814e87eff252cff422. This is where our token was deployed. Now let’s see it in action.

The post Ethereum DApps: Compiling, Deploying, Testing TNS tokens appeared first on SitePoint.


Source: Sitepoint

Best Market for WordPress Themes: TemplateMonster or ThemeForest?

This article was created in partnership with TemplateMonster. Thank you for supporting the partners who make SitePoint possible.

Most users feel overwhelmed when they need to select the best ready-made design for their website. There are plenty of agencies and web design studios offering unique designs to help users get started with websites for multiple purposes.

The number of web platforms selling themes crafted by vendors worldwide grows quickly all the time. If you want to select the best ready-made design for your site and feel confident that you’ve made the right choice, then it’s always a great idea to choose the industry leaders.

TemplateMonster and ThemeForest have proven to be the two leading digital marketplaces selling WordPress templates of top quality. Comparing these two options, which one is a better place to buy themes for your websites? That’s the question that we are going to answer in this post.

Why You Should Select WordPress Themes with Caution

WordPress has become one of the leading content management systems in the world. With its help, you will find no difficulty launching any kind of website, representing any business niche in an effective style.

Selecting the most optimal starting point for your site, you need to make sure that your WordPress theme complements the content that you are going to share on your site. Using WordPress, you can create stunning blogs, portfolios, business and corporate web projects, landing pages, and even eCommerce sites. Depending on the goal and the type of the online project that you need to launch, you need to select WordPress themes that meet your specific requirements. For example, launching a blog, you need to select a template that improves the readability of your content. If you want to launch a portfolio site, then the template of your choice should be optimized for handling image-rich web projects perfectly well.

Many WordPress templates available today are pre-installed with plugins and extensions intended to enhance the performance of niche-specific web projects. Just in case the selected WordPress theme isn’t loaded with the necessary tools, make sure that it’s compatible with the respective functionality.

Security is one of the top priorities that you need to take into consideration while selecting the best WordPress theme for your site. Although WordPress is known as one of the safest CMSs on the web, featuring regular updates, you need to make sure that you download a template that features regular updates so it won’t become outdated a few months after the launch of your site.

Let’s compare the functionality included in two of the top-selling business WordPress themes from both marketplaces. There are some features they have in common and certain peculiarities that make each of them unique. So, let’s compare and choose the best theme of the two reviewed.

EasyJet vs Argenta Multipurpose WordPress Themes

EasyJet is a functional multipurpose template sold by ZEMEZ in the TemplateMonster digital marketplace. This is a usable ready-made solution that is easy-to-handle by both beginners and expert webmasters. This is a feature-rich WordPress template that comes loaded with everything that you need for the launch of personal, business or eCommerce sites. There is no need to be an expert web designer or a programming specialist in order to handle the theme on your own. The theme’s download pack includes a wide range of features that will appeal to users of all skill levels.

Argenta is a creative multipurpose WordPress template sold by Colabrio on the ThemeForest marketplace. This is one of those feature-rich WordPress templates suited to be used for content-heavy web projects. Collections of the fully editable layouts that are included in the theme’s download pack are ready to be customized by means of the usable modification features that can be accessed via the dashboard.

Both of the reviewed WordPress templates are multipurpose solutions that include a handful of tools and features that provide for specific needs. Both templates include similar options and different sets of tools, which make one of them stronger than the other. Well, enough said. Let’s get straight to the comparison.

Installation

In order to start working with any WordPress template, you need to have WordPress installed. If you haven’t done this yet, make sure you install the latest WordPress version on your web host.

In order to start working with the EasyJet WordPress template, you need to make all the necessary preparations and run the plugin installations. This guarantees that the chosen template will work correctly after the installation of all its components.

The post Best Market for WordPress Themes: TemplateMonster or ThemeForest? appeared first on SitePoint.


Source: Sitepoint

How to Add Auth to Your PWA with Okta and Stencil

This article was originally published on OKTA Blog. Thank you for supporting the partners who make SitePoint possible.

Progressive Web Applications (PWAs) are the newest technology on the web dev block, and they’ve arrived just in time to solve a growing problem. Many companies are struggling to keep isolated development teams across their organization up-to-date when new features are released. Some companies are even trying to decide if it’s worth the cost to develop both a web app and a mobile application. Not surprisingly, it’s a headache most companies are looking to avoid. PWAs can give companies a lot of the features they need from a mobile app without the need to manage multiple teams and codebases.

A PWA performs spectacularly when on a fast connection, and still performs well when offline or on Wi-Fi that’s not really fast enough to be called Wi-Fi (sometimes called “Lie-Fi”). It does so via caching and a JavaScript “Service Worker” that intercepts server calls and tries to serve the data from cache first, then when the server finally responds, it will replace the cached data with possibly “fresher” data from the server.

Recently, the Ionic team released a new project called Stencil. Stencil is a compiler that generates standards-compliant web components. Unlike most JavaScript frameworks, it doesn’t deliver a “framework” of code to the browser. It simply takes the code you write and uses its compiler to create vanilla components. You can also use Stencil’s compiler with your favorite framework. The Stencil starter project is the easiest way to get started with Stencil and produces a base application that scores nearly a 100% score on Lighthouse’s progressive web app scorecard.

To get started building a PWA using Stencil, clone the starter application and detach it from the GitHub remote.

WARNING: Stencil is not at a 1.0 release yet (as of this writing). So be aware that if you continue, you’re in early-adopter territory. If you find bugs, submit an issue.

Set Up the Starter Application

git clone https://github.com/ionic-team/stencil-starter.git first-stencil
cd first-stencil
git remote rm origin

Then, install all the dependencies that your new Stencil app will need.

npm install

You may see a couple of warnings from node-pre-gyp around fsevents. There’s nothing to see here. This is just to get around a nasty little npm bug.

Next, add the Okta Auth SDK (via CDN) to the bottom of the index.html page, right before the closing </body> tag.

<script src="https://ok1static.oktacdn.com/assets/js/sdk/okta-auth-js/1.8.0/okta-auth-js.min.js" type="text/javascript"></script>

While there is an npm package for Okta’s Auth SDK, Stencil has a hard time compiling it. Overall it works better for now if you just use the CDN to include it.

If you’re like me, the next thing you’ll want to do is run npm start and check the site with Lighthouse. If you do, you’ll notice that the score is kind of low. In particular, it doesn’t register a service worker or return a 200 when offline. That’s because it’s a development build, and generally, you don’t want the service worker intercepting server calls and returning cached data in development.

To ensure an accurate depiction of the kind of PWA you get out of the box with Stencil, make sure to run a production build using npm run build. Once you do, you’ll see a www folder and inside that folder, you’ll see a sw.js file. That’s your service worker!

Set Up Your Okta Application

If you haven’t already done so, create a free-forever developer account.

Once you’ve registered, click on Applications in the top menu. Then click Add Application.

Application Listing Screen

You will then be taken to the application creation wizard. Choose Single-Page App and click Next at the bottom.

Create Application Screen SPA

On the next screen, you’ll see the default settings provided by the single-page application template. Change the name of the application to something more descriptive, like “Stencil SPA”. Also, change the base URIs and the login redirect URIs settings to use port 3333 because that’s where your application will be running. The rest of the default settings are fine.

Application Settings Screen

Click Done at the bottom.

Select your newly created application from the listing, and click on the General tab to view the general settings.

General Settings Client Id

At the bottom, you’ll see a Client ID setting (yours won’t be blurred out, obviously). Copy this to use in your Stencil application. You will also need your Okta organization URL, which you can find at the top right of the dashboard page. It will probably look something like “https://dev-XXXXXX.oktapreview.com”.

Add the Authentication Component

In the components folder, add a new folder called app-auth. This is where your login page component will go. You can call it whatever you want, I’m just following the naming conventions set out by the starter app here. I’d definitely recommend deciding on a naming convention early and sticking with it.

Inside the newly created app-auth folder create two files: app-auth.css and app-auth.tsx. Start by creating the shell of the app-auth.tsx file.

import { Component } from '@stencil/core';

@Component({
  tag: 'app-auth',
  styleUrl: 'app-auth.css'
})
export class AppAuth {
  render() {
    return <div>Hello</div>;
  }
}

If you are like I was, you might be thinking, “What kind of Frankenstein framework is this?”

You’ll notice the @Component decorator over the AppAuth class declaration like Angular, and then a render() method at the bottom like React. To me, that’s the beauty of Stencil. It takes some of the best parts of both popular frameworks and uses them to compile reusable components!

Add a Login Form

Next, you’ll add the JSX (that’s right, I said it) to the new component. Change the render() method to:

render() {
  return (
    <form class="app-auth">
      <div class="form-item">
        <label>
          Username:
          <input type="text" name="username" autocomplete="username" />
        </label>
      </div>
      <div class="form-item">
        <label>
          Password:
          <input
            type="password"
            name="password"
            autocomplete="current-password"
          />
        </label>
      </div>
      <div class="form-actions">
        <button type="button" onClick={() => this.login()}>
          Login
        </button>
      </div>
    </form>
  );
}

This is just a regular JSX form, but the login button’s onClick event is currently wired to function that doesn’t exist.

Add the Login Method’s Dependencies

Before you create that function, you’ll need to set up the OktaAuth JavaScript object to call the Okta API for authentication. You’ll add the object to the component’s state, so right below the class declaration, add the following line:

@State() authClient: any;

You will also have to import the @State() decorator. This is is used for values related to the internal state of the component. In the first import statement add State to the deconstruction list.

import { Component, State } from '@stencil/core'

You’ll also need to get the username and password values from the form itself, so add an @Element() to the code right below that @State() like you just created, so it read like this:

@State() authClient: any;
@Element() host: HTMLElement;

Then also add the @Element() decorator to the import so it reads:

import { Component, State, Element } from '@stencil/core';

One last thing that the login() function will need is access to the router, so you can redirect the user to their profile page if their authentication is successful. You’ll need a class property, so add it right below the @Element.

@State() authClient: any;
@Element() host: HTMLElement;
@Prop() history: RouterHistory;

To import it, add the @Prop() decorator to the main import and then import the RouterHistory from @stencil/router right below the core import statement. The @Prop decorator is used to define properties that can be passed in to your component. In this case, it’s not a passed in value, but it could be if need be. Your final import section should read:

import { Component, Prop, State, Element, Listen } from '@stencil/core';
import { RouterHistory } from '@stencil/router';

Finally, to use the OktaAuth JavaScript library you brought in from the CDN, add a declaration for it right below the import statements.

declare const OktaAuth: any;

Add the Login Method

Now you included everything you’ll need to get the login function to authenticate users with your Okta organization. First, set up the OktaAuth object in the constructor of the AppAuth class. Right below the property for the RouterHistory object, add:

constructor() {
  this.authClient = new OktaAuth({
    clientId: '{yourClientId}',
    url: 'https://{yourOktaDomain}.com',
    issuer: 'default'
  });
}

You can get your Client ID from that general settings page of your Okta application.

The post How to Add Auth to Your PWA with Okta and Stencil appeared first on SitePoint.


Source: Sitepoint

Building DApps with Ethereum: Creating, Deploying TNS Tokens

In part 1 of this tutorial series on building DApps with Ethereum, we bootstrapped two versions of a local blockchain for development: a Ganache version, and a full private PoA version.

In this part, we’ll dive right into it and build and deploy our TNS token — the token users will use to vote on proposals in the Story DAO.

Prerequisites

Have a Ganache version up and running, as per the previous part. Alternatively, have any local version of a blockchain running if you’re not following along from the first part, but make sure you can connect to it with tools we’ll need.

We’ll assume you have a working private blockchain and the ability to type commands into its console and the operating system’s terminal via the Terminal app or, on Windows, an app like Git Bash, Console, CMD Prompt, Powershell, etc.

The Basic Dependencies

To develop our application, we can use one of several frameworks and starter kits at our disposal: Dapp, eth-utils, Populus, Embark … and so on. But we’ll go with the current king of the ecosystem, Truffle.

Install it with the following:

npm install -g truffle

This will make the truffle command available everywhere. Now we can start the project with truffle init.

Starting the Token

Let’s get right into it and build our token. It’ll be a somewhat standard cookie-cutter ERC20 token with a twist. (You’ll see which twist lower in this post.) First, we’ll pull in some dependencies. The OpenZeppelin libraries are battle-tested high quality solidity contracts usable for extending and building contracts from.

npm install openzeppelin-solidity

Next, let’s create a new token file:

truffle create contract TNSToken

The default template that truffle generates here is a little out of date, so let’s get it updated:

pragma solidity ^0.4.24;

contract TNStoken {
    constructor() public {

    }
}

Up until now, the constructor of the token contract was supposed to be called the same as the contract itself, but for clarity it was changed to constructor. It should also always have a modifier telling the compiler who is allowed to deploy and interact with this contract (public meaning everyone).

SafeMath

The only Zeppelin contract we’ll be using in this case is their SafeMath contract. In Solidity, we import contracts with the import keyword, while the compiler will generally not require a full path, only a relative one, like so:

pragma solidity ^0.4.24;

import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";

contract TNStoken {
    using SafeMath for uint256;
    constructor() public {

    }
}

So, what is SafeMath? Long ago, there was an issue of 184 billion bitcoins being created because of a math problem in code. To prevent issues even remotely similar to these (not that this one in particular is possible in Ethereum), the SafeMath library exists. When two numbers are of the MAX_INT size (i.e. the maximum possible number in an operating system), summing them up would make the value “wrap around” to zero, like a car’s odometer being reset to 0 after reaching 999999 kilometers. So the SafeMath library has functions like these:

/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
  c = a + b;
  assert(c >= a);
  return c;
}

This function prevents this issue: it checks whether the sum of two numbers is still bigger than each of the two operands.

While it’s not too easy to make such silly mistakes when writing Solidity contracts, it’s still better to be safe than sorry.

By using SafeMath for uint256, we replace the standard uint256 numbers in Solidity (256bit unsigned — a.k.a. positive-only — whole numbers) with these “safe” versions. Instead of summing numbers like this: sum = someBigNumber + someBiggerNumber, we’ll be summing them like this: sum = someBigNumber.add(someBiggerNumber), thereby being safe in our calculations.

ERC20 from Scratch

With our math made safe, we can create our token.

ERC20 is a standard with a well-defined interface, so for reference, let’s add it into the contract. Read about the token standards here.

So the functions that an ERC20 token should have are:

pragma solidity ^0.4.24;

import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";

contract ERC20 {
    function totalSupply() public view returns (uint256);
    function balanceOf(address who) public view returns (uint256);
    function transfer(address to, uint256 value) public returns (bool);
    event Transfer(address indexed from, address indexed to, uint256 value);
    function allowance(address owner, address spender) public view returns (uint256);
    function transferFrom(address from, address to, uint256 value) public returns (bool);
    function approve(address spender, uint256 value) public returns (bool);
    event Approval(address indexed owner, address indexed spender, uint256 value);
}

contract TNStoken {

    using SafeMath for uint256;

    constructor() public {

    }
}

This might seem complex, but it’s actually very simple. This is a “directory” of functions our token needs to have, and we’ll build them one by one, explaining what each of them means. Consider the above an interface for our token. We’ll see how and why this is useful when we create the Story DAO application.

Basic balances

Let’s start. A token is actually just a “spreadsheet” in the Ethereum blockchain, like this:

| Name | Amount |
|:--|:--|
| Bruno | 4000 |
| Joe | 5000 |
| Anne | 0 |
| Mike | 300 |

So let’s create a mapping, which is essentially exactly like a spreadsheet in the contract:

mapping(address => uint256) balances;

According to the interface above, this needs to be accompanied by a balanceOf function, which can read this table:

function balanceOf(address _owner) public view returns (uint256) {
    return balances[_owner];
}

The function balanceOf accepts one argument: _owner is public (can be used by anyone), is a view function (meaning it’s free to use — does not require a transaction), and returns a uint256 number, the balance of the owner of the address sent in. Everyone’s balance of tokens is publicly readable.

Total supply

Knowing the total supply of the token is important for its users and for coin tracking applications, so let’s define a contract property (variable) to track this and another free function through which to read this:

uint256 totalSupply_;
function totalSupply() public view returns (uint256) {
    return totalSupply_;
}

The post Building DApps with Ethereum: Creating, Deploying TNS Tokens appeared first on SitePoint.


Source: Sitepoint

29 Awesome Tools for Web Designers & Developers

This article was created in partnership with Mekanism. Thank you for supporting the partners who make SitePoint possible.

We’re always on the lookout for the best web tools and services available for designers and developers. Which resources should we be using? Most customers don’t need a website built from scratch — only customizations are necessary for many to find a perfect fit for their projects. That’s why you can easily use the ListingPro WordPress directory theme to build business directory websites or Brizy, or other website builders we have included in the showcase. Using these resources will help you stay competitive in terms of pricing and project delivery dates.

Web designers and developers told us what they are using in their projects to get things done faster and better. Here are 29 solutions that work.

1. ListingPro: The #1 WordPress Directory Theme

ListingPro: The #1 WordPress Directory Theme

ListingPro is the world’s #1 best-selling end-to-end WordPress directory solution. It’s the only theme that includes all the core directory features, and no paid plugins are required. This makes it super easy to build an online directory and start monetizing from day one. All for a fraction of the cost, with no coding knowledge required.

Whether you want to build a directory like Yelp, the Yellow Pages, Zomato, Foursquare or even Justdial, ListingPro is the best directory listing software for all kinds of business directory use-cases, including:

  • Restaurants directories, like Yelp, Zomato or Foursquare
  • Local search business directories, like Yellow Pages and Justdial
  • Medical directories, like ZocDoc
  • Tour & travel review directories, like TripAdvisor
  • Hotel directories, like Airbnb
  • Software review sites, like Capterra

The core value proposition for ListingPro is simple: no paid plugins needed for all the core directory features. For more info on all the features, visit ListingPro’s official website.

2. Userfeel.com: Test Any Website or Mobile App‎

Userfeel

Userfeel is the usability testing tool that gives you videos of real users speaking their thoughts as they use your website or app. It is designed and developed by usability researchers, for usability researchers, but also for newcomers to UX research and anyone who wants to optimize their website or app.

Something that traditionally was difficult, costly and time-consuming, now is put at your disposal for an affordable cost. Every web designer, after they build their website with WordPress, should run a usability test to see whether the website is sending the right message and whether it’s easy to use.

Userfeel is offering the option to become a tester for the service, and earn $10 per test. Each test lasts 10-20 minutes, and you can do it from your home computer or smartphone.

Start testing your website for yourself or for your customers.

3. DealJumbo – Discounted Design Bundles

DealJumbo - Discounted Design Bundles

Dealjumbo brings you exclusive deals from the best web and graphic designers, writers, and artists from all over the world. The website was launched in 2013 and it was one of the first graphic design deal websites on the market, with excellent reviews in the industry.

You can download 1580+ free fonts and graphics. All come with a standard commercial license.

Check the website — it is packed with tons of items and design bundles with huge discounts.

4. Brizy – Create WordPress Pages Quickly

Brizy - Create WordPress Pages Quickly

Brizy is the friendliest and most complete WordPress page builder on the market, allowing users to build pages visually. Designers will find a huge collection of more than 4,000 icons at their disposal. There’s no need to have any coding skills.

As for developers, it comes with 150 pre-made design blocks. You can start from scratch and build anything you want, but if that is a little intimidating you can use the pre-made blocks to start your design. Developers can create a page on Brizy’s website and save the HTML for free, and use it anywhere they like in personal or commercial projects.

Brizy is a WordPress plugin and free to use. A Pro version is in the works with a presale lifetime deal available on its website.

5. Deeezy.com – Freebies for Web Designers

Deeezy

Deeezy is a brand new website offering awesome free and premium fonts and graphic design items. You will find 237 exclusive freebies and premium items offered with an extended license – for an unlimited number of commercial projects, or for your digital or physical items for sale.

You can subscribe for free and the premium plans start from $9 per month.

6. actiTIME

actiTIME

actiTIME is a powerful and popular time tracking app used by thousands of companies around the world. With its flexible configuration, actiTIME fits companies from many industries: IT, design, architecture, engineering and others.

Using actiTIME, you can easily manage project scope, assign tasks, track time and analyze your project performance based on the collected data. Everybody can benefit from using it day-to-day: employees, team managers and business owners.

7. Notism — Design & Video Collaboration for Teams

Notism — Design & Video Collaboration for Teams

Notism is an excellent design and video collaboration tool for creative teams making creative content review more effective. Yes, Notism also supports video collaboration. Finally, you can review and collaborate on your motion design work by adding notes, sketches or selections to the video timeline.

Sometimes it makes more sense to sketch directly on the work rather than adding notes. Notism offers several tools to draw on your uploaded content: a pencil, rectangle, and circle. You can also choose a line type, width or add a splashing color.

8. Goodie Website

Goodie Website

Goodie is a powerful web development service that allows you to have your website designed and coded by professionals from only $999. Everybody is looking to receive top quality for a reasonable price and this is what you will receive from this team of professionals. Goodie’s approach to help you is different: it hires only experienced web developers and lets them cooperate directly with you.

The post 29 Awesome Tools for Web Designers & Developers appeared first on SitePoint.


Source: Sitepoint

Build Custom Dashboards with MongoDB, Azure & Serverless Functions

This article was originally published on Ahmad Awais. Thank you for supporting the partners who make SitePoint possible.

TL;DR: I’m building a custom WordPress dashboard for an enterprise client which is powered by React.js on top of Node.js, with MongoDB Atlas as the database.

This dashboard uses several Microsoft Azure services, e.g., Cognitive Services, Azure App Services, and especially serverless Azure Functions. In this post, you’ll learn how to build a small module from it and the reason behind my choice of stack, apps, and products.


One of my enterprise clients who owns a huge networking and media company has a large-scale WordPress site set up. He recently consulted me about the possibility of building a custom WordPress dashboard (based on the WordPress REST API) — to help him make intelligent business decisions via Machine Learning and Artificial Intelligence.

With JavaScript eating up the world and WordPress adapting to the move by creating the Gutenberg project, I thought of an architecture/stack where WordPress would be our content layer, a familiar battle-tested environment that does its job well with a custom dashboard that’s built with JavaScript.

When you’re tasked to build a modern JavaScript application, you find yourself in a mix of different frameworks, tools, and dev workflows. The JavaScript ecosystem has grown a lot over the last couple of years. We have many, many good options available today.

So, after researching my options for a bit, I opted to use React.js on top of Node.js to start building the custom WordPress dashboard. While the project is in its ideation phase at the moment, I think it’s important that I share some of our goals here to define context behind my choice of the stack.

Custom WordPress Dashboard Goals

Imagine you own a large networking company where over 500 hotels (in three different countries) use your services to power their conference halls, IT meetings, and online property management like the sites and blogs. That’s what my client does.

Most of this is powered by a huge multi-site WordPress instance that manages everything for the hotels, websites, online booking, registrations, events, tickets, reviews, and comments. There’re also other systems running different software which are able to produce content via REST API.

We’ve set out to create a custom WordPress dashboard with many goals in mind, but I’m listing a few of them which are related to this particular article. Take a look at what I have built so far, it’s all based on serverless Azure functions — which are pretty awesome.

A Custom WordPress Dashboard with MongoDB Atlas, Microsoft Azure, & Serverless Functions!

👀 High-level Data Reporting

The custom dashboard will report all the high-level data, e.g. things like live sales happening throughout my client’s portfolio (500+ hotels), entity/time-based and date-based breakdowns.

And how each of his franchise performing on a daily, weekly, monthly basis. All of this data is being fed to MongoDB Atlas. More on that later.

⚡ Serverless Automation

Most of the modules are built upon serverless architecture — which in this case provides huge benefits. All the automation is always running and the cost is paid as you go i.e. pay for what you use.

An initial rough estimate puts this solution 34% more economical than having a server VM running all the time. We are using Azure Functions for this serverless automation.

🔥 IoT (Internet of Things) Hub

There are about ~200 IT managers working for my client who have IoT enabled devices that feed data into several online projects. This custom dashboard also includes that data for making better decisions and connecting the whole registration, management, maintenance team’s hub into a single place.

As you might have already guessed, this project makes use of IoT Hub from Microsoft Azure to connect, monitor, and manage all of the IoT assets.

🤖 Machine Learning and Artificial Intelligence

We’re using a lot of different services from Microsoft Azure for the sake of making this dashboard artificially intelligent by Machine Learning.

There’s a huge dataset that is fed to the ML Studio which later helps us predict different decisions like space management, low registrations trends for IT events, and questions like why and when these things happen.

While the Machine Learning part is beyond the scope of this article, I still plan to touch base with some of the awesome Artificial Intelligence I’ve been able to cook in via Azure’s Cognitive Services.

🕰 Live & Real-time

One of the most important aspects of this custom dashboard is that it’s live and real-time. Which means I need a managed database that can cope with this amount of data and still stay highly available.

But at the same time, it’s for the management purposes and doesn’t need to have any impact on the WordPress sites. That is a crucial system design decision for this dashboard.

By that what I mean is we can do all sorts of experiments with this custom dashboard but it shouldn’t have any impact on the database/servers which are running the multi-site WordPress instance.

MongoDB & MongoDB Atlas

For this custom WordPress dashboard, I am using MongoDB Atlas as a DBaaS (Database as a Service). And I couldn’t be happier. When I first shared that I’d be using MongoDB, many developers had concerns.

Mongodb

Most of the questions asked why I’d add another layer of complexity by adding yet another database to the mix. Why not use the WordPress database as it is? To answer these questions and more I have prepared a list of reasons as to why I am using MongoDB Atlas.

♨ Dislike for RDBMS

I personally dislike relational databases. Most of the time, for me they get in the way of building applications. I have to completely get out of the app I am building, think about my database in the future and design a good schema which always ends up a bad exercise for my dev workflow. It’s counter-intuitive at best — at least for me, it is.

💸 HDD Is Cheap — CPU/RAM Is Not

Old databases were mostly designed to save disk space, among other things. This led to a plethora of problems like normalization, indexing, and made sharding, auto-scaling, and replication harder.

Nowadays, disk space is dirt cheap. On the other hand, CPU/RAM is not, and your sysadmin costs can skyrocket very quickly if you end up with a bad choice here.

Like you wanted to create a custom dashboard but your system design architect cost you two sysadmins with how they chose to design your system. Similarly, my client wanted a managed solution without having to hire a team of IT/DevOps folks — at least for an experimental custom dashboard.

🍀 MongoDB’s Pros

  • Schema-less. Flexible schema for the win. I don’t have to change anything, my regular app development workflow, creating a Node.js-based app that I am manipulating with JSON type data, I can just feed that into MongoDB and it just works.
  • Workflow-consistency. Creates documents the way my custom dashboard is represented. Sales, Videos, Talks, Comments, Reviews, Registrations, etc. all of that have similar data representation on the frontend and the backend — and even in the database. I manage 3rd party data via middleware. This consistency translates to clean code.
  • Ease of scale-out. It scales reads by using replica sets. Scales writes by using sharding (auto-balancing). Just fire up another machine and away you go. Most importantly, instead of vertical scaling via RDBMS, MongoDB lets you scale horizontally with different levels of consistency. That’s a big plus. ➕
  • Cost. Depends on which RDBMS of course, but MongoDB is free and can run on Linux, ideal for running on cheaper commodity kits.

🍃 Why MongoDB Atlas?

Well, now that I know MongoDB is the right database choice, there are so many different options to host your database. I can self-host on my Linux machine via DigitalOcean, use a cloud provider like AWS/Azure or a choose a DBaaS service specific to MongoDB.

Mongodb Atlas

But I want a fast, secure, and managed MongoDB solution that I can easily scale with the growth of the number of modules we attach in this custom WordPress dashboard. That’s MongoDB Atlas.

MongoDB Atlas is a cloud-hosted MongoDB service engineered and run by the same team that builds the database. And guess what, I trust that they follow the best operational practices since they are the ones who’re building MongoDB in the first place.

I want this custom dashboard to be self-managed, serverless, and using MongoDB Atlas saves me from worrying about software patching, backups, and reliable configuration setup for new DB updates. Again a big plus. ➕

Also, the fact that MongoDB Atlas is supported cross-platform as well as cross-region and across different cloud providers makes it a much better choice. I think each Cluster comes with two replica sets, ready to scale.

🔋 MongoDB Compass

Now that we are going to work with MongoDB, it’d be great to have a tool through which we can explore our database, view the changes, debug and so on. For this purpose, MongoDB again takes the lead with a product called MongoDB Compass. Take a look.

Mongodb Compass

I suggest that you go ahead and download MongoDB Compass. It’s literally the best tool to visualize your MongoDB database. Here’s a set of features:

  • Visualize and explore: Take a look at your database, find out how things are looking, and even visualize stuff like maps/coordinates.
  • Insert, modify, and delete: You can also perform CRUD operations for your DB right from MongoDB compass. Makes testing easier.
  • Debug and optimize: Finally, analyze your data, debug it and even find out about performance issues right inside a great GUI for your database. This tool is a must-have if you work with MongoDB.
  • Extensible: And the best part is you can build your own plugins to extend MongoDB Compass. Here’s the documentation on building your own Compass plugins.
  • Enterprise Flavor: MongoDB Compass comes in a few flavors: Community (Free), and Enterprise (Licensed) — the Enterprise version is the one that lets you visualize DB schema.

✅ Getting Started with MongoDB Atlas

Let’s get started and build a simple module that’s part of the custom WordPress dashboard I am building. For this module, we are collecting all the sales related data. For that, we need a MongoDB instance, and of course we’re using MongoDB Atlas here.

Step #1: Go to MongoDB Atlas →

Go to the MongoDB Atlas site and register a completely free MongoDB instance hosted on AWS, with shared RAM and 512 MB storage. Click the Get Started Free button.

Mongodb Atlas

Step #2: Sign up at MongoDB Atlas →

Now go ahead and sign up with your email ID and fill up the details. It’s amazing that you can sign up and use a free MongoDB Atlas hosted DB instance, and they don’t even require you to add a credit card for that.

Mongodb Atlas Signup

Step #3: Create the Cluster

Now you’ll be redirected to a page with a bunch of information about the new MongoDB Cluster you’re about to create. I suggest that you review this information, and move ahead by clicking the Create Cluster button at the bottom just like in the screenshot below.

Mongodb Atlas Create Cluster

Step #4: Create DB Username & Password

It’ll take a minute and your DB will be created. Once that happens, head over to the Security > MongoDB Users and click on the + ADD NEW USER button on the right, to create a new user for your database. Let’s keep all the other settings set to default for the sake of this intro-article.

I’m setting the user/pass as usermongo but you know better.

GIF for MongoDB Atlas, Microsoft Azure, & Serverless Functions

Step #5: Add IP to Whitelist for Access

To be able to access your MongoDB Atlas database, you need to setup the IP Whitelist with the IP of your server where your app is hosted. Authentication is beyond what I am discussing here so for the purpose of this demo let’s just allow everyone (obviously a bad practice in production).

So, again, head over to the Security > IP Whitelist and click on the + ADD IP ADDRESS button on the right, and finally ALLOW ACCESS FROM ANYWHERE button to allow the anonymous access.

GIF for MongoDB Atlas, Microsoft Azure, & Serverless Functions

Step #6: Connect via MongoDB Compass

Now that our DB’s IP access and a user has been created, we can pick up the connection string and use it to connect to our database with our MongoDB Compass application.

Go to Connect then choose Connect with MongoDB Compass and download Compass if you haven’t. Copy the URI Connection String. Finally, open Compass and it should be able to detect the connection string in your clipboard, allow it to connect to your database.

And you are set to visualize your database, analyze its performance, and even run complete CRUD operations. Awesome! 💯

GIF for MongoDB Atlas, Microsoft Azure, & Serverless Functions

Now that we have created a MongoDB Atlas and connected it with MongoDB Compass, we can move forward and start building our Node.js application.

WordPress REST API — FTW!

This WordPress based Node.js custom dashboard interacts with the WordPress instance via the WordPress REST API. Since this is a Node.js app, I am using an awesome library called wpapi written by K Adam White. He has also built a demo Express based WordPress app. That’s what I got inspired by while building this custom dashboard, so you’ll see a lot of it here.

🚀 WordPress Custom Router Based on Express

The router is set up with Express. Here’s a basic error handler and router template for using WordPress with express.

'use strict';

var express = require('express');
var router = express.Router();
var siteInfoMiddleware = require('../middleware/site-info');

// Set global site info on all routes
router.use(siteInfoMiddleware);

// Public Routes
// =============

router.get('/', require('./index'));
router.get('/page/:page', require('./index'));
router.get('/:slug', require('./single'));
router.use('/tags/:tag', require('./tag'));
router.use('/categories/:category', require('./category'));

// Catch 404 and forward to error handler.
router.use(function (req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// Error Handling
// ==============

// Development error handler will print stacktrace.
function developmentErrorRoute(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: err
    });
}

// Production error handler. No stacktraces leaked to user.
function friendlyErrorRoute(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
}

// Configure error-handling behavior
if (router.get('env') === 'development') {
    router.use(developmentErrorRoute);
} else {
    router.use(friendlyErrorRoute);
}

module.exports = router;

View the code on Gist.

🎚 Basic Express Based Implementation

I am not hosting this entire thing on WordPress, but the initial plan was to do just that. If you want to go do that, you’d wanna build the index by querying all the info using the RSVP.hash utility for convenience and parallelism. For that here’s what you should do.

'use strict';

var wp = require( '../services/wp' );
var contentService = require( '../services/content-service' );
var pageNumbers = require( '../services/page-numbers' );
var pageTitle = require( '../services/page-title' );
var RSVP = require( 'rsvp' );

function getHomepage( req, res, next ) {
  var pages = pageNumbers( req.params.page );

  RSVP.hash({
    archiveBase: '',
    pages: pages,
    title: pageTitle(),
    // Primary page content
    posts: wp.posts().page( pages.current ),
    sidebar: contentService.getSidebarContent()
  }).then(function( context ) {
    if ( req.params.page && ! context.posts.length ) {
      // Invalid pagination: 404
      return next();
    }

    res.render( 'index', context );
  }).catch( next );
}

module.exports = getHomepage;

View the code on Gist.

🦏 Authentication Cooked In

For this setup, you’ll also need to authenticate your Node.js app by giving it the authentication data, which along with wpapi can be processed like this. Beware this is not always a best practice if you don’t use correct permissions and environment variables settings.

var WP = require( 'wordpress-rest-api' );
var _ = require( 'lodash' );

var config = _.pick( require( './config' ).wordpress, [
  // Whitelist valid config keys
  'username',
  'password',
  'endpoint'
]);

var wp = new WP( config );

module.exports = wp;

View the code on Gist.

🦁 Site Content Accumulation

And finally, you are able to consume all the content by creating a content service which handles recursively fetching:

  • All the pages of a paged collection.
  • Your WordPress site’s info.
  • An alphabetized list of categories.
  • A specific category (specified by slug) from the content cache.
  • An alphabetized list of tags.
  • A specific tag (specified by slug) from the content cache
  • Other content required to have some feature parity with WP.

The code for this looks somewhat like this.

'use strict';

var wp = require( './wp' );
var cache = require( './content-cache' );
var _ = require( 'lodash' );
var RSVP = require( 'rsvp' );

/**
 * Recursively fetch all pages of a paged collection
 *
 * @param {Promise} request A promise to a WP API request's response
 * @returns {Array} A promise to an array of all matching records
 */
function all( request ) {
  return request.then(function( response ) {
    if ( ! response._paging || ! response._paging.next ) {
      return response;
    }
    // Request the next page and return both responses as one collection
    return RSVP.all([
      response,
      all( response._paging.next )
    ]).then(function( responses ) {
      return _.flatten( responses );
    });
  });
}

function siteInfo( prop ) {
  var siteInfoPromise = cache.get( 'site-info' );

  if ( ! siteInfoPromise ) {
    // Instantiate, request and cache the promise
    siteInfoPromise = wp.root( '/' ).then(function( info ) {
      return info;
    });
    cache.set( 'site-info', siteInfoPromise );
  }

  // Return the requested property
  return siteInfoPromise.then(function( info ) {
    return prop ? info[ prop ] : info;
  });
}

/**
 * Get an alphabetized list of categories
 *
 * All archive routes display a sorted list of categories in their sidebar.
 * We generate that list here to ensure the sorting logic isn't duplicated
 * across routes.
 *
 * @method sortedCategories
 * @return {Array} An array of category objects
 */
function sortedCategories() {
  return all( wp.categories() ).then(function( categories ) {
    return _.chain( categories )
      .sortBy( 'slug' )
      .value();
  });
}

function sortedCategoriesCached() {
  var categoriesPromise = cache.get( 'sorted-categories' );

  if ( ! categoriesPromise ) {
    categoriesPromise = sortedCategories();
    cache.set( 'sorted-categories', categoriesPromise );
  }

  return categoriesPromise;
}

/**
 * Get a specific category (specified by slug) from the content cache
 *
 * The WP API doesn't currently support filtering taxonomy term collections,
 * so we have to request all categories and filter them down if we want to get
 * an individual term.
 *
 * To make this request more efficient, it uses sortedCategoriesCached.
 *
 * @method categoryCached
 * @param {String} slug The slug of a category
 * @return {Promise} A promise to the category with the provided slug
 */
function categoryCached( slug ) {
  return sortedCategoriesCached().then(function( categories ) {
    return _.findWhere( categories, {
      slug: slug
    });
  });
}

/**
 * Get a specific tag (specified by slug) from the content cache
 *
 * The WP API doesn't currently support filtering taxonomy term collections,
 * so we have to request all tags and filter them down if we want to get an
 * individual term.
 *
 * To make this request more efficient, it uses the cached sortedTags promise.
 *
 * @method tagCached
 * @param {String} slug The slug of a tag
 * @return {Promise} A promise to the tag with the provided slug
 */
function tagCached( slug ) {
  return sortedTagsCached().then(function( tags ) {
    return _.findWhere( tags, {
      slug: slug
    });
  });
}

/**
 * Get an alphabetized list of tags
 *
 * @method sortedTags
 * @return {Array} An array of tag objects
 */
function sortedTags() {
  return all( wp.tags() ).then(function( tags ) {
    return _.chain( tags )
      .sortBy( 'slug' )
      .value();
  });
}

function sortedTagsCached() {
  var tagsPromise = cache.get( 'sorted-tags' );

  if ( ! tagsPromise ) {
    tagsPromise = sortedTags();
    cache.set( 'sorted-tags', tagsPromise );
  }

  return tagsPromise;
}

function getSidebarContent() {
  return RSVP.hash({
    categories: sortedCategoriesCached(),
    tags: sortedTagsCached()
  });
}

module.exports = {
  // Recursively page through a collection to retrieve all matching items
  all: all,
  // Get (and cache) the top-level information about a site, returning the
  // value corresponding to the provided key
  siteInfo: siteInfo,
  sortedCategories: sortedCategories,
  sortedCategoriesCached: sortedCategoriesCached,
  categoryCached: categoryCached,
  tagCached: tagCached,
  sortedTags: sortedTags,
  sortedTagsCached: sortedTagsCached,
  getSidebarContent: getSidebarContent
};

View the code on Gist.

🛠 Custom Routes & Sales Data

Finally, I have cooked in quite a few custom routes from where I can attain any kind of sales related data. For the particular architecture I have in place, I’m again using the RSVP.hash utility for convenience and parallelism. It works like a charm.

The post Build Custom Dashboards with MongoDB, Azure & Serverless Functions appeared first on SitePoint.


Source: Sitepoint

Building DApps with Ethereum: App Rules and Blockchain Setup

This is the first part of a series on building decentralized applications using the Ethereum blockchain. We’re going to build 3 things: a custom token a DAO which uses the tokens as votes a prototype web UI for interacting with the smart contracts After following the instructions in this course, you’ll be able to build […]

The post Building DApps with Ethereum: App Rules and Blockchain Setup appeared first on SitePoint.


Source: Sitepoint