This website uses cookies to better the user experience of its visitors. Where applicable, this website uses a cookie control system, allowing users to allow or disallow the use of cookies on their computer/device on their first visit to the website. This complies with recent legislative requirements for websites to obtain explicit consent from users before leaving behind or reading files such as cookies on a user’s computer/device. To learn more click Cookie Policy.

Privacy preference center

Cookies are small files saved to a user’s computer/device hard drive that track, save, and store information about the user’s interactions and website use. They allow a website, through its server, to provide users with a tailored experience within the site. Users are advised to take necessary steps within their web browser security settings to block all cookies from this website and its external serving vendors if they wish to deny the use and saving of cookies from this website to their computer’s/device’s hard drive. To learn more click Cookie Policy.

Manage consent preferences

These cookies are necessary for the website to function and cannot be switched off in our systems. They are usually only set in response to actions made by you which amount to a request for services, such as setting your privacy preferences, logging in or filling in forms. You can set your browser to block or alert you about these cookies, but some parts of the site will not then work. These cookies do not store any personally identifiable information.
These cookies allow us to count visits and traffic sources so we can measure and improve the performance of our site. They help us to know which pages are the most and least popular and see how visitors move around the site. If you do not allow these cookies we will not know when you have visited our site, and will not be able to monitor its performance.
Cookies list
Name _rg_session
Provider rubygarage.org
Retention period 2 days
Type First party
Category Necessary
Description The website session cookie is set by the server to maintain the user's session state across different pages of the website. This cookie is essential for functionalities such as login persistence, ensuring a seamless and consistent user experience. The session cookie does not store personal data and is typically deleted when the browser is closed, enhancing privacy and security.
Name m
Provider m.stripe.com
Retention period 1 year 1 month
Type Third party
Category Necessary
Description The m cookie is set by Stripe and is used to help assess the risk associated with attempted transactions on the website. This cookie plays a critical role in fraud detection by identifying and analyzing patterns of behavior to distinguish between legitimate users and potentially fraudulent activity. It enhances the security of online transactions, ensuring that only authorized payments are processed while minimizing the risk of fraud.
Name __cf_bm
Provider .pipedrive.com
Retention period 1 hour
Type Third party
Category Necessary
Description The __cf_bm cookie is set by Cloudflare to support Cloudflare Bot Management. This cookie helps to identify and filter requests from bots, enhancing the security and performance of the website. By distinguishing between legitimate users and automated traffic, it ensures that the site remains protected from malicious bots and potential attacks. This functionality is crucial for maintaining the integrity and reliability of the site's operations.
Name _GRECAPTCHA
Provider .recaptcha.net
Retention period 6 months
Type Third party
Category Necessary
Description The _GRECAPTCHA cookie is set by Google reCAPTCHA to ensure that interactions with the website are from legitimate human users and not automated bots. This cookie helps protect forms, login pages, and other interactive elements from spam and abuse by analyzing user behavior. It is essential for the proper functioning of reCAPTCHA, providing a critical layer of security to maintain the integrity and reliability of the site's interactive features.
Name __cf_bm
Provider .calendly.com
Retention period 30 minutes
Type Third party
Category Necessary
Description The __cf_bm cookie is set by Cloudflare to distinguish between humans and bots. This cookie is beneficial for the website as it helps in making valid reports on the use of the website. By identifying and managing automated traffic, it ensures that analytics and performance metrics accurately reflect human user interactions, thereby enhancing site security and performance.
Name __cfruid
Provider .calendly.com
Retention period During session
Type Third party
Category Necessary
Description The __cfruid cookie is associated with websites using Cloudflare services. This cookie is used to identify trusted web traffic and enhance security. It helps Cloudflare manage and filter legitimate traffic from potentially harmful requests, thereby protecting the website from malicious activities such as DDoS attacks and ensuring reliable performance for genuine users.
Name OptanonConsent
Provider .calendly.com
Retention period 1 year
Type Third party
Category Necessary
Description The OptanonConsent cookie determines whether the visitor has accepted the cookie consent box, ensuring that the consent box will not be presented again upon re-entry to the site. This cookie helps maintain the user's consent preferences and compliance with privacy regulations by storing information about the categories of cookies the user has consented to and preventing unnecessary repetition of consent requests.
Name OptanonAlertBoxClosed
Provider .calendly.com
Retention period 1 year
Type Third party
Category Necessary
Description The OptanonAlertBoxClosed cookie is set after visitors have seen a cookie information notice and, in some cases, only when they actively close the notice. It ensures that the cookie consent message is not shown again to the user, enhancing the user experience by preventing repetitive notifications. This cookie helps manage user preferences and ensures compliance with privacy regulations by recording when the notice has been acknowledged.
Name referrer_user_id
Provider .calendly.com
Retention period 14 days
Type Third party
Category Necessary
Description The referrer_user_id cookie is set by Calendly to support the booking functionality on the website. This cookie helps track the source of referrals to the booking page, enabling Calendly to attribute bookings accurately and enhance the user experience by streamlining the scheduling process. It assists in managing user sessions and preferences during the booking workflow, ensuring efficient and reliable operation.
Name _calendly_session
Provider .calendly.com
Retention period 21 days
Type Third party
Category Necessary
Description The _calendly_session cookie is set by Calendly, a meeting scheduling tool, to enable the meeting scheduler to function within the website. This cookie facilitates the scheduling process by maintaining session information, allowing visitors to book meetings and add events to their calendars seamlessly. It ensures that the scheduling workflow operates smoothly, providing a consistent and reliable user experience.
Name _gat_UA-*
Provider rubygarage.org
Retention period 1 minute
Type First party
Category Analytics
Description The _gat_UA-* cookie is a pattern type cookie set by Google Analytics, where the pattern element in the name contains the unique identity number of the Google Analytics account or website it relates to. This cookie is a variation of the _gat cookie and is used to throttle the request rate, limiting the amount of data collected by Google Analytics on high traffic websites. It helps manage the volume of data recorded, ensuring efficient performance and accurate analytics reporting.
Name _ga
Provider rubygarage.org
Retention period 1 year 1 month 4 days
Type First party
Category Analytics
Description The _ga cookie is set by Google Analytics to calculate visitor, session, and campaign data for the site's analytics reports. It helps track how users interact with the website, providing insights into site usage and performance.
Name _ga_*
Provider rubygarage.org
Retention period 1 year 1 month 4 days
Type First party
Category Analytics
Description The _ga_* cookie is set by Google Analytics to store and count page views on the website. This cookie helps track the number of visits and interactions with the website, providing valuable data for performance and user behavior analysis. It belongs to the analytics category and plays a crucial role in generating detailed usage reports for site optimization.
Name _gid
Provider rubygarage.org
Retention period 1 day
Type First party
Category Analytics
Description The _gid cookie is set by Google Analytics to store information about how visitors use a website and to create an analytics report on the website's performance. This cookie collects data on visitor behavior, including pages visited, duration of the visit, and interactions with the website, helping site owners understand and improve user experience. It is part of the analytics category and typically expires after 24 hours.
Name _dc_gtm_UA-*
Provider rubygarage.org
Retention period 1 minute
Type First party
Category Analytics
Description The _dc_gtm_UA-* cookie is set by Google Analytics to help load the Google Analytics script tag via Google Tag Manager. This cookie facilitates the efficient loading of analytics tools, ensuring that data on user behavior and website performance is accurately collected and reported. It is categorized under analytics and assists in the seamless integration and functioning of Google Analytics on the website.

How To Build an Ethereum Smart Contract for a Blockchain Marketplace

  • 114708 views
  • 11 min
  • Jun 14, 2018
Ihor D.

Ihor D.

Ruby/JS Developer

Gleb B.

Gleb B.

Copywriter

Share

Smart contracts can literally revolutionize the way people and businesses interact. However, this technology is in its early days, so many software developers don’t have a clear understanding of how to create and execute smart contracts. No matter what technology you work with, being able to create smart contracts gives you a competitive advantage.

We’ve decided to shed light on this subject and show you how to build a smart contract on the Ethereum blockchain platform.

Ethereum as a platform for building decentralized applications

There are several blockchain platforms that allow developers to create and execute smart contracts, but we’re going to opt for Ethereum, the biggest and most mature platform created specifically for this purpose. It’s the first blockchain platform that can execute arbitrary code, so theoretically you can run any program on Ethereum.

The Ethereum blockchain is a powerful distributed global infrastructure that enables you to complete various projects with the help of smart contracts.

  • Create your own cryptocurrencies

    Ethereum allows you to create a tradable token that you can use as a new currency or virtual share. These tokens use a standard coin API, meaning they’re compatible with any wallet on the Ethereum blockchain.

  • Raise funds

    You can use smart contracts for fundraising on the Ethereum blockchain. You can create a smart contract that specifies a goal and a deadline so if you fail to achieve this goal, all donations will automatically be returned to donors without any commissions or disputes.

  • Build virtual organizations

    You can write a smart contract that creates a blockchain-based organization; you can then add people to your organization and set voting rules. Members of your organization will be able to vote and if the required number of votes is reached, your smart contract will execute automatically.

  • Develop decentralized applications

    Ethereum allows you to build fault-tolerant and secure decentralized applications (read: applications that run on the blockchain) that provide transparency and remove intermediaries.

How the Ethereum platform executes smart contracts

Before diving into building an Ethereum smart contract, you should have a clear understanding of what’s under the hood of the Ethereum blockchain platform and how exactly it executes smart contracts. So let’s go from the bottom up and start from the execution environment.

  • Ethereum Virtual Machine (EVM)

    To execute arbitrary code, Ethereum developed the EVM, a special virtual machine that’s an interpreter for the assembly language. The EVM’s functionality is more limited than that of similar virtual machines; for example, it can’t make delayed calls or requests on the internet or generate random numbers, so it’s simply a state machine. Writing programs in assembly language makes no sense, so Ethereum needed a programming language for the EVM.

  • Solidity

    Solidity is the smart contract language on Ethereum. It’s a general-purpose programming language developed on top of the EVM. Just like other object-oriented languages, Solidity uses a class (contract) and methods that define it. Theoretically, Solidity allows you to perform arbitrary computations, but its main purpose is to send and receive digital tokens as well as store states. In terms of syntax, Solidity was influenced by JavaScript, C++, and Python so experienced programmers can understand its syntax easily.

    To write an Ethereum smart contract properly, you should carefully read the documentation to learn more about Solidity and how to program with it.

  • Gas

    On the Ethereum blockchain, each smart contract is processed by one miner and the result of this operation is a block that’s added to the Ethereum blockchain. Miners must be rewarded for their efforts, so executing any smart contract on the EVM requires a fixed payment called gas. You should specify the amount of gas you want to spend for executing any smart contract you create. The more complicated the smart contract, the more gas it requires.

Getting started with an Ethereum smart contract

Time to get down to work and build a smart contract!

We’ve decided to develop a basic Ethereum smart contract for a blockchain-based marketplace, but you’re welcome to come up with your own ideas for smart contracts.

How Smart Contracts on Blockchain Marketplace Work

To implement an Ethereum smart contract for a blockchain marketplace, you need the following toolkit:

  • Node.js − A JavaScript runtime environment for server-side programming. You need Node.js for testing the functionality of your Ethereum smart contract and ensuring its proper and secure operation. Along with Node.js, you should install a package manager such as Yarn.
  • Truffle − A popular Ethereum development framework that allows you to write and test smart contracts. Truffle is written in JavaScript and contains a compiler for the Solidity programming language.Truffle Сontract is a JavaScript library that facilitates importing of compiled smart contracts.
  • Ganache CLI − An Ethereum remote procedure call (RPC) client within the Truffle framework; formerly known as TestRPC.
  • Web3.js − An Ethereum JavaScript API that communicates with the Ethereum network through RPC calls.
  • Parity − A fast and secure Ethereum client for managing accounts, tokens, and so on.
  • Visual Studio Code − A functional code editor; in fact, you’re welcome to use any other editor.

Step-by-step guide to building a smart contract on Ethereum

Writing a smart contract on Ethereum may seem simple, but you should make sure your contract functions properly and has no vulnerabilities, so we recommend covering all logic with automated tests.

We’re going to split this smart contract tutorial into four steps. During the first three steps we’re going to write and test the code, while in the last step we’re going to deploy the contract on the Ethereum blockchain.

Smart Contract Under the Hood

Let’s get started.

Step #1: Introducing two parties to an Ethereum smart contract

Any smart contract is concluded by two sides. Since we’re building a smart contract for a marketplace, we’re going to have two roles:

  • The client, who needs to get some home service done.
  • The tasker, who completes a task and gets paid for it.

A client pays a tasker for fulfilling a task, so you should add a payment amount to the smart contract as well; we called it payAmount.

Before coding these two roles and the payment amount into the smart contract, let’s write an automated unit test with JavaScript:

Now it’s time to implement exactly the same logic to write the actual smart contract with Solidity:

To find out whether your Solidity code is correct, run the test in Truffle using this code (it’s the same for all three steps):

The smart contract must pass the tests, otherwise there’s a mistake in your code.

Step #2: Enabling a client to transfer money to a smart contract

A smart contract acts like a separate account that can either send money to a tasker or send it back to a client. But first, a client must be able to send money to the smart contract. At this step, you need to add this functionality to the smart contract.

As usual, start from updating the test file. You should specify that nobody but a client can transfer money to a smart contract and that it’s impossible for anyone to increase the payAmount:

Now update the smart contract by adding the code that allows a client to transfer money to it:

Don’t forget to run tests against the smart contract to check if everything is okay.

Step #3: Allowing a smart contract to transfer money to a tasker

Finally, your smart contract must be able to automatically send money to a tasker as soon as a client confirms that the task has been completed. To implement this functionality, we need to introduce a new role in the smart contract – a deployer, which is a web application on your blockchain marketplace – and specify that only a deployer can initiate a transfer of money to a tasker. Also, make sure that the payAmount gets nullified once it has been sent to a tasker.

Let’s first implement all this logic in tests; you have to make it impossible for a deployer or any other third party to trigger a payAmount transfer from the smart contract to a tasker. At this step, you should get a long and detailed test file looking something like this:

Now you should add this logic to the smart contract itself: introduce a deployer and allow it to transfer money to a tasker. The full smart contract we built looks like this:

Finally, to check that the smart contract contains no errors, test it in Truffle.

Step #4: Deploying your smart contract

The smart contract in Solidity is ready so there’s one final step − compile and then deploy it. Since this is a tutorial, deploying the contract on the Ethereum network itself makes no sense, so we’re going to do it in Ropsten, a popular test network for Ethereum.

This is actually the most difficult step in our tutorial, so we’re going to split it into several sub-steps:

Create Ethereum wallets

There are three roles in our smart contracts, so to test if everything works, we need to create three wallets on Ethereum: for the client, for the tasker, and for the depolyer respectively. Needless to say, the deployer’s wallet is going to be the same for all smart contracts in our decentralized marketplace, while the client’s and deployer’s wallets will be different for each smart contract.

Get Ether on the Ropsten testnet

Newly created Ethereum wallets have a balance of zero ether, so to carry out a smart contract we need to get some ether. This is quite simple, as we’re deploying the smart contract on the Ropsten testnet.

There are several ways to get free test ether. Let’s use the Metamask plugin (we used the version for Google Chrome). Metamask is an Ethereum extension that allows you to work with decentralized applications right in your browser. Import a Metamask account and add the three wallets to it. Then, visit https://faucet.metamask.io/ and request free ether; however, be prudent as you can only get a limited number of free ether per account.

The logic of our smart contract works like this: the money is transferred from a client to a smart contract, then automatically sent to a tasker. Therefore, we need our eth in the client’s wallet.

Compile the smart contract with Truffle

We’ve already built a smart contract written in Solidity, but it should be turned into a .json file for deployment. Use Truffle to compile your smart contract; it will create a .json file that you can call whatever you want (we called it OddjobPayContract.json).

Run a deployment script

To deploy your smart contract on the Ropsten testnet, we produced the following script in JavaScript:

Execute your smart contract

Once your smart contract is deployed, you can execute it. To do this, you need to specify the wallets for the client, tasker, and deployer and the reward for the tasker.

Keep in mind that deploying a smart contract costs a specific amount of gas, so make sure to specify the amount of gas you’re including in your smart contract. If a smart contract requires less gas than you provide, the rest will be returned to you. But if the execution of a contract requires more gas, it will simply fail with the “out of gas” error. You can use the eth_estimateGas method to estimate the amount of gas it will require to deploy your smart contract. Unfortunately, this only provides an estimate and the actual amount of gas can be higher, so it’s always better to include more gas. Keep in mind that the lower the gas limit you provide, the lower the priority your smart contract will have on the Ethereum network (unless you increase the gas price), and it’s possible that web3 will return an error telling you that your transaction hasn’t been mined within 50 blocks. In this case you should either include more gas or simply use the gas limit from the latest successfully mined block.

Finally, execute the smart contract. In some time, you can check the balance in all three wallets to find out whether everything worked.

Final thoughts

Smart contracts have huge potential. Not only do they streamline transactions, they can revolutionize whole industries such as real estate, banking, ecommerce, and healthcare. We’ve shown how you can build a small and quite simple smart contract, but you can try creating more sophisticated contracts. If you’re facing challenges developing a smart contract, you can check out our full code in this repository on GitHub.

CONTENTS

Authors:

Ihor D.

Ihor D.

Ruby/JS Developer

Gleb B.

Gleb B.

Copywriter

Rate this article!

Nay
So-so
Not bad
Good
Wow
20 rating, average 4.6 out of 5

Share article with

Comments (0)

There are no comments yet

Leave a comment

Subscribe via email and know it all first!