Web3.js vs js-conflux-sdk

The latest version of JS-Conflux-SDK is 1.x, which is quite different from 0.x. However, since it is still in the testing stage, this paper only compares 0.13.4 and Web3. After 1.x version is stable, it will compare 1.x and Web3. Both Web3 and JS-Conflux-SDK are top-level modules, which include other sub-modules and some methods in the sub-modules exposed on the top layer for quick use by developers. We only compare each module here, and do not make special description of these shortcuts.

Module contrast

Web3 and JS-Conflux-SDK are mainly related to the following modules:

Modules in Ethereum Module in Conflux function
Eth Conflux Used to manage connection nodes, interact with nodes, send RPC requests, including reading status, sending transactions, etc
Contract + abi Contract For manipulating smart contracts, including creating contract instances, mobilizing contract methods, and providing some abi codec capabilities
accounts account + Message + Transaction Manage accounts, including creating and deleting accounts, and signing messages or transactions using the accounts
utils util Utility class, provide some general functions, such as HEX format conversion, unit conversion, private key to public key and address, generate random private key, judge data type, SHA3, etc., convenient dAPP development and other JS package use

Compare the methods of each module

Conflux Vs Eth

The following are the methods contained in the Conflux module and the corresponding relationship with Eth module. This module mainly encapsulates the interaction between JSONRPC and nodes. Some JSONRPC has not been implemented yet, and RPC will be continuously improved in the future. For details about RPC, see Conflux JSONRPC introduction and the difference between Conflux RPC and Ethereum RPC. The Epoch Number here refers to the partition of a group of Conflux blocks into one Epoch. The Conflux blockchain is organized in Epoch order.

Conflux module Ethereum Eth module Corresponding RPC
setProvider setProvider
getStatus getChainId cfx_getStatus
getGasPrice getGasPrice cfx_gasPrice
getEpochNumber getBlockNumber cfx_epochNumber
getBalance getBalance cfx_getBalance
getNextNonce getBlockTransactionCount cfx_getNextNonce
getBlockByEpochNumber getBlock cfx_getBlockByEpochNumber
getBlocksByEpochNumber cfx_getBlocksByEpoch
getBlockByHash getBlock cfx_getBlockByHash
getBlockByHashWithPivotAssumption cfx_getBlockByHashWithPivotAssumption
getTransactionByHash getTransaction cfx_getTransactionByHash
getTransactionReceipt getTransactionReceipt cfx_getTransactionReceipt
sendTransaction sendTransaction cfx_sendTransaction
sendRawTransaction sendSignedTransaction cfx_sendRawTransaction
getCode getCode cfx_getCode
call call cfx_call
estimateGasAndCollateral estimateGas cfx_estimateGasAndCollateral
getLogs GetPastLogs (contract module) cfx_getLogs
getBestBlockHash cfx_getBestBlockHash
getConfirmationRiskByHash cfx_getConfirmationRiskByHash
close

Contract module comparison

Conflux Contract module Eth Contract + ABI module
contract.mymethod methods.myMethod.call
contract.mymethod.call methods.myMethod.call
contract.mymethod.decodeData decodeParameters
contract.mymethod.decodeOutputs
contract.mymethod.encodeData methods.myMethod.encodeABI
contract.mymethod.send methods.myMethod.send
contract.mymethod.estimateGasAndCollateral methods.myMethod.estimateGas
contract.myEvent.getLogs getPastLogs
contract.myEvent.encodeTopics
contract.myEvent.decodeLog DecodeLog (ABI) module
contract.abi.decodeData decodeParameters
contract.abi.decodeLog DecodeLog (ABI) module

Account module comparison

Conflux Account module Ethereum Accounts module
random create
decrypt decrypt
encrypt encrypt
signTransaction signTransaction
signMessage sign
Conflux Message module Ethereum Accounts module
sign sign
recover recover
hash (getter)
from (getter)
sign sign
Conflux Transaction module Ethereum Accounts module
hash (getter)
from (getter)
sign signTransaction
recover recover
encode
serialize

Utils module comparison

Conflux util module Ethereum utils module
format.any (setter)
format.hex (setter) toHex, numberToHex
format.uInt (setter)
format.bigInt (setter) toBN
format.bigUInt (setter)
format.hexUInt (setter)
format.riskNumber (setter)
format.epochNumber (setter)
format.address (setter) bytesToHex
format.publicKey (setter) bytesToHex
format.privateKey (setter) bytesToHex
format.signature (setter) bytesToHex
format.blockHash (setter) bytesToHex
format.txHash (setter) bytesToHex
format.buffer (setter) toHex + hexToBytes
format.boolean (setter)
sha3 sha3
checksumAddress toChecksumAddress
randomBuffer
randomPrivateKey randomHex
privateKeyToPublicKey PrivateKeyToAccount (Accounts module)
publicKeyToAddress PrivateKeyToAccount (Accounts module)
privateKeyToAddress PrivateKeyToAccount (Accounts module)
ecdsaSign Sign (Accounts module)
ecdsaRecover Recover (Accounts module)
encrypt Encrypt (Accounts module)
decrypt Decrypt (Accounts module)
unit.fromCFXToGDrip
unit.fromCFXToDrip toWei
unit.fromGDripToCFX
unit.fromGDripToDrip
unit.fromDripToCFX fromWei
unit.fromDripToGDrip

Use the compare

Initialize the

Initialize the Web3 instance

var Web3 = require('web3');
// "Web3.providers.givenProvider" will be set if in an Ethereum supported browser.
var web3 = new Web3(Web3.givenProvider || 'ws://some.local-or-remote.node:8546');
// or
var web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'));

Copy the code

Example Initialize the Conflux instance

Conflux instantiation is similar to Web3, but the current version does not support WebScoket Provider

const { Conflux } = require('js-conflux-sdk');
const cfx = new Conflux({url:'http://test.confluxrpc.org'});
Copy the code

Read the state

Ethereum read state

web3.eth.getBalance("0x107d73d8a49eeb85d32cf465507dd71d507100c1").then(console.log);
> "1000000000000"
Copy the code

Read Conflux state

await cfx.getBalance("0x107d73d8a49eeb85d32cf465507dd71d507100c1");
// or
cfx.getBalance("0x107d73d8a49eeb85d32cf465507dd71d507100c1").then(console.log)
> "1000000000000"
Copy the code

Send a deal

Web3 sends transactions

Web3 sends a transaction and notifies it in the following stages through event:

  • transactionHashTransaction sent
  • receiptTransaction executed
  • confirmationTransaction confirmed
  • errorTransaction execution failure
// compiled solidity source code using https://remix.ethereum.org
var code = "603d80600c6000396000f3007c01000000000000000000000000000000000000000000000000000000006000350463c6888fa18114602d57005b600 7600435028060005260206000f3";

// using the callback
web3.eth.sendTransaction({
    from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'.data: code // deploying a contracrt
}, function(error, hash){... });// using the promise
web3.eth.sendTransaction({
    from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'.to: '0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe'.value: '1000000000000000'
})
.then(function(receipt){... });// using the event emitter
web3.eth.sendTransaction({
    from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'.to: '0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe'.value: '1000000000000000'
})
.on('transactionHash'.function(hash){... }) .on('receipt'.function(receipt){... }) .on('confirmation'.function(confirmationNumber, receipt){... }) .on('error'.console.error); // If a out of gas error, the second parameter is the receipt.
Copy the code

Conflux sends a transaction

Js-conflux-sdk Because the current version does not add the function of accessing the local wallet of the node, you need to specify the Account directly when sending transactions. SendTransaction returns a Promise. object and can be directly await the Transaction hash;

Transaction or Transaction Receipt can also be returned in different states using this object method, as follows:

  • getReturn after sendingtransaction.
  • minedReturn when the packaging is completetransaction.
  • executedReturns after execution is completetransaction receipt.
  • confirmedintransaction risk < thresholdWhen to return totransaction receipt
const account = cfx.Account(your_private_key);

const promise = cfx.sendTransaction({ // Not await here, just get promise
      from: account,
      to: "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe".value: Drip.fromCFX(0.007)}); >await promise; // transaction
   "0x91fbdfb33f3a585f932c627abbe268c7e3aedffc1633f9338f9779c64702c688"
> await promise.get(); // get transaction
   {
    "blockHash": null."transactionIndex": null."hash": "0x91fbdfb33f3a585f932c627abbe268c7e3aedffc1633f9338f9779c64702c688". } >await promise.mined(); // wait till transaction mined
   {
    "blockHash": "0xe9b22ce311003e26c7330ac54eea9f8afea0ffcd4905828f27c9e2c02f3a00f7"."transactionIndex": 0."hash": "0x91fbdfb33f3a585f932c627abbe268c7e3aedffc1633f9338f9779c64702c688". } >await promise.executed(); // wait till transaction executed in right status. and return it's receipt.
   {
    "blockHash": "0xe9b22ce311003e26c7330ac54eea9f8afea0ffcd4905828f27c9e2c02f3a00f7"."index": 0."transactionHash": "0x91fbdfb33f3a585f932c627abbe268c7e3aedffc1633f9338f9779c64702c688"."outcomeStatus": 0. } >await promise.confirmed(); // wait till transaction risk coefficient '<' threshold.
   {
    "blockHash": "0xe9b22ce311003e26c7330ac54eea9f8afea0ffcd4905828f27c9e2c02f3a00f7"."index": 0."transactionHash": "0x91fbdfb33f3a585f932c627abbe268c7e3aedffc1633f9338f9779c64702c688"."outcomeStatus": 0. }Copy the code
Points to note:

When sending a transaction, it is recommended to use estimateGasAndCollateral to return estimated gas usage and storage collateral. However, the actual execution consumption is different from the expected result. To prevent transaction execution failures, it is recommended that you set the values of gaslimit and storage_limit to the estimated value * 4/3 during actual transaction sending.

EpochHeight indicates that the transaction will be executed within the Epoch of EpochHeight-100000, EpochHeight+100000. If the Epoch exceeds the Epoch, the transaction will be discarded. It is recommended to set the current Epoch value.

Deployment of contract

The deployment contract essentially sends a transaction in which data is the contract bytecode and TO is null

Web3 deployment contract

Web3 can be deployed either by sending transactions directly or by contracting instances

// send transaction directly
await web3.eth.sendTransaction({
    from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'.data: contract_bytecode,
})
> {
  "status": true."contractAddress": "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe". }// or use contract instance
var myContract = new web3.eth.Contract(contract_abi, '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe', {
    from: '0x1234567890123456789012345678901234567891'.// default from address. }); myContract.deploy({data: '0x12345... '.arguments: [123.'My String']
})
.send({
    from: '0x1234567890123456789012345678901234567891'.gas: 1500000.gasPrice: '30000000000000'
}, function(error, transactionHash){... }) .on('error'.function(error){... }) .on('transactionHash'.function(transactionHash){... }) .on('receipt'.function(receipt){
   console.log(receipt.contractAddress) // contains the new contract address
})
.on('confirmation'.function(confirmationNumber, receipt){... }) .then(function(newContractInstance){
    console.log(newContractInstance.options.address) // instance with the new contract address
});
Copy the code

Conflux deployment contract

Conflux can currently only be deployed by sending transactions. The contractCreated field of Transaction Receipt is the deployed contract address. Note that contract_bytecode data requires data starting with 0x.

const account = cfx.Account(your_private_key);

await cfx.sendTransaction({ // Not await here, just get promise
      from: account,
      data: contract_bytecode,
    }).executed();
>  {
   "outcomeStatus": 0."contractCreated": "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe". }Copy the code

Call the contract

There are two types of invocation contracts:

  • One is read state, which does not need to send transactions. In read state, both Web3 and Conflux use the Call method.
  • One is to modify the contract state, need to send a transaction, modify the contract state web3 usesend.confluxusesendTransaction

Web3 invokes the contract

// create contract instance
var myContract = new web3.eth.Contract(contract_abi, contract_address);

// calling a method
myContract.methods.myMethod(123).call({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'}, function(error, result){... });// or sending and using a promise
myContract.methods.myMethod(123).send({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'})
.then(function(receipt){
    // receipt can also be a new contract instance, when coming from a "contract.deploy({... }).send()". });Copy the code

Conflux invokes the contract

Conflux invocation contract is similar to Web3, It should be noted that it is recommended to calculate gas (the same as Ethereum gasLimit) and storageLimit according to the gasUsed and storageCollateralized obtained by estimateGasAndCollateral before invoking the contract to send the transaction. Since the gas and storageCollateralized used in the actual transaction execution may be different from the estimated one, in order to prevent failure, Suggest setting gas = estimated gasUsed * four thirds, storageLimit = estimated. StorageCollateralized * four thirds

// create contract instance
var myContract = cfx.Contract({
    abi: contract_abi,
    address: contract_address
});

// call
await contract.myCallMethod(123)
await contract.myCallMethod().call(123)

// send
// set gasLimit and sotrageLimit large 1/3 than estimated value
const estimated = await contract.mySendMethod(123).estimateGasAndCollateral({from: '0x1e0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'});
let gasLimit = JSBI.multiply(estimated.gasUsed, JSBI.BigInt(4))
gasLimit = JSBI.divide(gasLimit, JSBI.BigInt(3))
let storageLimit = JSBI.multiply(estimated.storageCollateralized, JSBI.BigInt(4))
storageLimit = JSBI.divide(storageLimit, JSBI.BigInt(3))

// send transaction
await contract.mySendMethod(123).sendTransaction({from: "addres".gasLimit:estimated.gas*4/3}).executed();
Copy the code

Other modules in eth

In addition to the modules described above, the following modules are included in Web3; There is no corresponding module in conflux for these modules, and similar functions may be supported in the future

The web3 module role
personal Use the account of the node to sign, lock, or unlock the node
shh Used to propagate messages using the Whisper protocol
bzz Swarm is used to interact with swarm, a distributed file storage system
net Obtaining Node Information
subscribe New times generated on the subscription chain includelogs.pendingTransactions.newBlockHeaders.syncingEtc.
ens The domain name service used to operate Ethereum
Iban Ethereum address format andIBAN(International Bank account) BBAN(Basic bank account number)Address format conversion

The article quoted

  1. Js-conflux-sdk User Manual
  2. Web3 V1.2.11 User Manual
  3. Conflux JSONRPC introduction
  4. The difference between Conflux RPC and Ethereum RPC