Write a Smart Contract
To start our contract, we need to import the interface to our HybridAccount
contract. The address of this HybridAccount is passed to the constructor and is stored as an immutable variable. Next we define other contract variables and helper functions.
The "counters" mapping provides a unique numeric counter scoped to each user who calls the contract.
To implement our function to waste gas, we can leverage a for
loop to increase transaction time:
Now we can add the count()
method. We initialize the HybridAccount
with the hcAccount
created prior, and allow for parameters a
and b
, our numbers to add and subtract together. We define x
and y
, do a quick check for b == 0
, and encode our function offchain_addsub2()
. We registered HybridAccount
in the previous section to provide access to the offchain_addsub2()
function on our off-chain function.
The truly unique functionality of Hybrid Compute comes from HA.CallOffChain(userkey, req)
; this call will (assuming no error) return us the two numbers a
and b
after making computations off-chain The userKey
parameter we pass in, generated by encoding msg.sender
, distinguishes requests so that they may be processed concurrently without interefering with each other. As already mentioned in the previous section, our off-chain server maps the request made by the bundler via the hashed representation of our function-signature.
If we encounter an error during the CallOffChain()
call, we either revert or set the counter forward by varying amounts. We can add these different cases in a series of else if
blocks:
Notably, in the first if
block, we decode the returned object ret
into two uint256
values as the off-chain function returns two integers. The variables x
and y
hold the results of the addition and subtraction, respectively.
That finishes our smart contract! Proceed to the next section to learn how to deploy it.
Last updated