# Introduction to Smart Contracts and Web3.js
We are going to start with laying out the skill-sets and the terminology surrounding DApps. If you understand the terminology and basics and want to get to the curated resources, [jump there by clicking here](#Developing-Smart-Contracts-with-Solidity).
## What is Ethereum and Smart Contracts? (Beginner)
Ethereum is a network of thousands of nodes that are running all over the world. Anyone can run a node in that network, and each node is running the Ethereum virtual machine which implements the rules of the system. Each node downloads all transactions that have happened ever (kinda) and has the balance of every Ethereum account. An Ethereum account is represented by an Ethereum address, a balance, a public key, and a private key.
An Ethereum account can transfer part of its balance to another account, but you need to sign the transaction with the private key. Once you create the transaction in a node, it will propagate to the other nodes. Therefore, if you lose/publish your private key, anyone can transfer balance out of that account.
You can write a contract in Solidity and store it in the Ethereum network, and it will be assigned an address. Once a contract has been stored at an address, it can't be modified. Anyone can interact with a contract at an address by invoking its functions from any Ethereum node.
You can publish a web app to help users interact with a contract at a particular address. The web app will use the web3.js library to help it interact with the Ethereum network.
For a more comprehensive overview of Cryptocurrencies and Blockchain, please check out [this Hackernoon guide](https://hackernoon.com/the-ultimate-guide-to-understanding-blockchain-and-cryptocurrencies-f37cf4c0043).
Building dapps like [P3D](https://powh.io) requires multiple skill-sets, the most prominent two are:
* **Solidity Smart Contract Engineers (Solidity)** - At the heart of P3D is an exchange that can accept Ethereum and provide P3D tokens, selling tokens for Ethereum, and allowing the withdrawal or reinvestment of rewards. This functionality is powered by an underlying smart-contract deployed to the Ethereum blockchain. Smart contracts on the Ethereum network are developed with a special language called [Solidity](https://medium.com/@Xourse/solidity-for-beginners-bc6374a0c0c7). The code for this contract can be [found on the blockchain through Etherscan](https://etherscan.io/address/0xb3775fb83f7d12a36e0475abdd1fca35c091efbe#code).
For more details on this, check [this FAQ section](https://powh3d.hostedwiki.co/pages/FAQ#what-skill-sets-are-needed-to-develop-a-project-like-p3d).
Let's define the basics of a few terms before continuing on in this guide:
* **Blockchain** - A [complete digital record of transactions](https://hackernoon.com/the-ultimate-guide-to-understanding-blockchain-and-cryptocurrencies-f37cf4c0043) (distributed ledger) that have happened that cannot be easily forged or altered. Simply put, a distributed database of currency transactions. The name refers to the “chain” of data chunked into discrete "blocks", each containing transaction history.
* **Transaction** - Blockchains and smart contracts operate based on discrete units of data that are recorded onto a digital ledger (chain). Transactions on Ethereum tend to consist of a target contract or address, an amount of Ether, and a custom "message" which can contain arbitrary info.
* **Smart Contract** - Think of [smart contracts as a computer program](https://medium.com/@tjayrush/smart-contracts-are-immutable-thats-amazing-and-it-sucks-e0fbc7b0ec16) that runs on the Ethereum blockchain which, once deployed, can not have code directly modified. This program can do most anything but is often used to accept digital currency and then coded to perform specific purposes (games, arbitration, etc).
* **Solidity** - This is the [programming language](https://blockgeeks.com/guides/solidity/) that is used to develop smart contracts for the Ethereum blockchain.
* **Remix** - [Remix is a suite of tools](https://remix.ethereum.org/) to interact with the Ethereum blockchain in order to debug transactions, stored in this Git repository. This can be used to test contracts, deploy contracts and debug when your contracts are going wrong.
* **Front-end** - Front-end refers to the web pages that users are actually interacting with. These consist of [HTML/CSS/JS](http://www.htmldog.com/guides/) and usually data is displayed from the contract and actions can be taken there as well.
* **Mainnet/Testnet** - These refer to [two different Ethereum networks with separate chains](https://ethereum.stackexchange.com/a/6282). Mainnet is the primary live Ethereum blockchain (real "money"). Testnet is any testing environment where fake money can be used instead to test contracts.
* **Functions** - Smart contracts are composed of a few [different elements inside of them](http://solidity.readthedocs.io/en/v0.4.21/structure-of-a-contract.html). Functions are specific things that can be activated on the contract based on incoming transactions. They modify the state of the contract and can perform various operations.
* **Events** - Smart contracts contain [custom events that can notify of specific things happening](http://solidity.readthedocs.io/en/v0.4.21/contracts.html#events). Events are used most commonly to notify a website front-end as something happens in real-time (i.e buys/sells).
## Use Cases
There are a few major steps to producing functional dapps of your own. They follow a checklist like:
1. Think through and design your product idea
2. Write a first pass of your Solidity contract (state variables, functions, events)
3. Test your contract manually on [Remix](https://remix.ethereum.org/)
4. Make tweaks and tune your contract to fix any issues
5. Ask others to audit your contract to see how you can improve
1. Build a website with buttons to take actions, and sections to display data
2. Connect the website to contract using Web3.js to send and receive data
3. Read data from contract and display that data in the UI
4. Write data to contract and call functions as user takes actions
5. Subscribe to real-time events from contract and handle them in the UI
The details of each of these steps are described in the curated resources below.
## A Warning to Developers
Blockchain technologies and smart contracts are still very nascent technology and are different from other types of more traditional web/database programming. As a result, you can often get fooled into thinking you understand more than you currently do about contract design, security and deployment.
Please remember that smart contracts that accept real mainnet Ethereum **should never ever be hastily deployed**. Do not make the mistake of deploying an untested contract and accepting real Ethereum on the mainnet with a badly developed contract. Instead, **spend your time for a while locally testing** and testing on testnets before you ever accept even a small amount of real Ethereum.
Take your time and make sure that you understand things correctly. When deploying contracts, always **follow a clear and responsible test plan**. Test locally, ask others to audit your contracts, push to a testnet, have friends test on testnet. Do everything you possibly can to ensure you have a robust, secure and functioning contract before ever deploying to the main network. You owe this to yourself and to anyone that trusts your contract enough to send ETH.
## Learning to Code (No Experience)
* [Building Your First Webpage](https://learn.shayhowe.com/html-css/building-your-first-web-page/)
* [Refresher on HTML/CSS](https://www.khanacademy.org/computing/computer-programming/html-css)
You can also check out [freecodecamp](https://www.freecodecamp.org/). These resources will give you the foundations needed to begin developing Dapps with the resources listed below.
## Developing Smart Contracts with Solidity
Smart contracts are computer programs that runs on the Ethereum blockchain which, once deployed, can not have code directly modified. This program can do most anything but is often used to accept digital currency and then coded to perform specific purposes (games, arbitration, etc). Smart contracts hold funds securely based on their instructions (unless exploits are introduced in the code itself).
There are a few key constructs to Solidity contracts as [outlined here](http://solidity.readthedocs.io/en/v0.4.21/structure-of-a-contract.html). The most important of which are: **state variables** (values which are stored in contract storage and change over time), **functions** (methods or subroutines that modify state based on incoming transactions), **events** (contracts can send/emit custom notifications out in real-time).
1. If you are interested in learning about Solidity or DApps, we recommend you start with [CryptoZombies](https://cryptozombies.io/) which is a great interactive tutorial which teaches you to code Ethereum DApps through building your own game.
2. For a nice introduction, watch videos 1 and 2 of [this 9-part series by DesignCourse](https://www.youtube.com/watch?v=KU6bvciWgRE&list=PL0lNJEnwfVVMuX2Ds19Wj_7Mcze3FDJr3). You'll want to start getting familiar with [Remix](https://remix.ethereum.org/) which is the easiest way to deploy and test solidity contracts.
3. You can also check out this other [6-part video series on creating your first Solidity Contract](https://www.youtube.com/watch?v=4Taej55zNY4&list=PLUMwusiHZZhpf8ItZBkR95ekkMGNKvuNR). For a deeper dive, check this [27-part video playlist which is a deeper dive](https://www.youtube.com/watch?v=v_hU0jPtLto&list=PL16WqdAj66SCOdL6XIFbke-XQg2GW_Avg) or this [2-hour overview from Dapp University](https://www.youtube.com/watch?v=3681ZYbDSSk).
4. Then work through [the first 3-parts of this hackernoon tutorial](https://hackernoon.com/ethereum-development-walkthrough-part-1-smart-contracts-b3979e6e573e) focused on creating a smart contract which goes through the same concepts above but in a written tutorial form. You'll want to make sure you revisit the same concepts a few different times, working through and coding out the examples yourself, so they begin to click.
To get familiar with how more complicated contracts such as [P3D](https://powh.io) look like, check this [hour long detailed code review of P3D](https://www.youtube.com/watch?v=gDpOTL_KKys&feature=youtu.be) by @RockHardMeat. Take special notice as he goes through and [follow along using the source code](https://etherscan.io/address/0xb3775fb83f7d12a36e0475abdd1fca35c091efbe#code).
Check [this Awesome-Solidity github repo](https://github.com/bkrem/awesome-solidity) for an extended list of relevant Solidity tools and resources.
**Paid Solidity Courses**
In addition, here are a few paid courses available:
* [Udemy Ethereum Course](https://www.udemy.com/ethereum-and-solidity-the-complete-developers-guide/) - Full video course on developing Solidity smart contracts on the Ethereum network.
## Smart Contract Security Auditing
Given that smart contracts, once deployed, can never be directly modified to patch bugs or exploits, developers must be extra careful to properly review and audit their code for vulnerabilities and bugs. The importance of this cannot be overstated.
Failure to properly audit and review smart contracts **could result in a significant loss of Ethereum (your own or others)** by anyone using the Contract on the Main Network. A few resources which can help you understand security are below:
* [Ethereum Smart Contract Security Best Practices](https://consensys.github.io/smart-contract-best-practices/) - Great starting resource to [understand common vulnerabilities](https://consensys.github.io/smart-contract-best-practices/known_attacks/) and how to ensure your contracts are reasonably secure.
* [Capture the Ether](https://capturetheether.com/) - Capture the Ether is a game in which you hack Ethereum smart contracts to learn more about security in Solidity.
* [Ethernaut Zeppelin Challenges](https://ethernaut.zeppelin.solutions/) - Wargame played on the Ethereum Virtual Machine. Each level is a smart contract that needs to be 'hacked' in order to advance.
* [Reviewing a Solidity Contract Article](https://medium.com/@merunasgrincalaitis/how-to-audit-a-smart-contract-most-dangerous-attacks-in-solidity-ae402a7e7868) - Article walks through how a more formal contract audit works.
* [Audit Checklist](https://github.com/cryptofinlabs/audit-checklist) - Handy check-list to follow to validate your contract against common vulnerabilities.
* [How to Audit a Contract](https://www.devteam.space/blog/how-to-audit-a-smart-contract-a-guide/) - Handy guide to how auditing works.
In addition to learning about contract security yourself, you can also check out other methods to get your contract audited:
* [Solidified](https://solidified.io/) - Platform centered around auditing contracts
* [SmartDec](http://smartcontracts.smartdec.net/services-and-products) - Professional auditors, that also built a [free analysis tool](https://tool.smartdec.net/).
* [CoinFabrik](https://www.coinfabrik.com/) - Professional auditing services
* [Experfy](https://www.experfy.com/hire/smart-contract-audits) - Marketplace for finding smart contract auditors
Make sure to take security audits seriously before and during the Testnet, and far in advance of even considering a Main Network deployment.
## Testing Smart Contracts on the Ropsten Test Network
When testing contracts, you'll want to **first deploy them to the ropsten testnet** to try them out. This is fairly simple to do. Follow [this tutorial](https://medium.com/swlh/deploy-smart-contracts-on-ropsten-testnet-through-ethereum-remix-233cd1494b4b) on deploying to ropsten through [Remix](https://remix.ethereum.org/).
Ropsten ETH is free to test with. Just [go to this faucet](http://faucet.ropsten.be:3001/) to receive as much test ETH as you need to try out your applications.
You'll be using [web3.js](https://github.com/ethereum/web3.js/) to interact between your website UI and smart contracts.
1. First, watch through [this 9-part series](https://www.youtube.com/watch?v=KU6bvciWgRE&list=PL0lNJEnwfVVMuX2Ds19Wj_7Mcze3FDJr3). I would watch only some of them, skim the rest and maybe on 2x speed at times. Part 1 and 2 are on the backend contract. You can read [part 3](https://coursetro.com/posts/code/99/Interacting-with-a-Smart-Contract-through-Web3.js-(Tutorial)) and [part 4](https://coursetro.com/posts/code/100/Solidity-Events-Tutorial---Using-Web3.js-to-Listen-for-Smart-Contract-Events) in guide form as well.
2. Next [read through this 5-part hackernoon tutorial](https://hackernoon.com/ethereum-development-walkthrough-part-1-smart-contracts-b3979e6e573e) starting on creating a smart contract and all the way through to [part 5: creating a dapp](https://hackernoon.com/ethereum-development-walkthrough-part-5-making-a-dapp-4c2a3bbcd5e5) to see how that interacts with web3.js.
3. Finally [read through this 3-part hello world tutorial](https://medium.com/@mvmurthy/full-stack-hello-world-voting-ethereum-dapp-tutorial-part-1-40d2d0d807c2). [Part 2 is here](https://medium.com/@mvmurthy/full-stack-hello-world-voting-ethereum-dapp-tutorial-part-2-30b3d335aa1f) and [part 3 is here](https://medium.com/@mvmurthy/full-stack-hello-world-voting-ethereum-dapp-tutorial-part-3-331c2712c9df). Code from [each chapter is here on github](https://github.com/maheshmurthy/ethereum_voting_dapp/tree/master).
This should go a long way to getting you started.
## Official Docs
Solidity official docs:
* [Solidity API docs](http://solidity.readthedocs.io/en/v0.4.24/)
Web3.js Official Docs:
* [Web3.js 1.0 WIP Docs](https://web3js.readthedocs.io/en/1.0/getting-started.html)
* [Developing for Metamask](https://github.com/MetaMask/faq/blob/master/detecting_metamask.md)
* [Metamask Compatibility Guide](https://github.com/MetaMask/faq/blob/master/DEVELOPERS.md)
* [Web3 HttpProvider](https://github.com/ethereum/web3.js/blob/develop/lib/web3/httpprovider.js)
* [Official Docs](http://api.jquery.com/)
## Other Resources
Additional tutorials for smart contracts and/or web3.js:
When developing HTML/CSS, you may want to use a static site framework to reduce duplication (such as shared headers and footers):
Or check out one of the [many great static site generators](https://github.com/myles/awesome-static-generators).
## Other Notes
* Install <https://github.com/jeffbski/pkglink> to save yourself harddrive space by linking the local node modules rather than copying.
* Install <https://www.npmjs.com/package/ethereum-ens> for using the ENS system alongside Web3
## Environment Notes
* Setup local web server with [http-server](https://github.com/indexzero/http-server) to test with metamask