Web3.js vs js-conflux-sdk

js-conflux-sdk latest version 1.x , and 0.x are very different, but because of its still in the testing phase, this article only 0.13.4 and Web3 were compared, to be 1.x the stable version, again for 1.x were compared with Web3.

Web3 and js-conflux-sdk are the top-level modules. They contain other sub-modules and expose methods in some sub-modules at the top level to facilitate developers to use them quickly. We only compare the modules here, and will not give special instructions on these shortcuts.

Module comparison

Web3 and js-conflux-sdk have a corresponding relationship mainly with the following modules:

Modules in EthereumModules in ConfluxFeatures
EthConfluxUsed to manage connected nodes, interact with nodes, send rpc requests, including read status, send transactions, etc.
Contract + abiContractUsed to operate smart contracts, including creating contract instances, mobilizing contract methods, and providing some functions based on abi codec
accountsaccount + Message + TransactionUsed to manage accounts, including operations such as creating and deleting accounts, and using accounts to sign messages or transactions
utilsutilTools, provide some general functions, such as hex format conversion, unit conversion, private key to public key and address, generate random private key, determine data type, sha3, etc., convenient for dapp development and other js packages.

Comparison of each module method

Conflux module Vs Eth module

The following are the methods included in the Conflux module and the corresponding relationship with the Eth module. This module mainly encapsulates the interaction between JSONRPC and nodes, and some JSONRPC has not yet been implemented, and RPC will continue to be improved in the future. . For specific RPC introduction, please refer to Conflux JSONRPC Introduction and [The difference between Conflux RPC and Ethereum RPC]()

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

Conflux moduleEthereum Eth moduleCorresponding to 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 contrast

initialization

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

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

Read status

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 event when the following phases are reached through 061c3ed50d194f:

  • transactionHash transaction has been sent
  • receipt Transaction has been 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 due to the current version does not increase local access node wallet function, so it is necessary to specify when sending direct transaction Account ; sendTransaction returns a Promise.<PendingTransaction> objects, can be directly await get transaction hash ;

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

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

    ...

   }
Points to note:

When sending a transaction, it is recommended to use estimateGasAndCollateral to return the estimated amount of gas used and the amount of storage mortgage; however, due to the difference between the actual execution consumption and the estimated result, in order to prevent transaction execution failure, it is recommended to set gaslimit and storage_limit The value is estimated value * 4/3.

The parameter EpochHeight indicates that this transaction will be [EpochHeight-100000 , EpochHeight+100000] Epoch to 061c3ed50d1e98. When this interval is exceeded, the transaction will be discarded. It is recommended to set the current Epoch value.

Deployment contract

The essence of deploying a contract is to send a data is the contract bytecode and to is null

web3 deployment contract

web3 can be deployed by sending transactions directly, or deployed 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 of the current transaction can only be sent by way of deployment, transaction receipt of contractCreated contract after the address field is deployed. 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",

   ...

   }

Call contract

There are two types of calling contracts:

  • One is to read the status, without sending a transaction. Both web3 and conflux use the call method to read the status.
  • One is to modify the state of the contract, you need to send a transaction, modify the state of the contract web3 uses send , 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 calling contract is similar to web3. The point to note is that before calling the contract to send the transaction, it is recommended to calculate the gas (same as the gasLimit of Ethereum) and storageLimit based on the gasUsed and storageCollateralized obtained by estimateGasAndCollateral; because the gas and storageCollateralized used in the actual transaction are estimated and estimated There may be differences, in order to prevent failure, it is recommended to set gas = estimated.gasUsed * 4 / 3 , storageLimit = estimated.storageCollateralized * 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 introduced above, web3 also contains the following modules; there is no corresponding module in conflux for these modules, 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 spread messages using the whisper protocol
bzzUsed to interact with swarm, swarm is a distributed file storage system
netGet node information
subscribeThe new time generated on the subscription chain, including logs , pendingTransactions , newBlockHeaders . syncing etc.
ensDomain name service used to operate Ethereum
Iban address format to 161c3ed50d2370 IBAN (International Bank Account ) 161c3ed50d2373 BBAN (Basic Bank Account Number) address format

Article citation

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

Conflux中文社区
66 声望19 粉丝

Conflux网址:[链接]