2

I recently learnt that it is possible to deploy more than one smart contract into the network. This brings the question, can they and how do these smart contracts interact? All the online courses I've covered so far handle deploying one smart contract only.

2 Answers 2

4

Any smart contract can interact with any other smart contract (unless it's somehow restricted in code). All you need is:

  1. The address of the other contract

  2. Knowledge of the other contract's functionality you want to access. Typically this is provided as an interface.

Here's a minimal example on how to interact with another contract which is already deployed in the blockchain:

pragma solidity ^0.7.0;

interface IOtherContr {
    function doStuff(uint256 some) external;
}

contract Test {
    function doSomething(address otherContr) public {
        IOtherContr ref = IOtherContr(otherContr);
        ref.doStuff(65);
    }
}

If, however, you wish to create a new instance of a contract (instead of referencing an existing one) you can use the new keyword, but then you need the full implementation of the other contract and it will create a new contract in a new address.

4
  • what if the smart contract I want to interact with does not have an interface and I want to call methods on the existing smart contract?
    – Coreggon
    Commented Jun 15, 2021 at 19:44
  • 2
    Then you can just create the interface. It doesn't really matter who writes it. Commented Jun 16, 2021 at 4:35
  • Is it possible to establish a condition, that the 2nd smart contract only starts to execute when the 1st smart contract that called it has completed.
    – daparic
    Commented May 20, 2022 at 13:49
  • Such logic has to be included in the contract code and in the logic of how and when other contracts are called. Since a transaction is always just one call to one contract (with possibly internal calls to other contracts), you can't have it call multiple contracts after each other without explicit code to do so. Commented May 20, 2022 at 15:38
1

Yes, two smart contracts can interact with each other.

For example: you can use the events Solidity feature to have them communicate.

3
  • 2
    Events are not directly accessible on-chain (e.g. in smart contracts). They are purely meant to monitor contract interactions off-chain (e.g. by indexers).
    – Richard
    Commented Dec 20, 2021 at 20:04
  • 1
    By using call, delegatecall, and send you can interact with other contracts. Unfortunately, events are inaccessible from within the blockchain. Commented Dec 31, 2021 at 22:43
  • Will the 1st smart contract gets blocked and wait until the completion of the 2nd smart contract?
    – daparic
    Commented May 20, 2022 at 13:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.