Unpacking Multiple Inputs & Packing Multiple Outputs
Learn how to unpack multiple inputs and packing multiple outputs.
Unpack/Pack Functions For Each Operation
As with the MD5 precompile, the generator created the pack/unpack functions for each operation of our Calculator and CalculatorPlus precompiles. However, you might have noticed that the generator also created some struct in each respective contract.go
file. In the case of CalculatorPrecompile, we have:
The generator creates these structs whenever a function defined in the respective Solidity interface has more than one input or more than one output. These multiple values are now stored together via structs.
Unpacking Multiple Inputs
To understand how unpacking works when structs are introduced, let's take a look at the add function in the Calculator precompile, which takes in two inputs, and the nextTwo, which takes in only one input.
As you can see, both unpacker functions take a byte array as an input but the UnpackAddInput
returns a value of the type AddInput
(which contains two big.Int
values) and UnpackNextTwoInput
returns a value of the type big.Int
.
In each case, the respective unpacking function takes in a byte array as an input. However, UnpackAddInput
returns a value of the type AddInput
, which is a struct that contains two big.Int
values. UnpackNextTwo
, meanwhile, returns an value of type big.Int
.
To demonstrate how one could use the output of unpacking functions like UnpackAddInput
, below is the implementation of the add function of the Calculator precompile:
Packing Multiple Outputs
To understand how structs affect the packing of outputs, lets refer to PackNextTwoOutput
for the Calculator precompile:
Notice here that even though we are no longer working with singular types, the generator still is able to pack our struct so that it is of the type bytes.
As a result, we are able to return the packed version of any NextTwoOutput
struct as bytes at the end of nextTwo.