Solidity is the way to go for Ethereum DApps. However, for those new to Ethereum like me who have been developing for years, Solidity learning is one thing, but it’s more important to quickly get to know the conventions and routines and what to look out for. This is exactly what this paper tries to achieve. As for the grammar of the detailed document, reference HiBlock block chain solidity of the Chinese community translation document (https://solidity-cn.readthedocs.io/zh/develop/).

1

EVM and bytecode

Similar to Java code, Solidity code is compiled into bytecode and then EVM takes care of executing it. Logically, ethereum can be thought of as a computer, where each EVM node is like a process executing in the computer, and the distributed ledger is the storage for that computer.

Once deployed, its code is copied to other nodes on Ethereum and its source code can be viewed by command. Take the Truffle development environment for example:

  • truffle develop

  • Deploy MyCoin contract, deploy

  • Mycoin.at (address), the contract code can be seen from the source property in the JSON object it returns.

The inability to update after contract deployment presents considerable challenges for developers:

  • How do you develop high-quality contracts that are as bug-free as possible?

  • How to design an upgradeable contract?

2

Perform cost

When it comes to the cost of executing a program, it generally refers to how much memory, storage, and CPU time it takes. But executing code on Ethereum, in addition to the usual price tag, requires real money. This is because transaction confirmation on Ethereum costs money! They are mainly operations that change ethereum state, such as:

  • Account transfer

  • Deployment of contract

  • Write operations within the contract

And, unlike other systems, the results of these operations do not take effect immediately. They are submitted to a trading pool in the form of a transaction to be confirmed by the miner, and that’s where the transaction fee comes in. Also, the price is not a fixed value, it moves up and down with market fluctuations. If your trade goes nowhere for a long time, check to see if it’s due to low transaction fees.

On the transaction fee market, you can learn from the latest transaction (https://etherscan.io/txs).

This creates a challenge for developers: how to reduce transaction costs as much as possible without sacrificing functionality?

3

account

To operate on Ethereum, you must have an Ethereum account. There are currently two types of accounts:

  • External accounts, which can be thought of simply as “human users,” have private keys and balances that are used to sign transactions before they are sent.

  • Contract account, after the contract is deployed, there will be an account with the balance and corresponding contract status data. It is triggered by an external message. Trigger sources are external accounts or other contract accounts.

There are also some conceptual shifts in security:

  • The private key is the ultimate secret, it must be stored locally, otherwise it is not secure.

  • Since contracts are public, anyone can initiate enforcement. If you want to implement “only XXX can execute this contract”, you must control it in the internal code of the contract.

4

Contract syntax

A contract is similar to a class in Java, but unlike a class, its constructor is called only once, when the contract is deployed.

The state variables of the contract are equivalent to the instance variables of the class, but are also persistent. Also, mapping can only be declared as a state variable but can be referenced within a function.

Variable types also include value types and reference types, including arrays and structs, which provide scenarios for custom types.

Functions can return one or more values, and you can specify the variables to return. Such as:

function arithmetic(uint _a, uint _b)

    public

    pure

    returns (uint o_sum, uint o_product)

{

    o_sum = _a + _b;

    o_product = _a * _b;

}
Copy the code

Function modifiers, similar to interceptors in AOP, provide the opportunity to modify the flow of function execution, typically for validation and checking. “_” is used to return control flow to the modified function, as shown in the following example:

modifier onlySeller() { // Modifier

    require(

        msg.sender == seller,

        "Only seller can call this."); _; }function abort() public onlySeller { // Modifier usage

    // ...

}
Copy the code

A few important modifiers:

  • Payable, the function that receives aether must be added

  • View or Pure, indicating that the function does not change the ethereum state

Events provide a way for external applications to learn about changes in the state of the contract. The usual process is:

  • An event occurred within the contract

  • External applications use Web3 to listen for events

Visibility:

  • External, which applies only to functions, means that they can be called by external contracts or transactions, but not internally.

  • public

    The default visibility of functions, which can be called internally and via messages,

    State variables for which EVM automatically generates getters

  • Internal, functions and state variables can be called by the current contract and its subcontracts

    Default visibility of state variables

  • Private, functions and state variables are called only by the current contract

Contracts support multiple inheritance.

EVM provides four data locations for storing data:

  • Storage, persistence, stored throughout Ethereum

  • Memory, the function’s local memory, nonpersistent

  • Calldata, function entry, nonpersistent

  • Stack, EVM call stack

Rules:

  • Status variable: storage

  • External takes calldata

  • Function entry parameter: memory

  • Function local variables:

    Reference type, which is storage by default but can be overwritten

    Value type, memory, cannot be overwritten

    The mapping type refers to external state variables

  • Assigning values between state variables produces independent copies, that is, mutual changes are not referenced.

  • Storage and memory variables are assigned to each other, always producing independent copies.

  • Assignment between memory variables

    Value type that produces a separate copy

    Reference type, pointing to the same address

Because contract execution has a cost, you need to be wary of loop statements.

For multiple inheritance contracts, you need to specify the order, for example:

contract X {}contract A is X {}contract C is A, X {}
Copy the code

The fallback function has no function name and cannot be called directly, but is triggered in two cases:

  • When no function in the contract matches the request sent by the caller

  • When the contract receives aether, the fallback function needs to use Payable

Because it cannot be called externally, EVM limits it to consume a maximum of 2300 gas, beyond which the fallback function fails. Therefore, remember to test whether the contract’s fallback function will exceed this limit.

In addition, Fallback is a place with high incidence of safety accidents, so necessary safety-related tests should be carried out on it.

Interfaces and abstract contracts are not very different from interfaces and abstract classes in Java. A library is a piece of reusable code that executes within the context of the contract that calls it:

  • It can’t use state variables

  • Unable to inherit or be inherited

  • Unable to receive Aether

After a contract throws an exception, the state can be rolled back in three ways:

  • Require (expression), if the expression is false, an exception is thrown, and unused gas is returned

  • Suitable for validating the input parameter of a function

  • Assert, same as above, but unused gas is not returned and will be consumed entirely

  • Good for validating internal state

  • Revert () directly throws an exception

5

Common mode

You need to be very careful when coding solidity given the following features of ethereum apps:

  • Execution costs real money

  • Contracts are publicly visible, even if they are private

  • Contracts cannot be tampered with and cannot be changed once published

Common coding routines include:

  • For payment, “withdrawal” is preferred over “transfer” (i.e., send or Transfer) to avoid receiving contract malicious fallback functions.

  • For payments, the CDI model is used to avoid reentrant problems. That is:

    Check -> Change the status of this contract -> pay.

  • Use the Modifier to control permissions.

  • Use the Mapping type to save contract data, and even separate out two categories to facilitate upgrades:

    A data contract, which contains only mapping and retains functions that operate mapping, is objectively similar to a data table.

    The control contract, which contains only logical control, manipulates data through the interface of the data contract. If the logic is wrong, just upgrade this contract and the data will still be preserved.

  • Use the agency contract, see here (https://blog.zeppelin.solutions/proxy-libraries-in-solidity-79fbe4b970fd).

Finally, the easiest way to do this is to use a mature class library like OpenZeppelin. About the Solidity of a good thing, can pass the Awesome List (https://github.com/bkrem/awesome-solidity) to get to know.

HiBlock Blockchain Technology Evangelist Group – Hu Jian

Originally published in Jane’s book

Original link:

https://www.jianshu.com/p/ec5ad71e28aa

Add wechat baobaotalk_com to join the technical evangelist group

Online Course Recommendation