Solidity – Call x Transactions and Solidity functions

In Ethereum, it is possible to interact with contracts via calls (aka message calls) or via transactions. The official documentation says:

Transaction

A piece of data, signed by an External Actor. It represents either a Message or a new Autonomous Object. Transactions are recorded into each block of the blockchain.

Message Call

The act of passing a message from one Account to another. If the destination account is associated with non-empty EVM Code, then the VM will be started with the state of said Object and the Message acted upon. If the message sender is an Autonomous Object, then the Call passes any data returned from the VM operation.

In other words, a transaction is an asynchronous operation which is broadcasted to the network and processed by miners. A transaction consumes Ether and modify the blockchain. A message call is a read-only and not Ether consumer operation of a contract function. The results of a ‘call’ will not be published or broadcasted on the blockchain.

Modifiers and Visibility

Solidity Modifiers

Since Solidity 0.4.17, it provides the following functions modifiers on its framework: view and pure.

View – should be used in functions that did not change any state values of a contract;

Pure – should be used if it does not even read any state information. Pure functions can be used for tasks like permission-control, calculations and typecasting.

Visibility

public – are part of the contract interface and can be either called internally or via messages. For public state variables, an automatic getter function (see below) is generated;

private – and state variables are only visible for the contract they are defined in and not in derived contracts;

internal – and state variables can only be accessed internally (i.e. from within the current contract or contracts deriving from it), without using this;

external – are part of the contract interface, which means they can be called from other contracts and via transactions. An external function f cannot be called internally (i.e. f() does not work, but this.f() works). External functions are sometimes more efficient when they receive large arrays of data;


Solidity – Gas, gas price, fee and gas usage

gas – is the name for a special unit used in Ethereum

gas price – a value set by the creator of the transaction; it’s a single gas unit’s price;

fee – the result of gas * gas price

Transactions costs x Ethereum system

  • Have in mind if the gas price is too low, no one will process your transaction;

  • The fees are paid in ether, though, which is different from gas;

  • The transaction fails (still goes into the blockchain) in case of gas price is fine but the gas cost runs “over budget”. You don’t get the money back for the work that the miners did.

  • Transaction fee = Amount of work that goes into something + storage space your code will take;

Optimize gas usage of your smart contract

Gas is necessary for the execution of smart contracts, but you shouldn’t specify too low or high price. Consider optimizing your smart contract to minimize the amount of gas required.

What should I take into account for optimized contracts?

Global Variables usage – storage: Global variables are stored in a contract’s state on the blockchain, so you are going to be charged if you use global variables. Just use when it is necessary, this is a practice in several languages, but it is especially crucial in ethereum development;

Contract Size: The size of your contract will influence the transaction cost for all interactions with it. So how big is your contract, more expansive your contract will be to processed in the Ethereum’s network. If you are able to break the Solidity contract up into smaller separate contracts, this will decrease user’s gas costs;

Further Details

Take a look in this documentation from ConsenSys for Ethereum Smart Contract Security Best Practices and this Medium post about Optimizing gas usage.


Solidity – Block and Transaction Properties

Solidity provides special variables and functions which always exist in the global namespace and are mainly used to provide information about the blockchain or are general-use utility functions. The following is a list of properties related to the block and transactions:

block.blockhash (uint blockNumber) returns (bytes32): Hash of the given block, works for only the 256 most recent blocks
block.coinbase (address): Current block miner’s address
block.difficult (uint): Current block difficulty
block.gaslimit (uint): Current block gas limit
block.number (uint): Current block number
block.timestamp (uint): Current block timestamp
msg.data (bytes): Complete call data
msg.gas (uint): Remaining gas
msg.sender (address): Sender of the message (current call)
msg.sig (bytes4): First 4 bytes of the call data (function identifier)
msg.value (uint): Number of wei sent with the message
now (uint): Current block timestamp (alias for block.timestamp)
tx.gasprice (uint): Gas price of the transaction
tx.origin (address): Sender of the transaction (full call chain)


Solidity – Hashes and Typecasting

Hashes

In Solidity, it is possible to use the keccak256 function to get a hash. Ethereum’s KECCAK-256 algorithm produces a 256-bit hexadecimal number.

keccak256(…) returns (bytes32): compute the Ethereum-SHA-3 (Keccak-256) hash of the (tightly packed) arguments

Usage Examples

keccak256(6382179)
keccak256(97, 98, 99)

Typecasting

Solidity is a statically typed language, which means that the type of each variable (state and local) needs to be specified at compile-time. Solidity is able to perform operations between two variables that have the same type. Therefore you can convert one of the variables to the type of the others.

uint256 z = y * uint256(x);
uint8 x = 8;
uint256 y = 10 ** 18;

Hello Solidity, hello Ethereum

According to official Solidity docs is a contract-oriented, Solidity is a high-level language for implementing smart contracts. It was influenced by C++, Python and JavaScript and is designed to target the Ethereum Virtual Machine (EVM).

Alright, let’s talk about Solidity’ syntax and its features. Basically I’m mention the following subjects: Contracts, Types of variables, Math operations, Functions, Arrays, Structs and Events.

Let’s start

A contract is the fundamental building block of Ethereum applications — everything goes inside the contracts. This is very similar to Java, commonly all the code is encapsuled in ‘Class’.

First important thing you need to learn is how Solidity handles variables. Solidity is a statically typed language, which means that the type of each variable. Once you start coding variables and functions inside you Contract file, you need to understand Solidity has two types of variables: state and local. State variables are permanently stored in contract storage - into the Ethereum blockchain, it may cost some ‘gas’ in case you try to modify them. Local variable you can modify them freely but remember you will loose their value right after the context/scope change - they are not stored.

Booleans bool: The possible values are constants true and false.

Integers int / uint: Signed and unsigned integers of various sizes. Keywords uint8 to uint256 in steps of 8 (unsigned of 8 up to 256 bits) and int8 to int256. uint and int are aliases for uint256 and int256, respectively.

Address address: Holds a 20 byte value (size of an Ethereum address). Address types also have members and serve as a base for all contracts.

Members of Addresses balance and transfer: It is possible to query the balance of an address using the property balance and to send Ether (in units of wei) to an address using the transfer function.

Fixed-size byte arrays bytes1, bytes2, bytes3, …, bytes32. byte is an alias for bytes1.

Dynamically-sized byte array bytes: Dynamically-sized byte array. string: Dynamically-sized UTF-8-encoded string.

String Literals They are written with either double or single-quotes (“foo” or ‘bar’). They do not imply trailing zeroes as in C; “foo” represents three bytes not four. As with integer literals, their type can vary, but they are implicitly convertible to bytes1, …, bytes32, if they fit, to bytes and to string.

Math Operations

Solidity offers the following math operations (it is almost the same as in most programming languages):

Addition: x + y Subtraction: x - y, Multiplication: x * y Division: x / y Modulus / remainder: x % y Support an exponential operator (i.e. “x to the power of y”, x^y):

Structs

Sometimes you need a more complex data type. For this, Solidity provides structs:

`struct Person { uint age; string name; } Structs allow you to create more complicated data types that have multiple properties.

Events

Events are a way for your contract to communicate that something happened on the blockchain to your app front-end, which can be ‘listening’ for certain events and take action when they happen.

Events are inheritable members of contracts. When they are called, they cause the arguments to be stored in the transaction’s log - a special data structure in the blockchain. These logs are associated with the address of the contract and will be incorporated into the blockchain and stay there as long as a block is accessible (forever as of Frontier and Homestead, but this might change with Serenity). Log and event data is not accessible from within contracts (not even from the contract that created them).

Further details

I’d recommend this article Ethereum Smart Contract Best Practices for beginners.