Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the entry-level knowledge points of intelligent contract in ethernet square

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article introduces the relevant knowledge of "what are the basic knowledge points of intelligent contract in Ethernet Square". In the operation of actual cases, many people will encounter such a dilemma. Next, let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

What is the Yi Tai Fong Intelligence contract?

The etherfang intelligent contract is a collection of code (its function) and data (its state) stored in the etherfang block chain with a specific address. Intelligent contract accounts can transmit messages to each other to achieve Turing complete operation. The intelligent contract runs on the block chain with ethersquare-specific binary bytecodes through the ethersquare virtual machine (EVM).

Etherfang smart contracts are usually written in a high-level language called Solidity and are compiled into bytecode and uploaded to the chunk chain.

Solidity

Solidity is a JavaScript-like language that allows you to develop smart contracts that can be compiled into EVM bytecode. It is now the flagship language of ethernet and is the most popular.

Write a contract

The language that does not implement the Hello World program is incomplete, and in the ethernet environment, Solidity does not have a clear way to "output" a string. The closest way is to use the log event to put a string in the block chain:

Contract HelloWorld {event Print (string out); function () {Print ("Hello, World!");}}

After each execution of this contract, a log is put into the block chain through Print with the parameter "Hello World".

Compilation contract

The ethernet intelligent contract developed by solidity can be compiled through a variety of mechanisms.

Use the solc compiler from the command line.

Use web3.eth.compile.solidity through the javascript console provided by geth or eth`` (you still need to install the ``solc compiler).

Through a real-time online compiler.

Through Ethereum Wallet.

Set up the solidity compiler in geth

If you start the geth node, you can check which compilers are available with the following command.

> web3.eth.getCompilers (); ["lll", "solidity", "serpent"]

This command returns an array of strings for the currently available compiler.

Note

The solc compiler is installed with cpp-ethereum, and as an alternative, you can compile it yourself.

If your solc execution file is not in the specified standard path, you can specify the solc execution path with the-- solc parameter.

$geth-- solc / usr/local/bin/solc

Similarly, you can do this at run time from 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 compiles 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, which returns the result a * 7 by entering a positive integer a.

You have prepared the environment for compiling solidity code, using geth's JS command console eth.compile.solidity ():

> contract = eth.compile.solidity (source) .test {code: '605280600c6000396000f3006000357c0100000000000000000000000000000000000000000000000000000000000000000000000000000000098063c6888fa114602e57005b60376004356041565b8060005602060007829050604d565b91905056cm, abiDefinition: [{constant: false, inputs: [{name:' ajar, type: 'uint256'}], name:' multiply' Outputs: [{name: 'methods, type:' uint256'}], type: 'function'}], userDoc: {methods: {}}, developerDoc: {methods: {}}, source:' contract test {function multiply (uint a) returns (uint d) {return a * 7 }}

Note

The compiler supports RPC _ _, so you can use web3.js and connect to geth through RPC/IPC.

The following example shows how to use the compiler by using JSON-RPC 's geth.

$geth-- datadir ~ / eth/-- loglevel 6-- logtostderr=true-- rpc-- rpcport 8100-- rpccorsdomain'*'- mine console 2 > > ~ / eth/eth.log$ curl-X POST-- data'{"jsonrpc": "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, and the command eth.compile.solidity returns the mapping between the contract name and the contract object. In this example, our contract is called test, so the command eth.compile.solidity (source). Test returns a contract object named test And contains the following related fields: code: compiled ethersquare virtual machine bytecode info: extra metadata output by the compiler source: source code language: programming language used by the contract (Solidity, Serpent, LLL) languageVersion: version number of the contract language compilerVersion: version number of the compiler used to compile the contract code abiDefinition: application binary interface definition userDoc: [NatSpec Doc] developerDoc: [NatSpec Doc] provided to the user

The compiler's most intuitive output structures (code and info) reflect two completely different deployment paths, the compiled EVMcode will be sent to the blockchain for specific transactions, and the rest (info) will be stored in the decentralized blockchain cloud as metadata to improve the code.

If your source code contains multiple contracts, the output will contain the entry information of each contract. The contract expansion information can be obtained by name. You can try the effect by looking at the current GlobalRegistrar contract:

Contracts = eth.compile.solidity (globalRegistrarSrc) create and deploy a contract

Before you start this chapter, please make sure that you have an unlocked account and that there is some money in it.

You can now initiate a transaction to an empty address using the EVM code in the previous section.

Note

This can be done in an easier way, that is, through a real-time online Solidity compiler or Mix IDE.

Var primaryAddress = eth.accounts [0] var abi = [{constant: false, inputs: {name: 'asides, type:' uint256'}}] var MyContract = eth.contract (abi) var contract = MyContract.new (arg1, arg2,..., {from: primaryAddress, data: evmByteCodeFromPreviousSection})

All binary data is serialized into hexadecimal format, and hexadecimal strings are always prefixed with 0x.

Note

Please note that arg1, arg2,... Are the construction parameters of the contract, which can accept any input, and can be ignored if the contract does not require any construction parameters.

It is worth pointing out that you have to pay some fees to perform these steps, and once the transaction is packaged into a block, the balance of your account will be deducted according to the gas fee rules of the Ethernet Fang virtual machine, after some time, your transaction will appear in a block where the status is confirmed to be consistent, and your contract now exists in the block chain.

These steps are performed asynchronously as follows:

MyContract.new ([arg1, arg2,...,] {from: primaryAccount, data: evmCode}, function (err, contract) {if (! err & & contract.address) console.log (contract.address);); contract interaction

The abstraction layer eth.contract () is usually used to complete the interaction with the contract, which returns a JavaScript object that contains all the contract functions that can be called by JavaScript.

The standard way to describe the functions available for contracts is the ABI definition, which is an array containing the call signatures and return values of each available contract function.

Var Multiply7 = eth.contract (contract.info.abiDefinition); var myMultiply7 = Multiply7.at (address)

Now that all the functions defined in ABI can be used in the contract instance, you can call them in one of two ways:

> myMultiply7.multiply.sendTransaction (3, {from: address}) "0x12345" > myMultiply7.multiply.call (3) 21

When using sendTransaction, the function is called by sending a transaction. The etheric currency is consumed in this way, and the call is permanently recorded in the blockchain, and the return value in this way is the hash value of the transaction.

When using call, the function is executed on the local virtual machine (EVM), and the return value of the call is the return value of the function. Calls in this way are not recorded in the block chain and therefore do not change the internal state of the contract, which is called constant function calls. This invocation method does not consume etheric currency.

You should use call if you only care about the return value, and use sendTransaction if you are concerned about the status change of the contract.

In the above example, it does not involve changing the contract state, so the sendTransaction call will only burn fuel (gas) for nothing to increase the entropy of the universe.

Contract metadata

In the previous section we explained how to create a contract on a blockchain, and then we dealt with the compiler output, contract metadata or contract information.

When interacting with a contract you haven't created yet, you may want to document or view its source code. Contract authors are encouraged to register such information through blockchain or third-party services, such as EtherChain. API admin provides a convenient way to view contracts that register this kind of information.

/ / get the contract info for contract address to do manual verificationvar info = admin.getContractInfo (address) / / lookup, fetch, decodevar source = info.source;var abiDef = info.abiDefinition

The basic mechanism for this work to take effect is:

Contract information is uploaded to a publicly accessible location address URI

Anyone who knows the contract address can find the relevant URI

This contract information is packaged through a two-step blockchain registration: * step 1: a contract called HashReg registers the contract code through a content hash. * step 2: a contract called UrlHint registers url through a content hash. These registration contracts are part of the Frontier version and are brought into the Homestead version.

Using this structure, you only need to know the address of the contract, then get the url, and then get all the metadata related to the contract.

If you are a competent contract creator, you need to follow these steps:

Deploy the contract itself to the blockchain

Get the json file of contract information

Deploy the json file of contract information to the url of your choice

Registration code hash-> content hash-> url

JS API provides help to make these steps very simple, calling admin.register to get the contract summary, serializing the summary into the specified json file, calculating the content hash of the file, and eventually registering the content hash as a code hash. Once you deploy these files to any url, you can register your content hash url on the block chain by using admin.registerUrl (rul-hint is not required if you use a fixed content addressing model for document storage).

Source = "contract test {function multiply (uint a) returns (uint d) {return a * 7 }} "/ / use solc to compile contract = eth.compile.solidity (source). Test// creates contract object var MyContract = eth.contract (contract.info.abiDefinition) / / contract summary information Serialize to the specified json file contenthash = admin.saveInfo (contract.info, "~ / dapps/shared/contracts/test/info.json") / / send the contract to MyContract.new ({from: primaryAccount, data: contract.code}, function (error) on the block chain Contract) {if (! error & & contract.address) {/ / calculate the content hash and register it through `HashReg` as the code hash / / send the transaction / / return the content hash admin.register (primaryAccount, contract.address, contenthash) we use to register url / / deploy ~ / dapps/shared/contracts/test/info.json to a url admin.registerUrl (primaryAccount, hash, url)}}) Test contracts and transactions

Contracts and transactions are usually tested and debugged. In this chapter, we introduce several debugging tools and practices. To test contracts and transactions and avoid real impact, you'd better operate on a private chunk chain, which can be done by configuring the network ID (select a unique integer) without the need for other peer nodes. The recommended practice is to set up additional data directories and ports for the test to avoid possible effects from other nodes (assuming running with default parameters). Run geth in 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. For details, please see: test-networks

/ / create account. Will prompt for passwordpersonal.newAccount (); / / name your primary account, will often use itprimary = eth.accounts [0]; / check your balance (denominated in ether) balance = web3.fromWei (eth.getBalance (primary), "ether"); / / assume an existing unlocked primary accountprimary = eth.accounts [0]; / / mine 10 blocks to generate ether// starting minerminer.start (4); / / sleep for 10 blocks (this can take quite some time) .admin.blocks (10) / / then stop mining (just not to burn heat in vain) miner.stop (); balance = web3.fromWei (eth.getBalance (primary), "ether")

After you create deals, you can enforce them, as follows:

Miner.start (1); admin.sleepBlocks (1); miner.stop ()

Unvalidated deals can be checked as follows:

/ / shows transaction pooltxpool.status// number of pending txseth.getBlockTransactionCount ("pending"); / / print all pending txseth.getBlock ("pending", true) .transactions

If you have submitted a deal creation contract, you can check whether the required code has been inserted into the current block:

Txhash = eth.sendTansaction ({from:primary, data: code}) / /. Miningcontractaddress = eth.getTransactionReceipt (txhash); eth.getCode (contractaddress) "what are the basic knowledge points of intelligent contract in Ethernet Square"? thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report