Sign a provided transaction object or a hex formatted string
WARNING
Do not use this in any web / user-facing applications. This will expose the private key.
Usage
// sign a transaction
tronWeb.trx.sign(transaction, privateKey);
// or
// sign a Hex formatted string
tronWeb.trx.sign(str, privateKey)
Input Parameters
Parameter | Description | Data Type |
---|---|---|
transaction / Hex formatted string | The transaction object / hex formatted string | JSON / String |
privateKey | Private Key associated with the transaction (optional, when using tronweb object injected by Tronlink, passing a private key is forbidden, so please ignore this parameter) | String |
Example
sign a transaction
const tradeobj = await tronWeb.transactionBuilder.sendTrx("TNo9e8MWQpGVqdyySxLSTw3gjgFQWE3vfg", 100,"TM2TmqauSEiRf16CyFgzHV2BVxBejY9iyR",1);
const signedtxn = await tronWeb.trx.sign(tradeobj, privateKey);
console.log(signedtxn)
>{ visible: false,
txID:
'cbf76171dcf5f8fe00b4911a1a6cc4d2a4448e3348f44d240ca20af06025d0f2',
raw_data:
{ contract: [ [Object] ],
ref_block_bytes: '6394',
ref_block_hash: '8ad966a9b0b6a5d1',
expiration: 1580983512000,
timestamp: 1580983453441 },
raw_data_hex:
'0a02639422088ad966a9b0b6a5d140c0d7d7cf812e5a65080112610a2d747970652e676f6f676c65617069732e636f6d2f70726f746f636f6c2e5472616e73666572436f6e747261637412300a15417946f66d0fc67924da0ac9936183ab3b07c811261215418cb2ab880d4fa7b33c9645a2276dc9b192902e2d186470818ed4cf812e',
signature:
[ '47b1f77b3e30cfbbfa41d795dd34475865240617dd1c5a7bad526f5fd89e52cd057c80b665cc2431efab53520e2b1b92a0425033baee915df858ca1c588b0a1800' ] }
sign a string message
// sign a string message
var str = "helloworld";
// convert to hex format and remove the beginning "0x"
var hexStrWithout0x = tronWeb.toHex(str).replace(/^0x/, '');
// conert hex string to byte array
var byteArray = tronWeb.utils.code.hexStr2byteArray(hexStrWithout0x)
// keccak256 computing, then remove "0x". (please import ethers library)
var strHash=ethers.utils.keccak256(byteArray).replace(/^0x/, '');
// sign
var signedStr = await tronWeb.trx.sign(strHash);
var tail = signedStr.substring(128, 130);
if(tail == '01')
{
signedStr = signedStr.substring(0,128)+'1c';
}
else if(tail == '00')
{
signedStr = signedStr.substring(0,128)+'1b';
}
console.log(signedStr)
>0x5d47a0245a9ef1b94e484569db4bbe1bd9d7084c7a22dfdce0e91247225ff12521ea940bef310e5283bfea24489bce9e69b869fe4bc7d8c4630b86f3cb350cb11b