简体   繁体   中英

Web3.js Ethereum - Is it possible to call 2 functions in one transaction?

Perhaps it's a silly question. But I'd like to know if it's possible to put 2 (or more) smart contract methods calls in one single transaction in Ethereum.

The part of my code for one function call in a single transaction:

var data = self.MyContract.MyFunc1.getData(
        param1);
const options = {
    gasPrice: gasPrice,
    gasLimit: gasLimit,
    nonce,
    data,
    to: addressContract,
};
const tx = new Tx(options);
tx.sign(new Buffer(private_key, 'hex'));
const rawTx = `0x${tx.serialize().toString('hex')}`;
self.web3.eth.sendRawTransaction(rawTx, (err, result) => {
    if (err)
        reject(err);
    resolve(result);
});

It works perfectly. I tried to add another function call to data variable with a such way:

var data = self.MyContract.MyFunc1.getData(
        param1);
var data2 = self.MyContract.MyFunc2.getData(
        param2);
data += data2;
const options = {
    gasPrice: gasPrice,
    gasLimit: gasLimit,
    nonce,
    data,
    to: addressContract,
};
const tx = new Tx(options);
tx.sign(new Buffer(private_key, 'hex'));
const rawTx = `0x${tx.serialize().toString('hex')}`;
self.web3.eth.sendRawTransaction(rawTx, (err, result) => {
    if (err)
        reject(err);
    resolve(result);
});

This time transaction fails with a reason (according to etherscan.io info): Reverted.

So what am I doing wrong? Or perhaps there's only one contract function call possible in one transaction?

No, you cannot call multiple non-constant functions from an Ethereum client in a single transaction. However, you can initiate a transaction to contract A and then call a function in contract B from the first contract within the same transaction.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM