Inter-Contract Call on Bitcoin

sCrypt
2 min readJul 2, 2021

We introduce a novel approach to call one smart contract from another. It is built upon a technique called OP_PUSH_TX. We illustrate the approach by letting one contract call another to solve a quadratic equation. It has been generalized and extensively used in projects such as Sensible Contract.

Background

Sighash Preimage Format

From the specification of sighash preimage, we can see each input in a transaction has a different sighash preimage. We also see their preimages overlap. Most notably, they share the same outputs (colored). The preimage of input0 and input1 both include output0 and output1 as highlighted below in an example transaction¹. We leverage this observation for two contracts to communicate with each other.

Outputs are shared in 2 inputs’ sighash preimages

Inter-Contract Call

To demonstrate how to call a contract from another, we consider the example of solving a quadratic equation: a * x² + b * x + c = 0.

Inter-contract Call

The contract solving the equation is listed below. It writes a solution x into output0.

Callee contract

The caller contract, having access to output0, can extract the solution x and uses it, without solving for x itself. That is, it calls the above contract Callee.

Caller contract

Advantages

Compared to the straightforward way of calling a function by including it directly into a contract itself, there are several salient advantages of calling it through another separate contract.

  • Efficiency. A stateful contract can have multiple internal functions. Each time it mutates state, not all of them have to be called. However, since they are all part of the contract, they all have to be included and thus bloat transaction size. By placing them into separate contracts, only ones needed for a given call are invoked from the main contract, leading to huge savings especially when there are many functions.
  • Extensibility. A common function can be wrapped into a library contract, which can be called from any other contract, without knowing its internal implementation details. It is decoupled from the calling contract².

Acknowledgements

This technique has been independently invented by Chen Cheng, Jie Jiang, and Lu Gu of Sensible Contract and Ying Chan of Cambridge Cryptographic.

[1] Assume SIGHASH_ALL is used.

[2] A library contract author can potentially monetize his code by dictating that a small payment has to be made to an address he controls, whenever the contract is called.

--

--

sCrypt

sCrypt (https://scrypt.io) is a full-stack smart contract and token development platform for Bitcoin