Getting started with Ethereum smart contracts (authoring, compiling, creating, deploying, interacting, testing, trading)

Source: Internet
Author: User
# # What is an Ethereum smart contract? An Ethereum smart contract is a collection of code (its functions) and data (its state) that is stored in the Ethereum blockchain with a specific address. Smart contract accounts can pass messages to each other to achieve Turing complete operations. The smart contract runs on the blockchain with Ethereum-specific binary bytecode through the Ethereum virtual machine (EVM). [Ethereum Smart Contract] (HTTP://XC.HUBWIZ.COM/COURSE/5A952991ADB3847553D205D1) is usually named  [solidity] (https://solidity.readthedocs.org/ en/latest/)   is written in the high-level language and is compiled into bytecode to upload to the blockchain. # # # Soliditysolidity is a JavaScript-like language that allows you to develop smart contracts and can be compiled into EVM bytecode, which is now the flagship language of Ethereum and is the most popular. # # Writing a contract without implementing the language of the Hello World program is incomplete, in the ethereum environment, solidity does not have a clear way to "output" a string. The closest way is a practical * log event * Put a string into the blockchain: ' ' contract HelloWorld {event Print (string out); function () {Print ("Hello, world!");}} After each execution of this contract, a log is placed in the blockchain via print with the "Hello World" parameter. The build contract can be compiled from a variety of mechanisms to solidity developed by the [Ethereum Smart Contract] (HTTP://XC.HUBWIZ.COM/COURSE/5A952991ADB3847553D205D1). * Use the   ' Solc '   compiler from the command line. * Using the JavaScript console provided by   ' Geth '   or   ' ETH ' (still need to install   ' SOLC '   compilers ')   ' Web3.eth.compile.solidity '  . * via  [Real-time online compiler] (https://ethereum.github.io/browser-solidity/). * Through  [ethereum Wallet] (https://github.com/ ethereum/mist/releases). # # # Set the solidity compiler in Geth if you launch the   ' Geth '   node, you can check which compilers are available using the following command. "> Web3.eth.getCompilers (); ["LLL", "solidity", "Serpent"] "" This command returns an array of strings for the currently available compiler. **note** ' Solc '   compilers are installed with   ' Cpp-ethereum '  , as an alternative, you can [build yourself] (https://github.com/ethereum/ Go-ethereum/wiki/building-ethereum)  . If your   ' Solc '   execution file is not in the specified standard path, you can specify   ' SOLC '   execution path by   '--SOLC '   parameter. "$ Geth--solc/usr/local/bin/solc" Similarly, you can perform this operation at run time through the command line: "' > Admin.setsolc ("/usr/local/bin/solc ") Solc, the Solidity compiler commandline Interfaceversion:0.2.2-02bb315d/.-darwin/appleclang/jit linked to Libethereum-1.2.0-8007cef0/.-darwin/appleclang/jitpath:/usr/local/bin/solc "# # # Compile a simple contract let's compile a simple contract code:" > Source = "contract Test {function multiply (uint a) returns (UINT D) {return a * 7;}}" This contract provides a function called  **multiply** , enter a positive integer   ' a '   return result   ' a * 7 '  . You are ready to compile the solidity code environment, using the   ' geth '   JS Command console  [eth.compile.solidity ()] (https://github.com/ethereum/wiki/wiki/javascript-api#web3ethcompilesolidity): ' > Contract = eth.compile.solidity (source). test{ Code: ' 605280600c6000396000f3006000357c010000000000000000000000000000000000000000000000000000000090048063c6888fa114602e57005b603 76004356041565b8060005260206000f35b6000600782029050604d565b91905056 ', info: {language: ' solidity ', languageVersion : ' 0 ', compilerversion: ' 0.9.13 ', abidefinition: [{constant:false, inputs: [{name: ' A ', type: ' uint256 '}], name: ' Mul Tiply ', outputs: [{name: ' d ', type: ' uint256 '}], type: ' function '}], Userdoc: {methods: {}}, Developerdoc: {metho DS: {}}, Source: ' Contract test {function multiply (uint a) returns (UINT D) {return a * 7;} '}} "' **note** compiler supports ' RPC &LT;[HTTPS://GITHUB.COM/ETHEREUM/WIKI/WIKI/JSON-RPC] (https://github.com/ethereum/wiki/wiki /JSON-RPC) > ' __, so you can use [Web3.js] (https://github.com/ethereum/wiki/wiki/JavaScriptAPI#web3ethcompilesolidity)   Connect to   ' Geth '   via RPC/IPC. The following example shows how to use the Json-rpc   ' Geth '  To use the compiler. ' $ geth--datadir ~/eth/--loglevel 6--logtostderr=true--rpc--rpcport 8100--rpccorsdomain ' * '--mine console 2&GT;&G T ~/eth/eth.log$ curl-x POST--data ' {"JSONRPC": "2.0", "Method": "Eth_compilesolidity", "params": ["Contract Test { function multiply (UINT a) returns (UINT D) {return a * 7;} "]," id ": 1} ' http://127.0.0.1:8100 '" the compiler generates a contract object for each individual contract in the source code, Command   ' eth.compile.solidity '   returns the mapping of the contract name and the contract object. In this example, our contract is named   ' Test ' &nbsp, so the command   ' eth.compile.solidity (source). Test '   Returns the contract object named Test and contains the following related fields: ' Code ': Compile generated ethereum virtual machine bytecode ' info ': Additional metadata ' source ' for compiler output ' language ': The programming language used in the contract (solidity, serpent, LLL) ' Languageversion ' : Version number ' compilerversion ' of the contract language: The version number of the compiler used to compile the contract code ' abidefinition ': Application Binary Interface definition   ' userdoc ':  [natspec Doc provided to the user] ' Developerdoc ': the most intuitive output structure (' code '   and   ' info ') for the developer's  [natspec Doc] compiler reflects two completely different  ** deployment paths **  The compiled Evmcode will be sent to specific transactions on the blockchain, and the remainder (info) will be stored in the centralized blockchain cloud as the metadata for the perfect code. If your source code contains multiple contracts, then the output will contain the entry information for each contract, and the expansion information of the contract can be obtained by name, and you can try the effect by looking at the current Globalregistrar contract: "Contracts = eth.compile.solidity (GLOBALREGISTRARSRC) "# # # Create and deploy a contract before starting this chapter, make sure you have an unlocked account and there is some money in it. You can now initiate a transaction to an empty address  [by using the EVM code in the previous section] (https://github.com/ethereum/wiki/wiki/JavaScript-API#web3ethsendtransaction)  . **note** This can be done in an easier way, i.e. via  [real-time online solidity compiler] (https://ethereum.github.io/browser-solidity/)   or  [mix IDE] (Https://github.com/ethereum/wiki/wiki/Mix:-The-DApp-IDE)  . ' var primaryaddress = Eth.accounts[0]var Abi = [{constant:false, Inputs: {name: ' A ', type: ' uint256 '}}]var Mycontra ct = eth.contract (ABI) var contract = Mycontract.new (arg1, arg2, ..., {from:primaryaddress, data:evmbytecodefromprevious Section}) ' All binary data will be serialized into hexadecimal format, and the hexadecimal string is always prefixed with   ' 0x '  . **note** Please note   ' arg1, arg2,  '   is the construction parameter of the contract, can accept any input, if the contract does not need any construction parameters then these parameters can be ignored. It is worth noting that you will have to pay some fees to perform these steps, and once the trades are packaged into chunks, your account balance will be deducted according to the gas cost rules of the ethereum virtual machine, and after some time your trade will appear in a block that is confirmed to be consistent, and your contract now exists in the blockchain. Here's how to perform these steps asynchronously: "' mycontract.new ([Arg1, Arg2, ...,]{from:primaryaccount, Data:evmcode}, function (err, contract) {if (!err && contract.address) console.log (contract.address);}); "' # # The interaction of the contract usually uses the abstraction Layer  [eth.contract ()] (https://github.com/ethereum/wiki/wiki/JavaScript-API#web3ethcontract)   to complete the interaction with the contract, the function returns a JavaScript object that contains all the contract functions that can be called by JavaScript. The standard method for describing the available functions of a contract is the  [abi definition] (Https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI), which is an array, The array contains the call signature and return value for each available contract function. "var Multiply7 = eth.contract (contract.info.abiDefinition); var myMultiply7 = multiply7.at (address); Now all the functions defined in the ABI can be used in the contract instance, you can call it in one of the following two ways: "' > MyMultiply7.multiply.sendTransaction (3, {from:address})" 0x12345 "> MyMultiply7.multiply.call (3) 21" When using   ' sendtransaction '  , the function is called by sending a trade. This method consumes the etheric currency, and the call is permanently recorded in the blockchain, and the return value is the hash value of the transaction. When using   ' call '  , the function executes on the local virtual machine (EVM), which is the return value of the function. Calls in this way are not recorded in the blockchain and therefore do not change the internal state of the contract, which is called a constant function call. This method of invocation does not consume the etheric currency. Only care about the return value of the case you should use   ' call ' &nbsp, if you are concerned about the status of the contract then use   ' sendtransaction '  . In the above example, the change of contract status is not involved, so   ' sendtransaction '   callIt will only burn fuel (gas) to increase the entropy of the universe. # # Contract metadata in the last section we explained how to create a contract on a blockchain, and then we deal with the contents of the compiler output, the contract metadata, or the contract information. When interacting with a contract that you have not yet created, you may want to explain the document or view its source code. The contract author is encouraged to register such information through the blockchain or the services of a third-party agency, such as:  [etherchain] (https://www.etherchain.org/contracts)  . api  ' admin '   provides a convenient way to view contracts that register this type of information. "//Get the contract info for contract address to do manual verificationvar info = admin.getcontractinfo (address)//Loo Kup, Fetch, Decodevar Source = Info.source;var Abidef = info.abidefinition "The basic mechanism of this work is: * Contract information is uploaded to a publicly accessible location address  * uri*  * Know the contract address anyone can find the relevant  *uri* these contract information is packaged by two-step blockchain registration: * First step: A contract called   ' Hashreg '   is signed by the content hash the contract code. * Step two: The contract called   ' Urlhint '   is registered via the Content hash URL. These  [registration contracts] (HTTPS://GITHUB.COM/ETHEREUM/GO-ETHEREUM/BLOB/DEVELOP/COMMON/REGISTRAR/CONTRACTS.GO)   are used as frontier ( Frontier) version, and is brought into the home (Homestead) version. With this structure, you only need to know the address of the contract and then get to the URL to get all the metadata related to the contract. If you are a qualified contract creator, you need to follow the steps below: 1. Deploy the contract itself to the Blockchain 2. Gets the contract information for the JSON file 3. Deploy the JSON file of the contract information to the URL of your choice 4. Registration code Hash--Content hash--URLJS API provides help to make these steps very simple, call   ' Admin.register '   to get the contract summary, store the digest serialization into the specified JSON file, calculate the file's content hash, and eventually register the content hash as a code hash. A single You deploy these files to any URL, you can register your content hash URL on the blockchain by using   ' Admin.registerurl '   (if you use a fixed content addressing model as a document store then Rul-hint is not required). "Source =" Contract Test {function multiply (uint a) returns (UINT D) {return a * 7;}} " Use SOLC to compile contract = eth.compile.solidity (source). test//Create Contract object var mycontract = Eth.contract ( contract.info.abiDefinition)//Contract summary information, serialized into the specified json file Contenthash = Admin.saveinfo (Contract.info, "~/dapps/shared/ Contracts/test/info.json ")//contract is sent to the blockchain mycontract.new ({from:primaryaccount, data:contract.code}, function (Error, Contract) {if (!error && contract.address) {//compute the content hash and register it with ' Hashreg ' as the Code hash//Use address to send the transaction//return the content we used to register the URL hash adm In.register (Primaryaccount, contract.address, Contenthash)//deploy ~/dapps/shared/contracts/test/info.json to a URL Admin.registerurl (primaryaccount, hash, url)}); "' # # test contracts and transactions typically test and debug contracts and transactions, this chapter introduces several debugging tools and practice methods. To test contracts and transactions, and to avoid having a real impact, you'd better operate on a private blockchain, which can be implemented by configuring the network ID (selecting a unique integer), and no other peer nodes are required. RecommendedThe practice is to set up additional data directories and ports for the test to avoid possible effects from other nodes (assuming that the default parameters are used). Run   ' Geth ' &nbsp with debug mode, and set the highest level of logging: ' ' Geth--datadir ~/dapps/testing/00/--port 30310--rpcport 8110--networkid 4567890--nodiscover--maxpeers 0--vmdebug--verbosity 6--pprof--pprofport 6110 console 2>> ~/dapp/testint/00/00. Log "' Before submitting any transaction, you need to set up your test chain, please check the details:  <cite style=" Box-sizing:border-box; >test-networks</cite> '//Create account. would prompt for Passwordpersonal.newaccount ();//Name your primary account, would often use itprimary = eth.accounts[0];// Check your balance (denominated in ether) balance = Web3.fromwei (eth.getbalance (primary), "ether");//Assume an existing UN Locked Primary accountprimary = eth.accounts[0];//mine blocks to generate ether//starting Minerminer.start (4);//Slee P for ten blocks (this can take quite some time). admin.sleepblocks;/Then stop mining (just not to burn heat in vain) m Iner.stop (); balance = Web3.fromwei (eth.getbalance (primary), "Ether"); "' You can enforce them after the transaction is created, as follows: '' Miner.start (1); admin.sleepblocks (1); Miner.stop (); "You can check for unverified transactions by:" '//Shows transaction pooltxpool.status// Number of pending Txseth.getblocktransactioncount ("Pending");//Print all pending Txseth.getblock ("Pending", true). Transactions "If a transaction creation contract is submitted, you can check if the required code has been inserted into the current chunk: ' Txhash = eth.sendtansaction ({from:primary, data:code})/... miningcontractaddress = Eth.gettransactionreceipt (Txhash); Eth.getcode (contractaddress) "The content of this article originates from the Ethereum community, the crab translation. By the way, share a beginner's [Ethereum Tutorial] (HTTP://XC.HUBWIZ.COM/COURSE/5A952991ADB3847553D205D1), a tutorial that speaks the above content more clearly and thoroughly. 497 reads  
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.