Blockchain 100 talk: DAPP architecture and WEB3.JS interactive interface from the case of pet store

By June 28, 2020DApps
Click here to view original web page at www.programmersought.com
image

Article Summary

【Objectives of this article】
Understand the framework and interactive process of DAPP decentralized applications under the ETH ecosystem, and understand the role and interface functions of WEB3.JS.

【Preconditions】
Completed "How to develop a DAPP blockchain application (take pet store as an example)"https://www.jianshu.com/p/9844d97ef1d0) OrDevelopment combat | 3 steps to teach you to open a pet shop on Ethereum (with process + code)Learning practice, understanding of smart contracts.

【Technology Harvest】
1). DAPP architecture
2). ETH node framework
3). Business process flowchart and function introduction of the APP.js file in the pet store
4).web3.js interface

Ethereum node and DAPP framework

2.1 Ethereum node architecture

image

Ethereum node architecture diagram

Ethereum is a blockchain implementation. In the Ethereum network, many nodes are connected to each other to form the Ethereum network.

Ethereum node software provides two core functions: data storage and contract code execution.

In each Ethereum full node, complete blockchain data is stored. Ethereum not only saves transaction data on the chain, but also the compiled contract code on the chain. In the Ethereum full node, a virtual machine is also provided to execute the contract code.

Transaction data

Every transaction in Ethereum is stored on the blockchain. When you deploy a contract, one deployment is a transaction. When you vote for a candidate, one vote is another transaction. All these transactions are public and everyone can see and verify them. This data can never be tampered with.

In order to ensure that all nodes in the network have the same copy of data and no invalid data is written to the database, Ethereum currently uses the Proof Of Work (POW: Proof Of Work) algorithm to ensure network security, that is, mining by miners (Mining) to reach a consensus (Consensus)-synchronize data to all nodes.

Proof of work is not the only algorithm for reaching consensus, and mining is not the only option for blockchain. Now, we only need to understand that consensus means that the data of each node is consistent, and POW is just one of many algorithms used to establish consensus. This algorithm needs to be mined by miners to achieve untrusted environments. Letter trading. Consensus is the goal, POW is the means.

Contract code

Ethereum not only stores transaction data on the chain, it can also store contract code on the chain.

At the database level, the role of the blockchain is to store transaction data. So where is the logic for voting for candidates or retrieving the voting results? In the world of Ethereum, you can use Solidity language to write business logic/application code (that is, contract: Contract), then compile the contract code into Ethereum bytecode, and deploy the bytecode to the blockchain :

image

Other languages ​​can be used to write contract code, but Solidity is by far the most popular choice.

Ethereum Virtual Machine

The Ethereum blockchain not only stores data and code, each node also contains a virtual machine (EVM: Ethereum Virtual Machine) to execute the contract code-it sounds like a computer operating system.

In fact, this is the core point that distinguishes Ethereum from Bitcoin: the existence of a virtual machine has brought the blockchain into the 2.0 era, and also made the blockchain the first application-friendly platform for application developers. .

2.2 DAPP architecture

The following figure shows the decentralized application architecture based on Ethereum:

image

DAPP architecture diagram

Each client (browser) interacts with its respective node application instance, rather than requesting services from a centralized server.

In an ideal decentralized environment, everyone who wants to interact with a DApp needs to run a full blockchain node on their computer or mobile phone — in short, everyone runs a full node . This means that before being able to actually use a decentralized application, users have to download the entire blockchain.

However, we are not living in a utopia. It is unrealistic to expect every user to run a full node before using your application. But the core idea behind decentralization is that it does not depend on a centralized server. Therefore, some solutions have emerged in the blockchain community, such as Infura, which provides public blockchain nodes, and Metamask, a browser plug-in. Through these solutions, you don't need to spend a lot of hard disk, memory and time to download and run a complete blockchain node, and you can also take advantage of the decentralization.

Web3.js is the official Javascript API of Ethereum, which can help smart contract developers use HTTP or IPC to interact with local or remote Ethereum nodes. In fact, it is a collection of libraries, mainly including the following libraries:

  • web3-eth is used to interact with the Ethereum blockchain and smart contracts

  • web3-shh is used to control whisper protocol and p2p communication and broadcast

  • web3-bzz is used to interact with the swarm protocol

  • web3-utils contains some useful functions for Dapp development

The communication between Web3 and geth uses JSON-RPC, which is a lightweight RPC (Remote Procedure Call) protocol. The entire communication model can be abstracted as shown below.

image

WEB3 location map

Take the pet store as an example WEB3.JS code

"How to develop a DAPP blockchain application (take pet store as an example)"https://www.jianshu.com/p/9844d97ef1d0) OrDevelopment combat | 3 steps to teach you to open a pet shop on Ethereum (with process + code)This article details the case of a pet store DAPP. This section focuses on the analysis and reference of WEB3.JS related interface code.

3.1 Annotated app.js code

App = {

  web3Provider: null,

  contracts: {},

  init: function() {

    /*Load pet name, picture, age, location and other information*/

    // Load pets.

    $.getJSON('../pets.json', function(data) {

      var petsRow = $('#petsRow');

      var petTemplate = $('#petTemplate');

      for (i = 0; i < data.length; i ++) {

        petTemplate.find('.panel-title').text(data[i].name);       

 petTemplate.find('img').attr('src', data[i].picture);        

petTemplate.find('.pet-breed').text(data[i].breed);       

 petTemplate.find('.pet-age').text(data[i].age); 

       petTemplate.find('.pet-location').text(data[i].location);        

petTemplate.find('.btn-adopt').attr('data-id', data[i].id);       

 petsRow.append(petTemplate.html());

      }

    });

    return App.initWeb3();

  },

  initWeb3: function() {

    /*If web3 is defined in advance, use the wallet object of the current web3 instance. For example, a virtual wallet created by JavaScript VM under remix (there are 4 accounts with 100 ETH);

 Account wallet linked to MetaMask; or mist wallet*/

    if (typeof web3 !== 'undefined') {

      App.web3Provider = web3.currentProvider; 

   } else {

      // If no injected web3 instance is detected, fall back to Ganache

      /*If web3 does not exist, start the locally started Ganache wallet. [Premise: To start the local Ganache environment, otherwise it will not be created successfully]*/

      App.web3Provider = new Web3.providers.HttpProvider('http://localhost:7545');

    }

    /*Create a Web3 instance, the entrance parameter is the App.web3Provider just configured*/

    web3 = new Web3(App.web3Provider);

    /*Call the initialization contract function*/

    return App.initContract();

  },

  initContract: function() { 

   /*Refer to http://www.w3school.com.cn/jquery/ajax_getjson.asp to get getJSON method*/ 

   $.getJSON('Adoption.json', function(data) { 

     // Get the necessary contract artifact file and instantiate it with truffle-contract

      var AdoptionArtifact = data;

      App.contracts.Adoption = TruffleContract(AdoptionArtifact);  

        // Set the web3Provider wallet provider of the current contract

     App.contracts.Adoption.setProvider(App.web3Provider);  

        // Use our contract to extract and identify adopted pets

     return App.markAdopted();

    }); 

       /*Return binding event*/ 

   return App.bindEvents(); 

 }, 

 /*Clicking the click event with the'.btn-adopt' class will trigger the handleAdopt (handling adoption) function*/ 

 bindEvents: function() { 

   $(document).on('click', '.btn-adopt', App.handleAdopt); 

 },

 /*If the pet has been adopted, the text will display as "Success" and the button cannot be clicked*/

  markAdopted: function(adopters, account) 

{

    var adoptionInstance;   

 App.contracts.Adoption.deployed().then(function(instance)

 {

      adoptionInstance = instance;

          return adoptionInstance.getAdopters.call();

    }).then(function(adopters) {

      for (i = 0; i < adopters.length; i++) { 

       /* If the address of the adopter is not 0, set the button font and status, */ 

       if (adopters[i] !== '0x0000000000000000000000000000000000000000') { 

         $('.panel-pet').eq(i).find('button').text('Success').attr('disabled', true); 

       }

      }

    }).catch(function(err) {

      console.log(err.message); 

   });

  },  

handleAdopt: function(event) {

    event.preventDefault(); 

       The /*parseInt() function can parse a string and return an integer. */ 

   var petId = parseInt($(event.target).data('id')); 

   var adoptionInstance; 

       /*Get current ETH wallet account*/ 

   web3.eth.getAccounts(function(error, accounts) {

      if (error) {

        console.log(error);

      }

         /* Take the first wallet account */ 

     var account = accounts[0]; 

        /*ES6 then function call, chain call*/   

   App.contracts.Adoption.deployed().then(function(instance) {

        adoptionInstance = instance; 

       // The return value of the transaction that executes the adoption adoption function by sending the account

        // I didn’t understand it here. The smart contract Adoption.adopt has only one input parameter. Why did I add the second {from: account} parameter here?

        //TINY Bear believes that it can be used as a grammar, either set the default account in advance, or specify it when calling

       return adoptionInstance.adopt(petId, {from: account}); 

     }).then(function(result) { 

       /*Identify adoption status*/ 

       return App.markAdopted(); 

       /*Output error*/ 

     }).catch(function(err) { 

       console.log(err.message);

      });

    });

  }};

/*App.init function is called when the window is loaded*/

$(function() {

  $(window).load(function() {

    App.init(); 

 });

});

3.2 App.js call WEB3 process analysis

image

App.js calls WEB3 flow chart

Web3 JavaScript app API reference

Web3's official website documents give detailed interface documents and instructions.

4.1 web3

The web3 object provides all methods.

Example:

//Initialization process

var Web3 = require('web3');

if (typeof web3 !== 'undefined') { 

 web3 = new Web3(web3.currentProvider);

} else {

  // set the provider you want from Web3.providers

  web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));

}

web3.version.api

return value:

String-api version of Ethereum js

Examples:

//Omit the initialization process

var version = web3.version.api;

console.log(version);

$ node test.js

0.18.2

web3.version.node

Synchronously:

Asynchronous way:

web3.version.getNode(callback(error, result){ ... })

return value:

String-version information of client or node

Examples:

//Omit the initialization process

var version = web3.version.node;

console.log(version);

$ node test.js
EthereumJS TestRPC/v3.0.3/ethereum-js

web3.version.network

Synchronously:

web3.version.network

Asynchronous way:

web3.version.getNetwork(callback(error, result){ ... })

return value:

String-Network protocol version

Examples:

//Omit the initialization process

var version = web3.version.network;

console.log(version);

$ node test.js

1488546587563

web3.version.ethereum

Synchronously:

Asynchronous way:

web3.version.getEthereum(callback(error, result){ ... })

return value:

String-Ethereum's protocol version

Examples:

//Omit the initialization process

var version = web3.version.ethereum;

console.log(version);

$ node test.js

60

**Note: **The EthereumJS testRPC client does not support this command and reports an Error: Error: RPC method eth_protocolVersion not supported.

web3.version.whisper

Synchronously:

Asynchronous way:

web3.version.getWhisper(callback(error, result){ ... })

return value:

String-the version of the whisper protocol

Examples:

//Omit the initialization process

var version = web3.version.whisper;

console.log(version);

$ node test.js

20

note:The EthereumJS testRPC client does not support this command, an error is reported: Error: Error: RPC method shh_version not supported.

web3.isConnected

web3.isConnected

It can be used to check whether a connection to node exists.

parameter:

no

return value:

Boolean

Examples:

//Omit the initialization process

var connected = web3.isConnected();

if(!connected){

  console.log("node not connected!");

}else{

  console.log("node connected");

}

web3.setProvider

web3.setProvider

Set Provider

parameter:

no

return value:

undefined

Examples:

web3.setProvider(new web3.providers.HttpProvider('http://localhost:8545'));

web3.currentProvider

web3.currentProvider

If the Provider has been set, the current Provider is returned. This method can be used to check that the Provider has been set when using the mist browser, etc., to avoid repeated settings.

return value:

Object-null or the provider that has been set.

Examples:

if(!web3.currentProvider)
   web3.setProvider(new web3.providers.HttpProvider("http://localhost:8545"));

web3.reset

web3.reset

Used to reset the status of web3. Reset everything except the manager. Uninstall the filter and stop status polling.

parameter:

Boolean-If set to true, all filters will be uninstalled, but web3.eth.isSyncing() status polling will be retained.

return value:

undefined

Examples:

//Omit the initialization process

console.log("reseting ... ");

web3.reset();

console.log("is connected:" + web3.isConnected());

$ node test.js

reseting ...

is connected:true

web3.sha3

web3.sha3(string, options)

parameter:

  • String-The incoming string that needs to be hashed using the Keccak-256 SHA3 algorithm.

  • Object-Optional settings. If you want to parse a hex string in hex format. Need to set the encoding to hex. Because 0x is ignored by default in JS.

return value:

String-The result of hashing using Keccak-256 SHA3 algorithm.

Examples:

//Omit the initialization process

var hash = web3.sha3("Some string to be hashed");

console.log(hash); 

var hashOfHash = web3.sha3(hash, {encoding: 'hex'});

console.log(hashOfHash);

web3.toHex

web3.toHex

Convert any value to HEX.

parameter:

String|Number|Object|Array|BigNumber-the value to be converted to HEX. If it is an object or array type, it will first be converted to a string using JSON.stringify1. If the incoming is BigNumber2, you will get the HEX of the corresponding Number.

Examples:

//Initialize basic objects

var Web3 = require('web3');

var web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));

var BigNumber = require('bignumber.js');

var str = "abcABC";

var obj = {abc: 'ABC'};

var bignumber = new BigNumber('12345678901234567890');

var hstr = web3.toHex(str);

var hobj = web3.toHex(obj);

var hbg = web3.toHex(bignumber);

console.log("Hex of Sring:" + hstr);

console.log("Hex of Object:" + hobj);

console.log("Hex of BigNumber:" + hbg);

$ node test.js

Hex of Sring:0x616263414243

Hex of Object:0x7b22616263223a22414243227d

Hex of BigNumber:0xab54a98ceb1f0ad2

web3.toAscii

web3.toAscii(hexString)

Convert HEX string to ASCII3 string

parameter:

String-Hexadecimal string.

return value:

String- The ASCII code value corresponding to the given hexadecimal string.

Examples:

var str = web3.toAscii("0x657468657265756d000000000000000000000000000000000000000000000000");

console.log(str); // "ethereum"

web3.fromAscii

web3.fromAscii

Convert any ASCII string to HEX string.

parameter:

  • String-ASCII string

  • Number-The size of the returned string in bytes. If it is not long enough, it will be automatically filled.

return value:

String-The converted HEX string.

Examples:

var str = web3.fromAscii('ethereum');

console.log(str); // "0x657468657265756d"

var str2 = web3.fromAscii('ethereum', 32);

console.log(str2); // "0x657468657265756d000000000000000000000000000000000000000000000000"

$ node test.js

0x657468657265756d

0x657468657265756d

Remarks: The padding function seems to be unavailable.

web3.toDecimal

Convert a hexadecimal number to a decimal number

parameter:

String- Hexadecimal string

return:

Number- The hexadecimal value represented by the incoming string.

Examples:

var number = web3.toDecimal('0x15');

console.log(number); // 21

**web3.fromDecimal**

web3.fromDecimal

Convert a number, or a number in the form of a string, to a hexadecimal string.

parameter:

Number|String-Number

return value:

String-The hexadecimal representation corresponding to the given number.

Examples:

var value = web3.fromDecimal('21');

console.log(value); // "0x15"

web3.fromWei

web3.fromWei(number, unit)

Conversion between Ethereum currency units. Convert the quantity in units of wei to the following units, which can take the following values:

  • kwei/ada

  • mwei/babbage

  • gwei/shannon

  • szabo

  • finney

  • ether

  • kether/grand/einstein

  • mether

  • gether

  • tether

parameter:

  • Number|String|BigNumber-Number or BigNumber.

  • String-unit string

return value:

String|BigNumber-Depending on the parameters passed in, it is either a string in string form or a BigNumber.

Examples:

var value = web3.fromWei('21000000000000', 'finney');

console.log(value); // "0.021"

web3.toWei

web3.toWei(number, unit)

Convert to wei as the corresponding currency. The available units are as follows:

  • kwei/ada

  • mwei/babbage

  • gwei/shannon

  • szabo

  • finney

  • ether

  • kether/grand/einstein

  • mether

  • gether

  • tether

parameter:

  • Number|String|BigNumber-Number or BigNumber

  • String-string unit

return value:

String|BigNumber-Depending on the parameters passed in, it is either a string in string form or a BigNumber.

Examples:

var value = web3.toWei('1', 'ether');

console.log(value); // "1000000000000000000"

web3.toBigNumber

web3.toBigNumber (number or hexadecimal string)

Convert the given number or hexadecimal string to BigNumber5.

parameter:

Number|String-numbers in hexadecimal format

return value:

BigNumber-Examples of BigNumber

Examples:

var value = web3.toBigNumber('200000000000000000000001');

console.log(value); // instanceOf BigNumber

console.log(value.toNumber()); // 2.0000000000000002e+23

console.log(value.toString(10)); // '200000000000000000000001'

4.2 web3.net

web3.net.listening

Synchronously:

web3.net.listening

Asynchronous way:

web3.net.getListener(callback(error, result){ ... })

This attribute is read-only and indicates whether the currently connected node is listening to the network connection or not. listen can be understood as receiving.

return value:

Boolean-true means that the connected node is listening to the network request, otherwise it returns false.

Examples:

var listening = web3.net.listening;

console.log("client listening: " + listening);

$ node test.js
client listening: true

Remarks: If we close the test node we want to connect, an error will be reported: Error: Invalid JSON RPC response: undefined. So this method returns the listen status of the node we connected to.

web3.net.peerCount

Synchronously:

Asynchronous way:

web3.net.getPeerCount(callback(error, result){ ... })

The attribute is read-only and returns the number of other Ethereum nodes that the connected node has connected to.

return value:

Number-the number of other Ethereum nodes connected to the connected node

Examples:

var peerCount = web3.net.peerCount;

console.log("Peer count: " + peerCount); 

$ node test.js
Peer count: 0

4.3 web3.eth

Contains Ethereum blockchain related methods

Examples:

var eth = web3.eth;

**web3.eth.defaultAccount**

web3.eth.defaultAccount

The default address is used when using the following method. You can also choose to override this default setting by specifying the from attribute.

  • web3.eth.sendTransaction()

  • web3.eth.call()

The default value is undefined, 20 bytes in size, any address you have your own private key.

return value:

String-20 bytes of the currently set default address.

Examples:

console.log("Current default: " + web3.eth.defaultAccount);

web3.eth.defaultAccount = '0x8888f1f195afa192cfee860698584c030f4c9db1';

console.log("Current default: " + web3.eth.defaultAccount);

$ node test.js

Current default: undefined

Current default: 0x8888f1f195afa192cfee860698584c030f4c9db1

web3.eth.defaultBlock

web3.eth.defaultBlock

When using the following method, the default block settings will be used, and you can also override the default configuration by passing in defaultBlock.

  • web3.eth.getBalance()

  • web3.eth.getCode()

  • web3.eth.getTransactionCount()

  • web3.eth.getStorageAt()

  • web3.eth.call()

  • contract.myMethod.call()

  • contract.myMethod.estimateGas()

Optional block parameter, may be one of the following values:

  • Number-Block number

  • String-earliest, genesis block.

  • String-latest, the latest block just recently, the current block header.

  • String-pending, the block currently being mine, contains the transaction being packaged.

The default value is latest

return value:

Number|String-The block number whose status is checked by default.

Examples:

console.log("defaultBlock: " + web3.eth.defaultBlock);web3.eth.defaultBlock = 231;

console.log("defaultBlock: " + web3.eth.defaultBlock);

$ node test.js

defaultBlock: latest

defaultBlock: 231

web3.eth.syncing

Synchronously:

Asynchronous way:

web3.eth.getSyncing(callback(error, result){ ... })

This attribute is read-only. If synchronization is in progress, the synchronization object is returned. Otherwise it returns false.

return value:

Object|Boolean-If synchronization is in progress, return a synchronization object with the following properties. Otherwise it returns false.

return value:

  • startingBlock: Number-synchronization start block number

  • currentBlock: Number-The block number that the node is currently synchronizing

  • highestBlock: Number-Estimate the block to sync to

var sync = web3.eth.syncing;

console.log(sync);

$ node test.js

false

 //In the case of sync $ node test.js

{

   startingBlock: 300,

   currentBlock: 312, 

  highestBlock: 512

}

web3.eth.isSyncing

web3.eth.isSyncing(callback)

Provides callback function methods for synchronous start, update, and stop.

return value:

Object-A syncing object with the following methods:

  • syncing.addCallback(): Add another callback function to be called when the node starts or stops calling.

  • syncing.stopWatching(): Stop synchronization callback.

Callback return value:

  • Boolean-This value is true when synchronization starts, and this callback value is false when synchronization stops.

  • Object-When synchronization is in progress, the synchronization object is returned.

  • startingBlock: Number-synchronization start block number

  • currentBlock: Number-The block number that the node is currently synchronizing

  • highestBlock: Number-Estimate the block to sync to

Examples:

//Initialize basic objects

var Web3 = require('web3');

var web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));

var BigNumber = require('bignumber.js');

web3.eth.isSyncing(function(error, sync){

    if(!error) {

        // stop all app activity

        if(sync === true) {

           // we use `true`, so it stops all filters, but not the web3.eth.syncing polling 

          web3.reset(true); 

       // show sync info 

       } else if(sync) { 

          console.log(sync.currentBlock);  

      // re-gain app operation

        } else { 

           // run your app init function... 

       } 

   }

});

web3.eth.coinbase

Synchronously:

Asynchronous way:

web3.eth.getCoinbase(callback(error, result){ ... })

Read-only attribute, the address configured by the node and rewarded if mining is successful.

return value:

String-The mining reward address of the node.

Examples:

var coinbase = web3.eth.coinbase;

console.log(coinbase); // "0x407d73d8a49eeb85d32cf465507dd71d507100c1"

web3.eth.mining

Synchronously:

Asynchronous way:

web3.eth.getMining(callback(error, result){ ... })

The attribute is read-only, indicating whether the node is configured for mining.

return value:

Boolean-true means to configure mining, otherwise it means no.

var mining = web3.eth.mining;
console.log(mining); // true or false

web3.eth.hashrate

Synchronously:

Asynchronous way:

web3.eth.getHashrate(callback(error, result){ ... })

The attribute is read-only and represents the current hash difficulty per second.

return value:

Number-Number of hashes per second

Examples:

var hashrate = web3.eth.hashrate;

console.log(hashrate);

web3.eth.gasPrice

Synchronously:

Asynchronous way:

web3.eth.getGasPrice(callback(error, result){ ... })

The attribute is read-only and returns the current gas price. This value is determined by the median value of 6 gas prices in the last few blocks.

return value:

BigNumber-The BigNumber instance of the current gas price, in wei.

var gasPrice = web3.eth.gasPrice;

console.log(gasPrice.toString(10)); // "10000000000000"

web3.eth.accounts

Synchronously:

Asynchronous way:

web3.eth.getAccounts(callback(error, result){ ... })

Read-only attribute, returns the list of accounts held by the current node.

return value:

Array-List of accounts held by the node.

Examples:

var accounts = web3.eth.accounts;

console.log(accounts); 

web3.eth.blockNumber

Synchronously:

Asynchronous way:

web3.eth.getBlockNumber(callback(error, result){ ... })

The attribute is read-only and returns the current block number.

var number = web3.eth.blockNumber;

console.log(number); // 2744

web3.eth.register

web3.eth.register(addressHexString [, callback])

(Not yet implemented) Register the given address to web3.eth.accounts. This will allow accounts without private keys, such as contracts, to be linked to accounts with private keys, such as contract wallets.

parameter:

  • String-The address to be registered.

  • Function-(optional) callback function, used to support asynchronous execution 7.

return value:

To be determined

Examples:

web3.eth.register("0x407d73d8a49eeb85d32cf465507dd71d507100ca")

web3.eth.unRegister

Asynchronous mode

web3.eth.unRegister(addressHexString [, callback])

(Not yet implemented) Unregister the given address

parameter:

  • String-the address to be unregistered

  • Function-(optional) Callback function, used to support asynchronous execution 7.

return value:

To be determined

Examples:

web3.eth.unRegister("0x407d73d8a49eeb85d32cf465507dd71d507100ca")

web3.eth.getBalance

web3.eth.getBalance(addressHexString [, defaultBlock] [, callback])

Get the balance of the given address when specifying the block.

parameter:

  • String-The address to check the balance.

  • Number|String-(optional) If this value is not set, the block set by web3.eth.defaultBlock is used, otherwise the specified block is used.

  • Funciton-(optional) callback function, used to support asynchronous execution 7.

return value:

String-A BigNumber instance containing the current balance of the given address in wei.

Examples:

var balance = web3.eth.getBalance("0x407d73d8a49eeb85d32cf465507dd71d507100c1");

console.log(balance); // instanceof BigNumber

console.log(balance.toString(10)); // '1000000000000'

console.log(balance.toNumber()); // 1000000000000

web3.eth.getStorageAt

web3.eth.getStorageAt(addressHexString, position [, defaultBlock] [, callback])

Get the stored state value at a specified location in an address.

The contract consists of two parts: the EVM bytecode that controls execution and the storage used to save state. Storage is stored on the blockchain in the form of key and value pairs of 32 bytes each8.

parameter:

  • String-The address to be stored.

  • Number-the serial number of the storage to be obtained

  • Number|String-(optional) If no parameter is passed, the block defined by web3.eth.defaultBlock is used by default, otherwise the specified block is used.

  • Function-Callback function, used to support asynchronous execution 7.

return value:

String-the stored value at a given position

Examples:

var state = web3.eth.getStorageAt("0x407d73d8a49eeb85d32cf465507dd71d507100c1", 0);

console.log(state); // "0x03"

web3.eth.getCode

web3.eth.getCode(addressHexString [, defaultBlock] [, callback])

Get the code of the specified address

parameter:

  • String-The address of the code to get.

  • Number|String-(optional) If no parameter is passed, the block defined by web3.eth.defaultBlock is used by default, otherwise the specified block is used.

  • Function-Callback function, used to support asynchronous execution 7.

return value:

String-The compiled byte code for the given address contract.

Examples:

var code = web3.eth.getCode("0xd5677cf67b5aa051bb40496e68ad359eb97cfbf8");

console.log(code); // "0x600160008035811a818181146012578301005b601b6001356025565b8060005260206000f25b600060078202905091905056"

web3.eth.getBlock

web3.eth.getBlock(blockHashOrBlockNumber [, returnTransactionObjects] [, callback])

Returns the block corresponding to the block number or block hash

parameter:

  • Number|String-(optional) If no parameter is passed, the block defined by web3.eth.defaultBlock is used by default, otherwise the specified block is used.

  • Boolean-(optional) The default value is false. true will return all transactions contained in the block as objects. Otherwise, only the hash of the transaction is returned.

  • Function-Callback function, used to support asynchronous execution 7.

Return value-block object:

  • Number-Block number. When this block is pending it will return null.

  • hash-string, hash string of the block. When this block is pending it will return null.

  • parentHash-a string, a 32-byte hash of the parent block.

  • nonce-string, 8 bytes. The hash generated by POW. When this block is pending it will return null.

  • sha3Uncles-string, 32 bytes. Uncle block's hash value.

  • logsBloom-String, Bloom filter for block logs 9. When this block is pending it will return null.

  • transactionsRoot-string, 32 bytes, the root of the block's transaction prefix tree.

  • stateRoot-string, 32 bytes. The root of the final state prefix tree of the block.

  • miner-string, 20 bytes. Miners who are rewarded for this block.

  • difficulty-BigNumber type. The difficulty of the current block, integer.

  • totalDifficulty-BigNumber type. The total difficulty of the blockchain to the current block, integer.

  • extraData-string. The extra data field of the current block.

  • size-Number. The current byte size of this block.

  • gasLimit-Number, the maximum gas allowed in the current block.

  • gasUsed-The total gas used in the current block.

  • timestamp-Number. The unix timestamp when the block was packed.

  • transactions-array. Trading partners. Or a 32-byte transaction hash.

  • uncles-array. Array of uncle hashes.

Examples:

var info = web3.eth.getBlock(3150);
console.log(info);
/*
{  "number": 3, 

 "hash": "0xef95f2f1ed3ca60b048b4bf67cde2195961e0bba6f70bcbea9a2c4e133e34b46", 

 "parentHash": "0x2302e1c0b972d00932deb5dab9eb2982f570597d9d42504c05d9c2147eaf9c88", 

 "nonce": "0xfb6e1a62d119228b", 

 "sha3Uncles": "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347", 

 "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",  "transactionsRoot": "0x3a1b03875115b79539e5bd33fb00d8f7b7cd61929d5a3c574f507b8acf415bee",

  "stateRoot": "0xf1133199d44695dfa8fd1bcfe424d82854b5cebef75bddd7e40ea94cda515bcb", 

 "miner": "0x8888f1f195afa192cfee860698584c030f4c9db1", 

 "difficulty": BigNumber,

  "totalDifficulty": BigNumber,

  "size": 616,

  "extraData": "0x",

  "gasLimit": 3141592, 

 "gasUsed": 21662, 

 "timestamp": 1429287689, 

 "transactions": [    "0x9fc76417374aa880d4449a1f7f31ec597f00b1f6f3dd2d66f4c9c6c445836d8b"
 ], 

 "uncles": []
}
*/

web3.eth.getBlockTransactionCount

web3.eth.getBlockTransactionCount(hashStringOrBlockNumber [, callback])

Returns the number of transactions in the specified block.

parameter:

  • Number|String-(optional) If no parameter is passed, the block defined by web3.eth.defaultBlock is used by default, otherwise the specified block is used.

  • Function-Callback function, used to support asynchronous execution 7.

return value:

Nubmer-the number of transactions in a given block.

Examples:

var number = web3.eth.getBlockTransactionCount("0x407d73d8a49eeb85d32cf465507dd71d507100c1");

console.log(number); // 1

web3.eth.getUncle

web3.eth.getUncle(blockHashStringOrNumber, uncleNumber [, returnTransactionObjects] [, callback])

Return to the specified uncle block by specifying the uncle position.

parameter:

  • Number|String-(optional) If no parameter is passed, the block defined by web3.eth.defaultBlock is used by default, otherwise the specified block is used.

  • Number-Uncle's serial number.

  • Boolean-(optional) The default value is false. true will return all transactions contained in the block as objects. Otherwise, only the hash of the transaction is returned.

  • Function-Callback function, used to support asynchronous execution 7.

return value:

Object-The returned uncle block. Refer to web3.eth.getBlock() for the return value.

Remarks: Uncle Block does not have its own transaction data.

Examples:

var uncle = web3.eth.getUncle(500, 0);

console.log(uncle); // see web3.eth.getBlock

web3.eth.getTransaction

web3.eth.getTransaction(transactionHash [, callback])

Returns the transaction that matches the hash value of the specified transaction.

parameter:

  • String-The hash value of the transaction.

  • Function-Callback function, used to support asynchronous execution 7.

return value:

Object-a transaction object

  • hash: String-32 bytes, the hash value of the transaction.

  • nonce: Number-The number of transactions that the originator of the transaction has made before.

  • blockHash: String-32 bytes. The hash value of the exchange in the block. When this block is pending it will return null.

  • blockNumber: Number-The block number of the exchange in the block. When this block is pending it will return null.

  • transactionIndex: Number-Integer. The serial number of the transaction in the block. When this block is pending it will return null.

  • from: String-20 bytes, the address of the transaction initiator.

  • to: String-20 bytes, the address of the transaction recipient. When this block is pending it will return null.

  • value: BigNumber-The amount of currency attached to the transaction, in Wei.

  • gasPrice: BigNumber-the gas price configured by the transaction initiator, in wei.

  • gas: Number-Gas provided by the transaction initiator. .

  • input: String-Data attached to the transaction.

Examples:

var blockNumber = 668;

var indexOfTransaction = 0

var transaction = web3.eth.getTransaction(blockNumber, indexOfTransaction);

console.log(transaction);

/*

{ 

 "hash": "0x9fc76417374aa880d4449a1f7f31ec597f00b1f6f3dd2d66f4c9c6c445836d8b", 

 "nonce": 2,

  "blockHash": "0xef95f2f1ed3ca60b048b4bf67cde2195961e0bba6f70bcbea9a2c4e133e34b46", 

 "blockNumber": 3, 

 "transactionIndex": 0,

  "from": "0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b",  "to": "0x6295ee1b4f6dd65047762f924ecd367c17eabf8f", 

 "value": BigNumber, 

 "gas": 314159, 

 "gasPrice": BigNumber, 

 "input": "0x57cb2fc4"

}

*/

web3.eth.getTransactionFromBlock

Returns the transaction with the specified sequence number in the specified block.

parameter:

  • String-Block number or hash. Or earliest, latest or pending. See web3.eth.defaultBlock for optional values.

  • Number-The serial number of the transaction.

  • Function-Callback function, used to support asynchronous execution 7.

return value:

Object-transaction object, see web3.eth.getTransaction for details

Examples:

var transaction = web3.eth.getTransactionFromBlock('0x4534534534', 2);

console.log(transaction); // see web3.eth.getTransaction

web3.eth.getTransactionReceipt

web3.eth.getTransactionReceipt(hashString [, callback])

Through a transaction hash, return a transaction receipt.

Note: For transactions in the pending state, the receipt is not available.

parameter:

  • String-the hash of the transaction

  • Function-Callback function, used to support asynchronous execution 7.

return value:

Object-The receipt object of the transaction, or null if not found

  • blockHash: String-32 bytes, the hash of this exchange in the block.

  • blockNumber: Number-The block number of the exchange in the block.

  • transactionHash: String-32 bytes, the hash value of the transaction.

  • transactionIndex: Number-The serial number of the transaction in the block, integer.

  • from: String-20 bytes, the address of the transaction sender.

  • to: String-20 bytes, the address of the transaction recipient. If it is a contract created transaction, return null.

  • cumulativeGasUsed: Number-The cumulative value of gas spent after the execution of the current transaction is 10.

  • gasUsed: Number-The gas currently spent alone to execute this transaction.

  • contractAddress: String-20 bytes, the created contract address. If it is a contract to create a transaction, return the contract address, otherwise return null.

  • logs: Array-Array of log objects generated by this transaction.

Examples:

var receipt = web3.eth.getTransactionReceipt('0x9fc76417374aa880d4449a1f7f31ec597f00b1f6f3dd2d66f4c9c6c445836d8b');

console.log(receipt);

{

  "transactionHash": "0x9fc76417374aa880d4449a1f7f31ec597f00b1f6f3dd2d66f4c9c6c445836d8b", 

 "transactionIndex": 0, 

 "blockHash": "0xef95f2f1ed3ca60b048b4bf67cde2195961e0bba6f70bcbea9a2c4e133e34b46", 

 "blockNumber": 3, 

 "contractAddress": "0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b", 

 "cumulativeGasUsed": 314159, 

 "gasUsed": 30234, 

 "logs": [{ 

        // logs as returned by getFilterLogs, etc.  

   }, ...]

}

web3.eth.getTransactionCount

web3.eth.getTransactionCount(addressHexString [, defaultBlock] [, callback])

Returns the number of transactions initiated by the specified address.

parameter:

  • String-The address to get the number of transactions.

  • Number|String-(optional) If no parameter is passed, the block defined by web3.eth.defaultBlock is used by default, otherwise the specified block is used.

  • Function-Callback function, used to support asynchronous execution 7.

return value:

Number-The number of transactions sent by the specified address.

Examples:

var number = web3.eth.getTransactionCount("0x407d73d8a49eeb85d32cf465507dd71d507100c1");console.log(number); 

// 1

**web3.eth.sendTransaction**

web3.eth.sendTransaction(transactionObject [, callback])

Send a transaction to the network.

parameter:

Object-The transaction object to be sent.

  • from: String-The specified sender's address. If not specified, web3.eth.defaultAccount is used.

  • to: String-(optional) the target address of the transaction message, if the contract is created, it is not filled in.

  • value: Number|String|BigNumber-(optional) the amount of currency carried in the transaction, in wei. If the contract creates a transaction, it is the initial fund.

  • gas: Number|String|BigNumber-(optional) The default is automatic, the gas that can be used for transactions, unused gas will be returned.

  • gasPrice: Number|String|BigNumber-(optional) The default is automatically determined, the gas price of the transaction, the default is the average value of the network gas price.

  • data: String-(optional) or a byte string containing related data. If the contract is created, it is the code to be used for initialization.

  • nonce: Number-(optional) integer, use this value to allow you to override your own nonce of the same pending transaction 11.

Function-Callback function, used to support asynchronous execution 7.

return value:

String-32-byte transaction hash string. Expressed in hexadecimal.

If the transaction is a contract creation, please use web3.eth.getTransactionReceipt() to obtain the contract address after the transaction is completed.

Examples:

// compiled solidity source code using https://chriseth.github.io/cpp-ethereum/

var code = "603d80600c6000396000f3007c01000000000000000000000000000000000000000000000000000000006000350463c6888fa18114602d57005b6007600435028060005260206000f3";

web3.eth.sendTransaction({data: code}, function(err, address)

 { 

 if (!err)

    console.log(address); // "0x7f9fade1c0d57a7af66ab4ead7c2eb7b11a91385"

});

web3.eth.sendRawTransaction

web3.eth.sendRawTransaction(signedTransactionData [, callback])

Send a signed transaction. For example, the following signature example can be used:https://github.com/SilentCicero/ethereumjs-accounts

parameter:

  • String-signed transaction data in hexadecimal format.

  • Function-Callback function, used to support asynchronous execution 7.

return value:

String-32-byte transaction hash string in hexadecimal format.

If the transaction is a contract creation, please use web3.eth.getTransactionReceipt() to obtain the contract address after the transaction is completed.

Examples:

var Tx = require('ethereumjs-tx');

var privateKey = new Buffer('e331b6d69882b4cb4ea581d88e0b604039a3de5967688d3dcffdd2270c0fd109', 'hex')

var rawTx = { 

 nonce: '0x00', 

 gasPrice: '0x09184e72a000',

   gasLimit: '0x2710', 

 to: '0x0000000000000000000000000000000000000000', 

  value: '0x00', 

  data: '0x7f7465737432000000000000000000000000000000000000000000000000000000600057'

}

var tx = new Tx(rawTx);

tx.sign(privateKey);

var serializedTx = tx.serialize();

//console.log(serializedTx.toString('hex'));

//0xf889808609184e72a00082271094000000000000000000000000000000000000000080a47f74657374320000000000000000000000000000000000000000000000000000006000571ca08a8bbf888cfa37bbf0bb965423625641fc956967b81d12e23709cead01446075a01ce999b56a8a88504be365442ea61239198e23d1fce7d00fcfc5cd3b44b7215f

web3.eth.sendRawTransaction(serializedTx.toString('hex'), function(err, hash) { 

 if (!err) 

   console.log(hash); // "0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385"

});

web3.eth.sign

web3.eth.sign(address, dataToSign, [, callback])

To sign data to be sent using the specified account, the account needs to be in an unlocked state.

parameter:

  • String-the address used by the signature

  • String-the data to be signed

  • Function-(optional) callback function, used to support asynchronous execution 7.

return value:

String-The signed data.

The returned value corresponds to the string signed by ECDSA (Elliptic Curve Digital Signature Algorithm) 12.

r = signature[0:64]
s = signature[64:128]
v = signature[128:130]

It should be noted that if you use ecrecover, the v value here is 00 or 01, so if you want to use them, you need to convert the v value here to an integer, plus 27. The final value you will use is 27 or 2813.

Examples:

var result = web3.eth.sign("0x135a7de83802408321b74c322f8558db1679ac20",  

  "0x9dd2c369a187b4e6b9c402f030e50743e619301ea62aa4c0737d4ef7e10a3d49"); // second argument is web3.sha3("xyz")

console.log(result); // "0x30755ed65396facf86c53e6217c52b4daebe72aa4941d89635409de4c9c7f9466d4e9aaec7977f05e923889b33c0d0dd27d7226b6e6f56ce737465c5cfd04be400"

Note: If you use the Ethereum client for signing, they will add the prefix \x19Ethereum Signed Message:\n14 before the data you want to sign. Thanks to reader @ for feedback.

eth_sign

The sign method calculates an Ethereum specific signature with: sign(keccak256(“\x19Ethereum Signed Message:\n” + len(message) + message))).

By adding a prefix to the message makes the calculated signature recognisable as an Ethereum specific signature. This prevents misuse where a malicious DApp can sign arbitrary data (e.g. transaction) and use the signature to impersonate the victim.

web3.eth.call

web3.eth.call(callObject [, defaultBlock] [, callback])

In the node's VM, directly execute the message call transaction. But the data will not be merged into the blockchain (such calls will not modify the state).

parameter:

  • Object-returns a transaction object, same as web3.eth.sendTransaction. The difference with sendTransaction is that the from attribute is optional.

  • Number|String-(optional) If this value is not set, the block set by web3.eth.defaultBlock is used, otherwise the specified block is used.

  • Function-(optional) callback function, used to support asynchronous execution 7.

return value:

String-The value returned by the function call.

Examples:

var Web3 = require('web3');

if (typeof web3 !== 'undefined') {

  web3 = new Web3(web3.currentProvider);

} else {

  // set the provider you want from Web3.providers

  web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));

}

var from = web3.eth.accounts[0];

//The release address of the deployment contract

/*Contract content is as follows

pragma solidity ^0.4.0;

contract Calc{

  function add(uint a, uint b) returns (uint){

    return a + b;

  }

}

*/

var to = "0xa4b813d788218df688d167102e5daff9b524a8bc";

//Data to be sent

//For format description, see: http://me.tryblockchain.org/Solidity-call-callcode-delegatecall.html

var data = "0x771602f700000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000002";

var result = web3.eth.call({

  from : from,

  to : to, 

 data : data

});

//Return result 32 words long result 3

console.log(result);

web3.eth.estimateGas

web3.eth.estimateGas(callObject [, callback])

Perform a message call, or transaction, in the node's VM node. But it will not be incorporated into the blockchain. Returns the amount of gas used.

parameter:

As with web3.eth.sendTransaction, all attributes are optional.

return value:

Number-Gas cost for simulated call/transcation.

Examples:

var result = web3.eth.estimateGas({

    to: "0xc4abd0339eb8d57087278718986382264244252f", 

    data: "0xc6888fa10000000000000000000000000000000000000000000000000000000000000003"

});

console.log(result); // "0x0000000000000000000000000000000000000000000000000000000000000015"

web3.eth.filter

parameter:

  • String|Object-The value of the string [latest, pending]. latest means to monitor the latest block changes, pending means to monitor the pending block. If you need to filter by conditional objects, as follows:

  • fromBlock: Number|string-The starting block number (if using the string latest, which means the latest block being packed), the default value is latest.

  • toBlock: Number|string-Termination block number (if using the string latest, which means the latest block being packed), the default value is latest.

  • address: String-Single or multiple addresses. Get the log of the specified account.

  • topics: String[]-An array of strings that must appear in the log object. The order is very important, if you want to ignore the topic, use null. For example, [null,’0x00…’], you can also pass a separate option array for each topic, such as [null,[‘option1’,’option1’]].

return value:

  • Object-Filter object with the following methods.

  • filter.get(callback): returns the log that meets the filter conditions.

  • filter.watch(callback): monitor the state change that meets the condition, call callback 7 when the condition is met.

  • filter.stopWatching(): Stop listening and clear the filtering in the node. You should always perform this operation after monitoring is complete.

Listening callback return value:

String-When using the latest parameter. Returns the latest hash value of a block.

String-When using the pending parameter. Returns the latest transaction hash in pending.

Object-When using the manual filtering option, the following log object will be returned.

  • logIndex: Number-The serial number of the log in the block. If it is a pending log, it is null.

  • transactionIndex: Number-The serial number of the transaction that generated the log in the block. If it is a pending log, it is null.

  • transactionHash: String, 32 bytes-the transaction hash value that generated the log.

  • blockHash: String, 32 bytes-the hash of the block where the log is located. If it is a pending log, it is null.

  • blockNumber: Number-The block number of the block where the log is located. If it is a pending log, it is null.

  • address: String, 32 bytes-the contract address generated by the log.

  • data: string-Contains one or more 32-byte non-indexed parameters of the log.

  • topics: String[]-One to four 32-byte indexed log parameter arrays. (In Solidity, the first subject is the signature of the entire event (eg, Deposit(address, bytes32, uint256)), except if the event is defined anonymously)

The return result of the event listener, see the event of the contract object.

Examples:

var filter = web3.eth.filter('pending');

filter.watch(function (error, log) {

  console.log(log); //  {"address":"0x0000000000000000000000000000000000000000", "data":"0x0000000000000000000000000000000000000000000000000000000000000000", ...}

});

// get all past logs again.

var myResults = filter.get(function(error, logs){ ... });

...

// stops and uninstalls the filter

filter.stopWatching();

web3.eth.contract

web3.eth.contract(abiArray)

Create a Solidity contract object to initialize the contract at an address.

parameter:

Array-One or more ABI objects describing contract functions and events.

return value:

Object-a contract object.

Examples:

var MyContract = web3.eth.contract(abiArray);

// instantiate by address

var contractInstance = MyContract.at([address]);

// deploy new contrac

tvar contractInstance = MyContract.new([contructorParam1] [, contructorParam2], {data: '0x12345...', from: myAccount, gas: 1000000});

// Get the data to deploy the contract manually

var contractData = MyContract.new.getData([contructorParam1] [, contructorParam2], {data: '0x12345...'});

// contractData = '0x12345643213456000000000023434234'

You can either use a contract that already exists at an address, or deploy a completely new contract using compiled bytecode.

// Instantiate from an existing address:

var myContractInstance = MyContract.at(myContractAddress);

// Or deploy a new contract:

// Deploy the contract asyncronous from Solidity file:

...const fs = require("fs");

const solc = require('solc')

let source = fs.readFileSync('nameContract.sol', 'utf8');

let compiledContract = solc.compile(source, 1);

let abi = compiledContract.contracts['nameContract'].interface;

let bytecode = compiledContract.contracts['nameContract'].bytecode;

let gasEstimate = web3.eth.estimateGas({data: bytecode});

let MyContract = web3.eth.contract(JSON.parse(abi));

var myContractReturned = MyContract.new(param1, param2,

 {

   from:mySenderAddress, 

  data:bytecode,

   gas:gasEstimate}, function(err, myContract){

    if(!err) {

       // NOTE: The callback will fire twice! 

      // Once the contract has the transactionHash property set and once its deployed on an address. 

      // e.g. check tx hash on the first call (transaction send)       if(!myContract.address) {  

         console.log(myContract.transactionHash) // The hash of the transaction, which deploys the contract   

    // check address on the second call (contract deployed)  

     } else { 

          console.log(myContract.address) // the contract address

       } 

      // Note that the returned "myContractReturned" === "myContract",

       // so the returned "myContractReturned" object will also get the address set. 

   }

  });

// Deploy contract syncronous: The address will be added as soon as the contract is mined.

// Additionally you can watch the transaction by using the "transactionHash" property

var myContractInstance = MyContract.new(param1, param2, {

data: myContractCode, gas: 300000, from: mySenderAddress

});

myContractInstance.transactionHash // The hash of the transaction, which created the contract

myContractInstance.address // undefined at start, but will be auto-filled later

Examples:

// contract abi

var abi = [{

     name: 'myConstantMethod',

     type: 'function', 

    constant: true,

     inputs: [{ name: 'a', type: 'string' }], 

    outputs: [{name: 'd', type: 'string' }]

}, { 

    name: 'myStateChangingMethod', 

    type: 'function', 

    constant: false,

     inputs: [{ name: 'a', type: 'string' }, { name: 'b', type: 'int' }], 

    outputs: []

}, {   

  name: 'myEvent', 

    type: 'event', 

    inputs: [{name: 'a', type: 'int', indexed: true},{name: 'b', type: 'bool', indexed: false}]

}];

// creation of contract object

var MyContract = web3.eth.contract(abi);

// initiate contract for an address

var myContractInstance = MyContract.at('0xc4abd0339eb8d57087278718986382264244252f');

// call constant function

var result = myContractInstance.myConstantMethod('myParam');

console.log(result) // '0x25434534534'

// send a transaction to a function

myContractInstance.myStateChangingMethod('someParam1', 23, {value: 200, gas: 2000});

// short hand style

web3.eth.contract(abi).at(address).myAwesomeMethod(...);

// create filter

var filter = myContractInstance.myEvent({a: 5}, function (error, result) { 

 if (!error)

    console.log(result);

    /*

    { 

       address: '0x8718986382264244252fc4abd0339eb8d5708727',       

 topics: "0x12345678901234567890123456789012", "0x0000000000000000000000000000000000000000000000000000000000000005", 

       data: "0x0000000000000000000000000000000000000000000000000000000000000001",   

     ... 

   }  

  */

});

Contract object methods

// Automatically determines the use of call or sendTransaction based on the method type

myContractInstance.myMethod(param1 [, param2, ...] [, transactionObject] [, defaultBlock] [, callback]);

// Explicitly calling this method

myContractInstance.myMethod.call(param1 [, param2, ...] [, transactionObject] [, defaultBlock] [, callback]);

// Explicitly sending a transaction to this method

myContractInstance.myMethod.sendTransaction(param1 [, param2, ...] [, transactionObject] [, callback])

;// Get the call data, so you can call the contract through some other means

var myCallData = myContractInstance.myMethod.getData(param1 [, param2, ...]);

// myCallData = '0x45ff3ff6000000000004545345345345..'

The contract object encapsulates related methods of using the contract. You can use methods by passing in parameters and transaction objects.

parameter:

  • String|Number-(optional) zero or more function parameters. If you pass in a string, you need to use hexadecimal encoding, for example, 0xdedbeef.

  • Object-(optional) the last parameter (if the callback is passed, the penultimate parameter), which can be a transaction object. See the first parameter description of web3.eth.sendTransaction to learn more. Note that there is no need to fill in the data and to attributes.

  • Number|String-(optional) If this value is not set, the block set by web3.eth.defaultBlock is used, otherwise the specified block is used.

  • Function-(optional) callback function, used to support asynchronous execution 7.

return value:

String-If a call was initiated, the corresponding result is returned. If it is a transaction, it will either be a created contract address or a transaction hash. See web3.eth.sendTransaction to learn more.

Examples:

// creation of contract object

var MyContract = web3.eth.contract(abi);

// initiate contract for an address

var myContractInstance = MyContract.at('0x78e97bcc5b5dd9ed228fed7a4887c0d7287344a9');

var result = myContractInstance.myConstantMethod('myParam');

console.log(result) // '0x25434534534'

myContractInstance.myStateChangingMethod('someParam1', 23, {value: 200, gas: 2000}, function(err, result){ ... });

Contract object events

You can use events like web3.eth.filter, they have the same method, but you need to pass different objects to create event filters.

parameter:

  • Object-The index value you want to return (which logs are filtered). For example, {‘valueA’: 1, ‘valueB’: [myFirstAddress, mySecondAddress]}. By default, all filter items are set to null. It means that all the logs of the contract are matched by default.

  • Object-Additional filtering options. See the first parameter of web3.eth.filter. By default, this object sets the address to the current contract address, and the first subject is the signature of the event.

  • Function-(optional) Incoming a callback function will immediately start monitoring, so that you do not need to actively call myEvent.watch(function(){})7.

Callback return value:

Object-Event object, as follows:

  • address: String, 32 bytes-the contract address generated by the log.

  • args: Object-the parameters of the event.

  • blockHash: String, 32 bytes-the hash of the block where the log is located. If it is a pending log, it is null.

  • blockNumber: Number-The block number of the block where the log is located. If it is a pending log, it is null.

  • logIndex: Number-The serial number of the log in the block. If it is a pending log, it is null.

  • event: String-Event name.

  • removed: bool-Identifies whether the transaction that caused the event was removed (because of the orphan block), or never took effect (rejected transaction).

  • transactionIndex: Number-The serial number of the transaction that generated the log in the block. If it is a pending log, it is null.

  • transactionHash: String, 32 bytes-the transaction hash value that generated the log.

Examples:

var MyContract = web3.eth.contract(abi);

var myContractInstance = MyContract.at('0x78e97bcc5b5dd9ed228fed7a4887c0d7287344a9');

// watch for an event with {some: 'args'}

var myEvent = myContractInstance.MyEvent({some: 'args'}, {fromBlock: 0, toBlock: 'latest'});

myEvent.watch(function(error, result){ 

  ...

});

// would get all past logs again.

var myResults = myEvent.get(function(error, logs){ ... });.

..

// would stop and uninstall the filter

myEvent.stopWatching();

Contract allEvents

var events = myContractInstance.allEvents([additionalFilterObject]);

// watch for changes

events.watch(function(error, event){

  if (!error)

    console.log(event);

});

// Or pass a callback to start watching immediately

var events = myContractInstance.allEvents([additionalFilterObject,] function(error, log){

  if (!error) 

   console.log(log);

});

Callback for all events created by the contract.

parameter:

  • Object-Additional filtering options. See the first parameter of web3.eth.filter. By default, this object sets the address to the current contract address, and the first subject is the signature of the event.

  • Function-(optional) Incoming a callback function will immediately start monitoring, so that you do not need to actively call myEvent.watch(function(){})7.

Callback return value:

Object-See the event of the contract object for more details.

Examples:

var MyContract = web3.eth.contract(abi);

var myContractInstance = MyContract.at('0x78e97bcc5b5dd9ed228fed7a4887c0d7287344a9');

// watch for an event with {some: 'args'}

var events = myContractInstance.allEvents({fromBlock: 0, toBlock: 'latest'});

events.watch(function(error, result){

   ...

});

// would get all past logs again.

events.get(function(error, logs){ ... });

...

// would stop and uninstall the filter

myEvent.stopWatching();

web3.eth.getCompilers

web3.eth.getCompilers([callback])

Returns the available compiler.

Parameter value:

Function-(optional) callback function, used to support asynchronous execution 7.

return value:

  • Array-returns an array of strings, available compilers.

web3.eth.compile.solidity

web3.eth.compile.solidity(sourceString [, callback])

Compile the Solidity source code.

parameter:

  • String-Solidity source code.

  • Function-(optional) callback function, used to support asynchronous execution 7.

return value:

Object-Contract and compilation information.

Examples:

var source = "" +

     "contract test {\n" +

    "   function multiply(uint a) returns(uint d) {\n" +  

  "       return a * 7;\n" + 

   "   }\n" +  

  "}\n";

var compiled = web3.eth.compile.solidity(source);

console.log(compiled);

 // { 

 "test": {

    "code": "0x605280600c6000396000f3006000357c010000000000000000000000000000000000000000000000000000000090048063c6888fa114602e57005b60376004356041565b8060005260206000f35b6000600782029050604d565b91905056", 

   "info": {

      "source": "contract test {\n\tfunction multiply(uint a) returns(uint d) {\n\t\treturn a * 7;\n\t}\n}\n", 

     "language": "Solidity",  

    "languageVersion": "0", 

     "compilerVersion": "0.8.2", 

     "abiDefinition": [  

      { 

         "constant": false, 

         "inputs": [ 

           {  

            "name": "a",  

            "type": "uint256"

            } 

         ],

          "name": "multiply", 

         "outputs": [  

          { 

             "name": "d", 

             "type": "uint256" 

           } 

         ],  

        "type": "function" 

       }  

    ], 

     "userDoc": { 

       "methods": {}  

    },  

    "developerDoc": { 

       "methods": {}  

    } 

   } 

 }

}

web3.eth.compile.lll

web3. eth.compile.lll(sourceString [, callback])

Compile the LLL source code.

parameter:

  • String-LLL source code.

  • Function-(optional) callback function, used to support asynchronous execution 7.

return value:

String-LLL encoding compiled in hexadecimal format.

Examples:

var source = "...";

var code = web3.eth.compile.lll(source);

console.log(code); // "0x603880600c6000396000f3006001600060e060020a600035048063c6888fa114601857005b6021600435602b565b8060005260206000f35b600081600702905091905056"

web3.eth.compile.serpent

web3.eth.compile.serpent(sourceString [, callback])

Compile the serpent source code.

parameter:

  • String-serpent source code.

  • Function-(optional) callback function, used to support asynchronous execution 7.

return value:

String-The compiled serpent encoding in hexadecimal format.

**web3.eth.namereg**

web3.eth.namereg

Returns an object of global attention.

How to use:

Check out the example here:https://github.com/ethereum/web3.js/blob/master/example/namereg.html

4.4 web3.db

web3.db.putString

web3.db.putString(db, key, value)

This method should be used when we intend to store a string at the level of a local database.

parameter:

  • String-The database used for storage.

  • String-The stored key.

  • String-The stored value.

return value:

Boolean-true means success, otherwise returns false.

Examples:

web3.db.putString('testDB', 'key', 'myString') // true

**web3.db.getString**

web3.db.getString(db, key)

Return a string from the local leveldb database.

parameter:

  • String-Database used for storage.

  • String-The stored key.

return value:

String-The stored value.

Examples:

var value = web3.db.getString('testDB', 'key');

console.log(value); // "myString"

**web3.db.putHex**

web3.db.putHex(db, key, value)

Store binary data in local leveldb.

parameter:

  • String-The database used for storage.

  • String-The stored key.

  • String-Binary in hexadecimal format.

return value:

Boolean-Returns true on success and false on failure.

Examples:

web3.db.putHex('testDB', 'key', '0x4f554b443'); // true

**web3.db.getHex**

web3.db.getHex(db, key)

Returns the binary data in the local leveldb.

parameter:

  • String-Database used for storage.

  • String-The stored key.

return value:

String-Stored hexadecimal value.

Examples:

var value = web3.db.getHex('testDB', 'key');

console.log(value); // "0x4f554b443"

Reference documents

1] Web3 JavaScript app API English official website interface document (https://github.com/ethereum/wiki/wiki/JavaScript-API#web3ethaccounts

2] WEB3.JS code (https://github.com/ethereum/web3.js

3] WEB3 Chinese help document address (https://blog.csdn.net/qq_28114645/article/details/78802176

4] Ethereum DApp development tutorial-Blockchain voting system- (https://blog.csdn.net/mongo_node/article/details/79424450

5] Web3 and smart contract interactive combat-Xiong Libing (https://blog.csdn.net/xilibi2003/article/details/80338894

Further reading:

Hui Ge's article Other:Solidity language editor REMIX guide Daquan

Author: HiBlock block chain technology evangelism group -Pen name Huige

The original text is published in the brief book, the original address:https://www.jianshu.com/p/47174718960b

Add WeChat baobaotalk_com to join the technical preaching group

The following is an introduction to our community, all kinds of cooperation, exchange and learning are welcome

image

【Objectives of this article】
Understand the framework and interactive process of DAPP decentralized applications under the ETH ecosystem, and understand the role and interface functions of […]

Leave a Reply