Smart Contract Development

Influenced by Python and JavaScript, Solidity is a contract-oriented, high-level programming language for the implementation of smart contracts. It runs the Ethereum Virtual Machine (EVM) both Ethereu


Influenced by Python and JavaScript, Solidity is a contract-oriented, high-level programming language for the implementation of smart contracts. It runs the Ethereum Virtual Machine (EVM) both Ethereum and Wethio.


  • Statically typed

  • Supports libraries and inheritances

  • Underpins complex user-defined types

Solidity makes contract creation possible for crowdfunding, blind auctions, voting, multi-signature wallets, etc.

The next sections will take you through the Solidity in detail.


Solidity interprets contract as a collection of code (its functions) and data (its state) and stores it at a specific address on the Wethio blockchain.

In the code written, uint storedData declares a state variable storedData of type uint (u_nsigned int_eger of 256 bits). Understand it as a single slot in a database that you can query and make changes to by simply calling out the functions of the code that manages the database.

Compiler installation


Solidity follows a semantic versioning pattern. All the releases and nightly development builds are made available. For the compiler to work smoothly, we recommend you to install Solidity compiler versions <=0.5.0.

Learning Solidity

Remix is recommended for small contracts and learning Solidity on-the-go. Remix is available for online access and no extra installation is required. If you do not have an internet connection, you can still use Remix by visiting and downloading the .zip file as instructed. One more advantage of Remix is that developers can test nightly builds without installing multiple Solidity versions.

In case you require further compilation options or if you are working on a larger contract, you can install commandline Solidity compiler software on your system. The above page provides detailed instructions about installing the software.

For using Remix with Wethio, you can start by connecting your Metamask to Wethio using Wethio’s RPC and follow this tutorial: (link)

Installing solcjs

With the use of npm/Node.js, you can install the solcjs, a Solidity compiler conveniently. The solcjs comprises fewer features and its usage is documented inside its own repository.



The following section talks about implementing a voting contract by using Solidity’s features. The major problem with electronic voting is assigning the voting rights to the correct persons and preventing manipulation. Instead of providing the complete solution here, we will showcase the process of conducting delegated voting so that vote counting is automatic and completely transparent.

The proceeding begins by creating one contract per ballot i.e. providing a short name for each option. The creator of the contract, i.e. chairperson, grants the right to vote to each address individually. Now the person behind the addresses has the option to either vote themselves or delegate their vote to a person they trust.

The winningProposal at the end of the voting time will return the proposal with the largest number of votes.

The below code is subject to change.

pragma solidity &gt;=0.4.22 &lt;=0.5.0;

/// @title Voting with delegation.

contract Ballot {

    // This declares a new complex type which will

// be used for variables later.

// It will represent a single voter.

    struct Voter {

        uint weight; // weight is accumulated by delegation

        bool voted;  // if true, that person already voted

        address delegate; // person delegated to

        uint vote;   // index of the voted proposal


// This is a type for a single proposal.

    struct Proposal {

        bytes32 name;

        // short name (up to 32 bytes)

        uint voteCount; // number of accumulated


    address public chairperson;
    // This declares a state variable that
    // stores a `Voter` struct for each possible address.
    mapping(address => Voter) public voters;
    // A dynamically-sized array of `Proposal` structs.
    Proposal[] public proposals;

    /// Create a new ballot to choose one of `proposalNames`.
    constructor(bytes32[] memory proposalNames) public {
        chairperson = msg.sender;
        voters[chairperson].weight = 1;
// For each of the provided proposal names,
        // create a new proposal object and add it
        // to the end of the array.
        for (uint i = 0; i < proposalNames.length; i++) {
            // `Proposal({...})` creates a temporary
            // Proposal object and `proposals.push(...)`
            // appends it to the end of `proposals`.
                name: proposalNames[i],
                voteCount: 0
    // Give `voter` the right to vote on this ballot.
    // May only be called by `chairperson`.
    function giveRightToVote(address voter) public {
        // If the first argument of `require` evaluates
        // to `false`, execution terminates and all
        // changes to the state and to ZYN balances
        // are reverted.
        // This used to consume all gas in old EVM versions, but
        // not anymore.
        // It is often a good idea to use `require` to check if
        // functions are called correctly.
        // As a second argument, you can also provide an
        // explanation about what went wrong.
            msg.sender == chairperson,
            "Only chairperson can give right to vote."
            "The voter already voted."
        require(voters[voter].weight == 0);
        voters[voter].weight = 1;
    /// Delegate your vote to the voter `to`.
    function delegate(address to) public {
        // assigns reference
        Voter storage sender = voters[msg.sender];
        require(!sender.voted, "You already voted.");

        require(to != msg.sender, "Self-delegation is disallowed.");

        // Forward the delegation as long as
        // `to` also delegated.
        // In general, such loops are very dangerous,
        // because if they run too long, they might
        // need more gas than is available in a block.
        // In this case, the delegation will not be executed,
        // but in other situations, such loops might
        // cause a contract to get "stuck" completely.
        while (voters[to].delegate != address(0)) {
            to = voters[to].delegate;

            // We found a loop in the delegation, not allowed.
            require(to != msg.sender, "Found loop in delegation.");
        // Since `sender` is a reference, this
        // modifies `voters[msg.sender].voted`
        sender.voted = true;
        sender.delegate = to;
        Voter storage delegate_ = voters[to];
        if (delegate_.voted) {
            // If the delegate already voted,
            // directly add to the number of votes
            proposals[].voteCount += sender.weight;
        } else {
            // If the delegate did not vote yet,
            // add to her weight.
            delegate_.weight += sender.weight;
    /// Give your vote (including votes delegated to you)
    /// to proposal `proposals[proposal].name`.
    function vote(uint proposal) public {
        Voter storage sender = voters[msg.sender];
        require(sender.weight != 0, "Has no right to vote");
        require(!sender.voted, "Already voted.");
        sender.voted = true; = proposal;

        // If `proposal` is out of the range of the array,
        // this will throw automatically and revert all
        // changes.
        proposals[proposal].voteCount += sender.weight;

    /// @dev Computes the winning proposal taking all
    /// previous votes into account.
    function winningProposal() public view
            returns (uint winningProposal_)
        uint winningVoteCount = 0;
        for (uint p = 0; p  winningVoteCount) {
                winningVoteCount = proposals[p].voteCount;
                winningProposal_ = p;

    // Calls winningProposal() function to get the index
    // of the winner contained in the proposals array and then
    // returns the name of the winner
    function winnerName() public view
            returns (bytes32 winnerName_)
        winnerName_ = proposals[winningProposal()].name;

Blind Auction

Another sample we will talk about is creating a blind auction contract on Wethio. We will showcase how at first we start with an open auction, where every bid that is made is visible to everyone and then extend it into a blind auction where it is not possible to see the actual bid till the end of the bidding process.

Understanding simple open auction

A simple open auction contract means everyone can send their bids during the bidding period. Sending ZYN/money is necessary to bid in order to bind the bidders to their bid. When the highest bid is made, the previously highest bidder gets their money back. Contact has to be called manually for the beneficiary to receive the money at the end of the bidding period as contracts cannot activate themselves.

The below code is subject to change.

    pragma solidity >=0.4.22 <=0.5.0;

contract SimpleAuction {
    // Parameters of the auction. Times are either
    // absolute unix timestamps (seconds since 1970-01-01)
    // or time periods in seconds.
    address payable public beneficiary;
    uint public auctionEndTime;

    // Current state of the auction.
    address public highestBidder;
    uint public highestBid;

    // Allowed withdrawals of previous bids
    mapping(address => uint) pendingReturns;

    // Set to true at the end, disallows any change.
    // By default initialized to `false`.
    bool ended;

    // Events that will be emitted on changes.
    event HighestBidIncreased(address bidder, uint amount);
    event AuctionEnded(address winner, uint amount);

    // The following is a so-called natspec comment,
    // recognizable by the three slashes.
    // It will be shown when the user is asked to
    // confirm a transaction.

    /// Create a simple auction with `_biddingTime`
    /// seconds bidding time on behalf of the
    /// beneficiary address `_beneficiary`.
        uint _biddingTime,
        address payable _beneficiary
    ) public {
        beneficiary = _beneficiary;
        auctionEndTime = now + _biddingTime;

    /// Bid on the auction with the value sent
    /// together with this transaction.
    /// The value will only be refunded if the
    /// auction is not won.
    function bid() public payable {
        // No arguments are necessary, all
        // information is already part of
        // the transaction. The keyword payable
        // is required for the function to
        // be able to receive ZYN.

        // Revert the call if the bidding
        // period is over.
            now <= auctionEndTime,
            "Auction already ended."

        // If the bid is not higher, send the
        // money back (the failing require
        // will revert all changes in this
        // function execution including
        // it having received the money).
            msg.value > highestBid,
            "There already is a higher bid."

        if (highestBid != 0) {
            // Sending back the money by simply using
            // highestBidder.send(highestBid) is a security risk
            // because it could execute an untrusted contract.
            // It is always safer to let the recipients
            // withdraw their money themselves.
            pendingReturns[highestBidder] += highestBid;
        highestBidder = msg.sender;
        highestBid = msg.value;
        emit HighestBidIncreased(msg.sender, msg.value);

    /// Withdraw a bid that was overbid.
    function withdraw() public returns (bool) {
        uint amount = pendingReturns[msg.sender];
        if (amount > 0) {
            // It is important to set this to zero because the recipient
            // can call this function again as part of the receiving call
            // before `send` returns.
            pendingReturns[msg.sender] = 0;

            if (!msg.sender.send(amount)) {
                // No need to call throw here, just reset the amount owing
                pendingReturns[msg.sender] = amount;
                return false;
        return true;

    /// End the auction and send the highest bid
    /// to the beneficiary.
    function auctionEnd() public {
        // It is a good guideline to structure functions that interact
        // with other contracts (i.e. they call functions or send ZYN)    
        // into three phases:
        // 1. checking conditions
        // 2. performing actions (potentially changing conditions)
        // 3. interacting with other contracts
        // If these phases are mixed up, the other contract could call
        // back into the current contract and modify the state or cause
        // effects (ZYN payout) to be performed multiple times.
        // If functions called internally include interaction with external
        // contracts, they also have to be considered interaction with
        // external contracts.

        // 1. Conditions
        require(now >= auctionEndTime, "Auction not yet ended.");
        require(!ended, "auctionEnd has already been called.");

        // 2. Effects
        ended = true;
        emit AuctionEnded(highestBidder, highestBid);

        // 3. Interaction

Blind Auction

Here we will extend the open auction into the blind auction. Cryptography enables a fair mechanism of creating a blind auction on a transparent computing platform. One major advantage of a blind auction is the absence of any time pressure at the end of the bidding period.

When the bidding is on, the bidder doesn’t actually send their bid, but only a hashed version of it. Since it is currently considered practically impossible to find two (sufficiently long) values whose hash values are equal, the bidder commits to the bid by that. Once the bidding period ends, the bidders have to reveal their bids by sending their values unencrypted. The contract then matches if the hash value is the same as the one provided during the auction.

Making the auction binding and blind at the same time is a difficult task. Value transfers cannot be blinded with Wethio and anyone can see the value. This makes it possible to prevent the bidder from sending the money after they won the auction and make them send it together with the bid.

The below contract showcases how to solve this problem by accepting any value that is larger than the highest bid.

The below code is subject to change

pragma solidity >0.4.23 <=0.5.0;

contract BlindAuction {
    struct Bid {
        bytes32 blindedBid;
        uint deposit;

    address payable public beneficiary;
    uint public biddingEnd;
    uint public revealEnd;
    bool public ended;

    mapping(address => Bid[]) public bids;

    address public highestBidder;
    uint public highestBid;

    // Allowed withdrawals of previous bids
    mapping(address => uint) pendingReturns;

    event AuctionEnded(address winner, uint highestBid);

    /// Modifiers are a convenient way to validate inputs to
    /// functions. `onlyBefore` is applied to `bid` below:
    /// The new function body is the modifier's body where
    /// `_` is replaced by the old function body.
    modifier onlyBefore(uint _time) { require(now < _time); _; }
    modifier onlyAfter(uint _time) { require(now > _time); _; }

        uint _biddingTime,
        uint _revealTime,
        address payable _beneficiary
    ) public {
        beneficiary = _beneficiary;
        biddingEnd = now + _biddingTime;
        revealEnd = biddingEnd + _revealTime;

    /// Place a blinded bid with `_blindedBid` =
    /// keccak256(abi.encodePacked(value, fake, secret)).
    /// The sent ZYN is only refunded if the bid is correctly
    /// revealed in the revealing phase. The bid is valid if the
    /// ZYN sent together with the bid is at least "value" and
    /// "fake" is not true. Setting "fake" to true and sending
    /// not the exact amount are ways to hide the real bid but
    /// still make the required deposit. The same address can
    /// place multiple bids.
    function bid(bytes32 _blindedBid)
            blindedBid: _blindedBid,
            deposit: msg.value

    /// Reveal your blinded bids. You will get a refund for all
    /// correctly blinded invalid bids and for all bids except for
    /// the totally highest.
    function reveal(
        uint[] memory _values,
        bool[] memory _fake,
        bytes32[] memory _secret
        uint length = bids[msg.sender].length;
        require(_values.length == length);
        require(_fake.length == length);
        require(_secret.length == length);

        uint refund;
        for (uint i = 0; i < length; i++) {
            Bid storage bidToCheck = bids[msg.sender][i];
            (uint value, bool fake, bytes32 secret) =
                    (_values[i], _fake[i], _secret[i]);
            if (bidToCheck.blindedBid != keccak256(abi.encodePacked(value, fake, secret))) {
                // Bid was not actually revealed.
                // Do not refund deposit.
            refund += bidToCheck.deposit;
            if (!fake && bidToCheck.deposit >= value) {
                if (placeBid(msg.sender, value))
                    refund -= value;
            // Make it impossible for the sender to re-claim
            // the same deposit.
            bidToCheck.blindedBid = bytes32(0);

    /// Withdraw a bid that was overbid.
    function withdraw() public {
        uint amount = pendingReturns[msg.sender];
        if (amount > 0) {
            // It is important to set this to zero because the recipient
            // can call this function again as part of the receiving call
            // before `transfer` returns (see the remark above about
            // conditions -> effects -> interaction).
            pendingReturns[msg.sender] = 0;


    /// End the auction and send the highest bid
    /// to the beneficiary.
    function auctionEnd()
        emit AuctionEnded(highestBidder, highestBid);
        ended = true;

    // This is an "internal" function which means that it
    // can only be called from the contract itself (or from
    // derived contracts).
    function placeBid(address bidder, uint value) internal
            returns (bool success)
        if (value <= highestBid) {
            return false;
        if (highestBidder != address(0)) {
            // Refund the previously highest bidder.
            pendingReturns[highestBidder] += highestBid;
        highestBid = value;
        highestBidder = bidder;
        return true;

Modular Contracts

Identifying bugs and vulnerabilities during development and code review can be a challenging task. Taking a modular approach in building your contracts can solve this problem by reducing the complexity and improving the readability of the code.

Specifying and controlling the behavior of each module in isolation restricts the interactions between the module specifications and not every other moving part of the contract. The below example shows how the contract uses the move method of the Balances library to check and match the balances sent between addresses. In this way, the Balances library provides an isolated component that properly tracks balances of accounts.

Due to which, it becomes easy to verify that the Balances library never produces negative balances or overflows and the sum of all balances is an invariant across the lifetime of the contract.

The below code is subject to change

pragma solidity >=0.4.22 <=0.5.0;

library Balances {
    function move(mapping(address => uint256) storage balances, address from, address to, uint amount) internal {
        require(balances[from] >= amount);
        require(balances[to] + amount >= balances[to]);
        balances[from] -= amount;
        balances[to] += amount;

contract Token {
    mapping(address => uint256) balances;
    using Balances for *;
    mapping(address => mapping (address => uint256)) allowed;

    event Transfer(address from, address to, uint amount);
    event Approval(address owner, address spender, uint amount);

    function transfer(address to, uint amount) public returns (bool success) {
        balances.move(msg.sender, to, amount);
        emit Transfer(msg.sender, to, amount);
        return true;


    function transferFrom(address from, address to, uint amount) public returns (bool success) {
        require(allowed[from][msg.sender] >= amount);
        allowed[from][msg.sender] -= amount;
        balances.move(from, to, amount);
        emit Transfer(from, to, amount);
        return true;

    function approve(address spender, uint tokens) public returns (bool success) {
        require(allowed[msg.sender][spender] == 0, "");
        allowed[msg.sender][spender] = tokens;
        emit Approval(msg.sender, spender, tokens);
        return true;

    function balanceOf(address tokenOwner) public view returns (uint balance) {
        return balances[tokenOwner];

Last updated