Account can be used to sign Transaction or Message. Wallet like Fluent can help you manage your accounts (privateKeys) and provide signing functions to you. SDK also provide account manage and signing functions.
Send transaction
// If you want send transaction signed by your own private key, it's need add to wallet before you send transactionconstprivateKey='0x0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; // use your own private keyconstaccount=conflux.wallet.addPrivateKey(privateKey);awaitconflux.cfx.sendTransaction({ from:account.address, to:'cfxtest:xxxx', value:100});
Random create
// create through walletconstaccount=conflux.wallet.addRandom();// create though PrivateKeyAccountconst { PrivateKeyAccount } =require('js-conflux-sdk');constnetworkId=1;constrandomSeed='0xfffff'; // any random bufferconstaccount=PrivateKeyAccount.random(randomSeed, networkId);
Import keystore file
constkeystoreJson= {}; // read from keystore fileconstaccount=conflux.wallet.addKeystore(keystoreJson,'password');
Export to keystore file
constkeystoreJson=account.encrypt('password');
Sign message
The Message class can be used to sign an arbitrary message.
const { Message } =require('js-conflux-sdk');constprivateKey='0x0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; // privateKeyconstmessageHash='0x592fa743889fc7f92ac2a37bb1f5ba1daf2a5c84741ca0e0061d243a2e6707ba';constsignatureHexStr=Message.sign(privateKey, messageHash);constpublicKey=Message.recover(signatureHexStr, messageHash);// Or you can build a Message instanceconstmsg=newMessage('hello world');console.log(msg.hash);msg.sign(privateKey, networkId);console.log(msg.r,msg.s,msg.v);console.log(msg.from);
HD Wallet
If you want to use account from mnemonic, there is a independent package @conflux-dev/hdwallet can fulfill your requirements.
First step is install it by npm
$npminstall@conflux-dev/hdwallet
Then you can use it to get the private key and add it to conflux wallet.
const { HDWallet } =require('@conflux-dev/hdwallet');constmnemonic='faint also eye industry survey unhappy boil public lemon myself cube sense';constrootNode=newHDWallet(mnemonic);constprivateKey0=wallet.getPrivateKeyByIndex(0);constaccount0=conflux.wallet.addPrivateKey(privateKey0);console.log(privateKey0.toString('hex'));// 40d0f137665463584cc57fce2b761572a85d1cbf1601fc93d001c129b2a11c92console.log(account0.address);// cfxtest:aargrnff46pmuy2g1mmrntctkhr5mzamh6nmg361n0constprivateKey1=wallet.getPrivateKey("m/44'/503'/0'/0/1");constaccount1=conflux.wallet.addPrivateKey(privateKey1);