solidity 入门

solidity 入门,第1张

官方入门指南

hello world
// SPDX-License-Identifier: MIT
// compiler version must be greater than or equal to 0.8.13 and less than 0.9.0
pragma solidity ^0.8.13;

contract HelloWorld {
    string public greet = "Hello World!";
}

编译运行
进入:https://remix.ethereum.org/ 线上ide

新建一个test.sol
把代码复制上去
编译

Variables

There are 3 types of variables in Solidity

local
declared inside a function
not stored on the blockchainstate
declared outside a function
stored on the blockchainglobal (provides information about the blockchain)
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;

contract Variables {
    // State variables are stored on the blockchain.
    string public text = "Hello";
    uint public num = 123;

    function doSomething() public {
        // Local variables are not saved to the blockchain.
        uint i = 456;

        // Here are some global variables
        uint timestamp = block.timestamp; // Current block timestamp
        address sender = msg.sender; // address of the caller
    }
}

Constants
Constants are variables that cannot be modified.

Their value is hard coded and using constants can save gas cost.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;

contract Constants {
    // coding convention to uppercase constant variables
    address public constant MY_ADDRESS = 0x777788889999AaAAbBbbCcccddDdeeeEfFFfCcCc;
    uint public constant MY_UINT = 123;
}

Reading and Writing to a State Variable

To write or update a state variable you need to send a transaction.

On the other hand, you can read state variables, for free, without any transaction fee.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;

contract SimpleStorage {
    // State variable to store a number
    uint public num;

    // You need to send a transaction to write to a state variable.
    function set(uint _num) public {
        num = _num;
    }

    // You can read from a state variable without sending a transaction.
    function get() public view returns (uint) {
        return num;
    }
}

Ether and Wei
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;

contract EtherUnits {
    uint public oneWei = 1 wei;
    // 1 wei is equal to 1
    bool public isOneWei = 1 wei == 1;

    uint public oneEther = 1 ether;
    // 1 ether is equal to 10^18 wei
    bool public isOneEther = 1 ether == 1e18;
}

1以太币1 ether
1 ether = 1 0 18 10^{18} 1018 wei

Gas

How much ether do you need to pay for a transaction?
You pay gas spent * gas price amount of ether, where

gas is a unit of computation
gas spent is the total amount of gas used in a transaction
gas price is how much ether you are willing to pay per gas
Transactions with higher gas price have higher priority to be included in a block.

Unspent gas will be refunded.

Gas Limit
There are 2 upper bounds to the amount of gas you can spend

gas limit (max amount of gas you’re willing to use for your transaction, set by you)
block gas limit (max amount of gas allowed in a block, set by the network)

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;

contract Gas {
    uint public i = 0;

    // Using up all of the gas that you send causes your transaction to fail.
    // State changes are undone.
    // Gas spent are not refunded.
    function forever() public {
        // Here we run a loop until all of the gas are spent
        // and the transaction fails
        while (true) {
            i += 1;
        }
    }
}

function

Function Declarations

function eatHamburgers(string memory _name, uint _amount) public {

}
the function visibility as public_name variable should be stored- in memory
.

In Solidity, functions are public
by default. This means anyone (or any other contract) can call your contract’s function and execute its code.

View function declares that no state will be changed.

Pure function declares that no state variable will be changed or read.
`
``cpp
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;

contract Function {
// Functions can return multiple values.
function returnMany()
public
pure
returns (
uint,
bool,
uint
)
{
return (1, true, 2);
}

// Return values can be named.
function named()
    public
    pure
    returns (
        uint x,
        bool b,
        uint y
    )
{
    return (1, true, 2);
}

// Return values can be assigned to their name.
// In this case the return statement can be omitted.
function assigned()
    public
    pure
    returns (
        uint x,
        bool b,
        uint y
    )
{
    x = 1;
    b = true;
    y = 2;
}

// Use destructuring assignment when calling another
// function that returns multiple values.
function destructuringAssignments()
    public
    pure
    returns (
        uint,
        bool,
        uint,
        uint,
        uint
    )
{
    (uint i, bool b, uint j) = returnMany();

    // Values can be left out.
    (uint x, , uint y) = (4, 5, 6);

    return (i, b, j, x, y);
}

// Cannot use map for either input or output

// Can use array for input
function arrayInput(uint[] memory _arr) public {}

// Can use array for output
uint[] public arr;

function arrayOutput() public view returns (uint[] memory) {
    return arr;
}

}


# error
An error will undo all changes made to the state during a transaction.

You can throw an error by calling require, revert or assert.

require is used to validate inputs and conditions before execution.
revert is similar to require. See the code below for details.
assert is used to check for code that should never be false. Failing assertion probably means that there is a bug.

# Function Modifier
Modifiers are code that can be run before and / or after a function call.

Modifiers can be used to:

Restrict access
Validate inputs
Guard against reentrancy hack

# event
***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.

```cpp
// declare the eventevent IntegersAdded(uint x, uint y, uint result);

function add(uint _x, uint _y) public returns (uint) {
  uint result = _x + _y;
// fire an event to let the app know the function was called:
emit IntegersAdded(_x, _y, result);
  return result;
}

Your app front-end could then listen for the event. A javascript implementation would look something like:

YourContract.IntegersAdded(function(error, result) {
// do something with result
})

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/2992085.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-09-23
下一篇 2022-09-23

发表评论

登录后才能评论

评论列表(0条)

保存