Skip to content

Multiple Contract Calls

You can execute multiple contract calls in a single transaction, either to the same contract or to different contracts. This can improve efficiency and reduce the overall transaction costs.

Same Contract Multi Calls

Use the multiCall method to call multiple functions on the same contract in a single transaction:

ts
const { waitForResult } = await counterContract
  .multiCall([
    counterContract.functions.get_count(),
    counterContract.functions.increment_counter(2),
    counterContract.functions.increment_counter(4),
  ])
  .call();

const { value: results } = await waitForResult();

expect(results[0].toNumber()).toBe(0);
expect(results[1].toNumber()).toBe(2);
expect(results[2].toNumber()).toBe(6);
See code in context

Different Contracts Multi Calls

The multiCall method also allows you to execute multiple contract calls to distinct contracts within a single transaction:

ts
const { waitForResult } = await echoContract
  .multiCall([
    echoContract.functions.echo_u8(17),
    counterContract.functions.get_count(),
    counterContract.functions.increment_counter(5),
  ])
  .call();

const { value: results } = await waitForResult();

expect(results[0]).toEqual(17);
expect(results[1].toNumber()).toBe(0);
expect(results[2].toNumber()).toBe(5);
See code in context

You can also chain supported contract call methods, like callParams, for each contract call:

ts
const { waitForResult } = await contextContract
  .multiCall([
    echoContract.functions.echo_u8(10),
    contextContract.functions.return_context_amount().callParams({
      forward: [100, provider.getBaseAssetId()],
    }),
  ])
  .call();

const { value: results } = await waitForResult();

const echoedValue = results[0];
const fowardedValue = new BN(results[1]).toNumber();

expect(echoedValue).toEqual(10);
expect(fowardedValue).toEqual(100);
See code in context

When using multiCall, the contract calls are queued and executed only after invoking one of the following methods: .get, .simulate, or .call.

Using multiCall for Read-Only Contract Calls

When you need to read data from multiple contracts, the multiCall method can perform multiple read-only calls in a single transaction. This minimizes the number of requests sent to the network and consolidates data retrieval, making your dApp interactions more efficient.

ts
const { value: results } = await counterContract
  .multiCall([
    counterContract.functions.get_count(),
    echoValuesContract.functions.echo_u8(10),
    echoValuesContract.functions.echo_str('Fuel'),
  ])
  .get();

expect(results[0].toNumber()).toBe(bn(0).toNumber());
expect(results[1]).toBe(10);
expect(results[2]).toBe('Fuel');
See code in context