etk icon indicating copy to clipboard operation
etk copied to clipboard

Brainstorm how to insert constants into code while constructing a contract

Open SamWilsn opened this issue 3 years ago • 0 comments

It'd be nice to make it easier to insert constants into code while constructing a contract.

These are pretty much off the top of my head, so bear with me.

I think I'm partial to Solution 1 because it seems the most general / least opinionated, but Solution 2 probably has less footguns.

Solution 1: Exported Labels

We modify %include to expose the labels of the included file.

main.etk

foo:
push32 0x0000000000000000000000000000000000000000000000000000000000000000

bar:
push32 0x0000000000000000000000000000000000000000000000000000000000000000

ctor.etk

# Copy the runtime code.
%push(end-start)
dup1
%push(start)
%push(0)
codecopy

# Set the constants.
caller
%push(start.foo - start + 1)
mstore

caller
%push(start.bar - start + 1)
mstore

# Return the adjusted code.
%push(0)
return
start:
    %include("main.etk")
end:

Solution 2: %const(...)

We add a new built-in instruction macro %const(n). It errors if compiled directly, but expands to a push32 with some sentinel value (0xdeadc0de...) when included.

Then we modify %include to take extra parameters. Each parameter is the name of a label pointing to where the constant should be written.

Then your initcode can reference those labels to write the constants:

main.etk

%const(0)
%const(1)

ctor.etk

# Copy the runtime code.
%push(end-start)
dup1
%push(start)
%push(0)
codecopy

# Set the constants.
caller
%push(foo - start)
mstore

caller
%push(bar - start)
mstore

# Return the adjusted code.
%push(0)
return
start:
    %include("main.etk", foo, bar)
end:

SamWilsn avatar Aug 01 '22 18:08 SamWilsn