Smart Contracts

Updating Solidity code and Testing a Smart Contract

Books on the Blockchain

Publica Self Publishing

Goodbye Contracting

Hello brave new old world...

Ruby-Selenium Webdriver

In under 10 Minutes

%w or %W? Secrets revealed!

Delimited Input discussed in depth.

Wednesday, 3 July 2019

Ethereum - Updating and Testing a Raffle Smart Contract

This article is also available on Kauri (Ropsten Testnet).

Over on the Bitfalls website there’s a couple of great tutorials(1) for learning Solidity and Ethereum. The tutorials guide readers through the making of a Raffle. Now, the code is not meant to be bullet proof, but as a software tester by day the ‘gaps’ piqued my interest.

In this post I’m going to do two things; firstly provide a few updates to the code readers pointed out or that have become the more current way of doing things since Solidity version updates and secondly, to execute the code in the online tool, Remix, so we can see how it actually runs.

Naturally, the below makes more sense if you’ve either worked through the tutorials, will do or have just grabbed the code. Let’s crack on.

Code Updates
Firstly, let’s look at what needs a refresh since Bruno wrote the original articles. Open up the Blocksplit.sol file you’ve been working on. You can always get the completed script from their GitHub repository

Review the code for the randomGen() function from their last tutorial:

function randomGen() constant internal returns (uint256 randomNumber) { 
uint256 seed = uint256(block.blockhash(block.number - 200)); return(uint256(keccak256(block.blockhash(block.number-1), seed )) % players.length);

In here we can see the '… block.blockhash(block.number …' construct, this needs to be changed to read '… blockhash(block.number …'.

Additionally, the last line of the randomGen() function should be changed to use `abi.encodePacked` and the trailing space after seed removed. It will look like this:

return(uint256(keccak256(abi.encodePacked(blockhash(block.number-1), seed))) % players.length);

This will give a final code block for the randomGen() function of:

function randomGen() internal view returns (uint256 randomNumber) {
uint256 seed = uint256(blockhash(block.number - 200)); return(uint256(keccak256(abi.encodePacked(blockhash(block.number-1), seed))) % players.length);

One final change just so we don’t lose any test Ether is to change the address public charity to be one of your test accounts, make it the one you deploy the contract under. Account set-up is discussed next.

address public charity = put-the-full-address-here-for-your-test-acccount;

One last thing is to change the ‘Unix epoch’ time in the draw() function to something in the near past if it’s very current.

Set-up the Testing Environment
There’s a few things we need to have in place to test this contract effectively:
  • MetaMask
  • Three Ethereum Accounts
  • Remix open in a browser window
  • The updated contract code ready to deploy
Make sure the MetaMask browser extension is running in either of Brave(2) or Chrome.

We’ll need to have three Ethereum accounts available to us via MetaMask – one to act as the contract owner and two additional ones to act as the players. If you’ve not done so, read the Bitfalls MetaMask article that explains how to set up MetaMask and add accounts. You’ll need to get some free Ether from one of the faucet sites in order to play the raffle.

Remix is a free browser-based IDE for writing smart contracts in Solidity, then compiling and deploying them. It’s available at

Compile and Execute the Contract Code
The Remix UI was updated mid 2019 so may have a different look compared to other tutorials you’ve worked through - be sure to select ‘Solidity’ under the Environments section of the Home page before you start.

To the top-left, change the Compiler version to read 0.4.26+commit.4563 as from version 0.5.0 there were breaking changes to the Solidity codebase. This is also above the 0.4.20 compiler version we stated in the contract code, so the code will compile just fine.

Choose the Solidity environment and Compiler version

In Remix, click on the ‘File explorers’ icon, create a new file and call it 'Blocksplit.sol', then paste the updated contract code into the file and save it.

Create a new file for the contract code

Now click on the ‘Solidity compiler’ icon and hit ‘Compile Blocksplit.sol’

Compile the contract code

Finally, click the ‘Deploy & Run Transactions’ icon, we’ll use this tab to deploy and test our contract. We’ll deploy to the Ropsten test network and to do so we need to change a few things before we hit Deploy.
  • In the ‘Environment’ field select 'Injected Web3' from the dropdown
  • In MetaMask, switch to the ‘Ropsten Test Network’
  • Also in MetaMask, select the account you have chosen as the contract owner account 
Now hit the orange ‘deploy’ button to deploy the contract to Ropsten, accepting the MetaMask transaction window when it pops-up. This is charging the cost of writing to the blockchain.

Deploy the contract to Ropsten

Check the Deployed Contract and Interface
Now we’ve deployed the contract we’ll have a set of buttons that provide an interface to the contract elements, shown under ‘Deployed Contracts’. Click the arrow next to the contract name to show the set of buttons that give us an interface to the contract.

View the contract elements

Next to the contract name is also the contract address that can be copied and searched for on Etherscan against the Ropsten network. Copy the address shown and look up the Etherscan record. Between Etherscan and MetaMask we can readily see how the transaction details match up.

Matching transaction details

We can see that the ‘From’ address, Contract Creator address and the address we used in MetaMask all match. This shows us how organisations can deploy a contract, then use the msg.sender = owner code pattern to assign the ability to perform certain actions only to a given address; in this case the one that deployed the contract.

As a reminder, blue buttons read data and so are free of Gas, whereas orange buttons write data to the blockchain and so will cost us Gas.

Click on the blue ‘charity’ button and you’ll see a) no MetaMask window as we don’t need to pay anything and b) the address we assigned to the `address public charity` variable. Note the contract value is showing as ‘0 Ether’ as no raffle monies have been transacted yet.

Play the Raffle
Ordinarily, the public raffle elements we can get to would be wrapped in a Web3.js enabled webpage, using the ABI file, to give us a smart interface. However, for testing, the Remix interface is good enough.

Player One Plays
To play we need to switch to an alternate account in MetaMask, so we’re acting like the raffle’s Player One and not the owner. Open MetaMask and switch accounts now, that same account will be shown in Remix in the ‘Account’ field.
  • in the ‘Value’ field enter 0.1 and make sure ‘ether’ is selected
  • in the field next to the ‘play’ button, paste the address you’re using as Player One
  • hit the ‘play’ button and accept the MetaMask prompt to pay the fee plus gas
After a few seconds MetaMask will bring up a prompt stating the transaction went through. If we check the contract again on Etherscan, we’ll see it now has a second transaction worth 0.1 ETH from the address we’re using for Player One.

Player One Played

If you now enter '0' in the field next to ‘players’ it will return the address of Player One. This is because we declared address[] public players; at the start of our contract then players.push(_participant); in the play() function - which takes an address (as we tested above), then pushes it onto the players array.

A Quick Sanity Test
Something we can test now is clicking on the ‘draw’ button. The code here is that we can only run a draw if the number of winners is less than 2: require (winners.length < 2, "");. This is interesting as when we click ‘draw’ now it should work and indeed it does. If we enter `0` in the field next to the ‘winners’ button it will return the address of Player One.

It may be that we should change this code in two ways:
  • Change draw() to Require the msg.sender to be the owner of the contract so not just anyone can call the function
  • Set a Require of players.length == 2 to ensure two players are needed for a draw to happen
Player Two Plays
To play a second player is just like playing the first. Switch accounts, set the value to 0.1 ETH, add your Player 2 address into the ‘play’ field and hit ‘play’ as before.

Now in Etherscan we can see:
  • two transactions of 0.1 ETH which are the raffle ‘plays’
  • one transaction between these that are the possibly unwanted pressing of ‘draw’ by a player
Two Plays and one Draw

Both of the above can be proven using Etherscan’s logs:
  • Click on the ‘Txn hash’ for the draw (0 ETH transaction)
  • At the bottom of the page that opens, click on ‘Click to see More’
  • Under ‘Input Data’ check to see it says ‘Function: draw() ***’ 

Draw made by Player One

Repeat the steps above to check one of the Plays made by either player.

Play made by a Player 

However, we may have another potential issue. In the draw() function we have the line of players.length--; which with the line of code above it is a way to remove the winner from the list of players (so they don’t become winner number 2 as well as winner number 1, fair enough). We can test this too by entering a '0' or a '1' in the field next to ‘players’ and seeing what’s returned. We expect two player’s addresses but for index '1' we should get ‘0x0000000000000…’ which tells us Player One got removed from the players[] array (because when I tested, Player One won. It may be Player Two for you). OK, the code works, but the change suggested above might prevent this if we feel it’s an issue.

As we have clause in draw() that won’t allow us to send any ETH balance off to the charity address until winners.length == 2 we need another player to win. As it happens, we can just hit draw() again and watch our remaining player win.

Re-draw and Contract Payout
Go ahead and hit draw() for a second time, then refresh the Etherscan page for your contract. You’ll eventually see a new 0 ETH transaction for the second draw and the contract value is now 0 ETH. That proves the charity.transfer(address(this).balance); line in draw() must have worked – but where’s the transaction?

End of the Test Run

You’ll notice there’s a new tab in Etherscan called ‘Internal Txns’, our `transfer` of 0.2 ETH is recorded in there as it occurs as part of the code in the function, not a call from outside. The balance is sent to the address that was defined under the `charity` variable.

Transfer of balance to contract owner

We’ve seen that at every step of the way we can control how the contract is deployed, deploy it to a non-live blockchain such as the Ropsten Testnet, then carefully test out the contract functionality. Remix and Etherscan combined provide us with a host of features and information to allow us to test our code and check the results.

There are more tests we could add, but the core features have been checked here. We’ve also discovered there are some (expected) weaknesses in the code that could be fixed up. Overall, a good couple of tutorials and a great way to learn more about Solidity and Smart Contract development.

Until next time!

1) Tutorials: and 2) Brave Browser:

Tuesday, 2 July 2019

Blockchain - Books on the Ethereum Blockchain

This article is also available on the blockchain at Kauri (Ropsten Testnet).
Taking book publishing onto the Blockchain is the idea of the Publica project. However, since the ICO in November 2017, and like many blockchain oriented projects attempting to shake up traditional spaces and come out of the late 2017 crypto crash, it’s a project that launched well, is backed by knowledgeable and capable staff - but that hasn’t been as successful as a more traditional approach might have been. That said, the ‘traditional’ nature of book publishing has been in the process of a complete shakeup for many years, so adding in a blockchain solution was a natural and logical next step.
In the indie book publishing space there are now many alternatives to getting your book into brick-and-mortar shops, usually filled by publishers who were once the only pathway to authorial success. Today, tens of thousands of books are self-published by their authors every year, without ever coming near the traditional publishing houses. Books that cover a multitude of genres from fantasy, spy, thriller, adult, young adult, teen, cooking, car mechanics, computing and business to name a few. While high street shops like Barnes & Noble or Waterstones might be suffering, the market for books, particularly eBooks, has never been bigger. Whether readers are buying from the likes of Amazon or direct from an indie author - book sales are buoyant, despite the doom and gloom around book sales we often read about. In 2017, when Publica launched, the global publishing industry was estimated to be worth $261bn USD. Of this, books accounted for 46% or $121bn USD(1). Not an insignificant market to chase even single digits percentage share of.

Publica Book Catalogue

Enter Publica – ‘Blockchain for Publishing’, as the site tells us. Publica offers two routes to publishing; a book ICO for funding new publications or direct publishing of already completed manuscripts. There’s a page on Medium that Publica keep up to date with the current Book ICOs(2) so they can be learned about and contributed to. There’s an online store(3) and a mobile app(4) where users can access the store of available books, the reader’s own library of owned works and the wallet in which the Pebble tokens are held. Imagine the Kindle or Apple Books store, with an appropriate reader with built in shop that also shows your balance of funds. That’s what Publica have – same idea, just using crypto and blockchain.

At the time of the ICO, which ran from November 1st to 15th in 2017, Publica raised $1.04m USD(5) and have regularly stated in their various Telegram channels that the project’s success is not predicated on funding, which is good to hear. So, what’s preventing the project from seeing the success that was hoped for? Two things: it’s a cutting-edge solution that takes time to achieve adoption and secondly, it’s not in any way as straightforward to get started as buying a physical book or firing up your Kindle or other eReader. That said, eReaders were a strange phenomenon at one point but we all got used to them too, so there’s hope for Publica.
Publica is for the author who wants to regain control of their work, business and writing career. They will control exactly how their audience enjoys their content. There are no rules from Publica. The rules are just between you and your readers. - Josef Marc, CEO
Ethereum Blockchain, ETH, Pebble, BOOK tokens and Book ICO Contracts
The Publica solution is deployed on the Ethereum blockchain, which makes issuing the Pebble (PBL) ERC20 compliant token and the BOOK non-fungible token (NFT) the easy part. It also means authors and readers can interact with the underlying smart contracts using convenient tools such as a browser and MetaMask.

PBL’s are the fungible token that act as the internal currency for Publica. All books are priced in PBL and the tokens can be bought and sold on various exchanges and swap services for ETH or using a credit card.

BOOK tokens are the interesting one; every book that you buy is actually acquired by purchasing a BOOK token. This represents the tokenisation of the book. You pay PBL for the BOOK tokenised asset and get that in your Publica library. Think of it as an access key to a copy of the book you own that’s stored on the blockchain.

For each Book ICO, Publica deploy a smart contract that has the unique details of your book ICO. That includes obvious things such as the title, but also details of hard and soft cap, the number of PBLs you want to sell each BOOK token for and so on. This is interesting as it’s a potential bottleneck to growth due to it being a manual process.

Running a Book ICO
The entry point that Publica seem to promote most actively via their website(6) is the funding of book writing and creation by running a Book ICO. This is a novel idea, akin to running a Kickstarter project to get funding in advance of working on whatever the project is about. Authors are required to provide details for a book ICO page and then get promoting it in order for potential readers to find the page, buy some PBL to buy a BOOK token, then await the ICO ending and the book being written.

Buying a Published Book
When a published book is added to the Publica library, a reader simply has to view the library via the mobile app or online store, find a book they like and purchase it using PBL tokens stored in their connected wallet or due to a recent change, they can now pay with their credit card.

Screenshots from the Publica App

Benefits over Traditional Publishing
Two major benefits that are gained by using Publica are that authors acquire Borderless Publishing and Censorship Resistance. Never again can a book be banned from a given country and the contents of that book cannot be altered once published. Not even by Publica - this is a paradigm shift. Let's get this clear - never in human history has this been the case and could fundamentally shift the way publishing works.

There is a caveat to the process of getting a completed book published – it’s entirely manual. You fill in a form, send it to an admin (the amazing, hardworking Alex!), they create a contract and deploy it. All manual. If Publica ever had hundreds of authors hit them, they’d be backlogged overnight. Though I suspect they'd love the challenge. The Book ICO is also a manually created campaign and manually written and deployed contract. Neither have been an issue so far, the team are pretty efficient and accurate, but growth could see this needing to be addressed.

Benefits over Typical eBook Publishing
Once often overlooked issue with buying eBooks on say the Kindle, is you don’t actually own them. What you are granted is the right to host a copy of the book on your device and retain it in a library you can access. Amazon can, and have, deleted access to the books from people’s devices. Not so with Publica. No one can delete the data on the blockchain. Once you buy it, you own it.

What’s slowing the Publica project?
In short, adoption by new users. In both cases, the work on deciphering the path-way to buying books, via an ICO or straight from the Shop, is definitely pushed to the buyer – and that work required to get going with Publica, besides the relative newness of blockchain that also needs to be understood, is above all else slowing the project’s growth. Sure they have good FAQs, but it’s a big hurdle the likes of Amazon didn’t put in front of their own Kindle device and store. 

Before they even get to Publica, the potential readers have to learn about the blockchain first. They need to understand what Ethereum and Pebble are, how to use crypto exchanges to get the PBL tokens into a wallet, how to use that wallet and what buying a BOOK, as an NFT version of the eBook they want entails, the pros and the cons. Once that’s out of the way the App or online shop is no more complex than hitting the Google Play store, Kindle eBook Store or Apple’s Book store on an appropriate device. Still, imagining a flood of new customers that would joyously surmount that first part was a bit optimistic by the project team, to say the least.

The move to accepting card payments was both a needed change, to ease adoption by the general public, but also a great way to just get people buying books and become familiar with Publica. Grab the app, search the store, buy your books. Done. However, that raises the question of what the point of the internal PBL token is now?

The Trials and Future Purpose of PBL
Pebbles or PBLs, have been through a rocky time. They were intended as the internal currency for making BOOK token purchases, rewarding authors and something that the investors in Publica, via buying of the PBL, could be rewarded through as Publica became more successful.

Since 2017, PBL have gone down from an ICO price of $0.10 to a current average price of $0.0188. Trading volumes have hit the floor as current holders HODL, potential investors look for something more active to invest in and Publica readers switch to using their credit cards. Being able to buy BOOK tokens directly via fiat is great news for readers and authors, but bad news for PBL holders already stung by the decline in value since the ICO.

To add to this, finding a place to trade PBL has also proven difficult, since PBLs were delisted off KuCoin, the main exchange used since PBLs became available. Currently, the best place to find PBLs appears to be ForkDelta or Bilaxy(7) where there is low trading volume but a high amount of tokens that can be bought quite cheaply. Why they are needed now still remains a question. Investment? Perhaps. Funding the project? Possibly. Central to making the project work technically? Apparently, not anymore. PBL is still used to calculate the internal price for BOOKS and the total cost of purchase, i.e. including gas, transaction fees, etc., and if you sell a BOOK token on the Publica secondary market you’ll get PBL back, so you want it to be worth something.

Only one possible idea comes to mind for investment; HODL a large enough amount of PBL that when Publica is bought out by someone like Amazon, then PBL shoots up in value and you can cash in. That’s not trading advice though so DYOH. Right now, it looks like PBL could be dropped altogether, but we’ll see. Not reassuring for those HODLing since 2017, but as the saying roughly goes; the pioneers get the arrows, the settlers the spoils.

The Publica project is a great example of a meaningful use case being applied to the use of blockchain. It’s meaningful because resolving issues such as censorship, borderless publishing and permanent ownership are serious issues that need addressing. A database of books controlled from the centre, by a company beholden to worldwide legal systems isn’t the answer. Could Publica rise to the challenge?

Publica has it's strengths, but also some significant weaknesses that thankfully are being addressed. More books need to be published directly, ideally by known authors. Landing a deal with a known publishing house or a store such as Barnes & Noble or Waterstones would be an incredible boost. As for Book ICOs – they should be left on the backburner for now, they are rarely successful, so not the way to build the Publica Store of books in the short term. Holding PBL seems an uncertain prospect at this time as, beyond being a means for fundraising at the ICO stage and as a means for internal accounting, there’s no real need for them. That said, they could also be the one that 'moons' once he project really gets going.

Overall, it’s early days for this exciting project, but there’s uncertainty as to when it will see the growth many feel it deserves and when the traditional model of self-publishing can be replaced with the help of the blockchain. Could Publica be the next Amazon or arm of Google. It's a possibility, better still they might just become the Publica they want to be, now that would be something to be part of.


References: 1. 2. Book ICO List: 3. Book Shop: 4. Mobile App: 5. Publica ICO: 6. Publica Website: 7. ForkDelta:!/trade/PBL-ETH. Bilaxy:

I published my debut novel, The Hannover Game, on Publica.