Hello World of Smart Contract Development!

1. Solidity language

Solidity is a smart contract high-level language that runs on the Ethereum Virtual Machine (EVM: Ethereum Virtual Machine).
Solidity's syntax is close to Javascript, it is an object-oriented language, and various development tool chains around Solidity are provided using npm , which belongs to the Javascript ecosystem .

Solidity语言:http://www.tryblockchain.org
Solidity documentation:https://solidity.readthedocs.org
GitHub:https://github.com/ethereum/solidity

2. Editor

I am currently using Atom with the solidity (linter-solium) plugin for development.

3. Truffle framework

Truffle is a development framework for the Ethereum-based Solidity language, itself based on Javascript.

4. Tool installation

1. Install Node.js and NPM ;
2. Install the Truffle framework and run the command in the terminal:

$ sudo npm install -g truffle

Install Truffle

3. Install the Truffle client EthereumJS TestRPC :

$ sudo npm install -g ganache-cli

Install TestRPC

5. Start TestRPC

Use the following command to start the Ethereum test environment:

$ ganache-cli

Start the Ethereum test environment

You can see that 10 accounts (Accounts) are automatically established after startup, and the private key (Private Key) corresponding to each account is. Each account has 100 Ether for testing purposes. Note that the ethereum test environment only runs in memory, so every time it restarts, it goes back to a fresh state.

6. Create a project

Reopen a terminal window and run the following commands to create the project:

$ mkdir SmartContractProject
$ cd SmartContractProject/
$ mkdir HelloWorld
$ cd HelloWorld/
$ truffle init

Initialize Truffle

HelloWorld project directory

[email protected]

Directory Structure:

  • contracts/: Truffle's default contract file storage address;
  • migrations/: store the published script file;
  • test/: store test files for testing applications and contracts;
  • truffle.js 和 truffle-config.js: Truffle configuration file.

7. Create a new HelloWorld contract

Create a new HelloWorld.sol file in contractsthe folder:

$ cd contracts/
$ truffle create contract HelloWorld

Create a new HelloWorld contract

[email protected]

HelloWorld.solThe contents of the file are as follows:

HelloWorld.sol

 

explain:

pragma solidity ^0.4.4;

The first line specifies the currently used solidity version. Different versions of solidity may compile different bytecodes. ^Represents a solidity-compatible 0.4.4 ~ 0.4.9version.

 function HelloWorld() {
   // constructor
 }
}

contractKeywords are similar to those more common in other languages class. Because solidity is a language designed for smart contracts (Contact), the functions required to develop smart contracts are built-in contractafter . This can also be understood as class HelloWorld extends Contract.

The structure of the function is similar to other programs, but if there is an incoming parameter or return value, you need to specify the type of the parameter or return value ( type).

8. Add new methods to the contract

function sayHello() returns (string) {
    return ("Hello World");
}

add new method

9. Compile the contract

Now executing the truffle compilecommand , we can compile the HelloWorld.solsource code into Ethereum bytecode:

$ cd ..
$ truffle compile

Compile the contract

[Note that there is a warning]
Re-modify the method in the HelloWorld.solfile :

pragma solidity ^0.4.4;

contract HelloWorld {
  function HelloWorld() public {
    // constructor
  }

  function sayHello() public pure returns (string) {
    return ("Hello World");
}

}

Modify the method in the contract

Rerun the command after saving:

$ truffle compile

Recompile the contract

After the command runs successfully, there will be an buildadditional directory, as follows:

build directory

 

Under HelloWorldthe folder under the build/contractsfolder you will see the HelloWorld.jsonfile :

HelloWorld.json

 

10. Modify the content of the truffle.js file:

Add the following to the truffle.js file and save:

networks: {
        development: {
            host:"localhost",
            port:8545,
            network_id:"*"  // 匹配任何network id
        }
    }

Modify the truffle.js file

11. Deployment contract

Create a migration file in the migrationsdirectory :

$ cd migrations/
$ truffle create migration 2_deploy_helloworld

Create migration file

migrations directory

1516095208_2_deploy_helloworld.js file content

Modify the file name and file content as follows:

var HelloWorld = artifacts.require("./HelloWorld.sol");

module.exports = function(deployer) {
  deployer.deploy(HelloWorld);
};

Modify the content of the migration file

Use the artifacts.requirestatement to get the contract ready to deploy.
Use the deployer.deploystatement to deploy the contract to the blockchain.
Here HelloWorldis contractthe name of instead of the filename.
So any contract in any .solfile .

Now execute the truffle migratecommand :

$ truffle migrate

deploy contract

After the deployment is successful, you will see the following changes in the terminal window that started TestRPC:

 

Terminal window changes for TestRPC

12. Interacting with contracts

Truffle provides command-line tools. After executing the truffle consolecommand , Javascript can be used to interact with the contract just deployed:

$ cd ..
$ truffle console
$ HelloWorld.deployed().then(instance => contract = instance)

Interact with contracts 1

Interact with contracts 2

yutaos-MacBook-Pro:migrations yutaozhang$ cd ..
yutaos-MacBook-Pro:HelloWorld yutaozhang$ truffle console
truffle(development)> HelloWorld.deployed().then(instance => contract = instance)
TruffleContract {
  constructor: 
   { [Function: TruffleContract]
     _static_methods: 
      { setProvider: [Function: setProvider],
        new: [Function: new],
        at: [Function: at],
        deployed: [Function: deployed],
        defaults: [Function: defaults],
        hasNetwork: [Function: hasNetwork],
        isDeployed: [Function: isDeployed],
        detectNetwork: [Function: detectNetwork],
        setNetwork: [Function: setNetwork],
        resetAddress: [Function: resetAddress],
        link: [Function: link],
        clone: [Function: clone],
        addProp: [Function: addProp],
        toJSON: [Function: toJSON] },
     _properties: 
      { contract_name: [Object],
        contractName: [Object],
        abi: [Object],
        network: [Function: network],
        networks: [Function: networks],
        address: [Object],
        links: [Function: links],
        events: [Function: events],
        binary: [Function: binary],
        deployedBinary: [Function: deployedBinary],
        unlinked_binary: [Object],
        bytecode: [Object],
        deployedBytecode: [Object],
        sourceMap: [Object],
        deployedSourceMap: [Object],
        source: [Object],
        sourcePath: [Object],
        ast: [Object],
        compiler: [Object],
        schema_version: [Function: schema_version],
        schemaVersion: [Function: schemaVersion],
        updated_at: [Function: updated_at],
        updatedAt: [Function: updatedAt] },
     _property_values: {},
     _json: 
      { contractName: 'HelloWorld',
        abi: [Array],
        bytecode: '0x6060604052341561000f57600080fd5b6101578061001e6000396000f300606060405260043610610041576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff168063ef5fb05b14610046575b600080fd5b341561005157600080fd5b6100596100d4565b6040518080602001828103825283818151815260200191508051906020019080838360005b8381101561009957808201518184015260208101905061007e565b50505050905090810190601f1680156100c65780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6100dc610117565b6040805190810160405280600b81526020017f48656c6c6f20576f726c64000000000000000000000000000000000000000000815250905090565b6020604051908101604052806000815250905600a165627a7a72305820b825548240e74063f6a0c0dd2a2b787ed288e3359cb7682b670288211d37f14f0029',
        deployedBytecode: '0x606060405260043610610041576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff168063ef5fb05b14610046575b600080fd5b341561005157600080fd5b6100596100d4565b6040518080602001828103825283818151815260200191508051906020019080838360005b8381101561009957808201518184015260208101905061007e565b50505050905090810190601f1680156100c65780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6100dc610117565b6040805190810160405280600b81526020017f48656c6c6f20576f726c64000000000000000000000000000000000000000000815250905090565b6020604051908101604052806000815250905600a165627a7a72305820b825548240e74063f6a0c0dd2a2b787ed288e3359cb7682b670288211d37f14f0029',
        sourceMap: '25:164:0:-;;;49:53;;;;;;;;25:164;;;;;;',
        deployedSourceMap: '25:164:0:-;;;;;;;;;;;;;;;;;;;;;;;;106:80;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;23:1:-1;8:100;33:3;30:1;27:2;8:100;;;99:1;94:3;90;84:5;80:1;75:3;71;64:6;52:2;49:1;45:3;40:15;;8:100;;;12:14;3:109;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;106:80:0;147:6;;:::i;:::-;161:22;;;;;;;;;;;;;;;;;;;;106:80;:::o;25:164::-;;;;;;;;;;;;;;;:::o',
        source: 'pragma solidity ^0.4.4;\n\ncontract HelloWorld {\n  function HelloWorld() public {\n    // constructor\n  }\n\n  function sayHello() public pure returns (string) {\n    return ("Hello World");\n}\n\n}\n',
        sourcePath: '/Users/yutaozhang/SmartContractProject/HelloWorld/contracts/HelloWorld.sol',
        ast: [Object],
        compiler: [Object],
        networks: [Object],
        schemaVersion: '1.0.1',
        updatedAt: '2018-01-16T09:55:58.496Z' },
     setProvider: [Function: bound setProvider],
     new: [Function: bound new],
     at: [Function: bound at],
     deployed: [Function: bound deployed],
     defaults: [Function: bound defaults],
     hasNetwork: [Function: bound hasNetwork],
     isDeployed: [Function: bound isDeployed],
     detectNetwork: [Function: bound detectNetwork],
     setNetwork: [Function: bound setNetwork],
     resetAddress: [Function: bound resetAddress],
     link: [Function: bound link],
     clone: [Function: bound clone],
     addProp: [Function: bound addProp],
     toJSON: [Function: bound toJSON],
     web3: 
      Web3 {
        _requestManager: [Object],
        currentProvider: [Object],
        eth: [Object],
        db: [Object],
        shh: [Object],
        net: [Object],
        personal: [Object],
        bzz: [Object],
        settings: [Object],
        version: [Object],
        providers: [Object],
        _extend: [Object] },
     class_defaults: 
      { from: '0xcb009af857f4e65d3b234f491ffebe76cee6cbe7',
        gas: 6721975,
        gasPrice: 100000000000 },
     currentProvider: 
      HttpProvider {
        host: 'http://localhost:8545',
        timeout: 0,
        user: undefined,
        password: undefined,
        send: [Function],
        sendAsync: [Function],
        _alreadyWrapped: true },
     network_id: '1516087157119' },
  abi: 
   [ { constant: true,
       inputs: [],
       name: 'sayHello',
       outputs: [Array],
       payable: false,
       stateMutability: 'pure',
       type: 'function' },
     { inputs: [],
       payable: false,
       stateMutability: 'nonpayable',
       type: 'constructor' } ],
  contract: 
   Contract {
     _eth: 
      Eth {
        _requestManager: [Object],
        getBalance: [Object],
        getStorageAt: [Object],
        getCode: [Object],
        getBlock: [Object],
        getUncle: [Object],
        getCompilers: [Object],
        getBlockTransactionCount: [Object],
        getBlockUncleCount: [Object],
        getTransaction: [Object],
        getTransactionFromBlock: [Object],
        getTransactionReceipt: [Object],
        getTransactionCount: [Object],
        call: [Object],
        estimateGas: [Object],
        sendRawTransaction: [Object],
        signTransaction: [Object],
        sendTransaction: [Object],
        sign: [Object],
        compile: [Object],
        submitWork: [Object],
        getWork: [Object],
        coinbase: [Getter],
        getCoinbase: [Object],
        mining: [Getter],
        getMining: [Object],
        hashrate: [Getter],
        getHashrate: [Object],
        syncing: [Getter],
        getSyncing: [Object],
        gasPrice: [Getter],
        getGasPrice: [Object],
        accounts: [Getter],
        getAccounts: [Object],
        blockNumber: [Getter],
        getBlockNumber: [Object],
        protocolVersion: [Getter],
        getProtocolVersion: [Object],
        iban: [Object],
        sendIBANTransaction: [Function: bound transfer] },
     transactionHash: null,
     address: '0x742c7a36d3a2b65a5607180fdee7fd5befc8a164',
     abi: [ [Object], [Object] ],
     sayHello: 
      { [Function: bound ]
        request: [Function: bound ],
        call: [Function: bound ],
        sendTransaction: [Function: bound ],
        estimateGas: [Function: bound ],
        getData: [Function: bound ],
        '': [Circular] },
     allEvents: [Function: bound ] },
  sayHello: 
   { [Function]
     call: [Function],
     sendTransaction: [Function],
     request: [Function: bound ],
     estimateGas: [Function] },
  sendTransaction: [Function],
  send: [Function],
  allEvents: [Function: bound ],
  address: '0x742c7a36d3a2b65a5607180fdee7fd5befc8a164',
  transactionHash: null }
truffle(development)> 

explain:

HelloWorld.deployed().then(instance => contract = instance)

truffle consoleThe truffle-contractfunction in to facilitate the operation of contracts deployed on the blockchain.
Here, the HelloWorld.deployed().thenstatement is used to obtain HelloWorldthe (instance) of the contract Instanceand store it in the contractvariable to facilitate subsequent calls.

Enter the following command:

$ contract.sayHello.call()

Interacting with contracts 3

Calling directly here contract.sayHello()will get the same result. truffle-contractProvides use call()to read read-only (read only)data so that it is not required gas. So if we encounter an operation that requires writing data to the blockchain, we cannot use the callstatement .

In this way, we have written and deployed the first smart contract, and verified that the contract actually works.

Thirteen, adding new methods

HelloWorld.solWe add another echomethod in , echowhich accepts an input parameter and returns the passed parameter`:

function echo(string name) public pure returns (string) {
    return name;
}

add new method

Since the content of the contract has been updated, we need to recompile once, deploy the compilation result testrpcto , and then truffle consoleexecute it to see the result.

$ truffle compile
$ truffle migrate --reset

transplant reset

$ truffle console
$ let contract
HelloWorld.deployed().then(instance => contract = instance)

Interact with the contract again 1

 

Interact with the contract again 2

One thing to note is that if we still use the $ truffle migratecommand , we will get the following information:

$ truffle migrate
Using network 'development'.
Network up to date.

Truffle will tell you that the contracts on the network are all up to date, but in fact the methods newly added in the program have not been updated to the memory block chain. To update the deployed program on the memory block chain, it is necessary to migrationsrewrite the script in . Fortunately, it does not matter how the memory block chain we use for development is modified testrpc. You can use the truffle migrate --resetcommand to directly re- testrpcdeploy it on .

Summarize

I just started researching, some places are not very clear, please let me know if there are any mistakes, thank you!

QQ:3500229193

Reference link

Changelog

  • 2018.01.16 First update
  • 2018.02.23 Second update

Original link: https://www.jianshu.com/p/ba360dd2b57d

----------------------------------------------------------------------------------

If you want to learn Ethereum DApp development efficiently , you can visit the most popular online interactive tutorials provided by Huizhi.com:

1.  An introductory tutorial for Ethereum DApps for blockchain newbies
2.  Blockchain +IPFS+Node.js+ MongoDB+Express decentralized Ethereum e-commerce application development practice

3. Other more content can also visit this Ethereum blog .

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325857261&siteId=291194637