tronprotocol / tronweb

Javascript API Library for interacting with the TRON Network
MIT License
431 stars 272 forks source link

Unable to broadcast transaction #498

Closed teootoledo closed 6 months ago

teootoledo commented 6 months ago

Hello, I'm trying to create, sign and broadcast a transaction.

After building the transaction I'm getting the transaction object:

{
        "visible": false,
        "txID": "cc0b19fb85c62b46e469c89dc63971ff141451f40812036178861825a298c811",
        "raw_data": {
            "contract": [
                {
                    "parameter": {
                        "value": {
                            "to_address": "41212c2ed341bc91735684cae530cfb3a89b39e970",
                            "owner_address": "41159468498169886cfca235dead5a775d21def67d",
                            "amount": 100000
                        },
                        "type_url": "type.googleapis.com/protocol.TransferContract"
                    },
                    "type": "TransferContract"
                }
            ],
            "ref_block_bytes": "6d19",
            "ref_block_hash": "90a3364cf24d6c72",
            "expiration": 1711555431000,
            "timestamp": 1711555371000
        },
        "raw_data_hex": "0a026d19220890a3364cf24d6c7240d8949d85e8315a67080112630a2d747970652e676f6f676c65617069732e636f6d2f70726f746f636f6c2e5472616e73666572436f6e747261637412320a1541159468498169886cfca235dead5a775d21def67d121541212c2ed341bc91735684cae530cfb3a89b39e97018a08d0670f8bf9985e831"
    }

Following the docs and helping me with the types of the most recent beta version, I need to sign this transaction object.

await tronWeb.trx.sign(transaction, privateKey)

This function fails with:

error TypeError: Cannot read properties of undefined (reading 'contract')

So I tried another way, converting the transaction object to hex.

await tronWeb.trx.sign(this.objectToHex(transaction), privateKey)

// objectToHex:
private objectToHex(obj: any) {
    const str = JSON.stringify(obj); // Convert object to string
    let hex = '';
    for(let i=0;i<str.length;i++) {
        hex += ''+str.charCodeAt(i).toString(16);
    }
    return hex;
  }

With that modification it returns an string like this: "0x62f5a9853dd7f7bdeab7470078d77ed61d431b3e5cf777ebe84ed36117e006042cf722a19a98aa6014d3bee2361a28789355fd0104179893443028a2ce6ec2ea1b"

And now I've tried with sendRawTransaction

tronSdk.trx.sendRawTransaction(signedTransaction);

signedTransaction being the unsignedTransaction object with signature: 0x62f5a9853dd7f7bdeab7470078d77ed61d431b3e5cf777ebe84ed36117e006042cf722a19a98aa6014d3bee2361a28789355fd0104179893443028a2ce6ec2ea1b

It returns an error:

Error: Transaction is not signed
              at Trx.sendRawTransaction

Its is a simple sendTrx transaction over Shasta.