Statement: The following is the "Xunlei Global Blockchain Application Competition Development Guide" document written by Xunlei Company, why use the document written by Xunlei Company as a blockchain development guide?
Thunder is actually a private chain built with Ethereum smart contracts, the technology has been very mature, and it has in-depth research on blockchain technology, which has guiding significance for our blockchain development.
As the saying goes, "draw inferences from one example", we can develop other blockchain applications by reading the blockchain development guide document written by Xunlei, thanks to Xunlei.
The document reads:
1/16 Thunder Global Blockchain Application Competition Development Guide Contract development into the line recommendation 1. Before writing smart contracts, you need to have a certain understanding of blockchain fundamentals (attached: Ethereum Overview). 2. Learn the solidity language (solidity API). 3. Learn to use the truffle framework in combination with solidity learning. Use truffle develop locally Run contracts in a blockchain environment. 4. Learn and use zeppelin-solidty (a standardized contract framework dedicated to security) and design integration Contract mode, separate data and logical contracts, control permission security, and consider upgrade logic. 5. Learn to interact with contracts using web3.js. Use the Metamask plugin and web service with blockchain Interaction. 6. Forum Q&A: http://wanke.xunlei.com/forum.php? mod=forumdisplay&fid=53 (Any issues you encounter can be reverted on this forum.) We will reply to you within 3 working days) Basic concepts Blockchain Blockchain is a decentralized distributed computing system, the main feature of which is the permanent immutability of data, It cannot be forged, and has a high degree of openness, transparency, and trust. The core technologies include the Byzantine Fault Tolerant Consensus Algorithm (PBFT), encryption technology, P2P technology, etc. Transaction Blockchain can be understood as a globally shared transaction database system. Any software with permission can read it Take data from the blockchain network. When it is necessary to change the data in the block network, a blanket must be initiated There are requests accepted by block nodes, which are collectively referred to as transactions in the system. Transactions are transactional and are submitted to the blockchain, either not all or all executed. A trading executive After the row is completed, it is permanently saved to the blockchain and cannot be modified or executed again. Transactions are initiated and signed by the account in the system, and through cryptography, transactions can only be held by the private key 2/16 Someone initiates it, others cannot modify and forge. This ensures the authenticity and security of the transaction. Account There are two types of accounts in the blockchain system, one is external and the other is the contract account. External account owned Your own unique public and private keys, and your account is controlled by this key pair. Futures accounts have their own code, and the account is made by Own code control. The account is identified by an address, and the address length is the same, and there is no difference between the two types of accounts. The address of the external account is provided by The public key is generated, and the contract address uses the address from which the contract account was created and the number of transactions that created the contract account (nonce) is produced. Contracts are deployed by the official address, and ordinary accounts cannot directly publish contracts. The user's combination It must be officially reviewed and released by Xunlei. Within the system, there is no difference between the two types of accounts. Each account has 256bits inside the system The key-value storage structure up to 256 bits is called storage. Each account has a balance called balance, in wei, can be modified by sending a transaction with a numerical value to the account. Contract A contract is a blockchain account that stores the code, and the contract call is made by sending transactions to this account. When The previous more popular contract programming language was Solidity. Currently, the contest only supports contract submission in Solidity language. The contract is divided into two parts, data storage and function, the data stores the state of the contract, and the function is the contract The external interface realizes data query and state modification by calling functions. Write a contract through a programming language, and get the EVM bytecode after compilation. By sending a transaction to the contract account, real Current contract call. Gas Gas is the payment unit of the blockchain, and when a transaction is created, a certain amount of gas will be specified. Lord If it is to constrain the amount of computation on the transaction and to pay a fee for the execution of the transaction. During the execution of the transaction, Gas It will be consumed by a rule set by the EVM. Gas price is a value specified by the transaction creator and the number of fees required to execute the transaction The amount is Gas_Price*Gas. Transaction Ends If there is a gas leftover, the remaining portion is returned to the creator suggestion users. If the gas is insufficient, the transaction execution will fail, and the transaction will fail to prevent flood attacks for system security The handling fee is not returned. The smallest unit of gas price is wei, 10^18 wei = 1 chain gram. Solidity 3/16 Solidity is a high-level programming language designed for smart contracts, running on EVM (Ethereum). Virtual Machine)。 The language design implementation is influenced by C++/Python/JavaScript. Solidity is a strongly typed language that supports inheritance, polymorphism, interfaces, abstraction, libraries, custom data types, and more Sex. Solidity supports assembly instruction programming, and the code is compiled into bytecode and runs on the EVM. Solidity is The most popular smart contract development language is also the language recommended and supported by the Thunder Contract Platform. Notes: 1. Ethereum Virtual Machine is a virtual environment on Ethereum that provides a runtime environment for smart contracts Simulated machine. The competition platform is compatible with EVM, but it must comply with the usage restrictions of the official platform. 2. Account types are divided into external accounts (ordinary trading account addresses) and futures accounts. Create a contract It is the process of sending a transaction to the destination account address 0. 3. The competition specifies the use of truffle (truffle v4.1.5 solidity v0.4.21) to develop intelligent combinations The platform will verify the bytecode according to the source code of the document submitted by the participant. , Develop contracts with truffle Smart contract solidity development framework truffle. It provides a complete set of development, debugging and editing Translation, deployment, and testing of on-premises environments. You can use the template command unbox quickly based on some templates Generate the corresponding contract structure. Install Truffle npm i -g truffle [root@opennode sandai]# truffle version Truffle v4.1.5 (core: 4.1.5) Solidity v0.4.21 (solc-js) Begin 1. Initialize the contract project with truffle 4/16 mkdir simple-storage cd simple-storage truffle init 2. Create a new contract file: You can use truffle to create contract You can also create a new file directly from the SimpleStorage command line contract/SimpleStorage.sol // SimpleStorage.sol pragma solidity ^0.4.21; contract SimpleStorage { uint myVariable; function set(uint x) public { myVariable = x;
} function get() constant public returns (uint) { return myVariable;
}
} 3. Add migrate scripts: You can use truffle create migration 2_deploy_contract Command-line method is added, and you can also directly create a new file migrations/2_deploy_contract.js 2_deploy_contract.js; the execution of truffle migrate The line order is related to the file name, so multiple deployment scripts need to be named in order var SimpleStorage = artifacts.require("SimpleStorage"); module.exports = function(deployer) { deployer.deploy(SimpleStorage); 5/16 }; 4. Run the truffle compile contract, and the compiled contract is in the build folder. per contract There is a corresponding json file containing bytecode, abiCode, etc. required for deployment 5. Edit the truffle.js to set up the truffle deployment contract and the RPC connection to interact with the blockchain. [root@localhost opennode]# vi truffle.js module.exports = {
networks: {
development: {
host: "127.0.0.1",
port: 8545, network_id: "*"
}
} }; 6. Turn on Truffle's default blockchain environment on the console. truffle develop Truffle Develop started at
http://127.0.0.1:9545/
Accounts: (0) 0x627306090abab3a6e1400e9345bc60c78a8bef57 (1) 0xf17f52151ebef6c7334fad080c5704d77216b732 (2) 0xc5fdf4076b8f3a5357c5e395ab970b5b54098fef (3) 0x821aea9a577a9b44299b9c15c88cf3087f3b5544 (4) 0x0d1d4e623d10f9fba5db95830f7d3839406c6af2 (5) 0x2932b7a2355d6fecc4b5c0b6bd44cc31df247a2e (6) 0x2191ef87e392377ec08e7c08eb105ef5448eced5 (7) 0x0f4f2ac550a1b4e2280d04c21cea7ebd822934b5 (8) 0x6330a553fc93768f612722bb8c2ec78ac90b3bbc (9) 0x5aeda56215b167893e80b4fe645ba6d5bab767de 6/16 Private Keys: (0) c87509a1c067bbde78beb793e6fa76530b6382a4c0241e5e 4a9ec0a0f44dc0d3 (1) ae6ae8e5ccbfb04590405997ee2d52d2b330726137b87505 3c36d94e974d162f (2) 0dbbe8e4ae425a6d2687f1a7e3ba17bc98c673636790f1b8 ad91193c05875ef1 (3) c88b703fb08cbea894b6aeff5a544fb92e78a18e19814cd8 5da83b71f772aa6c (4) 388c684f0ba1ef5017716adb5d21a053ea8e90277d086833 7519f97bede61418 (5) 659cbb0e2411a44db63778987b1e22153c086a95eb6b18bd f89de078917abc63 (6) 82d052c865f5763aad42add438569276c00d3d88a2d062d3 6b2bae914d58b8c8 (7) aa3680d5d48a8283413f7a108367c7299ca73f553735860a 87b08f39395618b7 (8) 0f62d96d6675f32685bbdb8ac13cda7c23436f63efbb9d07 700d8669ff12b7c4 (9) 8d5366123cb560bb606379f90a0bfd4769eecc0557f1b362 dcae9012b548b1e5
Mnemonic: candy maple cake sugar pudding cream honey rich smooth crumble sweet treat ⚠ Important ⚠ : This mnemonic was created for you by Truffle. It is not secure. Ensure you do not use it on production 7/16 blockchains, or else you risk losing funds. truffle(develop)> This provides a native blockchain environment for Truffle to run contracts, generating 10 accounts by default, each of which is generated The initial account balance is 100 ether. You can also use the graphical interface provided by Ganache , you need to modify the port to which the configuration is connected. 7. Execute the truffle migrate port deployment contract in a new console (or in truffle develop console to perform migrate). 8. Test the contract code with truffle develop. SimpleStorage.deployed().then(function(instance ){return instance.get.call(); }).then(function(value) {return value.toNumber()}) // 0 SimpleStorage.deployed().then(function(instance ){return instance.set(100); }); Output transaction information SimpleStorage.deployed().then(function(instance ){return instance.get.call(); }).then(function(value) {return value.toNumber()}); // 100 9. Test the contract with truffle test Use truffle create test SimpleStorage to create a new or Create a new file test/SimpleStorage.test.js directly. const SimpleStorage = artifacts.require('SimpleStorage'); contract('SimpleStorage', function(accounts) { 8/16 it("should assert true", function(done)
{ var simpleStorage = SimpleStorage.deployed(); var instance; simpleStorage.then(res => { instance = res; return instance.get() }).then(value => { assert.equal('0', value.toNumber(), 'not equal 0') }).then(() => { instance.set(100) }).then(() => { return instance.get() }).then(value => { assert.equal('100', value.toNumber(), 'not equal 100') }) done(); }); }); In the new console, enter truffle test ./test/SimpleStorage.test.js. 10. Test contracts with remix Put contracts developed using truffle in remix to quickly modify Deployment and invocation of the proposed contract. Remix provides a compilation runtime environment for contracts and can be controlled by the contract The table can see the detailed information of each transaction of the contract, such as input and output parameters, signed method data, transaction hash and other information. Support debugging. 1. Use compile detail to see the contract compilation details. Including bytecode, abi and using web3.js rapid deployment of the Drip Ah method. 9/16 2. Use run to create a contract, and the console can view the transaction that created the contract. Use Truffle Unbox to create interactive contract apps The above steps create a contract environment that can be compiled, deployed, and debugged using basic truffle init. Below Create a new project with Truffle Unbox, which provides us with a truffle project template, inside Some contract application interaction environment dependencies. You can check out the official offerings in Truffle Boxes Template boxes. The following is the react template. 1. New project truf-react mkdir truf-react 10/16 cd truf-react truffle unbox react The unbox process downloads the extraction template and performs operations such as npm install. 2. Configure the truffle.js of the project module.exports = { // See <http://truffleframework.com/docs/advanced/confi guration> // to customize your Truffle configuration!
networks: {
development: {
host: '127.0.0.1',
port: '9545', network_id: '*' // Match any network id
}
} }; 3. Start a truffle develop 4. Amendment to the SRC/App.js import React, { Component } from 'react' import SimpleStorageContract from '.. /build/contracts/SimpleStorage.json' import getWeb3 from './utils/getWeb3' import './css/oswald.css' import './css/open-sans.css' import './css/pure-min.css' 11/16 import './App.css' const contract = require('truffle-contract') const simpleStorage = contract(SimpleStorageContract) class App extends Component { constructor(props) { super(props) this.state = {
storageValue: 0,
web3: null,
inputValue: 0,
address: null
} this.changeValueHandle = this.changeValueHandle.bind(this) this.setHandle = this.setHandle.bind(this)
} componentWillMount() { // Get network provider and web3 instance. // See utils/getWeb3 for more info. getWeb3 .then(results => { this.setState({
web3: results.web3 }) // Instantiate contract once web3 provided. 12/16 this.instantiateContract() }) .catch(() => { console.log('Error finding web3.') })
} instantiateContract() {
/* * SMART CONTRACT EXAMPLE
* * Normally these functions would be called in the context of a * state management library, but for convenience I've placed them here. */ this.simpleStorageSet(5)
} changeValueHandle(event) { this.setState({
inputValue: Number(event.target.value) })
} setHandle() { this.simpleStorageSet(this.state.inputValue)
} simpleStorageSet(x) { simpleStorage.setProvider(this.state.web3.curren tProvider) // Declaring this for later so 13/16 we can chain functions on SimpleStorage. var simpleStorageInstance // Get accounts. this.state.web3.eth.getAccounts((error, accounts) => { simpleStorage.deployed().then((instance) => { simpleStorageInstance = instance this.setState({
address: instance.address }) // Stores a given value, 5 by default. return simpleStorageInstance.set(x, {from: accounts[0]}) }).then((result) => { // Get the value from the contract to prove it worked. return simpleStorageInstance.get.call(accounts[0]) }).then((result) => { // Update state with the result. return this.setState({ storageValue: result.c[0] }) }) })
} render() { return ( <div className="App"> <nav className="navbar pure-menu pure-menuhorizontal"> 14/16 <a href="#" className="pure-menu-heading puremenu-link">Truffle Box</a> </nav> <main className="container"> <div className="pure-g"> <div className="pure-u-1-1"> <h1>Good to Go!</h1> <p>Your Truffle Box is installed and ready.</p> <h2>Smart Contract Example</h2> <p>If your contracts compiled and migrated successfully, below will show a stored value of 5 (by default).</p> <p>Try changing the value stored on <strong>line 59</strong> of App.js.</p> <p>The stored value is: {this.state.storageValue}</p> <p>deployed contract address: {this.state.address}</p> </div> <div> <input type="number" onChange= {this.changeValueHandle}/> <button onClick={this.setHandle}>set</button> 15/16 </div> </div> </main> </div> );
}
} export default App Added the call of the contract set method. And show the address of the contract. 5. Open a new console and run npm run start 6. Open the http://lcoalhost:3000 in your browser to see the results of the contract. 7. Set the value of the contract storedData via the set and input boxes. 8. Enter in trufle develop
//将xxx替换为address SimpleStorage.at('xxxx').then(res => {return res.get()}) The return value of the BigNUmber type is obtained, and the value in the c array is set storedData. Use the browser plugin Metamask to interact with the blockchain Reference http://truffleframework.com/tutorials/pet-shop Participants submit documents The competition specifies the use of Truffle to develop smart contracts, with Truffle version v4.1.5 corresponding to the solcjs version v0.4.21. Developers need to submit the Truffle project zip package and related project introduction documents, which include, at least The following: 16/16 1. Truffle Project Basic File Structure: Build Contracts Migrations Test package.json truffle.js truffle-config.js README.md // Description of engineering documentation No node_modules required 2. Need to provide PPT or PDF explanation of the entire project product, including product background introduction, product significance, App download address (optional), product usage process introduction. Subsequent third-party developers can implement contract applications and Chain pockets according to the upcoming ThunderChain guidance document Interaction. Documentation & Tools solidity API truffle documentation Ganache provides a graphical interface for the native blockchain environment Zeppelin-Solidty is committed to a secure and standardized contract framework MetaMask provides browser plugins for browsers with a blockchain environment via RPC connections web3.js Ethereum-encapsulated JS for interacting with the blockchain Finally, the pdf document download:
Dev_Guide_zh.pdf
(373.55 KB, Number of downloads: 6)
|