Conflux JS SDK and Ethereum Web3 JS difference

Web3.js vs js-conflux-sdk

The latest version of JS conflux SDK is 1 x. And 0 X is very different, but because it is still in the testing stage, this article only focuses on 0.13 4 compare with Web3 and wait for 1 After the X version is stable, it will be targeted at 1 X was compared with Web3.

Web3 and JS conflux SDK are top-level modules. They contain other sub modules and methods exposed in some sub modules at the top level, which are convenient for developers to use quickly. We only compare each module here, and do not give special instructions on these shortcut methods.

Module comparison

Web3 and JS conflux SDK correspond to the following modules:

Modules in EthereumModules in Confluxfunction
EthConfluxIt is used to manage connected nodes, interact with nodes and send rpc requests, including reading status, sending transactions, etc
Contract + abiContractIt is used to operate smart contracts, including creating contract instances, transferring contract methods, and providing some functions of encoding and decoding according to abi
accountsaccount + Message + TransactionIt is used to manage accounts, including creating and deleting accounts, and signing messages or transactions with accounts
utilsutilThe tool class provides some general functions, such as hex format conversion, unit conversion, private key to public key and address, generating random private key, judging data type, sha3, etc., which are convenient for dapp development and other js packages

Comparison of methods of each module

Conflux module Vs Eth module

The following are the methods contained in the Conflux module and the corresponding relationship with the Eth module. This module mainly encapsulates the interaction between JSONRPC and nodes. Some JSONRPC have not been implemented yet and will be improved in the future.. For details, see Introduction to Conflux JSONRPC And [difference between Conflux RPC and Ethereum RPC] ()

The Epoch Number here refers to the Epoch used to divide a group of Conflux blocks into one Epoch, and the Conflux blockchain is organized in the order of Epoch.

Conflux moduleEthereum Eth moduleCorresponding RPC
setProvidersetProvider-
getStatusgetChainIdcfx_getStatus
getGasPricegetGasPricecfx_gasPrice
getEpochNumbergetBlockNumbercfx_epochNumber
getBalancegetBalancecfx_getBalance
getNextNoncegetBlockTransactionCountcfx_getNextNonce
getBlockByEpochNumbergetBlockcfx_getBlockByEpochNumber
getBlocksByEpochNumber-cfx_getBlocksByEpoch
getBlockByHashgetBlockcfx_getBlockByHash
getBlockByHashWithPivotAssumption-cfx_getBlockByHashWithPivotAssumption
getTransactionByHashgetTransactioncfx_getTransactionByHash
getTransactionReceiptgetTransactionReceiptcfx_getTransactionReceipt
sendTransactionsendTransactioncfx_sendTransaction
sendRawTransactionsendSignedTransactioncfx_sendRawTransaction
getCodegetCodecfx_getCode
callcallcfx_call
estimateGasAndCollateralestimateGascfx_estimateGasAndCollateral
getLogsgetPastLogs(contract module)cfx_getLogs
getBestBlockHash-cfx_getBestBlockHash
getConfirmationRiskByHash-cfx_getConfirmationRiskByHash
close--

Contract module comparison

Conflux Contract moduleEth Contract + abi module
contract.mymethodmethods.myMethod.call
contract.mymethod.callmethods.myMethod.call
contract.mymethod.decodeDatadecodeParameters
contract.mymethod.decodeOutputs-
contract.mymethod.encodeDatamethods.myMethod.encodeABI
contract.mymethod.sendmethods.myMethod.send
contract.mymethod.estimateGasAndCollateralmethods.myMethod.estimateGas
contract.myEvent.getLogsgetPastLogs
contract.myEvent.encodeTopics-
contract.myEvent.decodeLogdecodeLog(ABI module)
contract.abi.decodeDatadecodeParameters
contract.abi.decodeLogdecodeLog(ABI module)

accounts module comparison

Conflux Account moduleEthereum Accounts module
randomcreate
decryptdecrypt
encryptencrypt
signTransactionsignTransaction
signMessagesign
Conflux Message moduleEthereum Accounts module
signsign
recoverrecover
hash (getter)-
from (getter)-
signsign
Conflux Transaction moduleEthereum Accounts module
hash (getter)-
from (getter)-
signsignTransaction
recoverrecover
encode-
serialize-

utils module comparison

Conflux util moduleEthereum 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)-
sha3sha3
checksumAddresstoChecksumAddress
randomBuffer-
randomPrivateKeyrandomHex
privateKeyToPublicKeyprivateKeyToAccount(Accounts module)
publicKeyToAddressprivateKeyToAccount(Accounts module)
privateKeyToAddressprivateKeyToAccount(Accounts module)
ecdsaSignsign(Accounts module)
ecdsaRecoverrecover(Accounts module)
encryptencrypt(Accounts module)
decryptdecrypt(Accounts module)
unit.fromCFXToGDrip-
unit.fromCFXToDriptoWei
unit.fromGDripToCFX-
unit.fromGDripToDrip-
unit.fromDripToCFXfromWei
unit.fromDripToGDrip-

Use comparison

initialization

Initialize 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'));

 

Initialize the Conflux instance

Conflux instantiation is similar to web3, but the current version does not support websocket provider

const { Conflux } = require('js-conflux-sdk');

const cfx = new Conflux({url:'http://test.confluxrpc.org'});

Read state

Ethereum read status

web3.eth.getBalance("0x107d73d8a49eeb85d32cf465507dd71d507100c1").then(console.log);

> "1000000000000"

Conflux read status

await cfx.getBalance("0x107d73d8a49eeb85d32cf465507dd71d507100c1");

// or

cfx.getBalance("0x107d73d8a49eeb85d32cf465507dd71d507100c1").then(console.log)

> "1000000000000"

Send transaction

web3 send transaction

After web3 sends the transaction, it will be notified in the following stages through event:

  • transactionHash transaction sent
  • receipt transaction executed
  • confirmation transaction confirmed
  • error transaction execution failed
// compiled solidity source code using <https://remix.ethereum.org>

var code = "603d80600c6000396000f3007c01000000000000000000000000000000000000000000000000000000006000350463c6888fa18114602d57005b6007600435028060005260206000f3";

 

// 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.

Conflux send transaction

JS conflux SDK does not add the function of accessing the local wallet of the node in the current version, so the account needs to be specified directly when sending transactions; Sendtransaction returns a promise< Pendingtransaction > object, you can directly obtain transaction hash from await;

You can also return transaction or transaction receipt in different states through this object method. The methods are listed as follows:

  • get returns transaction after sending,
  • mined returns transaction after packaging,
  • executed returns transaction receipt after execution,
  • confirmed returns transaction receipt when transaction risk < threshold
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,

    ...

   }
Points needing attention:

When sending a transaction, it is recommended to use estimateGasAndCollateral to return the estimated gas usage and storage collateral; However, due to the difference between the actual execution consumption and the estimated results, in order to prevent transaction execution failure, it is recommended to set gaslimit and storage when actually sending transactions_ The value of limit is the estimated value * 4 / 3.

The parameter EpochHeight indicates that the transaction will be executed within the range of [EpochHeight-100000, EpochHeight + 100000]. When it exceeds this range, the transaction will be discarded. It is recommended to set the current Epoch value.

Deployment contract

The essence of a deployment contract is to send a transaction with data as contract bytecode and to as null

web3 deployment contract

web3 can be deployed by directly sending transactions or by contract 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

});

conflux deployment contract

conflux can only be deployed by sending transactions. The contractCreated field of transaction receipt is the deployed contract address. Pay attention to contract_bytecode data requires data beginning 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",

   ...

   }

Call contract

There are two types of call contracts:

  • One is the read status, which does not need to send transactions. Both web3 and conflux use the call method.
  • One is to modify the contract status and send the transaction. web3 uses send to modify the contract status, and conflux uses sendTransaction

web3 call 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()"

    ...

});

conflux call contract

The conflux call contract is similar to web3, It should be noted that before calling the contract to send the transaction, it is recommended to calculate gas according to gasUsed and storageCollateralized obtained from estimategasandcollaterale (the same as Ethereum's gasLimit) and storageLimit; because the gas and storagecoordinated used in actual transaction execution may be different from the estimate, in order to prevent failure, it is recommended to set gas = estimated. gasUsed * 4 / 3, storageLimit = estimated. Storagecoordinated * 4 / 3

// 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();

Other modules in eth

In addition to the modules described above, web3 also includes the following modules; There are no corresponding modules in conflux for the time being, and similar functions may be supported in the future

web3 moduleeffect
personalUse the account of the requested node to sign, lock, unlock, etc
shhUsed to propagate messages using the whistler protocol
bzzUsed to interact with swarm, which is a distributed file storage system
netGet node information
subscribeThe new time generated on the subscription chain, including logs, pendingtransactions and newblockheaders Syncing et al
ensDomain name service for operating Ethereum
IbanConversion between Ethereum address format and Iban (international bank account number) bban (basic bank account number) address format

Article citation

  1. JS conflux SDK user manual
  2. Web3 v1.2.11 user manual
  3. Introduction to Conflux JSONRPC
  4. The difference between Conflux RPC and Ethereum RPC

Keywords: Blockchain

Added by Cazrin on Thu, 23 Dec 2021 23:53:54 +0200