Developer’s Guide to Smart Contract Open Platform

1. Document Description

1.1 Targeted Readers

This document is applicable to the enterprise or individual developers for smart contract app development based on ThunderChain technology. It guides the users to register, have enterprise and individual qualification authentication, submit, test and publish the smart contract, carry out app development based on the smart contract technology.

1.2 Release Notes

V1.0(2018.04.08)
Create the Document

2. Terms

2.1 Blockchain

A blockchain technology is a decentralized and distributed computing system characterized by permanent prevention from data falsification and forgery and high openness, transparency, and trustworthiness of data. Its core technologies include, among others, Practical Byzantine Fault Tolerance Algorithm (PBFT), encryption technology, and P2P technology, etc.

2.2 ThunderChain

ThunderChain is a high-performance Blockchain with millions of tps high-concurrent processing capability and one-second-confirmation capability created by its Onething Technologies. On this basis, ThunderChain Open Platform is built to assist developers in quickly developing and deploying smart contracts. Enterprises or individuals can easily implement their products and services to take easier steps to develop Blockchain applications.

2.3 Transaction

Blockchain can be deemed as a global shared transaction databse system. Any software with the authority can access the data in Blockchain network. When there is a need to change the data in Blockchain network, a request to be accepted by all the block nodes must be initiated. The request is universally called Transaction in the system. The transaction is transactional. If submitted to Blockchain, they are all executed or not executed at all. After one transaction is executed, it is permanently saved in Blockchain and no more revision or re-execution can be carried out. The transaction is initiated and signed by Account in the system. With the encryption technology, the transaction can only be initiated by private key owner, and others cannot revise or counterfeit, which ensures the authenticity and security of the transaction.

2.4 Account

There are two types of accounts in Blockchainsystem, namely external account and contract account. External account has its unique public key and private key, and is controlled by the key pair. Contract account has its own code and is controlled by its code. The account is identified by an address, and the address length is the same. There is no difference in the two types of accounts. The address of external account is generated by its public key, and contract address is generated by contract account address and nonce creating contract account. The smart contract of ThunderChain open platform is unitarily deployed by official address, and normal account cannot publish contract in ThunderChain. The user’s contract must pass official assessment and unitarily published by Thunder.

There is no treatment difference for the two types of accounts inside the system. Every account has a key-value storage structure of 256bits to 256bits in the system, which is called storage. There is a balance of each account, called balance, with the unit of wei. It can be revised by sending the transaction with value to the account.

2.5 Contract

Contract is Blockchain account that saves the codes, and achieves contract call by sending transaction to the account. The currently popular contract programming language is Solidity. Currently, the open platform only supports the smart contract submission in the language of Solidity. There are two parts of the smart contract, namely data storage and function. The data saves the contract status, and the function is external interface of the contract. The function call achieves data inquiry and status revision. The contract is edited in programming language, and EVM byte code will be received after compiling. When the transaction is sent to contract account, contract call is achieved.

2.6 Gas

Gas is payment unit of the Blockchain. When a transaction is created, it designates the payment of Gas in certain quantity. It mainly aims to restrict the transaction computing volume, and payment amount for transaction execution. In transaction execution process, Gas will be consumed according to EVM prescribed rules. Gas price is the value designated by the transaction creator. The payment amunt for transaction execution is Gas_Price*Gas. After transaction ends if there is remaining Gas, the remaining part will be returned to the user creating the suggestion. If Gas is insufficient, the transaction execution will fail. For the system security, and to avoid flood attack, the service fee of transaction failure will not be refunded. The minimum unit of Gas price is wei, 10^18 wei = 1 LinkToken. The current fixed value of Gas_Price is 10^11, and free setting is not available for now.

2.7 Solidity

Solidity is an advanced programming language designed for smart contract. The operation environment is EVM(Ethereum Virtual Machine). The language design realization is influenced by C++/Python/JavaScript. Solidity is strongly-typed language, and supports the features of inheritance, polymorphism, interface, abstraction, library, and user-defined data type, etc. Assembly instruction programming is available for Solidity. The code is compiled as byte code, which then operates on EVM. Solidity is the currently most popular smart contract development language, and the language recommended by and available on Thunder contract platform.

3. Beginner's Guide

3.1 Introduction to ThunderChain

3.1.1 What is ThunderChain?

ThunderChain is a high-performance Blockchain with millions of tps high-concurrent processing capability and one-second-confirmation capabilities created by its Onething Technologies. On this basis, ThunderChain Open Platform is built to assist developers in quickly developing and deploying smart contracts. Enterprises or individuals can easily uplinktheir products and services to take easier steps to develop Blockchain applications.

3.1.2 What is ThunderChain Open Platform?

ThunderChain Open Platform is an open platform for Blockchain services built by Onething Technologies on the strength of the "ThunderChain". Xunlei opens more than ten years of distributed technology precipitation and its hundreds of millions of user base, shares millions of active individuals of LinkToken ecology to lead the industry with a high starting point, which jointly build the world-leading Blockchain ecology.

3.1.3 What is LinkToken Exchange?

It allows the user of LinkToken Pocket to activate the LinkToken Pocket Exchange Module when LinkToken Pocket users scan QR codes or access from APP, making it easy to complete exchange of LinkToken into corresponding services.

3.1.4 What is Open Contract Platform?

ThunderChain provides stable, fast and low-cost blockchain services, helping developers reduce costs and create decentralized applications in various industries including financing, e-commerce, game and social media. It helps developers quickly deploy the smart contracts, allows enterprises to easily implement their products and services on the blockchain and develop blockchain applications more conveniently.

3.2 How to register for an account and authenticate

3.2.1 Developer Registration and Login

Before an individual or enterprise developer wants to use the LinkToken exchange and the smart contract, you must firstly regist as the user of the platform. The phone number is the unique identification of the user. After successful registration, you can bind the E-mail. Login

The registration process is as follows:

User registration process

3.2.2 E-mailBinding

After binding the E-mail, it is convenient to receive the message notification, which is convenient for contacting with the official. If you forget your password, you can reset your password via E-mail. [E-mail binding][E-mailbind]

3.2.3 Forget Password

User may fail to login if he/she forgot the password; under the circumstance, the password can be reset by phone number or email address.

Reset password by phone number verification code

[Reset password by E-mail verification][password_reset_E-mail]

3.2.4 Individual Authentication

Individual developers who want to submit a contract or use the LinkToken exchange function must first authenticate their personal information. Please register as a platform user before performing personal authentication. Please have your ID card and the photos of both sides of the ID card (the photos must be clear, where your profile picture must be included).

Authentication Now

3.2.5 Enterprise Authentication

Enterprise developers need to conduct enterprise authentication whose information includes the name of the enterprise, the scanned copy of the business license, the scanned copy of the legal representative's ID card or the scanned copy of the authentication. After the enterprise authentication is passed, the LinkToken exchange and smart contract functions can be used.

Authentication Now

3.3 How to create an app

LinkToken exchange and smart contract are related to the app. Before using the functions, the app must be created. Or else, the functions cannot be used. The user needs to submit the app information to the open platform for review. The app is in two types, namely mobile app and web app. Software package for downloading or verification should be provided for mobile app. The accessible website page and website registration information must be provided for web app.

Create mobile app

Create web app

3.4 How to Create Smart Contract

Before using the open platform to Create smart contract, please confirm that the smart contract has been submitted to test environment and passed function test.

Create Smart contract

4. Developer’s Guide to Smart Contract

4.1 Platform Usage Specifications

  1. For the purpose of security and legal compliance, the smart contract will be unitarily reviewed and published by ThunderChain, and normal account cannot publish contract. This restriction has relatively significant influence on contract function.
  2. The smart contract must meet the requirements of local laws and standards, and ThunderChain will carry out source code and binary system review for the submitted contract. The smart contract function accuracy and internal security of the smart contract should be ensured by the developer.
  3. Smart contract is decentralized software, and ThunderChain only provides contract execution platform. Contract update is determined by software logic. Please make software update available.
  4. Smart contract development of Thunder ChainBlockchain only supports the language of Solidity currently.
  5. In consideration of security and regulations, the smart contract provided by the developer cannot contain selfdestruct code for contract destruction.

4.2 Contract Development Fundamentals

4.2.1 Cautions

  1. Before editing smart contract, basic knowledge of [Blockchain basics] (http://solidity.readthedocs.io/en/develop/introduction-to-smart-contracts.html#blockchain-basics) should be gained. (P.S. ethereum-overview)
  2. Ethereum Virtual Machine is virtual machine on Ethereum that provides operation environment for smart contract. ThunderChain open platform is compatible with EVM, and the platform use restrictions of official platform should be observed.
  3. The account types are external account (normal transaction account address) and contract account.
  4. Contract creation is the process to send transaction to target account address 0.
  5. gas will be consumed in contract deployment and call process (change internal status variable of contract). gas_price*gas is the service fee incurred for each transaction.

4.2.2 compile

  1. Smart contract environment of browser compilation debugging operation Remix can be used to compile the smart contract, and there is no dependence on environment configuration.
  2. solcjs of npm package is used to globally install npm i -g solc. Solc is used in command line to compile corresponding contract.
  3. compile command using truffle.
  4. The platform recommends the development with truffle.

Smart contract solidity development framework truffle. A completed set of development, debugging, compilation, deployment and test local environment is provided. Template command unbox can be used to rapidly create corresponding contract framework according to some templates.

4.2.3 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)

4.2.4 Start

  1. Use truffle to initiate contract project

    mkdir simple-storage
    cd simple-storage
    truffle init
  2. Create smart contract file: Command line truffle Create smart contract SimpleStorage can be used to create, or directly create new file 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 script: Command line truffle create migration 2_deploy_contract can be used to add, or directly create new file migrations/2_deploy_contract.js

    // 2_deploy_contract.js;Execution sequence of truffle migrate command is related to file name. So the deployed scripts should be named in sequence
    var SimpleStorage = artifacts.require("SimpleStorage");
    module.exports = function(deployer) {
    deployer.deploy(SimpleStorage);
    };
  4. Execute compilation contract truffle compile, and the compiled contract will be in build folder. Every contract has a corresponding json file, which includes bytecode, abiCode and others for deployment.

  5. Edit truffle.js, and set truffle deploy contract and rpc connection of Blockchain interaction.

    [root@localhost opennode]# vi truffle.js
    module.exports = {
    networks: {
     development: {
       host: "127.0.0.1",
       port: 8545,
       network_id: "*"
     }
    }
    };
  6. The console enables truffle default Blockchain environment.

    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
    Private Keys:
    (0) c87509a1c067bbde78beb793e6fa76530b6382a4c0241e5e4a9ec0a0f44dc0d3
    (1) ae6ae8e5ccbfb04590405997ee2d52d2b330726137b875053c36d94e974d162f
    (2) 0dbbe8e4ae425a6d2687f1a7e3ba17bc98c673636790f1b8ad91193c05875ef1
    (3) c88b703fb08cbea894b6aeff5a544fb92e78a18e19814cd85da83b71f772aa6c
    (4) 388c684f0ba1ef5017716adb5d21a053ea8e90277d0868337519f97bede61418
    (5) 659cbb0e2411a44db63778987b1e22153c086a95eb6b18bdf89de078917abc63
    (6) 82d052c865f5763aad42add438569276c00d3d88a2d062d36b2bae914d58b8c8
    (7) aa3680d5d48a8283413f7a108367c7299ca73f553735860a87b08f39395618b7
    (8) 0f62d96d6675f32685bbdb8ac13cda7c23436f63efbb9d07700d8669ff12b7c4
    (9) 8d5366123cb560bb606379f90a0bfd4769eecc0557f1b362dcae9012b548b1e5
    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 Blockchains, or else you risk losing funds.
    truffle(develop)>

    It provides local Blockchain environment for truffle to operate the smart contract. 10 accounts will be created in default. The initial balance of each account is 100ether. The graphic interface app provided by Ganache can also be used, and the port configuring the connection should be revised.

  7. Execute contract migration and deployment truffle migrate on a new console (or execute migrate on truffle develop console).

  8. Use truffle develop contract test code.

    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. Use test contract truffle test Use truffle create test SimpleStorage to create or directly create file test/SimpleStorage.test.js.

    const SimpleStorage = artifacts.require('SimpleStorage');
    contract('SimpleStorage', function(accounts) {
     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();
     });
    });

    Enter truffle test ./test/SimpleStorage.test.js in newly-opened console.

  10. Use test contract remix Put contract developed with truffle in remix, and rapidly simulate contract deployment and call.
    remix provides contract compilation operation environment, and allows the review of details of each transaction of the smart contract in the console, such as input and output parameters, method data after signature, transaction hash, etc. Debugging is available.

  11. Use compile detail to view contract compilation details, such as bytecode, abi and method rapidly deployed with web3.js. picture_1.png

  12. Use run to create smart contract, and the console allows the review of the transaction creating the smart contract. picture.png

4.2.5 Use truffle unbox to Create Interactive Contract App

The above steps use basic truffle init to create a contract environment available for compilation, deployment and debugging.
Below truffle unbox is used to create a new project. Unbox provides truffle project template for us and embeds some environment dependence of contract app interaction.
Various template boxes provided by ThunderChain can be viewed in truffle boxes.
Below is react template.

  1. Create new project truf-react
    mkdir truf-react
    cd truf-react
    truffle unbox react

    In unbox process, template will be downloaded and decompressed, and operations such as npm install will be executed.

  2. Configure project truffle.js
    module.exports = {
     // See <http://truffleframework.com/docs/advanced/configuration>
     // to customize your Truffle configuration!
     networks: {
         development: {
             host: '127.0.0.1',
             port: '9545',
             network_id: '*' // Match any network id
         }
     }
    };
  3. Initiate one truffle develop
  4. Revise 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'
    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.
             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.currentProvider)
         // Declaring this for later so 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 smart 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-menu-horizontal">
                     <a href="#" className="pure-menu-heading pure-menu-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 (bdefault).</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>
                         </div>
                     </div>
                 </main>
             </div>
         );
     }
    }
    export default App

    The call of contract set method is newly added, and contract address is demonstrated.

  5. Open a new console and execute npm run start
  6. Open http://lcoalhost:3000 in browser and see the smart contract result.
  7. Set contract storedData value through set and input box.
  8. Input in trufle develop
    //Replace xxx with address
    SimpleStorage.at('xxxx').then(res => {return res.get()})
    // Get returned value inBigNUmber type. The value in c array is the value of storedData set.

    4.2.6 Use Browser Plug-in metamask to Interact with Blockchain

    Refer to http://truffleframework.com/tutorials/pet-shop

4.2.7 Reference File and Tool of Contract Development

solidity API
trufflefile ganache provides graphic interface of local Blockchain environment zeppelin-solidty is devoted to safe standardized contract framework MetaMask provides browser plug-in of Blockchain environment through RPC connection web3.js Ethereum packaging and Blockchain interaction js Smart Contract Security Best Practices

4.3 Contract Coding Method and Tool

For contract call and inquiry, input parameters are function and function parameter data after ABICode coding of the smart contract. For details, refer to solidity - Application Binary Interface Specification
Below iscorresponding coding data for contract call inABICode method in several modes.

4.3.1 Use remix to Call Smart Contract and Get data

When using remix to execute contract method, each transaction has corresponding transaction details. input of function call, Corresponding coding data for contract call inABICode method in several modes is shown as follows.
input is data in JSON sent to Blockchain environment during function call. In the corresponding open platform, the input data can be directly used as data of remix during contract call.
remix input data

4.3.2 Use ethers.js to Achieve Coding and Decoding

ethers.js is js dependence package of Ethereum, which includes the methods of coding function name according to ABICode and static method of coding parameters.
For example:

//HelloWorld.sol
pragma solidity^0.4.23;
contract HelloWorld {
    address public owner;
    string public info;
    constructor(address _owner) public {
        owner = _owner;
    }
    function saySomething(string _str) public returns(string) {
        info = _str;
        return info;
    }
}
//abi of coding function function saySomething
var ethers = require('ethers')
var  abi = [
    {
        "constant": false,
        "inputs": [
            {
                "name": "_str",
                "type": "string"
            }
        ],
        "name": "saySomething",
        "outputs": [
            {
                "name": "",
                "type": "string"
            }
        ],
        "payable": false,
        "stateMutability": "nonpayable",
        "type": "function"
    },
    {
        "inputs": [
            {
                "name": "_owner",
                "type": "address"
            }
        ],
        "payable": false,
        "stateMutability": "nonpayable",
        "type": "constructor"
    },
    {
        "constant": true,
        "inputs": [],
        "name": "info",
        "outputs": [
            {
                "name": "",
                "type": "string"
            }
        ],
        "payable": false,
        "stateMutability": "view",
        "type": "function"
    },
    {
        "constant": true,
        "inputs": [],
        "name": "owner",
        "outputs": [
            {
                "name": "",
                "type": "address"
            }
        ],
        "payable": false,
        "stateMutability": "view",
        "type": "function"
    }
];
var interface = new ethers.Interface(abi)
var abiInstance = interface.functions[abi[0].name] // abi[0] namely abi of saySomething function
return abiInstance.sighash // 0xfe6b3783

Method to get function parameter coding data:
Use encode method of ethers.utils.ABICoder. For example

// data of input parameter 'Hello World' for coding function saySomething
var abiCoder = new ethers.utils.AbiCoder()
return abiCoder.encode(['string'], ['Hello World'])
//0x0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000b48656c6c6f20576f726c64000000000000000000000000000000000000000000

input of actual called function is: first eight digits of functionsaySomething encode + encode of function input parameter. The result is

0xfe6b37830000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000b48656c6c6f20576f726c64000000000000000000000000000000000000000000

In comparison with above input value for using remix call method, it can be seen that the results are the same.

After contract execution ends, info value is set as "Hello World". Then request constant method ([same with 8.3 DemoContract Inquiry]( #83-Contract Call and Contract Inquiry Business)), info value is analyzed according to the result.

curl -k -X POST --data '{"jsonrpc":"2.0","method":"eth_call","params":[{"from":"0x7eff122b94897ea5b0e2a9abf47b86337fafebdc","to":"0xd5b0df861803a07f330868104eec92ebdcce4c79","data":"0x370158ea"}, "latest"],"id":1}' https://sandbox-blockchain.xunlei.com/call
{"jsonrpc":"2.0","id":1,"result":"0x0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000b48656c6c6f20576f726c64000000000000000000000000000000000000000000"}
var ethers = require('ethers')
var outputTypes = ['string']
var response = "0x0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000b48656c6c6f20576f726c64000000000000000000000000000000000000000000"
var abiCoder = new ethers.utils.AbiCoder()
abiCoder.decode(outputTypes, response)
// [ 'Hello World' ]

decode result analyzes corresponding parameters according to input outputTypes array length.

5. Contract Access Process

5.1 Contract Submission Review

After the developer develops the smart contract, it should be submitted to ThunderChain test environment for deployment and test. After the test verifies accuracy, it will be submitted to open platform and deployed in official environment. This process relies on the smart contract address deployed by test environment, and the transaction execution record of test environment will be reviewed.

5.2 Contract Submission Process in Test Environment

Test Environment Process

5.2.1 Register Developer Account for Test Environment

  1. Based on the test, the developer accesses the API to call get E-mail verification code. The verification code is valid for 30 minutes. Every unregistered E-mail can request 3 verification codes at most in 24 hours.
  2. The developer calls interface register with E-mail, and uses the verification code and E-mail from the previous step for registration.
  3. Test platform sends an E-mail to developer's E-mail address according to E-mail address (required) and verification code (required) submitted by developer interface, which contains servce_id and secret.
  4. All the subsequent test interface requests need to include this E-mail address and md5 value of combining string of E-mail address, service_id and secret. All the interfaces of test platform will verify this md5.
  5. The interface does not provide extra inquiry function. If the developer information is lost, please follow customer service process to recover.

5.2.2 Call the recharging interface

  1. Based on the test, the developer accesses the API to call test account recharging interface.
  2. After recharging interfacecall succeeds, test platform will transfer 1 LinkToken into address account submitted by the interface.
  3. The Blockchain environment of test platform is completely independent, so the test LinkToken can be only used in test environment, and will be ineffective when transferred into other Blockchain environment.
  4. Each email address can at most initiate 10 transfer requests per day.
  5. In test environment, LinkToken Pocket test version should be used. Download address of LinkToken Pocket test version

5.2.3 Develop contract application and upper-level business

  1. Developers develop contract applications and encapsulate calls to contracts through upper-level business (APP, H5, etc.).
  2. For the smart contract development, refer to Developer’s Guide to Smart Contract.

5.2.4 Deploy the smart contract to ThunderChain test environment

  1. ThunderChain test and the formal environment do not provide a direct RPC connection to execute the smart contract to send the transaction. The release and invocation of the smart contract need to be implemented by calling the API interface.
  2. The developer deploys the smart contract to ThunderChain test environment by calling the smart contract release interface.
  3. The release of contract API interface requires contract bytecode and params. byetecode is bytecode compiled by contract, and params is code for deployment directly combined after bytecode after constructed function parameter is signed. Refer to Contract Coding Tool
  4. Since contract deployment is carried out by the platform, msg.sender should be avoided in contract constructor method. If the authority or caller restriction requires msg.sender, it can be replaced by user address input through parameters.

For example:

contract HelloWorld {
  address owner;
  constructor(address ownerArg) public {
    //owner = msg.sender; use ownerArg to replace msg.sender
    owner = ownerArg;
  }
}

5.3 Contract Submission Process in Product Environment

Before accessing to official environment, contract should be deployed in test environment and pass completed function test, and then be submitted for review of official environment.
When it is submitted for official review of open platform, the smart contract address in test environment should be submitted. The platform will carry out verification and review according to contract address in test environment & corresponding bytecode and bytecode submitted to official environment.

Contract Assessment Process

The steps are as follows

  1. Register account of development platform
  2. Authenticate individual or enterprise developer account
  3. Create app and submit for review
  4. Create new contract based on new app
  5. Submit contract contents, including contract address in test environment, source code package, byetecode, initialization parameters, and abicode, etc.
  6. Open platform reviews the smart contract according to bytecode of contract address in test environment and submitted bytecode, source code package, and transaction record of contract execution in test environment, etc.
  7. After passing the review, the smart contract can be released to generate contract address in official environment.

Submit (create) contract

Notes:

  • When accessing the formal environment, the platform will review the App or Web application for the smart contract application and check that whether the smart contract code complies with Platform Usage Specifications.
  • If the smart contract fails in the review, corresponding contract status will be demonstrated in contract list, and the developer will be notified via E-mail. User's revision should have another deployment and debugging in test environment before being submitted to official environment.
  • If the smart contract passes the review, the developer can choose to officially release the smart contract. After the release, contract address in official environment will be created.
  • The method of contract call and inquiry in official environment is the same with test environment with different domain names.
  • Submit basic file structure of truffle project in official environment:
    build
    contracts
    migrations
    test
    package.json
    truffle.js
    truffle-config.js
    README.md // project file statement
    // do not need node_modules

6. Interaction between Contract and ThunderChain Platform

API and process of contract call and inquiry in official environment is the same with test environment with different request host. For details, refer to API list.

6.1 Call the smart contract method

Contract call refers to the change of function call of contract status. When executing the function, the transfer into contract account can also be made. After entering user request in user interface, contract call is triggered.
There are two contract call modes currently: the transaction of sending contract call through QR code scanning of LinkToken Pocket App; the transaction of initiating contract call by business part App to wake LinkToken Pocket.

The call process of typical third-party contract application is as follows (separately C-end call and B-end operation call):
contract_interactive

contract_interactive

6.1.1 Call the Contract in Wake LinkToken Pocket Mode

The steps are as follows:

  1. Third-party app receives the user input and initiates contract call process
  2. The user makes a request in the Blockchain background for a prepay_id by using the service_id assigned by the LinkToken Blockchain.
  3. After receiving the request in the background, it generates a prepay_id to the third-party application.
  4. Third-party app packages the transaction, mainly including the information of contract address, gas_limit, transfer amount, execution function and parameter coding (data), and signature, etc.
  5. Wake up the LinkToken Pocket App and send the transaction information to the LinkToken Pocket.
  6. LinkToken Pocket packages the transaction, sends to Blockchain transaction processing center, sends payment process result callback to third-party app, and finally forwards the transaction to the Blockchain for processing.
  7. After Blockchain transaction finishes, it is returned to third-party background according to callback of third-party request information.
  8. Third-party background confirms transaction status and contract data according to callback and prepayid transaction inquiry, and refreshes app interaction data (contract call interfaction completes).

Third-party app can synchronize the data to its background service. (Third-party function)

After the Blockchain background processes the smart contract call request, if the user fills in the callback information, the callback center will notify the third-party application background (refer to Callback Protocol). The third-party application interface is able to synchronize information with the third-party application background to display the results after the transaction.

Example: Call LinkToken Pocket from OneThing Cloud

otst://payment/?tx-data=ZGVzYz3nlLXlvbFYWFhYJnRvPTB4MTIzNDU2Nzg5MDEyMzQ1Njc4OTAmdmFsdWU9MTIzLjQwJmdhc2xpbWl0PTUwMDAwJmRhdGE9MHgwMTAyMDMwNDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDEmc2lnbj0wNEI3QTU1QzQ3NDQwRDk4NUE0NDgzNkZENTVFQkVCNw==&resource=d2t5&x-source=wky&callback=wky://x-callback-url/&cb-data=base64 Callback transparent transmission parameter after coding

Specific analysis

  • Contract execution business otst://payment
  • Name of source app, resource=d2t5. It is wky after decoding
  • Callback prefix of source app, x-source=wky
  • callback=www.bai.com||schema://host/, app callback url or schema
  • Directly return when callback&cb-data=abcdefg
  • Transaction information tx-data=ZGVzYz3nlLXlvbFYWFhYJnRvPTB4MTIzNDU2Nzg5MDEyMzQ1Njc4OTAmdmFsdWU9MTIzLjQwJmdhc2xpbWl0PTUwMDAwJmRhdGE9MHgwMTAyMDMwNDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDEmc2lnbj0wNEI3QTU1QzQ3NDQwRDk4NUE0NDgzNkZENTVFQkVCNw==

The following information is included after decoding

  • Payment address &to=0x12345678901234567890
  • Quantity of LinkToken payment &value=123.4
  • Maximum payment amount &gaslimit=50000
  • Call code &data=0x010203040000000000000000000000000000000000000000000000000000000000000001
  • For title &desc= film XXXX
  • sign transaction signature &sign=04B7A55C47440D985A44836FD55EBEB7

APPcallback return

(http://www.xx.com|scheme://host)?hash=transaction receipt&msg=error description (base64)&code=error code&cb-data=transparent transmission information&result=(success|fail|cancel)

6.1.2 Call the Smart Contract through Scanning QR Code with LinkToken Pocket

The steps are as follows:

  1. Third-party app receives the user input and initiates contract call process
  2. The user makes a request in the Blockchain background for a prepay_id by using the service_id assigned by the LinkToken Blockchain.
  3. After receiving the request in the background, it generates a prepay_id to the third-party application.
  4. Third-party app packages the transaction, mainly including the information of contract address, gas_limit, transfer amount, execution function and parameter coding (data), and signature, etc., combined into tx-data according to the rules.
  5. Third party receives url request through web service, and the request link returns the aforementioned generated tx-data as response.body. The structure is as follows structure retunred by request url.
  6. Create QR code with the link http://red.xunlei.com/html/guider.html?action=**url**.
  7. Scan QR code with LinkToken Pocket.

Structure returned by request url

{
    "iRet":0,
    "sMsg": "ok",
    "data": {
        "tx_data": ""
    }
}

6.2 Inquire constant Contract Method

Inquire contract constant status and method with no gas consumed. Directly call in eth_call API method.

For example: Example

In case of successful contract deployment, the following operation should be executed:

  • Non-deployed contract
    [root@t05f058s2 ~]# curl -k -X POST --data '{"jsonrpc":"2.0","method":"eth_call","params":[{"from":"0x7eff122b94897ea5b0e2a9abf47b86337fafebdc","to":"0xfe2587bdc1781f23d105002c328d3d2ea6cfcbdd","data":"0xb0f0c96a0000000000000000000000000000000000000000000000000000000000000005"}, "latest"],"id":1}' https://sandbox-blockchain.xunlei.com/call
    {"error":{"message":"invalid request","code":-32600},"jsonrpc":"2.0","id":1}
  • Deployed contract
    [root@t05f058s2 ~]# curl -k -X POST --data '{"jsonrpc":"2.0","method":"eth_call","params":[{"from":"0x7eff122b94897ea5b0e2a9abf47b86337fafebdc","to":"0xe0e39a57a044451a00e4c73a2ea6bf83bd229a68","data":"0xb0f0c96a0000000000000000000000000000000000000000000000000000000000000005"}, "latest"],"id":1}' https://sandbox-blockchain.xunlei.com/call
    {"jsonrpc":"2.0","id":1,"result":"0x0000000000000000000000007eff122b94897ea5b0e2a9abf47b86337fafebdc0000000000000000000000000000000000000000000000000000000000000005"}
  • Parameter description

to: contract address received after successful contract deployment data: calculation method

abi=[{"payable":true,"stateMutability":"payable","type":"fallback"},{"constant":false,"inputs":[{"name":"to","type":"address"},{"name":"value","type":"uint256"}],"name":"transfer","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"value","type":"uint256"}],"name":"hello","outputs":[{"name":"","type":"address"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"}]
ctx=eth.contract(abi).at('0xc197e61edcbccc4bf7a0f76250ca7246de03e773')
ctx.hello.getData.call(null, 5, {from:from})
"0xb0f0c96a0000000000000000000000000000000000000000000000000000000000000005"

7. API List

  1. Domain name of test environment https://sandbox-blockchain.xunlei.com
  2. Domain name of product environment https://walletapi.onethingpcs.com

7.1 Test Environment API

7.1.1 Get E-mail Verification Code

Function

Get E-mail verification code for test user registration.

Request

Method: POST
URL: /api/linktest/email_code
BODY: JSON

Parameter description:

Parameter name Parameter type required description
email string Yes E-mail used for test

Response

Parameter name Parameter type required description
code int Yes error code, 0:succeeded, not 0:failed
msg string Yes error prompt information
data object No returned data of request

7.1.2 Register with E-mail

Function

Test registration interface and use E-mail address. When the user registers for the first time, generated service_id/secret will be sent to the developer via E-mail. If the E-mail address is already registered, error code is returned.

Request

Method: POST
URL: /api/linktest/regist
BODY: JSON

Parameter description:

Parameter name Parameter type required description
email string Yes E-mail used for test, mainly for receiving test information
emailcode string Yes E-mail verification code used before registration

Response

Parameter name Parameter type required description
code int Yes error code, 0: succeeded, not 0: failed
msg string Yes error prompt information
data object No returned data of request

7.1.3 Charging for Test Account

Function

The application is to charge LinkToken in designated account. The developer charges self-owned accounts for test activity. Every application is for the transfer of 1 LinkToken. Every E-mail can call 10 times at most every day.

Request

Method: POST
URL: /api/linktest/recharge
BODY: JSON

Parameter description:

Parameter name Parameter type required description
email string Yes E-mail used for test, mainly for receiving test information
address string Yes account address for charging
sign string Yes signature md5(E-mail=xxx&address=xxx&secret=xxx), xxx is actual value of request

Response

Parameter name Parameter type required description
code int Yes error code, 0: succeeded, not 0: failed
msg string Yes error prompt information
data object No returned data of request

7.1.4 Contract Release

Function

The user releases the smart contract in test environment, and provides compiled byte code.

Request

Method: POST
URL: /api/linktest/contract/deploy
BODY: JSON

Parameter description:

Parameter name Parameter type required description
email string Yes E-mail used for test, mainly for receiving test information
bytecode string Yes compiled contract byte code, in hexadecimal ABI format
params string No initialization paramaters of constructed function, in hexadecimal ABI format
sign string Yes signature md5(E-mail=xxx&bytecode=xxx&params=xxx&secret=xxx), xxx is actual value of request. Though param sis blank, it should be computed in sign

Response

Parameter name Parameter type required description
code int Yes error code, 0: succeeded, not 0: failed
msg string Yes error prompt information
data object No returned data of request

data

Parameter name Parameter type required description
id int Yes id generated in contract deployment. With the id, the smart contract address after deployment can be inquired

7.1.5 Contract Address Inquiry

Function

With id generated in contract deployment, contract account address can be inquired.

Request

Method: POST
URL: /api/linktest/contract/address
BODY: JSON

Parameter description:

Parameter name Parameter type required description
email string Yes E-mail used for test, mainly for receiving test information
id int Yes id returned in contract deployment
sign string Yes signature md5(E-mail=xxx&id=xxx&secret=xxx), xxx is actual value of request

Response

Parameter name Parameter type required description
code int Yes error code, 0: succeeded, not 0: failed
msg string Yes error prompt information
data object No returned data of request

data

Parameter name Parameter type required description
address string Yes account address

7.1.6 Inquire Recently Deployed Contract Address

Function

Inquire recently deployed contract id and contract address.

Request

Method: POST
URL: /api/linktest/contract/last
BODY: JSON

Parameter description:

Parameter name Parameter type required description
email string Yes E-mail used for test, mainly for receiving test information
sign string Yes signature md5(E-mail=xxx&id=xxx&secret=xxx), xxx is actual value of request

Response

Parameter name Parameter type required description
code int Yes error code, 0: succeeded, not 0: failed
msg string Yes error prompt information
data object No returned data of request

data

Parameter name Parameter type required description
id int Yes contract ID
address string Yes account address

7.1.7 Generate URL Information for Scanning Payment

Function

The developer submits transaction information and gets a transaction URL to support code scanning. Contract payment and third-party payment are available. The interface is for the convenience of developer's test, and process of requesting prepay_id is packaged, only applicable to test environment. Official environment does not provide this interface, and the developer is required to realize prepayid interface and url request at the background.

Request

Method: POST
URL: /api/linktest/tx_generate
BODY: JSON

Request parameters

Parameter name Parameter type required description
email string Yes E-mail for test registration
to string Yes contract address or LinkToken receiving address
value string Yes transferred LinkToken number, decimal integer, unit wei
callback string Yes callback URL
title string Yes transaction information title. For example: “contract callback-LinkToken Mall”
desc string Yes transaction details. For example: “exchange service xxx”
gas_limit string No maximum GAS number for contract execution, decimal integer, only filled for contract transaction
data string No contract code for execution, hexadecimal character string beginning with 0x. it includes function address and call parameters. It is blank if only transfer is initiated. Only filled for contract transaction
tx_type string Yes transaction type, contract transaction: contract, third-party transaction: tx_third
sign string Yes request signature to verify the authenticity of the request md5(E-mail=xxx&to=xxx&value=xxx&secret=xxx)

Response

BODY: JSON

Response parameter

Parameter name Parameter type required description
code int Yes error code, 0: succeeded, not 0: failed
msg string Yes error prompt information
data object No returned data of request

data

Parameter name Parameter type required description
url string Yes generated URL to get transaction information through code scanning
expire int Yes URL expiry duration, unit millisecond

7.1.8 Scan Code to Get Transaction Information

Function

To get order details. Request URL is generated by interface (/api/linktest/tx_generate). The developer gets order URL through code scanning of LinkToken Pocket APP. LinkToken Pocket APP requests the UR to get transaction information and sign the transaction.

Request

Method: GET URL: /api/linktest/tx_info/:tx_id
BODY: null

Parameter description:

Parameter name Parameter type required description
tx_id string Yes parameter contained in path, dynamic transaction ID, hexadecimal character string

Response

Parameter name Parameter type required description
content stream Yes transaction information of payment protocol format of LinkToken Pocket APP

7.2 Common API

7.2.1 Wake LinkToken Pocket Protocol

Wake Protocol

The smart contract exeuction requests third-party app to wake LinkToken Pocket APP or code scanning through LinkToken Pocket APP. Wake LinkToken Pocket Protocol is otst://payment?

Request parameter description

Parameter type required description
scheme string Yes LinkToken Pocket scheme otst
host string Yes LinkToken Pocket host value: payment
tx-data byte[] Yes Base64 coding, mainly including order details for payment, key=value format, connected by &
resource byte[] Yes Base64 coding, source app (source dealer name), restricted to 10 characters
cb-data byte[] No Base64 coding (optional), payment caller needs extra information returned by LinkToken Pocket
x-source string No source app scheme eg. wky-app (iOS callback optional, no processing for Andriod), reserved field
callback string No url coding. After payment is completed, LinkToken callback address or schema http://www.xx.com or scheme://host/?hash=transaction receipt&msg=error description(base64)&code=error code&cb-data=transparent transmission information&result=(success|fail|cancel)
  • If third-party business is not connected by LinkToken Pocket (i.e. browser, third-party app), callback can support webpage or protocol app return, and callback will be made after business completion (the indication is returning to browser or third-party app)
  • If the business is connected by LinkToken Pocket (i.e. open business page through scanning QR code in LinkToken Pocket), callback only supports webpage protocol return, and callback will be made after business completion (the indication is opening webpage in LinkToken Pocket)
  • If callback is not sent, it is recommended that third party polls the business result or waits for server callback
  • Third party can inquire web UserAgent to know whether the business is complete User-Agent under key field 'OneWallet' in LinkToken Pocket
    iOS-User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 11_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E302 OneWallet/2.0.3 (iPhone; iOS 11.3.1; Scale/3.00; origin/2; nc/IN)

tx-data parameter description

Parameter type required description
desc string Yes contract execution description. The prefix “contract execution-” must be attached
callback string No url coding. Third-party app background is to receive callback address after Blockchain transaction is completed
to string Yes transfer-out LinkToken Pocket address
value string Yes LinkToken number (unit wei), 1 LinkToken= 10 ** 18 wie, input integer, with no unit. For example, transfer of 1 LinkToken is 1 000 000 000 000 000 000
prepay_id string Yes prepayment order No. Get from interface getPrepayId
service_id string Yes business id. Apply for LinkToken exchange service to get service_id and signature key
data string No In case of contract execution, input contract execution function and parameter code beginning with 0x. In case of LinkToken exchange, it is blank.
gas_limit string No Maximum gas for payment: In contract transaction, it is estimated execution service fee; it is blank in case of LinkToken exchange service, and the default transaction fee is 0.01; if transaction fee is above actual execution deduction amount, exceeding amount will be refunded to the payer;
tx_type string No In case of contract transaction, fixed value is contract; for LinkToken exchange, fixed value is tx_third; default value is tx_third
sign string Yes Transaction signature sign=md5(sha512(callback=xxx&prepay_id=xxx&service_id=xxx&to=xxx&value=xxx&key=private key)) callback url here do not need coding

APP callback returns

(http://www.xx.com|scheme://host)?hash=transaction receipt&msg=error description(base64)&code=error code&cb-data=transparent transmission information&result=(success|fail|cancel)

7.2.2 Contract constant Method Inquiry

The method is used for inquiry of contract method. The method is to execute designated message call, and does not create transaction. So the call of the method is test and does not change Blockchain status database. constant method in contract should call this rpc method.

Request

Method: POST
URL: /call
BODY: JSON

Parameter description:

Field type restriction remarks
jsonrpc String required fixed value "2.0"
method String required fixed value "eth_call"
params Array required refer to the table below for details
id Int required fixed value 1

params details

index type restriction remarks
0 Object required structure as object details below
1 String required fixed value "latest"

object details

  • object – transaction call target
Field type restriction size remarks
from common.Address required 20 bytes  transaction initiator
to     common.Address required 20 bytes    address the transaction directs. For example, contract call method contains contract address
gas    hexutil.Big optional necessary gas for transaction execution. eth_call normally does not consume gas, but this parameter is used in some execution operations
gasPrice hexutil.Big optional    price for gas per unit
value    hexutil.Big optional        the value of the transaction to be sent
data   hexutil.Bytes optional Hash of the method signature and encoded parameters. Refer to Ethereum Contract ABI

Examples

{
    "jsonrpc": "2.0",
    "method": "eth_call",
    "params": [
        {
            "from": "",
            "to": "",
            "gas": "",
            "gasPrice": "",
            "value": "",
            "data": ""
        }, 
        "latest"
    ],
    "id": 1
}

Response

Field type restriction size remarks
DATA transaction call target contract execution result

7.2.3 Inquire Estimated gas Consumption (estimateGas)

Function

To get estimated gas number for consumption in contract call. The user needs to input gas_limit value when calling the smart contract. Because gas consumption is related to difficulty value of current operational environment of Blockchain, it is computed in real time.
In case of out-of-gas during contract execution call (namely, gas is exhausted but the smart contract is not completed), the smart contract execution fails and consumed gas will not be refunded.
If gas is smaller or equal to given gas value during contract execution call, the smart contract execution is completed and remaining gas will be refunded.
It is recommended that the developer adds some to make it more than estimated gas consumption value so as to ensure successful contract execution.

Request

Method: POST
URL: /estimateGas
BODY: JSON

Parameter description:

Field type restriction remarks
jsonrpc String required fixed value "2.0"
method String required fixed value "eth_estimateGas"
params Array required refer to the table below for details
id Int required fixed value 1

params details

index type restriction remarks
0 Object required structure as object details below

object details

  • object - transaction call target
Field type restriction size remarks
from common.Address optional 20 bytes  transaction initiator
to     common.Address required 20 bytes    address the transaction directs. For example, contract call method contains contract address
value    hexutil.Big optional        the value of the transaction to be sent
data   hexutil.Bytes optional Hash of the method signature and encoded parameters. Refer to Ethereum Contract ABI

Examples

{
    "jsonrpc": "2.0", 
    "method": "eth_estimateGas", 
    "params":[
        {
            "from": "",
            "to": "", 
            "data": "",
            "value": ""
        }
    ], 
    "id": 1
}

Response

Parameter name Parameter type required description
content stream Yes transaction information of payment protocol format of LinkToken Pocket APP

7.2.4 prepay_id to Get Contract Execution

Refer to LinkToken Exchange-Get prepay_id

7.2.5 Inquire Order Status According to prepay_id

Refer to LinkToken Exchange-Inquire Order Status

7.2.6 Contract Execution Result Callback

Refer to [LinkToken Exchange-Callback Protocol] (https://blockchain.xunlei.com/site/docex.html#43)

8. Call the Smart Contract in DEMO-QR Code Mode

8.1 Development Contract

  1. Develop HelloWorld contract
pragma solidity^0.4.23;

contract HelloWorld {
    address public owner;
    string public info;

    constructor(address _owner) public {
        owner = _owner;
    }

    function saySomething(string _str) public returns(string) {
        info = _str;
        return info;
    }
}
  1. Use remix test and local debugging (truffle framework optional) HelloWorld-remix

8.2 Register Test Environment Account and Deploy Test Environment

  1. Use E-mail registration account in test environment and get service_id and key. The developer can achieve interface request on his/her own or register with the tools such as postman.
    api interface for [apiary](https://Thunder Chain.docs.apiary.io/#) is given below for registration. For interface call, sign should be computed and request parameters should be revised according to actual situation.
    demo-apiary-regist

  2. Download test version of LinkToken Pocket, and create individual test account. Charge the corresponding account with the interface in step 1.

  3. Compile the smart contract and get bytecode for contract deployment.
    If truffle is used for development, command truffle compile can be used to compile contract/build folder to get corresponding json file of contract and extract corresponding bytecode.
    If remix is used for development, click compile => Details to get corresponding bytecode.

    // HelloWorld.sol bytecode
    0x608060405234801561001057600080fd5b506040516020806104f783398101806040528101908080519060200190929190505050806000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555050610474806100836000396000f300608060405260043610610057576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff168063370158ea1461005c5780638da5cb5b146100ec578063fe6b378314610143575b600080fd5b34801561006857600080fd5b50610071610225565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156100b1578082015181840152602081019050610096565b50505050905090810190601f1680156100de5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b3480156100f857600080fd5b506101016102c3565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b34801561014f57600080fd5b506101aa600480360381019080803590602001908201803590602001908080601f01602080910402602001604051908101604052809392919081815260200183838082843782019150505050505091929192905050506102e8565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156101ea5780820151818401526020810190506101cf565b50505050905090810190601f1680156102175780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b60018054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156102bb5780601f10610290576101008083540402835291602001916102bb565b820191906000526020600020905b81548152906001019060200180831161029e57829003601f168201915b505050505081565b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b606081600190805190602001906103009291906103a3565b5060018054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156103975780601f1061036c57610100808354040283529160200191610397565b820191906000526020600020905b81548152906001019060200180831161037a57829003601f168201915b50505050509050919050565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f106103e457805160ff1916838001178555610412565b82800160010185558215610412579182015b828111156104115782518255916020019190600101906103f6565b5b50905061041f9190610423565b5090565b61044591905b80821115610441576000816000905550600101610429565b5090565b905600a165627a7a72305820e93b6ccfaace4a512cc7b4a45ba826b940ce758758fe21abe52cb4c1fecf211f0029
  4. If constructed function of the smart contract includes initialization parameter, data of initialization paramater params should be computed.
    If remix is used to develop the smart contract, click run, select the smart contract to be deployed, enter initialization parameter, and click deploy. The details of the transaction can be viewed in the console. input is data composed of bytecode of contract compilation and initialization parameter. Because deployment interface in test environment separates bytecode of contract compilation and params of initialization parameter, corresponding data of params should be extracted separately.
    If ethers.js is used, encode method of ethers.utils.ABICoder should be used to compile the corresponding initialization parameter as params of contract deployment.

    var ethers = require('ethers')
    var abiCoder = new ethers.utils.AbiCoder()
    return abiCoder.encode(['address'], ['0xca35b7d915458ef540ade6068dfe2f44e8fa733c'])
    // 0x000000000000000000000000ca35b7d915458ef540ade6068dfe2f44e8fa733c
  5. The interface of deploy contract in test environment in test environment should be called. Theparameters are aforementioned bytecode, params, E-mail of contract development, and computed signature sign. The request result will return an id of contract deployment.
    Then the interface of inquire contract address according to id should be called to inquire deployed contract address.

8.3 Contract Call and Contract Inquiry Business

  1. The interface of inquire contract constant method should be called to inquire info value of HelloWorld.
    In the method of contract inquiry coding, data computed for info is 0x370158ea.

    curl -k -X POST --data '{"jsonrpc":"2.0","method":"eth_call","params":[{"from":"0x7eff122b94897ea5b0e2a9abf47b86337fafebdc","to":"0xd5b0df861803a07f330868104eec92ebdcce4c79","data":"0x370158ea"}, "latest"],"id":1}' https://sandbox-blockchain.xunlei.com/call
    {"jsonrpc":"2.0","id":1,"result":"0x00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000000"}
    // AbiCoder.decode decoding value is blank

    When initiating the function, info value is blank.

  2. Encode saySomething function and get data of function call. Refer to [contract inquiry coding](#432-Use ethers.js to Achieve Coding and Decoding).

    0xfe6b37830000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000b48656c6c6f20576f726c64000000000000000000000000000000000000000000
  3. Request inquire estimated gas consumption interface, and inquire estimated gas value of saySomething function execution. It is recommended that the developer adds some to make it more than gas value of call function so as to avoid out-of-gas.

    curl -k -XPOST --data '{"jsonrpc":"2.0", "method":"eth_estimateGas", "params":[{"from":"0x7eff122b94897ea5b0e2a9abf47b86337fafebdc","to":"0xd5b0df861803a07f330868104eec92ebdcce4c79", "data":"0xfe6b37830000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000b48656c6c6f20576f726c64000000000000000000000000000000000000000000","value":""}], "id":1}' -H 'content-type:application/json' https://sandbox-blockchain.xunlei.com/estimateGas
    // Returned value
    {"jsonrpc":"2.0","id":1,"result":"0xaebc"}

    The above result is converted intodecimal number:

    0xaebc.toString('10')
    // "44732"

    When inputting in execution interface of the next step, 10000 should be added to the value, and the input gas number is 54732.

  4. Request saySomethingfunction of interfaceURL information genereating payment of code scanningfor contract execution.
    to address in request parameter is contract address 0xd5b0df861803a07f330868104eec92ebdcce4c79. Data is data generated above, and gas_limit is 54732 in the previous step.
    Compute sign md5(email=xxx&to=xxx&value=xxx&secret=xxx).
    url in returned data is the address for LinkToken Pocket app to scan the QR code. The link is temporary and default duration is 30 minutes.

    {
    "code": 0,
    "data": {
     "url": "http://red.xunlei.com/html/guider.html?action=https%3A%2F%2Fsandbox-blockchain.xunlei.com%2Fapi%2Flinktest%2Ftx_info%2Ff4ebcdf4d756f0d8041c82d8e32e912a",
     "expire": 1800000
    },
    "msg": ""
    }
  5. According to url in previous step, QR code generation tool is used to generate a QR code. Then LinkToken Pocket app test version is used to scan.
    LinkToken Pocket will call smart contract execution page. The user should select the account used for contract execution, and input corresponding password. After transaction is confirmed, contract execution result can be viewed in transaction record.

  1. Call inquire contract constant method interface again, and inquire info value of HelloWorld.
    curl -k -X POST --data '{"jsonrpc":"2.0","method":"eth_call","params":[{"from":"0x7eff122b94897ea5b0e2a9abf47b86337fafebdc","to":"0xd5b0df861803a07f330868104eec92ebdcce4c79","data":"0x370158ea"}, "latest"],"id":1}' https://sandbox-blockchain.xunlei.com/call
    {"jsonrpc":"2.0","id":1,"result":"0x0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000b48656c6c6f20576f726c64000000000000000000000000000000000000000000"}
    // AbiCoder.decode decoding value is Hello World. The call succeeds.

8.4 Differences of the Interface for Test Environment and Official Environment

  1. The account registration in current test environment and contract deployment needs the developer to carry out interface call. Official environment realizes registration and deployment on ThudnerChain open platform.
  2. The smart contract inquiry, contract execution, estimated gas of contract execution, and get prepay_id interface of official environment and test environment are the same with different domain names.
  3. URL information generating payment of code scanning interface is temporarily not available in official environment. The developer needs to provide url for QR code and corresponding background web service in the steps described in [Call the smart Contract through Scanning QR Code with LinkToken Pocket](#612-Call the smart Contract through Scanning QR Code with LinkToken Pocket).

9. FAQ

9.1 How to Download LinkToken Pocket Mobile APP in Formal Environment

Scan code, download and install

app download

9.2 How to Download LinkToken Pocket Mobile App in Test Environment

Scan code, download and install

app download

9.3 How to get the Blockchain account

After the user downloads and installs the APP, the account can be generated through the APP.