Chidume Nnamdi I'm a software engineer with over six years of experience. I've worked with different stacks, including WAMP, MERN, and MEAN. My language of choice is JavaScript; frameworks are Angular and Node.js.

How to build secure smart contracts using Vyper

5 min read 1494

How to Build Smart Contracts Using Vyper

It was only a matter of time before more programming languages were written to rival Solidity. Vyper is similar to Solidity, but it is written in a more modern way.

In this tutorial, we’ll walk you through how to build smart contracts using Vyper.

What is Vyper?

Vyper is a pythonic language that is similar to Solidity but written in a more modern way. It is used to write smart contracts that run on the Ethereum Virtual Machine.

Next to Solidity, Vyper is the second-most popular choice of contract programming language for developers. From its name, we can easily deduce it is based on the Python language.

Vyper is a strongly typed language, which means we can only use one type of data; no data type can be used in place of another.

Why use Vyper over Solidity?

Why would you choose Vyper for writing smart contracts over the more well-known and widely used Solidity? Vyper’s killer features are fueling its rapid rise in popularity and adoption. These unique features are designed to alleviate some of the issues developers commonly face when writing smart contracts in Solidity.

Research from the National University of Singapore School of Computing found that many smart contracts are faulty and can perform unpredictably.

Specifically, the researchers discovered that some smart contracts give away Ethers to arbitrary addresses that have never deposited Ethers, provided data, or owned the contract. These contracts are called prodigal contracts.

By contrast, according to the research, contracts that can be killed by their owners when they are drained of Ethers, when attacked, or in the event of an emergency are called suicidal contracts. Greedy contracts are those that lock Ethers and lack the instructions to send them out due to errors.

Then there are posthumous contracts, which do reside in the Ethereum blockchain when they are killed off but keep receiving transactions even though the transactions cannot call the contract code. These lock the Ethers in the contract balance.

We made a custom demo for .
No really. Click here to check it out.

Vyper aims to help you avoid these problems. Vyper features bounds and overflow checks on arrays and arithmetic ops. It also enables you to compute a precise upper bound for gas consumption and has support for signed integers and decimal fixed-point numbers.

You can read more about Vyper’s unique features, principles, and goals — including security, language and compiler simplicity, and auditability — in the official Vyper docs.

To put it simply, Vyper eliminates the problems associated with prodigal, suicidal, greedy, and posthumous contracts by tightening the loop on the free roam it gives to developers.

With the basics out of the way, let’s walk through the process of building smart contracts with Vyper.

Installing Vyper

First, we need to install Vyper. To do that, we will need Python 3.6 or higher. You can download Python binaries from the Python website.

We’ll also need the pip package manager. To install it, we can use the following command:

sudo apt-get install python3-pip

Alternatively, you can download a script from here and then run the following command:

python3 get-pip.py

Make sure the pip package manager is installed globally on your machine:

pip

If we get command not found, we need to manually set the path to point to our pip installation folder.

For Mac users, you can do this by adding the following line to the ~/.bashrc file:

export PATH="$PATH:/Users/chidumennamdi/Library/Python/3.8/bin"

We test if the pip command works by typing pip in the terminal.

Next, we install Vyper using the pip command:

pip install vyper

Writing a smart contract in Vyper

For our demonstration, we’ll build a smart contract that can store and display a user’s name. To test our smart contract, we’ll use the Ropsten Testnet. This will enable us to test our smart contract with virtual Eths before deploying to the Ethereum mainnet.

First, we need to install MetaMask. MetaMask is a browser extension that enables you to interact with the Ethereum blockchain.

If you have not registered MetaMask yet, you can do so by clicking the MetaMask logo in the top-right corner of the browser. This will open a new tab.

Register and log in, then click the dropdown menu and select Ropsten Test Network. There is a copy icon next to a series of alphanumerical numbers. This is the address of your Ethereum wallet. Copy this address; we will use it to get free Eth.

Visit the Ropsten Ethereum Faucet and paste the address in the text box. Click the button labeled Send me test Ether to get free Eth.

Going back to our MetaMask, we’ll see 0.3Eth in our account. Now we can write and deploy our smart contract.

Vyper programs are written in files with a .vy extension. Let’s break down the structure of a smart contract in Vyper.

A smart contract contains:

  • Version pragma, which specifies the version of the smart contract and ensures that the contract is compiled by the correct version
  • State variables, which are used to store the state of the smart contract. They are declared outside of the functions in the smart contract and have initial values. These state variables are accessed via the self object
  • Functions, which are executable units of code that are used to perform actions on the smart contract. They can be visible internally or externally, accept arguments, and return values
  • Events, which are triggered and logged in the EVM’s logging channel
  • Interface, which is used to specify the functions that are used by the smart contract
  • Structs, which define the types of state variables.

We will write a simple contract that will save a user’s name and also enable the user to retrieve it.

We will create a folder, vyper_contract, and a file, contract.vy, inside this folder.

Paste the below code in the contract.vy file:

# @version ^0.3.1

userName: public(String[100])

@external
def __init__(name: String[100]):
    self.userName = name

@view
@external
def getUserName() -> String[100]:
    return self.userName

The first line, # @version ^0.3.1, is the pragma that tells the Vyper compiler to use version 0.3.1 to compile the smart contract.

The second bit of code is a state variable, userName, which holds the name of the user.

We see an @external being used; this tells Vyper that the function is an external function — i.e., the function can be called from the outside.

The __init__ function is the constructor of the smart contract. It is called when the smart contract is deployed.

The @view in the getUserName function tells Vyper that the function does not change the state of the blockchain — i.e., it only reads state from the blockchain. This getUserName function returns the userName state variable, which is the name of the user.

Compiling our smart contract

We’ll compile our smart contract using the vyper command:

vyper contract.vy

We’ll see a hexadecimal string in the terminal. This is the bytecode of the smart contract.

Bytecode Smart Contract

Next, run the Vyper server, vyper-server. This will start a server on http://localhost:8000; we’ll use this URL in Remix to compile remotely and deploy.

URL for Remix

We will use the Remix IDE to compile our smart contract remotely and deploy it. Navigate to the Remix IDE, create a new file called contract.vy, and paste the above code into the file.

Pasting Code Into File

Next, we will install the Vyper plugin in our Remix IDE, click on the socket icon in the sidebar, and search for “vyper.”

Search Vyper

Click Activate on the item that appears. Then, click on the Vyper icon and press the Compile contract.vy button. You should see this:

Contract Compiled

Deploying our smart contract

We’ll now deploy our smart contract.

Click the Ethereum icon in the sidebar:

Ethereum Sidebar Icon

From the ENVIRONMENT dropdown, select Injected Web3. A small UI underneath it will change to the Ropseten Testnet we are connected to.

Ropsten Network Connection

Click on Deploy and enter your name beside the Deploy button.

Deploy Button

Clicking the Deploy button will cause the MetaMask UI to appear.

MetaMask UI

Click Confirm and your Vyper smart contract will be deployed to the Ropsten Testnet.

Deployed Contracts Confirmation

Testing the deployed smart contract

Above is our deployed smart contract. We can interact with it to call the methods in our Remix browser IDE or view the deployed contract on the Ropsten Ethereum Faucet.

Click on the CONTRACT AT 0x26… dropdown. We’ll see our functions and state variables: getUserName, and userName.

Let’s click getUserName:

GetUserName

It returns “nnamdi,” the string we passed to the constructor during deployment. This action called the getUserName function in the contract.

Congratulations! If you’ve made it this far, you have successfully tested and deployed your Vyper smart contract.

Conclusion

In this tutorial, we introduced you to Vyper and the issues — namely, prodigal, suicidal, greedy, and posthumous contracts — Vyper is designed to remediate.

Next, we demonstrated how to install Vyper and built a simple smart contract that can store and display a user’s name. We learned how to deploy a smart contract using Vyper and Remix and how to interact with it.

: Full visibility into your web apps

LogRocket is a frontend application monitoring solution that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.

In addition to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single-page and mobile apps.

.
Chidume Nnamdi I'm a software engineer with over six years of experience. I've worked with different stacks, including WAMP, MERN, and MEAN. My language of choice is JavaScript; frameworks are Angular and Node.js.

Leave a Reply