Cross contract calls

This section covers the more advanced topic of calling another contract from your code.

Before we start, you may want to check out our Bulletin Board Example repository: all the code you will find in this tutorial is there in its full form. The examples in there are not limited to cross-contract calls and cover almost every aspect of smart contract development, so we encourage you to study it in addition to reading this guide.

The ability of smart contracts to call methods of another contract is arguably one of the most powerful concepts offered by Ink!. For example, a DEX will need to call the transfer_from method of a PSP22 token. However, this is also a feature that requires a lot of care during implementation.

Basics

Ink! offers two ways of calling another contract, each with a different set of trade-offs:

  • importing a reference to another contract and using it almost like any other method:

    • very convenient

    • the compiler is able to check whether a method you want to call exists and if the parameter types match

    • it doesn't allow you to dynamically construct calls

    • it doesn't allow you to send tokens with the call

  • dynamically building a call (the CallBuilder method):

    • a lot of control over the execution

    • it allows for sending tokens along with the call

    • it allows for dynamically choosing a method to call

    • the compiler is not able to assist you in creating a valid call so you need to be extra careful

While the choice of a particular method may be a matter of personal preference, we suggest using the references by default and choosing the CallBuilder only if you really need it.

The examples

In the two subsequent sections, we will use the BulletinBoard contract as an example. The contract allows users to post pieces of text ('bulletins') to the board and highlight selected posts. The highlighted posts are tracked by a separate contract: HighlightedPosts.

The split between the two contracts is pretty arbitrary and not really necessary for this logic to work. However, it serves a higher purpose of demonstrating cross-contract calls in an easy-to-understand example.

Last updated