├── .github
└── pull_request_template.md
├── README.md
├── examples
├── erc20
│ ├── .gitignore
│ ├── Makefile
│ ├── equiv.sol
│ ├── erc20.sol
│ ├── impl.c
│ └── interface_compile.json
└── siphash
│ ├── .gitignore
│ ├── Makefile
│ ├── main.c
│ └── siphash.c
├── include
├── bebi.h
├── hostio.h
├── stdlib.h
├── storage.h
├── string.h
├── stylus_debug.h
├── stylus_entry.h
├── stylus_types.h
└── stylus_utils.h
├── licenses
├── Apache-2.0
├── COPYRIGHT.md
├── DCO.txt
└── MIT
└── src
├── bebi.c
├── simplelib.c
├── stdlib.c
├── storage.c
└── utils.c
/.github/pull_request_template.md:
--------------------------------------------------------------------------------
1 | ## Description
2 |
3 | Please provide a summary of the changes and any backward incompatibilities.
4 |
5 | ## Checklist
6 |
7 | - [ ] I have documented these changes where necessary.
8 | - [ ] I have read the [DCO][DCO] and ensured that these changes comply.
9 | - [ ] I assign this work under its [open source licensing][terms].
10 |
11 | [DCO]: licenses/DCO.txt
12 | [terms]: licenses/COPYRIGHT.md
13 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
The Stylus SDK
8 |
9 |
10 | C/C++ contracts on Arbitrum »
11 |
12 |
13 |
14 |
15 | ## General
16 |
17 | The C/C++ SDK allows you to take full control of the underlying web-assembly executed in your smart contract.
18 |
19 | ## Required Tools
20 |
21 | The Stylus VM executes WebAssembly, so you'll need a C/C++ compiler with support for wasm32 targets. Support for this varies, so some users may have to build `clang` or `gcc` from source. Your package manager may also include a compatible version.
22 |
23 | We suggest using these tools:
24 |
25 | * [`llvm`](https://releases.llvm.org/) must include clang and have WebAssembly support, including the common `bulk-memory` extension. Make sure that clang accepts `--target=wasm32` and that llvm ships with the `wasm-ld` binary. Availability varies between distributions, but package managers commonly include these preconfigured in their "llvm" and/or "clang" recipies.
26 | * [`cargo-stylus`](https://github.com/OffchainLabs/cargo-stylus) is used to generate c-code, and to check and deploy contracts. Rust support is not required.
27 | * `make`, `git`
28 |
29 | ## C/C++ SDK library
30 |
31 | This SDK is neither audited, nor stable. Future versions may ship with backward incompatible changes.
32 |
33 | | Header | Info |
34 | |:-------------------------------------------|:---------------------------------------------------------------------------------------------------------------|
35 | | [`stylus_types.h`](include/stylus_types.h) | Types used by the wasm entrypoint to define return values from stylus |
36 | | [`stylus_entry.h`](include/stylus_entry.h) | Includes used to generate stylus entrypoints |
37 | | [`hostio.h`](include/hostio.h) | Functions supplied by the stylus environment to change and access the VM state (see Host I/O) |
38 | | [`stylus_debug.h`](include/stylus_debug.h) | Host I/Os only available in debug mode. The best way to get a debug-enabled node is to [run one locally][node] |
39 | | [`bebi.h`](include/bebi.h) | Tools for handling Big-Endian Big Integers in wasm-32 |
40 | | [`storage.h`](include/storage.h) | Contract storage utilities |
41 | | [`stylus_utils.h`](include/stylus_utils.h) | Higher-level utils that might help smart contract developers |
42 | | [`string.h`](include/string.h) | Minimal (and incomplete) implementation of the standard `string.h` |
43 | | [`stdlib.h`](include/stdlib.h) | Minimal (and incomplete) implementation of the standard `stdlib.h` |
44 |
45 | [node]: https://docs.arbitrum.io/stylus/how-tos/local-stylus-dev-node
46 |
47 | ## Examples
48 |
49 | The library includes two examples, each with a makefile that builds a wasm from source using the command `make`. Both are annotated, and users are encouraged to read through the code.
50 |
51 | ### siphash
52 |
53 | Demonstrates a custom precompile, compute-only smart contract that processes input bytes and returns their hash. This minimal example uses very little of the SDK library.
54 |
55 | ### erc20
56 |
57 | Provides an erc20-like smart contract implementation. This example uses the library as well as the c-code generation capabilities of cargo-stylus.
58 |
59 | ## Host I/Os
60 |
61 | [`include/hostios.h`](hostios.h). There you can call VM hooks directly, which allows you to do everything from looking up the current block number to calling other contracts.
62 |
63 | For example, the VM provides an efficient implementation of [keccak256][keccak256] via
64 | ```c
65 | void native_keccak256(const uint8_t * bytes, size_t len, uint8_t * output)
66 | ```
67 |
68 | Unlike with the Rust SDK, however, you will have to work with raw pointers and deserialize arguments manually. This makes [`stylus.h`](stylus.h) an ideal environment for bytes-in bytes-out programming, but not general smart contract development.
69 |
70 | For a comprehensive list of hostios, please see [The Host I/O Reference][hostios].
71 |
72 | [hostios]: TODO
73 | [keccak256]: https://en.wikipedia.org/wiki/SHA-3
74 | [siphash]: examples/siphash/main.c
75 |
76 | ## Notes about using C to build wasm32
77 |
78 | ### Clang flags
79 |
80 | The table below includes `clang` flags commonly used to build Stylus contracts. The [siphash][siphash] example uses most of the following, and is a great starting point for programs that opt out of the standard library.
81 |
82 | | Flag | Info | Optional |
83 | |:------------------------|---------------------------------------------------------------|:---------|
84 | | --target=wasm32 | compile to wasm | |
85 | | --no-standard-libraries | opt out of the stdandard library | ✅ |
86 | | -mbulk-memory | enable bulk-memory operations (accelerates memset and memcpy) | ✅ |
87 | | -O2 / -O3 / -Oz | optimize for speed or size | ✅ |
88 |
89 | ### Wasm-ld flags
90 |
91 | Flags that should be used when linking a wasm file with wasm-ld.
92 |
93 | | Flag | Info | Optional |
94 | |:------------------------|---------------------------------------------------------------|:---------|
95 | | --no-entry | let Stylus decide the entrypoint | |
96 | | --stack-first | puts the shadow-stack at the beginning of the memory | ✅ |
97 | | -z stack-size=... | sets size for the shadow-stack | ✅ |
98 |
99 |
100 | ### Performance
101 | C binaries are both small and very efficient. The [`siphash`][siphash] example is only **609 bytes** onchain and costs **22 gas** to execute a 32-byte input. By contrast, 22 gas only buys 7 ADD instructions in Solidity.
102 |
103 | How did we achieve this efficiency? All we had to do was Google for an example siphash program and add a simple entrypoint. In the Stylus model, you can deploy highly-optimized and thouroughly-audited, industry-standard reference implementations as-is. With the Stylus SDK, cryptography, algorithms, and other high-compute applications are both straightforward and economically viable.
104 |
105 | ## Roadmap
106 |
107 | Stylus is currently testnet-only and not recommended for production use. This will change as we complete an audit and add additional features.
108 |
109 | Arbitrum [Orbit L3s][Orbit] may opt into Stylus at any time. Arbitrum One and Arbitrum Nova will upgrade to Stylus should the DAO vote for it.
110 |
111 | If you'd like to be a part of this journey, join us in the `#stylus` channel on [Discord][discord]!
112 |
113 | [Orbit]: https://docs.arbitrum.io/launch-orbit-chain/orbit-gentle-introduction
114 |
115 | ## Don't know C?
116 |
117 | The Stylus VM supports more than just C. In fact, any programming language that compiles down to WebAssembly could in principle be deployed to Stylus-enabled chains. The table below includes the official ports of the SDK, with more coming soon.
118 |
119 | | Repo | Use cases | License |
120 | |:-----------------|:----------------------------|:------------------|
121 | | [Rust SDK][Rust] | Everything! | Apache 2.0 or MIT |
122 | | [C/C++ SDK][C] | Cryptography and algorithms | Apache 2.0 or MIT |
123 | | [Bf SDK][Bf] | Educational | Apache 2.0 or MIT |
124 |
125 | Want to write your own? Join us in the `#stylus` channel on [discord][discord]!
126 |
127 | [Rust]: https://github.com/OffchainLabs/stylus-sdk-rs
128 | [C]: https://github.com/OffchainLabs/stylus-sdk-c
129 | [Bf]: https://github.com/OffchainLabs/stylus-sdk-bf
130 |
131 | [discord]: https://discord.com/invite/5KE54JwyTs
132 |
133 | ## License
134 |
135 | © 2022-2023 Offchain Labs, Inc.
136 |
137 | This project is licensed under either of
138 |
139 | - [Apache License, Version 2.0](https://www.apache.org/licenses/LICENSE-2.0) ([licenses/Apache-2.0](licenses/Apache-2.0))
140 | - [MIT license](https://opensource.org/licenses/MIT) ([licenses/MIT](licenses/MIT))
141 |
142 | at your option.
143 |
144 | The [SPDX](https://spdx.dev) license identifier for this project is `MIT OR Apache-2.0`.
145 |
--------------------------------------------------------------------------------
/examples/erc20/.gitignore:
--------------------------------------------------------------------------------
1 | *.o
2 | *.wasm
3 |
4 | interface-gen/
5 | build/
6 |
7 |
--------------------------------------------------------------------------------
/examples/erc20/Makefile:
--------------------------------------------------------------------------------
1 |
2 | STACK_SIZE=8192
3 | CC=clang
4 | LD=wasm-ld
5 | CFLAGS=-I../../include/ -Iinterface-gen/ --target=wasm32 -Os --no-standard-libraries -mbulk-memory -Wall -g
6 | LDFLAGS=-O2 --no-entry --stack-first -z stack-size=$(STACK_SIZE) -Bstatic
7 |
8 | OBJECTS=build/impl.o build/lib/bebi.o build/lib/storage.o build/lib/simplelib.o build/lib/utils.o build/gen/ERC20_main.o
9 |
10 | all: ./erc20.wasm
11 |
12 | # STEP1 : compile solidity
13 | # The output is used by cargo and can also be used by any web3 for ABI
14 | # For interface_compile.json see: https://docs.soliditylang.org/en/v0.8.20/using-the-compiler.html#compiler-input-and-output-json-description
15 | build/interface.json: interface_compile.json erc20.sol
16 | mkdir -p build
17 | cat $< | solc --standard-json --pretty-json > $@
18 |
19 | # STEP 2 : generate headers and main function from the compiled solidity
20 | cargo-generate: build/interface.json
21 | mkdir -p build
22 | cargo-stylus c-gen $< interface-gen
23 |
24 | interface-gen/erc20/ERC20_main.c: cargo-generate
25 |
26 | # Step 3.1: build the generated main file (ERC20_main.o)
27 | build/gen/%.o: interface-gen/erc20/%.c
28 | mkdir -p build/gen/
29 | $(CC) $(CFLAGS) -c $< -o $@
30 |
31 | # Step 3.2: build the reuqired library files
32 | build/lib/%.o: ../../src/%.c
33 | mkdir -p build/lib
34 | $(CC) $(CFLAGS) -c $< -o $@
35 |
36 | # STEP 3.3: implement / build the functions creating the logic of the smart contract
37 | build/%.o: %.c cargo-generate
38 | mkdir -p build
39 | $(CC) $(CFLAGS) -c $< -o $@
40 |
41 | # Step 4: link
42 | build/erc20.wasm: $(OBJECTS)
43 | $(LD) $(LDFLAGS) $(OBJECTS) -o $@
44 |
45 | # Step 5: strip symbols (they won't help on-chain)
46 | erc20.wasm: build/erc20.wasm
47 | wasm-strip -o $@ $<
48 |
49 | # Step 6: check the wasm using cargo-stylus
50 | # cargo stylus check --wasm-file-path ./erc20.wasm --endpoint $ENDPOINT --private-key=$PRIVATE_KEY
51 |
52 | # Step 7: deploy the wasm using cargo-stylus
53 | # cargo stylus check --wasm-file-path ./erc20.wasm --endpoint $ENDPOINT --private-key=$PRIVATE_KEY
54 |
55 | clean:
56 | rm -rf interface-gen build erc20.wasm
57 |
58 | .phony: all cargo-generate clean
59 |
--------------------------------------------------------------------------------
/examples/erc20/equiv.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: MIT
2 |
3 | pragma solidity ^0.8.20;
4 |
5 | /**
6 | * This contract exists to implement similar logic to the c-example ERC20.
7 | * It exists for documentation and testing of the c-example.
8 | *
9 | * This contract is:
10 | * * NOT Audited / well tested
11 | * * NOT a good solidity example.
12 | * * NOT a good or a safe way to to manage minters for an ERC20.
13 | *
14 | * The implementation here is specifically meant to be easily comparable to
15 | * the C implementation.
16 | * The C implementation itself is meant only as an example code.
17 | *
18 | */
19 |
20 | contract Equivalent {
21 | // total supply of the token
22 | uint256 private _totalSupply;
23 |
24 | // how many minters exist currently
25 | uint64 public minters_current;
26 | // has the contract been initialized
27 | bool private initialized;
28 |
29 | // array of minters
30 | // The array could hold blank values when removing a minter
31 | // slot 0 is always empty
32 | address[] public minters;
33 |
34 | // balances of each account
35 | mapping(address account => uint256) private _balances;
36 |
37 | // a map from minters to their index in minters array
38 | // also used to check if an address is a minter
39 | mapping(address minter => uint64) public minter_idx;
40 |
41 |
42 | // Standard pure functions of ERC20
43 | function name() public pure returns (string memory) {
44 | return "C Token (sample code)";
45 | }
46 |
47 | // Standard pure functions of ERC20
48 | function symbol() public pure returns (string memory) {
49 | return "CTOK";
50 | }
51 |
52 | // Standard pure functions of ERC20
53 | function decimals() public pure returns (uint8) {
54 | return 18;
55 | }
56 |
57 | // solidity accessor to the private field
58 | function totalSupply() public view returns (uint256) {
59 | return _totalSupply;
60 | }
61 |
62 | // solidity accessor to the private field
63 | function balanceOf(address account) public view returns (uint256) {
64 | return _balances[account];
65 | }
66 |
67 | // standard ERC20: move "value" tokens from message sender to "to"
68 | function transfer(address to, uint256 value) public returns (bool) {
69 | uint256 current_source = _balances[msg.sender];
70 | // check if sender has enough balance
71 | if (current_source < value) {
72 | return false;
73 | }
74 | uint256 current_dest = _balances[to];
75 | require(current_dest + value > current_dest, "overflow");
76 | _balances[msg.sender] = current_source - value;
77 | _balances[to] = current_dest + value;
78 | return true;
79 | }
80 |
81 | /**
82 | * Minters
83 | *
84 | * A call to init initializes the contract with one minter
85 | * Each minter may mint tokens, add or remove other minters
86 | *
87 | * Minters are kept in two databases: an array of all minters
88 | * (may contain blanks), and a map from minter to it's index
89 | * in the array. Index 0 is always blank so index 0 in the map
90 | * is used to signify an address that's not a minter.
91 | */
92 |
93 | // push_minter adds to the end of minters_array, and updates minter_idx map
94 | function push_minter(address minter) internal {
95 | uint64 index = uint64(minters.length);
96 | minters.push(minter);
97 | // address 0 is never marked "minter"
98 | if (uint160(minter) != 0) {
99 | minter_idx[minter] = index;
100 | }
101 | }
102 |
103 | // set the first minter
104 | function init(address first_minter) public {
105 | // revert with reason string
106 | require(!initialized, "already initialized");
107 | // first blank entry reserves index 0 for non-minters
108 | push_minter(address(uint160(0)));
109 | // push the first minter
110 | push_minter(first_minter);
111 | // set minters_current and initialized
112 | initialized = true;
113 | minters_current = 1;
114 | }
115 |
116 | // helper function: check if message was sent from a minter
117 | function from_minter() internal view returns (bool) {
118 | return minter_idx[msg.sender] != 0;
119 | }
120 |
121 | // add a new minter
122 | function add_minter(address new_minter) public {
123 | require(from_minter(), "must be aminter");
124 | minters_current+=1;
125 | push_minter(new_minter);
126 | }
127 |
128 | // remove minter
129 | // array entry is replaced with blank
130 | // minter_idx map entry is removed
131 | function remove_minter(address old_minter) public {
132 | require(from_minter(), "must be aminter");
133 | uint64 old_idx = minter_idx[old_minter];
134 | require(old_idx!=0, "remove: not minter");
135 | minter_idx[old_minter];
136 | minters_current-=1;
137 | minters[old_idx] = address(uint160(0));
138 | }
139 |
140 | // mint new tokens for an account
141 | function mint(address account, uint256 value) public {
142 | require(from_minter(), "must be aminter");
143 | require(_totalSupply + value >= _totalSupply);
144 | _totalSupply += value;
145 | _balances[account] += value;
146 | }
147 |
148 | // TODO: complete the ERC20 interface
149 | // function allowance(address owner, address spender) public view virtual returns (uint256);
150 | // function approve(address spender, uint256 value) public virtual returns (bool);
151 | // function transferFrom(address from, address to, uint256 value) public virtual returns (bool);
152 | // function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool);
153 | // function decreaseAllowance(address spender, uint256 requestedDecrease) public virtual returns (bool);
154 | }
--------------------------------------------------------------------------------
/examples/erc20/erc20.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: MIT
2 |
3 | /**
4 | * Solidity interface - declaration
5 | *
6 | * Interface is inspired by ERC20, with minters that can be added/removed by
7 | * other minters
8 | *
9 | * Documentation in this file does not explain the ABI or contract, but how
10 | * c-code is generated from the solidity.
11 | * This file will be compiled by solidity compiler and used to generate:
12 | * * ABI that can be used by any web3 client
13 | * * C code framework (headers and main function) for the smart contract
14 | *
15 | * Also see: Makefile, interface_compile.json
16 | *
17 | * This file is based on the MIT-license implementation of ERC20 by OpenZepplin
18 | * See original implementation: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol
19 | * Original License: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/LICENSE
20 | */
21 |
22 | pragma solidity ^0.8.20;
23 |
24 | /**
25 | * Name of the contract will set name of files generated. Name of the solidity file
26 | * in interface_compile.json sets the name of the directory.
27 | * This will create: erc20/ERC20.h and erc20/ERC20_main.c
28 | *
29 | * abstract contract can contain functions without implementation.
30 | *
31 | * generated c only cares about storage and function declarations as they appear here.
32 | */
33 | abstract contract ERC20 {
34 | /**
35 | * PART I - storage
36 | *
37 | * in the generated .h file, two defines will be created for each storage variable:
38 | * STORAGE_SLOT__* - 32-bytes initializer with the appropriate base_slot
39 | * STORAGE_OFFSET__* - offset inside that slot for the variable
40 | *
41 | * see also:
42 | * * https://docs.soliditylang.org/en/v0.8.20/internals/layout_in_storage.html
43 | * * storage.h
44 | */
45 |
46 | /**
47 | * First variable is in slot zero. This will generate:
48 | * #define STORAGE_SLOT__totalSupply {0x00, 0x00, ... 0x00, 0x00, 0x00}
49 | */
50 | uint256 private _totalSupply;
51 |
52 | /**
53 | * Both these variables share a slot. A STORAGE_SLOT_* define will be created for each, all are identical.
54 | * The offsets generated, however, are not:
55 | *
56 | * #define STORAGE_END_OFFSET_minters_current 32
57 | * #define STORAGE_END_OFFSET_initialized 24
58 | *
59 | * These are offsets to the END of the values, as the name suggests, so the minters_current u64
60 | * can be read from bytes [24-32), and the "initialized" boolean from the byte [23-24)
61 | */
62 | uint64 public minters_current;
63 | bool initialized;
64 |
65 | /**
66 | * A dynamic array stores it's size in (slot) and values starting in keccak256(slot)
67 | * so in addition to the slot value, base is also generated in the header file:
68 | *
69 | * #define STORAGE_BASE_minters {0x40, 0x57, 0x87, ... 0xbb, 0x5a, 0xce}
70 | */
71 | address[] public minters;
72 |
73 | /**
74 | * for maps the base is not hashed. see storage.h for utils helping to calculate position of hashed values
75 | */
76 | mapping(address account => uint256) private _balances;
77 |
78 | /**
79 | * notice: defining a variable as public also creates a getter function (here: minter_idx(address) returns uint64)
80 | * you will have to implement this function as well.
81 | */
82 | mapping(address spender => uint64) public minter_idx;
83 |
84 |
85 | /**
86 | * PART II - functions
87 | *
88 | * Only need to define public/external functions for the ABI (no difference for our use).
89 | * Define all functions virtual to avoid requiring a solidity implementation.
90 | *
91 | * The generated h file will contain declarations for all functions declared here and selectors
92 | * for them.
93 | *
94 | * The generated _main file will contain an entry point that parses the function selector and
95 | * calls the appropriate function.
96 | *
97 | * The programmer's should implement the functions declared in the generated h-file.
98 | *
99 | * a default payable function will be called if input doesn't match any selector.
100 | */
101 |
102 | /*
103 | * Pure functions should not access storage.
104 | * This is the generated c declaration:
105 | *
106 | * ArbResult symbol(uint8_t *input, size_t len);
107 | *
108 | * see stylus_types for definition of ArbResult.
109 | * input and input_length don't include the function selector
110 | * the function should validate it's input and parse output accordingly
111 | */
112 | function name() public pure virtual returns (string memory);
113 | function symbol() public pure virtual returns (string memory);
114 | function decimals() public pure virtual returns (uint8);
115 |
116 | /*
117 | * A view function can read storage.
118 | * This is the generated c declaration:
119 | *
120 | * ArbResult totalSupply(const void *storage, uint8_t *input, size_t len); // totalSupply()
121 | *
122 | * the storage pointer isn't really set or used, but should be passed to storage functions
123 | * for compile-time verification that we should access storage. see storage.h
124 | */
125 | function totalSupply() public view virtual returns (uint256);
126 | function balanceOf(address account) public view virtual returns (uint256);
127 |
128 | /**
129 | * a mutating functions gets a non-const storage pointer:
130 | *
131 | * ArbResult mint(void *storage, uint8_t *input, size_t len); // mint(address,uint256)
132 | *
133 | * Notice again that apart from function-selector, the environment does not parse or
134 | * encode any input/output variable unless explicitly done by the function implementor
135 | */
136 | function mint(address account, uint256 value) public virtual;
137 |
138 | function transfer(address to, uint256 value) public virtual returns (bool);
139 |
140 | function init(address first_minter) public virtual;
141 | function add_minter(address new_minter) public virtual;
142 | function remove_minter(address old_minter) public virtual;
143 |
144 | // TODO: complete the ERC20 interface
145 | // function allowance(address owner, address spender) public view virtual returns (uint256);
146 | // function approve(address spender, uint256 value) public virtual returns (bool);
147 | // function transferFrom(address from, address to, uint256 value) public virtual returns (bool);
148 | // function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool);
149 | // function decreaseAllowance(address spender, uint256 requestedDecrease) public virtual returns (bool);
150 | }
--------------------------------------------------------------------------------
/examples/erc20/impl.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include
5 | #include
6 | #include
7 | #include
8 | #include
9 |
10 | /**
11 | * Implementation of the C ERC20-style contract.
12 | *
13 | * Also see:
14 | * * erc20.sol - declaring the interface that's generated
15 | * * Makefile - the process of building the different parts
16 | * * equiv.sol - equivalent solidity implementation
17 | *
18 | * This contract is:
19 | * * NOT Audited / well tested
20 | * * NOT a good or a safe way to to manage minters for an ERC20.
21 | *
22 | * It is an example code explaining how to do things in stylus C-SDK.
23 | *
24 | * Notes to the reader:
25 | * 1) Different languages are good at different thing.
26 | * Unsurprisingly, solidity is very good at solidity-compatibility.
27 | * C requires low level understanding and implementation of things
28 | * that are ready out-of-the box in solidity.
29 | * On the other hand, C with stylus allows you to do a level of process
30 | * power that is just not available to solidity smart contracts.
31 | *
32 | * 2) A C-SDK smart contract should conform to solidity for it's public
33 | * ABI to allow easy interaction with other contracts.
34 | * Storage compatibility is a matter of choice and standard.
35 | * The strongest argument for compatibility is it allows external tools
36 | * to find data easily, and it allows contract upgrades across languages.
37 | *
38 | */
39 |
40 | /**
41 | * General utils/helpers
42 | */
43 |
44 | // buffer used to write output, avoiding malloc
45 | uint8_t buf_out[32];
46 |
47 | // succeed and return a bebi32
48 | ArbResult inline _success_bebi32(bebi32 const retval) {
49 | ArbResult res = {Success, retval , 32};
50 | return res;
51 | }
52 |
53 | /**
54 | * Storage access helpers
55 | */
56 |
57 | // initialized and minters_current are in the same slot.
58 | // We access both these "short" values in the same function to remain in control of
59 | // the number of underline SLOAD/SSTORE operations
60 | void inline load_shorts(const void *storage, uint64_t *minters_current_out, bool *initialized_out) {
61 | bebi32 storage_slot = STORAGE_SLOT_minters_current;
62 | bebi32 buf;
63 | storage_load(storage, storage_slot, buf);
64 | if (minters_current_out != NULL) {
65 | // END_OFFSET tells us where the value ends, we load from where it starts.
66 | uint64_t res = bebi_get_u64(buf, STORAGE_END_OFFSET_minters_current - sizeof(uint64_t));
67 | *minters_current_out = res;
68 | }
69 | if (initialized_out != NULL) {
70 | uint8_t res = bebi_get_u8(buf, STORAGE_END_OFFSET_initialized - sizeof(uint8_t));
71 | *initialized_out = (res != 0);
72 | }
73 | }
74 |
75 | // always initialized==1 when storing
76 | void inline store_shorts(void *storage, uint64_t minters_current) {
77 | bebi32 storage_slot = STORAGE_SLOT_minters_current;
78 | bebi32 buf;
79 | bebi_set_u64(buf, STORAGE_END_OFFSET_minters_current - sizeof(uint64_t), minters_current);
80 | bebi_set_u8(buf, STORAGE_END_OFFSET_initialized - sizeof(uint8_t), 1);
81 | storage_store(storage, storage_slot, buf);
82 | }
83 |
84 | // calculate slot for minter_idx map of a minter
85 | void minter_idx_storage_slot(bebi32 const minter, bebi32 slot_out) {
86 | bebi32 base = STORAGE_SLOT_minter_idx;
87 | map_slot(base, minter, 32, slot_out);
88 | }
89 |
90 | // calculate slot for balances map of an account
91 | void balance_slot(bebi32 const account, bebi32 slot_out) {
92 | bebi32 base = STORAGE_SLOT__balances;
93 | map_slot(base, account, 32, slot_out);
94 | }
95 |
96 | // get index of a minter from minter_idx map
97 | uint64_t _minter_idx(const void *storage, bebi32 const minter) {
98 | bebi32 slot;
99 | minter_idx_storage_slot(minter, slot);
100 | bebi32 buffer;
101 | storage_load(storage, slot, buffer);
102 | return bebi32_get_u64(buffer);
103 | }
104 |
105 |
106 | /**
107 | * Implementing the contract's API
108 | *
109 | * These functions implement API defined by the solidity interface,
110 | * and/or have comparable implementation in equiv.sol
111 | */
112 |
113 | // the default function is called if input doesn't match any selector
114 | ArbResult default_func(void *storage, uint8_t *input, size_t len, bebi32 value) {
115 | // This will cause a revert with a reason strong, which can help debug
116 | return _return_short_string(Failure, "not supported");
117 | }
118 |
119 | // Standard pure functions of ERC20
120 | ArbResult name(uint8_t *input, size_t len){ // name()
121 | if (len != 0) {
122 | return _return_nodata(Failure);
123 | }
124 | return _return_short_string(Success, "C Token (sample code)");
125 | }
126 |
127 | // Standard pure functions of ERC20
128 | ArbResult symbol(uint8_t *input, size_t len) { // symbol()
129 | if (len != 0) {
130 | return _return_nodata(Failure);
131 | }
132 | return _return_short_string(Success, "CTOK");
133 | }
134 |
135 | // Standard pure functions of ERC20// Standard pure functions of ERC20
136 | ArbResult decimals(uint8_t *input, size_t len) { // decimals()
137 | if (len != 0) {
138 | return _return_nodata(Failure);
139 | }
140 | bebi32_set_u8(buf_out, 18);
141 | return _success_bebi32(buf_out);
142 | }
143 |
144 | // accessor to the _totalSupply field
145 | ArbResult totalSupply(const void *storage, uint8_t *input, size_t len){ // totalSupply()
146 | if (len != 0) {
147 | return _return_nodata(Failure);
148 | }
149 | bebi32 total_supply_slot = STORAGE_SLOT__totalSupply;
150 |
151 | storage_load(storage, total_supply_slot, buf_out);
152 | return _success_bebi32(buf_out);
153 | }
154 |
155 | // standard ERC20: a read accessor to the balances map
156 | ArbResult balanceOf(const void *storage, uint8_t *input, size_t len) { // balanceOf(address)
157 | // validate input is an address padded to 32 bytes
158 | if (len != 32) {
159 | return _return_nodata(Failure);
160 | }
161 | if (!bebi32_is_u160(input)) {
162 | return _return_nodata(Failure);
163 | }
164 | // calculate slot for address
165 | bebi32 slot;
166 | balance_slot(input, slot);
167 | // load and return value
168 | storage_load(storage, slot, buf_out);
169 | return _success_bebi32(buf_out);
170 | }
171 |
172 | // standard ERC20: move "value" tokens from message sender to "to"
173 | ArbResult transfer(void *storage, uint8_t *input, size_t len) { // transfer(address,uint256)
174 | // input should be two bytes32: destination (an address) and amount (uint256)
175 | if (len != 64) {
176 | return _return_nodata(Failure);
177 | }
178 | // const pointers to the two values
179 | uint8_t const *dest = input;
180 | uint8_t const *amount = (input + 32);
181 | // test if destination is an address
182 | if (!bebi32_is_u160(dest)) {
183 | return _return_nodata(Failure);
184 | }
185 |
186 | // read message sender
187 | bebi32 sender;
188 | msg_sender_padded(sender);
189 | // calculate the storage slot for sender's balance
190 | bebi32 balance_slot_buf;
191 | balance_slot(sender, balance_slot_buf);
192 | // read the sender's balance
193 | bebi32 balance_buf;
194 | storage_load(storage, balance_slot_buf, balance_buf);
195 | // check if sender has enough balance
196 | if (bebi32_cmp(balance_buf, amount) < 0) {
197 | // return false
198 | // notice we return a Success here because we do not revert
199 | bebi32_set_u8(buf_out, 0);
200 | return _success_bebi32(buf_out);
201 | }
202 | // reduce sender balance and store into the same slot
203 | bebi32_sub(balance_buf, amount);
204 | storage_store(storage, balance_slot_buf, balance_buf);
205 |
206 | // load/increase/store receiver balance
207 | balance_slot(dest, balance_slot_buf);
208 | storage_load(storage, balance_slot_buf, balance_buf);
209 | int overflow = bebi32_add(balance_buf, amount);
210 | if (overflow) {
211 | return _return_nodata(Failure);
212 | }
213 | storage_store(storage, balance_slot_buf, balance_buf);
214 |
215 | // return true
216 | bebi32_set_u8(buf_out, 1);
217 | return _success_bebi32(buf_out);
218 | }
219 |
220 | // push_minter adds to the end of minters_array, and updates minter_idx map
221 | void push_minter(void *storage, bebi32 minter) {
222 | // read array size
223 | bebi32 array_size_slot = STORAGE_SLOT_minters;
224 | bebi32 array_size;
225 | storage_load(storage, array_size_slot, array_size);
226 | // in solidity array size is uint256 - but a going over 1<<64
227 | // is not feasible, so for C we use a u64 index.
228 | if (!bebi32_is_u64(array_size)) {
229 | revert();
230 | }
231 | uint64_t index = bebi32_get_u64(array_size);
232 |
233 | // address 0 is never marked "minter"
234 | if (!bebi32_is_zero(minter)) {
235 | // compute memory slot for the index
236 | bebi32 idx_slot;
237 | minter_idx_storage_slot(minter, idx_slot);
238 | // store the u64 index into a 32-byte value
239 | bebi32 idx_bebi;
240 | bebi32_set_u64(idx_bebi, index);
241 | // store value
242 | storage_store(storage, idx_slot, idx_bebi);
243 | }
244 |
245 | // calculate storage slot in the end of the array
246 | bebi32 minters_slot;
247 | bebi32 minters_base = STORAGE_BASE_minters;
248 | array_slot_offset(minters_base, 32, index, minters_slot, NULL);
249 | // store minter into it's slot
250 | storage_store(storage, minters_slot, minter);
251 | // store the increased array size into it's slot
252 | bebi32_set_u64(array_size, index+1);
253 | storage_store(storage, array_size_slot, array_size);
254 | }
255 |
256 | // set the first minter
257 | ArbResult init(void *storage, uint8_t *input, size_t len) { // init()
258 | // validate_input
259 | if (len != 32 || !bebi32_is_u160(input)) {
260 | return _return_nodata(Failure);
261 | }
262 | bool initialized;
263 | load_shorts(storage, NULL, &initialized);
264 | if (initialized) {
265 | // revert with reason string
266 | return _return_short_string(Failure, "already initialized");
267 | }
268 | // first blank entry reserves index 0 for non-minters
269 | bebi32 zero_minter = {0};
270 | push_minter(storage, zero_minter);
271 | // push the first minter
272 | push_minter(storage, input);
273 | // store_shorts sets minters_current and initialized
274 | store_shorts(storage, 1);
275 | return _return_nodata(Success);
276 | }
277 |
278 | // helper function: check if message was sent from a minter
279 | bool from_minter(const void *storage) {
280 | bebi32 sender;
281 | msg_sender_padded(sender);
282 | return _minter_idx(storage, sender) != 0;
283 | }
284 |
285 | // add a new minter
286 | ArbResult add_minter(void *storage, uint8_t *input, size_t len) { // add_minter(address)
287 | if (!from_minter(storage)) {
288 | //revert with reason string
289 | return _return_short_string(Failure, "must be a minter");
290 | }
291 | if (len != 32 || !bebi32_is_u160(input)) {
292 | return _return_nodata(Failure);
293 | }
294 | uint64_t minters_current;
295 | load_shorts(storage, &minters_current, NULL);
296 |
297 | push_minter(storage, input);
298 | minters_current +=1;
299 | store_shorts(storage, minters_current);
300 | return _return_nodata(Success);
301 | }
302 |
303 | // remove minter
304 | // array entry is replaced with blank
305 | // minter_idx map entry is removed
306 | ArbResult remove_minter(void *storage, uint8_t *input, size_t len) { // remove_minter(address)
307 | if (!from_minter(storage)) {
308 | //revert with reason string
309 | return _return_short_string(Failure, "must be a minter");
310 | }
311 | if (len != 32 || !bebi32_is_u160(input)) {
312 | return _return_nodata(Failure);
313 | }
314 | // compute slot and load minter index
315 | bebi32 idx_slot;
316 | bebi32 buf;
317 | minter_idx_storage_slot(input, idx_slot);
318 | storage_load(storage, idx_slot, buf);
319 | uint64_t idx = bebi32_get_u32(buf);
320 | if (!idx) {
321 | //revert with reason string
322 | return _return_short_string(Failure, "remove: not minter");
323 | }
324 | bebi32 zero;
325 | memset(zero, 0, 32);
326 |
327 | // remove index from map
328 | storage_store(storage, idx_slot, zero);
329 |
330 | // compute slot of minter in the minters array
331 | bebi32 minters_slot;
332 | bebi32 minters_base = STORAGE_SLOT_minters;
333 | array_slot_offset(minters_base, 32, idx, minters_slot, NULL);
334 | // store 0 in the minters array
335 | storage_store(storage, minters_slot, zero);
336 |
337 | // reduce minters_current count
338 | uint64_t minters_current;
339 | load_shorts(storage, &minters_current, NULL);
340 | store_shorts(storage, minters_current-1);
341 | return _return_nodata(Success);
342 | }
343 |
344 | // mint new tokens for an account
345 | ArbResult mint(void *storage, uint8_t *input, size_t len){ // mint(address,uint256)
346 | if (!from_minter(storage)) {
347 | //revert with reason string
348 | return _return_short_string(Failure, "must be a minter");
349 | }
350 | if (len != 64) {
351 | return _return_nodata(Failure);
352 | }
353 | uint8_t const *dest = input;
354 | uint8_t const *amount = (input + 32);
355 | // check dest is an address
356 | if (!bebi32_is_u160(dest)) {
357 | return _return_nodata(Failure);
358 | }
359 | // compute slot and load balance
360 | bebi32 balance_slot_buf;
361 | balance_slot(dest, balance_slot_buf);
362 | bebi32 balance_buf;
363 | storage_load(storage, balance_slot_buf, balance_buf);
364 | // update balance (make sure there is no overflow)
365 | int overflow = bebi32_add(balance_buf, amount);
366 | if (overflow) {
367 | return _return_nodata(Failure);
368 | }
369 | storage_store(storage, balance_slot_buf, balance_buf);
370 |
371 | //update total-supply (make sure there is no overflow)
372 | bebi32 total_supply_slot = STORAGE_SLOT__totalSupply;
373 | bebi32 total_supply;
374 | storage_load(storage, total_supply_slot, total_supply);
375 | overflow = bebi32_add(total_supply, amount);
376 | if (overflow) {
377 | return _return_nodata(Failure);
378 | }
379 | storage_store(storage, total_supply_slot, total_supply);
380 | return _return_nodata(Success);
381 | }
382 |
383 | /**
384 | * Public field accessors
385 | *
386 | * Below functions are implicitly created in solidity - because these are public
387 | * fields in the contract.
388 | *
389 | * No free lunches in C - we need to implement these accessors as well.
390 | */
391 |
392 | ArbResult minters(const void *storage, uint8_t *input, size_t len) { // minters(uint256)
393 | // test input is a valid uint256
394 | if (len != 32) {
395 | return _return_nodata(Failure);
396 | }
397 | // get array size
398 | bebi32 array_size_slot = STORAGE_SLOT_minters;
399 | bebi32 array_size_buf;
400 | storage_load(storage, array_size_slot, array_size_buf);
401 | uint64_t array_size = bebi32_get_u64(array_size_buf);
402 |
403 | // check index is within bounds
404 | uint64_t index = bebi32_get_u64(input);
405 | if (!bebi32_is_u64(input) || index >= array_size) {
406 | // revert with reason
407 | return _return_short_string(Failure, "index out of bounds");
408 | }
409 | // load entry and return it
410 | bebi32 minters_slot;
411 | bebi32 minters_base = STORAGE_SLOT_minters;
412 | array_slot_offset(minters_base, 32, index, minters_slot, NULL);
413 | storage_load(storage, minters_slot, buf_out);
414 | return _success_bebi32(buf_out);
415 | }
416 |
417 | ArbResult minters_current(const void *storage, uint8_t *input, size_t len) { // minters_current()
418 | if (len != 0) {
419 | return _return_nodata(Failure);
420 | }
421 | uint64_t minters_current;
422 | load_shorts(storage, &minters_current, NULL);
423 | bebi32_set_u64(buf_out, minters_current);
424 | return _success_bebi32(buf_out);
425 | }
426 |
427 | ArbResult minter_idx(const void *storage, uint8_t *input, size_t len) { // minter_idx(address)
428 | if (len != 32 || !bebi32_is_u160(input)) {
429 | return _return_nodata(Failure);
430 | }
431 | uint64_t idx = _minter_idx(storage, input);
432 | bebi32_set_u64(buf_out, idx);
433 | return _success_bebi32(buf_out);
434 | }
435 |
436 |
--------------------------------------------------------------------------------
/examples/erc20/interface_compile.json:
--------------------------------------------------------------------------------
1 | {
2 | "language": "Solidity",
3 | "sources":
4 | {
5 | "erc20":
6 | {
7 | "urls":
8 | [
9 | "./erc20.sol"
10 | ]
11 | }
12 | },
13 | "settings":
14 | {
15 | "outputSelection": {
16 | "*": {
17 | "*": [
18 | "abi",
19 | "storageLayout"
20 | ]
21 | }
22 | }
23 | }
24 | }
--------------------------------------------------------------------------------
/examples/siphash/.gitignore:
--------------------------------------------------------------------------------
1 | *.o
2 | siphash.wasm
3 | siphash_unstripped.wasm
--------------------------------------------------------------------------------
/examples/siphash/Makefile:
--------------------------------------------------------------------------------
1 |
2 | STACK_SIZE=1024
3 | CC=clang
4 | LD=wasm-ld
5 | CFLAGS=-I../../include/ -Iinterface-gen/ --target=wasm32 -Os --no-standard-libraries -mbulk-memory -Wall -g
6 | LDFLAGS=-O2 --no-entry --stack-first -z stack-size=$(STACK_SIZE) -Bstatic
7 |
8 | OBJECTS=main.o siphash.o
9 |
10 | all: ./siphash.wasm
11 |
12 | # Step 1: build c-files
13 | %.o: %.c
14 | $(CC) $(CFLAGS) -c $< -o $@
15 |
16 | # Step 2: link
17 | siphash_unstripped.wasm: $(OBJECTS)
18 | $(LD) $(LDFLAGS) $(OBJECTS) -o $@
19 |
20 | # Step 3: strip symbols from wasm
21 | siphash.wasm: siphash_unstripped.wasm
22 | wasm-strip -o $@ $<
23 |
24 | # Step 4: check the wasm using cargo-stylus
25 | # cargo stylus check --wasm-file-path ./siphash.wasm --endpoint $ENDPOINT --private-key=$PRIVATE_KEY
26 |
27 | # Step 5: deploy the wasm using cargo-stylus
28 | # cargo stylus check --wasm-file-path ./siphash.wasm --endpoint $ENDPOINT --private-key=$PRIVATE_KEY
29 |
30 | clean:
31 | rm $(OBJECTS) siphash_unstripped.wasm siphash.wasm
32 |
33 | .phony: all cargo-generate clean
34 |
--------------------------------------------------------------------------------
/examples/siphash/main.c:
--------------------------------------------------------------------------------
1 | // Copyright 2022-2023, Offchain Labs, Inc.
2 | // For licensing, see https://github.com/OffchainLabs/stylus-sdk-c/blob/stylus/licenses/COPYRIGHT.md
3 | //
4 | // You can compile this file with stock clang as follows
5 | // clang *.c -o siphash.wasm --target=wasm32 --no-standard-libraries -mbulk-memory -Wl,--no-entry -O3
6 | //
7 | // For C programs that use the standard library, cross compile clang with wasi if your compiler doesn't support it
8 | // https://github.com/WebAssembly/wasi-sdk
9 |
10 | #include "stylus_entry.h"
11 |
12 | // siphash impl from siphash.c
13 | extern uint64_t siphash24(const void *src, unsigned long len, const uint8_t key[16]);
14 |
15 | // the entrypoint
16 | ArbResult user_main(uint8_t * args, size_t args_len) {
17 | const uint8_t * key = args;
18 | const uint8_t * input = args + 16;
19 | const uint64_t length = args_len - 16;
20 |
21 | // call siphash on the args
22 | uint64_t hash = siphash24(input, length, key);
23 |
24 | // re-use args for efficiency
25 | __builtin_memcpy(args, &hash, sizeof(hash));
26 |
27 | return (ArbResult) {
28 | .status = Success,
29 | .output = args,
30 | .output_len = sizeof(hash),
31 | };
32 | }
33 |
34 | // sets user_main as the entrypoint
35 | ENTRYPOINT(user_main);
36 |
--------------------------------------------------------------------------------
/examples/siphash/siphash.c:
--------------------------------------------------------------------------------
1 | // Copyright 2022-2023, Offchain Labs, Inc.
2 | // For licensing, see https://github.com/OffchainLabs/stylus-sdk-c/blob/stylus/licenses/COPYRIGHT.md
3 | //
4 | // Note for just this file: an MIT variant of this program may be found at
5 | // https://github.com/majek/csiphash/
6 | //
7 |
8 | #include
9 |
10 | // wasm is always little endian
11 | #define _le64toh(x) ((uint64_t)(x))
12 |
13 | #define ROTATE(x, b) (uint64_t)( ((x) << (b)) | ( (x) >> (64 - (b))) )
14 |
15 | #define HALF_ROUND(a,b,c,d,s,t) \
16 | a += b; c += d; \
17 | b = ROTATE(b, s) ^ a; \
18 | d = ROTATE(d, t) ^ c; \
19 | a = ROTATE(a, 32);
20 |
21 | #define DOUBLE_ROUND(v0,v1,v2,v3) \
22 | HALF_ROUND(v0,v1,v2,v3,13,16); \
23 | HALF_ROUND(v2,v1,v0,v3,17,21); \
24 | HALF_ROUND(v0,v1,v2,v3,13,16); \
25 | HALF_ROUND(v2,v1,v0,v3,17,21);
26 |
27 |
28 | uint64_t siphash24(const void *src, unsigned long len, const uint8_t key[16]) {
29 | const uint64_t *_key = (uint64_t *)key;
30 | uint64_t k0 = _le64toh(_key[0]);
31 | uint64_t k1 = _le64toh(_key[1]);
32 | uint64_t b = (uint64_t)len << 56;
33 | const uint64_t *in = (uint64_t*)src;
34 |
35 | uint64_t v0 = k0 ^ 0x736f6d6570736575ULL;
36 | uint64_t v1 = k1 ^ 0x646f72616e646f6dULL;
37 | uint64_t v2 = k0 ^ 0x6c7967656e657261ULL;
38 | uint64_t v3 = k1 ^ 0x7465646279746573ULL;
39 |
40 | while (len >= 8) {
41 | uint64_t mi = _le64toh(*in);
42 | in += 1; len -= 8;
43 | v3 ^= mi;
44 | DOUBLE_ROUND(v0,v1,v2,v3);
45 | v0 ^= mi;
46 | }
47 |
48 | uint64_t t = 0; uint8_t *pt = (uint8_t *)&t; uint8_t *m = (uint8_t *)in;
49 | switch (len) {
50 | case 7: pt[6] = m[6];
51 | case 6: pt[5] = m[5];
52 | case 5: pt[4] = m[4];
53 | case 4: *((uint32_t*)&pt[0]) = *((uint32_t*)&m[0]); break;
54 | case 3: pt[2] = m[2];
55 | case 2: pt[1] = m[1];
56 | case 1: pt[0] = m[0];
57 | }
58 | b |= _le64toh(t);
59 |
60 | v3 ^= b;
61 | DOUBLE_ROUND(v0,v1,v2,v3);
62 | v0 ^= b; v2 ^= 0xff;
63 | DOUBLE_ROUND(v0,v1,v2,v3);
64 | DOUBLE_ROUND(v0,v1,v2,v3);
65 | return (v0 ^ v1) ^ (v2 ^ v3);
66 | }
67 |
--------------------------------------------------------------------------------
/include/bebi.h:
--------------------------------------------------------------------------------
1 |
2 | #ifndef __BEBI_H
3 | #define __BEBI_H
4 |
5 | /**
6 | * BEBI stands for Big Endian Big Int
7 | *
8 | * It is meant to be used in a small-endian environment, specifically WASM-32
9 | *
10 | * It is a library mostly meant to support encoding/decoding of big-endian big-int values
11 | * Only addition/subtraction and comparisons are supported for math (which is enough for quite a lot)
12 | * Currently only supporting unsigned.
13 | *
14 | * c-file: bebi.c
15 | * requires: string.h
16 | */
17 |
18 | #include
19 | #include
20 | #include
21 |
22 | #ifdef __cplusplus
23 | extern "C" {
24 | #endif
25 |
26 | /**
27 | * bebi type does not have a predefined size or alignment requirements
28 | */
29 | typedef uint8_t bebi[];
30 |
31 | /**
32 | * Set/get functions allow extracting or setting a u8/16/32/64 from any offset inside the bebi
33 | */
34 | inline void bebi_set_u8(bebi dst, size_t offset, uint8_t val);
35 | inline void bebi_set_u16(bebi dst, size_t offset, uint16_t val);
36 | inline void bebi_set_u32(bebi dst, size_t offset, uint32_t val);
37 | inline void bebi_set_u64(bebi dst, size_t offset, uint64_t val);
38 |
39 | inline uint8_t bebi_get_u8(const bebi src, size_t offset);
40 | inline uint16_t bebi_get_u16(const bebi src, size_t offset);
41 | inline uint32_t bebi_get_u32(const bebi src, size_t offset);
42 | inline uint64_t bebi_get_u64(const bebi src, size_t offset);
43 |
44 | /**
45 | * Adds rhs into lhs. Lhs must be at least as long as rhs.
46 | *
47 | * return values:
48 | * -1 : ERROR rhs_size > lhs_size
49 | * 0 : O.k
50 | * 1 : O.k but there was an overflow
51 | */
52 | inline int bebi_add(bebi lhs, size_t lhs_size, const bebi rhs, size_t rhs_size);
53 |
54 | /**
55 | * Subtracts rhs from lhs. Lhs must be at least as long as rhs.
56 | *
57 | * return values:
58 | * -1 : ERROR rhs_size > lhs_size
59 | * 0 : O.k
60 | * 1 : O.k but there was an overflow
61 | */
62 | inline int bebi_sub(bebi lhs, size_t lhs_size, const bebi rhs, size_t rhs_size);
63 |
64 | /**
65 | * compares two values
66 | *
67 | * return values:
68 | * lhs > rhs: 1
69 | * lhs < rhs: -1
70 | * lhs == rhs: 0
71 | */
72 | inline int bebi_cmp(const bebi lhs, size_t lhs_size, const bebi rhs, size_t rhs_size);
73 |
74 | inline bool bebi_is_zero(const bebi bebi, size_t size);
75 |
76 | /**
77 | * bebi32 is a specialized bebi of size 32, which is used a lot in solidity
78 | * there are no alignment requirements.
79 | */
80 | typedef uint8_t bebi32[32];
81 |
82 | /**
83 | * bebi32 get/set functions are different from generic bebi.
84 | * according to solidity standards - they require the value to be stored in
85 | * the last (least significant) bytes, padded by zeroes
86 | *
87 | * setting a bebi32 to e.g. uint32 will pad it with zeroes accordingly
88 | *
89 | * get functions don't test if value is padded - testing can be done separately
90 | * by the bebi32_is_*
91 | *
92 | * notice you can use generic bebi variants for a bebi32 when they fit better
93 | */
94 | uint16_t bebi32_get_u16(const bebi32 dst);
95 | uint32_t bebi32_get_u32(const bebi32 dst);
96 | uint64_t bebi32_get_u64(const bebi32 dst);
97 |
98 | void bebi32_set_u8(bebi32 dst, uint8_t val);
99 | void bebi32_set_u16(bebi32 dst, uint16_t val);
100 | void bebi32_set_u32(bebi32 dst, uint32_t val);
101 | void bebi32_set_u64(bebi32 dst, uint64_t val);
102 |
103 | bool bebi32_is_u8(const bebi32 dst);
104 | bool bebi32_is_u16(const bebi32 dst);
105 | bool bebi32_is_u32(const bebi32 dst);
106 | bool bebi32_is_u64(const bebi32 dst);
107 | bool bebi32_is_u160(const bebi32 dst);
108 |
109 | int bebi32_add(bebi32 lhs, const bebi32 rhs);
110 | int bebi32_sub(bebi32 lhs, const bebi32 rhs);
111 | int bebi32_add_u64(bebi32 lhs, uint64_t rhs);
112 |
113 | int bebi32_cmp(const bebi32 lhs, const bebi32 rhs);
114 | bool bebi32_is_zero(const bebi bebi);
115 |
116 |
117 | /******* implementation of previously-declated functions *********/
118 | inline int bebi_add(bebi lhs, size_t lhs_size, const bebi rhs, size_t rhs_size) {
119 | if (rhs_size > lhs_size) {
120 | return -1;
121 | }
122 | size_t left = lhs_size;
123 | size_t right = rhs_size;
124 | uint8_t carry = 0;
125 | while (left > 0 && right > 0) {
126 | left--;
127 | right--;
128 | uint8_t res = lhs[left] + rhs[right] + carry;
129 | carry = res < lhs[left] ? 1 : 0;
130 | lhs[left] = res;
131 | }
132 | while (left > 0 && carry) {
133 | left--;
134 | uint8_t res = lhs[left] + carry;
135 | carry = res < lhs[left] ? 1 : 0;
136 | lhs[left] = res;
137 | }
138 | return carry;
139 | }
140 |
141 | inline int bebi_sub(bebi lhs, size_t lhs_size, const bebi rhs, size_t rhs_size) {
142 | if (rhs_size > lhs_size) {
143 | return -1;
144 | }
145 | size_t left = lhs_size;
146 | size_t right = rhs_size;
147 | uint8_t carry = 0;
148 | while (left > 0 && right > 0) {
149 | left--;
150 | right--;
151 | uint8_t res = lhs[left] - rhs[right] - carry;
152 | carry = res > lhs[left] ? 1 : 0;
153 | lhs[left] = res;
154 | }
155 | while (left > 0 && carry) {
156 | left--;
157 | uint8_t res = lhs[left] - carry;
158 | carry = res > lhs[left] ? 1 : 0;
159 | lhs[left] = res;
160 | }
161 | return carry;
162 | }
163 |
164 | inline int bebi_cmp(const bebi lhs, size_t lhs_size, const bebi rhs, size_t rhs_size) {
165 | size_t left = 0;
166 | size_t right = 0;
167 | while (lhs_size - left > rhs_size) {
168 | if (lhs[left] != 0) {
169 | return 1;
170 | }
171 | left++;
172 | }
173 | while (rhs_size - right > lhs_size) {
174 | if (rhs[right] != 0) {
175 | return -1;
176 | }
177 | right++;
178 | }
179 | while (left < lhs_size) {
180 | if (lhs[left] > rhs[right]) {
181 | return 1;
182 | }
183 | if (lhs[left] < rhs[right]) {
184 | return -1;
185 | }
186 | right++;
187 | left++;
188 | }
189 | return 0;
190 | }
191 |
192 | inline void bebi_set_u8(bebi dst, size_t offset, uint8_t val) {
193 | dst[offset] = val;
194 | }
195 |
196 | inline bool bebi_is_zero(const bebi bebi, size_t size) {
197 | size_t idx = 0;
198 | while (idx < size) {
199 | if (bebi[idx] != 0) {
200 | return false;
201 | }
202 | idx++;
203 | }
204 | return true;
205 | }
206 |
207 | inline uint8_t bebi_get_u8(const bebi src, size_t offset) {
208 | return src[offset];
209 | }
210 |
211 | inline void bebi_set_u16(bebi dst, size_t offset, uint16_t val) {
212 | dst[offset+1] = val & 0xff;
213 | val >>= 8;
214 | dst[offset] = val & 0xff;
215 | }
216 |
217 | inline uint16_t bebi_get_u16(const bebi src, size_t offset) {
218 | uint16_t val;
219 | val = src[offset];
220 | val <<= 8;
221 | val |= src[offset+1];
222 | return val;
223 | }
224 |
225 | inline void bebi_set_u32(bebi dst, size_t offset, uint32_t val) {
226 | dst[offset+3] = val & 0xff;
227 | val >>= 8;
228 | dst[offset+2] = val & 0xff;
229 | val >>= 8;
230 | dst[offset+1] = val & 0xff;
231 | val >>= 8;
232 | dst[offset] = val & 0xff;
233 | }
234 |
235 | inline uint32_t bebi_get_u32(const bebi src, size_t offset) {
236 | uint32_t val;
237 | val = src[offset];
238 | val <<= 8;
239 | val |= src[offset+1];
240 | val <<= 8;
241 | val |= src[offset+2];
242 | val <<= 8;
243 | val |= src[offset+3];
244 | return val;
245 | }
246 |
247 | inline void bebi_set_u64(bebi dst, size_t offset, uint64_t val) {
248 | dst[offset+7] = val & 0xff;
249 | val >>= 8;
250 | dst[offset+6] = val & 0xff;
251 | val >>= 8;
252 | dst[offset+5] = val & 0xff;
253 | val >>= 8;
254 | dst[offset+4] = val & 0xff;
255 | val >>= 8;
256 | dst[offset+3] = val & 0xff;
257 | val >>= 8;
258 | dst[offset+2] = val & 0xff;
259 | val >>= 8;
260 | dst[offset+1] = val & 0xff;
261 | val >>= 8;
262 | dst[offset] = val & 0xff;
263 | }
264 |
265 | inline uint64_t bebi_get_u64(const bebi src, size_t offset) {
266 | uint64_t val;
267 | val = src[offset];
268 | val <<= 8;
269 | val |= src[offset+1];
270 | val <<= 8;
271 | val |= src[offset+2];
272 | val <<= 8;
273 | val |= src[offset+3];
274 | val <<= 8;
275 | val |= src[offset+4];
276 | val <<= 8;
277 | val |= src[offset+5];
278 | val <<= 8;
279 | val |= src[offset+6];
280 | val <<= 8;
281 | val |= src[offset+7];
282 | return val;
283 | }
284 |
285 | #ifdef __cplusplus
286 | }
287 | #endif
288 |
289 | #endif // __BEBI_H
--------------------------------------------------------------------------------
/include/hostio.h:
--------------------------------------------------------------------------------
1 | // Copyright 2022-2023, Offchain Labs, Inc.
2 | // For licensing, see https://github.com/stylus-sdk-c/blob/stylus/licenses/COPYRIGHT.md
3 |
4 | #ifndef STYLUS_HOSTIO_H
5 | #define STYLUS_HOSTIO_H
6 |
7 | #include
8 | #include
9 |
10 | #ifdef __cplusplus
11 | extern "C" {
12 | #endif
13 |
14 | #define VM_HOOK(name) extern __attribute__((import_module("vm_hooks"), import_name(#name)))
15 |
16 | /**
17 | * Gets the ETH balance in wei of the account at the given address.
18 | * The semantics are equivalent to that of the EVM’s [`BALANCE`] opcode.
19 | *
20 | * [`BALANCE`]: https://www.evm.codes/#31
21 | */
22 | VM_HOOK(account_balance) void account_balance(const uint8_t * address, uint8_t * dest);
23 |
24 | /**
25 | * Gets the code hash of the account at the given address. The semantics are equivalent
26 | * to that of the EVM's [`EXT_CODEHASH`] opcode. Note that the code hash of an account without
27 | * code will be the empty hash
28 | * `keccak("") = c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470`.
29 | *
30 | * [`EXT_CODEHASH`]: https://www.evm.codes/#3F
31 | */
32 | VM_HOOK(account_codehash) void account_codehash(const uint8_t * address, uint8_t * dest);
33 |
34 | /**
35 | * Reads a 32-byte value from permanent storage. Stylus's storage format is identical to
36 | * that of the EVM. This means that, under the hood, this hostio is accessing the 32-byte
37 | * value stored in the EVM state trie at offset `key`, which will be `0` when not previously
38 | * set. The semantics, then, are equivalent to that of the EVM's [`SLOAD`] opcode.
39 | *
40 | * [`SLOAD`]: https://www.evm.codes/#54
41 | */
42 | VM_HOOK(storage_load_bytes32) void storage_load_bytes32(const uint8_t * key, uint8_t * dest);
43 |
44 | /**
45 | * Stores a 32-byte value to permanent storage. Stylus's storage format is identical to that
46 | * of the EVM. This means that, under the hood, this hostio is storing a 32-byte value into
47 | * the EVM state trie at offset `key`. Furthermore, refunds are tabulated exactly as in the
48 | * EVM. The semantics, then, are equivalent to that of the EVM's [`SSTORE`] opcode.
49 | *
50 | * [`SSTORE`]: https://www.evm.codes/#55
51 | */
52 | VM_HOOK(storage_store_bytes32) void storage_store_bytes32(const uint8_t * key, const uint8_t * value);
53 |
54 | /**
55 | * Gets the basefee of the current block. The semantics are equivalent to that of the EVM's
56 | * [`BASEFEE`] opcode.
57 | *
58 | * [`BASEFEE`]: https://www.evm.codes/#48
59 | */
60 | VM_HOOK(block_basefee) void block_basefee(uint8_t * basefee);
61 |
62 | /**
63 | * Gets the unique chain identifier of the Arbitrum chain. The semantics are equivalent to
64 | * that of the EVM's [`CHAIN_ID`] opcode.
65 | *
66 | * [`CHAIN_ID`]: https://www.evm.codes/#46
67 | */
68 | VM_HOOK(chainid) uint64_t chainid();
69 |
70 | /**
71 | * Gets the coinbase of the current block, which on Arbitrum chains is the L1 batch poster's
72 | * address. This differs from Ethereum where the validator including the transaction
73 | * determines the coinbase.
74 | */
75 | VM_HOOK(block_coinbase) void block_coinbase(uint8_t * coinbase);
76 |
77 | /**
78 | * Gets the gas limit of the current block. The semantics are equivalent to that of the EVM's
79 | * [`GAS_LIMIT`] opcode. Note that as of the time of this writing, `evm.codes` incorrectly
80 | * implies that the opcode returns the gas limit of the current transaction. When in doubt,
81 | * consult [`The Ethereum Yellow Paper`].
82 | *
83 | * [`GAS_LIMIT`]: https://www.evm.codes/#45
84 | * [`The Ethereum Yellow Paper`]: https://ethereum.github.io/yellowpaper/paper.pdf
85 | */
86 | VM_HOOK(block_gas_limit) uint64_t block_gas_limit();
87 |
88 | /**
89 | * Gets a bounded estimate of the L1 block number at which the Sequencer sequenced the
90 | * transaction. See [`Block Numbers and Time`] for more information on how this value is
91 | * determined.
92 | *
93 | * [`Block Numbers and Time`]: https://developer.arbitrum.io/time
94 | */
95 | VM_HOOK(block_number) uint64_t block_number();
96 |
97 | /**
98 | * Gets a bounded estimate of the Unix timestamp at which the Sequencer sequenced the
99 | * transaction. See [`Block Numbers and Time`] for more information on how this value is
100 | * determined.
101 | *
102 | * [`Block Numbers and Time`]: https://developer.arbitrum.io/time
103 | */
104 | VM_HOOK(block_timestamp) uint64_t block_timestamp();
105 |
106 | /**
107 | * Calls the contract at the given address with options for passing value and to limit the
108 | * amount of gas supplied. The return status indicates whether the call succeeded, and is
109 | * nonzero on failure.
110 | *
111 | * In both cases `return_data_len` will store the length of the result, the bytes of which can
112 | * be read via the `read_return_data` hostio. The bytes are not returned directly so that the
113 | * programmer can potentially save gas by choosing which subset of the return result they'd
114 | * like to copy.
115 | *
116 | * The semantics are equivalent to that of the EVM's [`CALL`] opcode, including callvalue
117 | * stipends and the 63/64 gas rule. This means that supplying the `u64::MAX` gas can be used
118 | * to send as much as possible.
119 | *
120 | * [`CALL`]: https://www.evm.codes/#f1
121 | */
122 | VM_HOOK(call_contract) uint8_t call_contract(
123 | const uint8_t * contract,
124 | const uint8_t * calldata,
125 | const size_t calldata_len,
126 | const uint8_t * value,
127 | const uint64_t gas,
128 | size_t * return_data_len
129 | );
130 |
131 | /**
132 | * Gets the address of the current program. The semantics are equivalent to that of the EVM's
133 | * [`ADDRESS`] opcode.
134 | *
135 | * [`ADDRESS`]: https://www.evm.codes/#30
136 | */
137 | VM_HOOK(contract_address) void contract_address(uint8_t * address);
138 |
139 | /**
140 | * Deploys a new contract using the init code provided, which the EVM executes to construct
141 | * the code of the newly deployed contract. The init code must be written in EVM bytecode, but
142 | * the code it deploys can be that of a Stylus program. The code returned will be treated as
143 | * WASM if it begins with the EOF-inspired header `0xEFF000`. Otherwise the code will be
144 | * interpreted as that of a traditional EVM-style contract. See [`Deploying Stylus Programs`]
145 | * for more information on writing init code.
146 | *
147 | * On success, this hostio returns the address of the newly created account whose address is
148 | * a function of the sender and nonce. On failure the address will be `0`, `return_data_len`
149 | * will store the length of the revert data, the bytes of which can be read via the
150 | * `read_return_data` hostio. The semantics are equivalent to that of the EVM's [`CREATE`]
151 | * opcode, which notably includes the exact address returned.
152 | *
153 | * [`Deploying Stylus Programs`]: https://developer.arbitrum.io/TODO
154 | * [`CREATE`]: https://www.evm.codes/#f0
155 | */
156 | VM_HOOK(create1) void create1(
157 | const uint8_t * code,
158 | const size_t code_len,
159 | const uint8_t * endowment,
160 | uint8_t * contract,
161 | size_t * revert_data_len
162 | );
163 |
164 | /**
165 | * Deploys a new contract using the init code provided, which the EVM executes to construct
166 | * the code of the newly deployed contract. The init code must be written in EVM bytecode, but
167 | * the code it deploys can be that of a Stylus program. The code returned will be treated as
168 | * WASM if it begins with the EOF-inspired header `0xEFF000`. Otherwise the code will be
169 | * interpreted as that of a traditional EVM-style contract. See [`Deploying Stylus Programs`]
170 | * for more information on writing init code.
171 | *
172 | * On success, this hostio returns the address of the newly created account whose address is a
173 | * function of the sender, salt, and init code. On failure the address will be `0`,
174 | * `return_data_len` will store the length of the revert data, the bytes of which can be read
175 | * via the `read_return_data` hostio. The semantics are equivalent to that of the EVM's
176 | * `[CREATE2`] opcode, which notably includes the exact address returned.
177 | *
178 | * [`Deploying Stylus Programs`]: https://developer.arbitrum.io/TODO
179 | * [`CREATE2`]: https://www.evm.codes/#f5
180 | */
181 | VM_HOOK(create2) void create2(
182 | const uint8_t * code,
183 | const size_t code_len,
184 | const uint8_t * endowment,
185 | const uint8_t * salt,
186 | uint8_t * contract,
187 | size_t * revert_data_len
188 | );
189 |
190 | /**
191 | * Delegate calls the contract at the given address, with the option to limit the amount of
192 | * gas supplied. The return status indicates whether the call succeeded, and is nonzero on
193 | * failure.
194 | *
195 | * In both cases `return_data_len` will store the length of the result, the bytes of which
196 | * can be read via the `read_return_data` hostio. The bytes are not returned directly so that
197 | * the programmer can potentially save gas by choosing which subset of the return result
198 | * they'd like to copy.
199 | *
200 | * The semantics are equivalent to that of the EVM's [`DELEGATE_CALL`] opcode, including the
201 | * 63/64 gas rule. This means that supplying `u64::MAX` gas can be used to send as much as
202 | * possible.
203 | *
204 | * [`DELEGATE_CALL`]: https://www.evm.codes/#F4
205 | */
206 | VM_HOOK(delegate_call_contract) uint8_t delegate_call_contract(
207 | const uint8_t * contract,
208 | const uint8_t * calldata,
209 | const size_t calldata_len,
210 | const uint64_t gas,
211 | size_t * return_data_len
212 | );
213 |
214 | /**
215 | * Emits an EVM log with the given number of topics and data, the first bytes of which should
216 | * be the 32-byte-aligned topic data. The semantics are equivalent to that of the EVM's
217 | * [`LOG0`], [`LOG1`], [`LOG2`], [`LOG3`], and [`LOG4`] opcodes based on the number of topics
218 | * specified. Requesting more than `4` topics will induce a revert.
219 | *
220 | * [`LOG0`]: https://www.evm.codes/#a0
221 | * [`LOG1`]: https://www.evm.codes/#a1
222 | * [`LOG2`]: https://www.evm.codes/#a2
223 | * [`LOG3`]: https://www.evm.codes/#a3
224 | * [`LOG4`]: https://www.evm.codes/#a4
225 | */
226 | VM_HOOK(emit_log) void emit_log(uint8_t * data, size_t len, size_t topics);
227 |
228 | /**
229 | * Gets the amount of gas left after paying for the cost of this hostio. The semantics are
230 | * equivalent to that of the EVM's [`GAS`] opcode.
231 | *
232 | * [`GAS`]: https://www.evm.codes/#5a
233 | */
234 | VM_HOOK(evm_gas_left) uint64_t evm_gas_left();
235 |
236 | /**
237 | * Gets the amount of ink remaining after paying for the cost of this hostio. The semantics
238 | * are equivalent to that of the EVM's [`GAS`] opcode, except the units are in ink. See
239 | * [`Ink and Gas`] for more information on Stylus's compute pricing.
240 | *
241 | * [`GAS`]: https://www.evm.codes/#5a
242 | * [`Ink and Gas`]: https://developer.arbitrum.io/TODO
243 | */
244 | VM_HOOK(evm_ink_left) uint64_t evm_ink_left();
245 |
246 | /**
247 | * The `ENTRYPOINT` macro handles importing this hostio, which is required if the
248 | * program's memory grows. Otherwise compilation through the `ArbWasm` precompile will revert.
249 | * Internally the Stylus VM forces calls to this hostio whenever new WASM pages are allocated.
250 | * Calls made voluntarily will unproductively consume gas.
251 | */
252 | VM_HOOK(memory_grow) void memory_grow(const uint16_t pages);
253 |
254 | /**
255 | * Gets the address of the account that called the program. For normal L2-to-L2 transactions
256 | * the semantics are equivalent to that of the EVM's [`CALLER`] opcode, including in cases
257 | * arising from [`DELEGATE_CALL`].
258 | *
259 | * For L1-to-L2 retryable ticket transactions, the top-level sender's address will be aliased.
260 | * See [`Retryable Ticket Address Aliasing`] for more information on how this works.
261 | *
262 | * [`CALLER`]: https://www.evm.codes/#33
263 | * [`DELEGATE_CALL`]: https://www.evm.codes/#f4
264 | * [`Retryable Ticket Address Aliasing`]: https://developer.arbitrum.io/arbos/l1-to-l2-messaging#address-aliasing
265 | */
266 | VM_HOOK(msg_sender) void msg_sender(const uint8_t * sender);
267 |
268 | /**
269 | * Get the ETH value in wei sent to the program. The semantics are equivalent to that of the
270 | * EVM's [`CALLVALUE`] opcode.
271 | *
272 | * [`CALLVALUE`]: https://www.evm.codes/#34
273 | */
274 | VM_HOOK(msg_value) void msg_value(const uint8_t * value);
275 |
276 | /**
277 | * Efficiently computes the [`keccak256`] hash of the given preimage.
278 | * The semantics are equivalent to that of the EVM's [`SHA3`] opcode.
279 | *
280 | * [`keccak256`]: https://en.wikipedia.org/wiki/SHA-3
281 | * [`SHA3`]: https://www.evm.codes/#20
282 | */
283 | VM_HOOK(native_keccak256) void native_keccak256(const uint8_t * bytes, size_t len, uint8_t * output);
284 |
285 | /**
286 | * Reads the program calldata. The semantics are equivalent to that of the EVM's
287 | * [`CALLDATA_COPY`] opcode when requesting the entirety of the current call's calldata.
288 | *
289 | * [`CALLDATA_COPY`]: https://www.evm.codes/#37
290 | */
291 | VM_HOOK(read_args) void read_args(const uint8_t * data);
292 |
293 | /**
294 | * Copies the bytes of the last EVM call or deployment return result. Reverts if out of
295 | * bounds. The semantics are equivalent to that of the EVM's [`RETURN_DATA_COPY`] opcode.
296 | *
297 | * [`RETURN_DATA_COPY`]: https://www.evm.codes/#3e
298 | */
299 | VM_HOOK(read_return_data) size_t read_return_data(uint8_t * dest, size_t offset, size_t size);
300 |
301 | /**
302 | * Writes the final return data. If not called before the program exists, the return data will
303 | * be 0 bytes long. Note that this hostio does not cause the program to exit, which happens
304 | * naturally when [`user_entrypoint`] returns.
305 | */
306 | VM_HOOK(write_result) void write_result(const uint8_t * data, size_t len);
307 |
308 | /**
309 | * Returns the length of the last EVM call or deployment return result, or `0` if neither have
310 | * happened during the program's execution. The semantics are equivalent to that of the EVM's
311 | * [`RETURN_DATA_SIZE`] opcode.
312 | *
313 | * [`RETURN_DATA_SIZE`]: https://www.evm.codes/#3d
314 | */
315 | VM_HOOK(return_data_size) size_t return_data_size();
316 |
317 | /**
318 | * Static calls the contract at the given address, with the option to limit the amount of gas
319 | * supplied. The return status indicates whether the call succeeded, and is nonzero on
320 | * failure.
321 | *
322 | * In both cases `return_data_len` will store the length of the result, the bytes of which can
323 | * be read via the `read_return_data` hostio. The bytes are not returned directly so that the
324 | * programmer can potentially save gas by choosing which subset of the return result they'd
325 | * like to copy.
326 | *
327 | * The semantics are equivalent to that of the EVM's [`STATIC_CALL`] opcode, including the
328 | * 63/64 gas rule. This means that supplying `u64::MAX` gas can be used to send as much as
329 | * possible.
330 | *
331 | * [`STATIC_CALL`]: https://www.evm.codes/#FA
332 | */
333 | VM_HOOK(static_call_contract) uint8_t static_call_contract(
334 | const uint8_t * contract,
335 | const uint8_t * calldata,
336 | const size_t calldata_len,
337 | const uint64_t gas,
338 | size_t * return_data_len
339 | );
340 |
341 | /**
342 | * Gets the gas price in wei per gas, which on Arbitrum chains equals the basefee. The
343 | * semantics are equivalent to that of the EVM's [`GAS_PRICE`] opcode.
344 | *
345 | * [`GAS_PRICE`]: https://www.evm.codes/#3A
346 | */
347 | VM_HOOK(tx_gas_price) void tx_gas_price(uint8_t * gas_price);
348 |
349 | /**
350 | * Gets the price of ink in evm gas basis points. See [`Ink and Gas`] for more information on
351 | * Stylus's compute-pricing model.
352 | *
353 | * [`Ink and Gas`]: https://developer.arbitrum.io/TODO
354 | */
355 | VM_HOOK(tx_ink_price) uint64_t tx_ink_price();
356 |
357 | /**
358 | * Gets the top-level sender of the transaction. The semantics are equivalent to that of the
359 | * EVM's [`ORIGIN`] opcode.
360 | *
361 | * [`ORIGIN`]: https://www.evm.codes/#32
362 | */
363 | VM_HOOK(tx_origin) void tx_origin(uint8_t * origin);
364 |
365 | #ifdef __cplusplus
366 | }
367 | #endif
368 |
369 | #endif
370 |
--------------------------------------------------------------------------------
/include/stdlib.h:
--------------------------------------------------------------------------------
1 | #ifndef __SIMPLELIB_STDLIB_H
2 | #define __SIMPLELIB_STDLIB_H
3 |
4 | /**
5 | * Not at all a full implementation of stdlib.h,
6 | * just the parts of it supported by simplelib
7 | *
8 | * requirements: -
9 | * c-file: stdlib.c
10 | */
11 |
12 | #include
13 | #include
14 |
15 | #ifdef __cplusplus
16 | extern "C" {
17 | #endif
18 |
19 | void *malloc(size_t size);
20 | void free(void *ptr);
21 |
22 | #ifdef __cplusplus
23 | }
24 | #endif
25 |
26 | #endif // __SIMPLELIB_STDLIB_H
27 |
--------------------------------------------------------------------------------
/include/storage.h:
--------------------------------------------------------------------------------
1 |
2 | #ifndef __STORAGE_H
3 | #define __STORAGE_H
4 |
5 | #include
6 | #include
7 | #include
8 | #include
9 |
10 | /**
11 | * Storage.h creates tools that help access storage from a c-sdk contract
12 | *
13 | * These user is still required to understand solidity storage and use accordingly
14 | * See: https://docs.soliditylang.org/en/v0.8.20/internals/layout_in_storage.html
15 | *
16 | * requires: bebi.h (string.h)
17 | * c-file: storage.c
18 | */
19 |
20 | #ifdef __cplusplus
21 | extern "C" {
22 | #endif
23 |
24 | /**
25 | * storage_load / store load or store a value from storage accordingly.
26 | *
27 | * The value of the first "storage" pointer is not used.
28 | * generated headers provide:
29 | * a const storage pointer when working for a view-only function
30 | * a non const pointer for a mutating function
31 | * no pointer (so don't call storage_load) for a pure function
32 | *
33 | */
34 | inline void storage_load(const void* storage, const uint8_t *key, uint8_t *dest) {
35 | storage_load_bytes32(key, dest);
36 | }
37 |
38 | /**
39 | * see documentation for storage_load
40 | */
41 | inline void storage_store(void *storage, const uint8_t *key, const uint8_t *value) {
42 | storage_store_bytes32(key, value);
43 | }
44 |
45 | /**
46 | * calculate slot for a map with base slot "storage" to put "key"
47 | * If key requires padding it must be applied before calling this function
48 | */
49 | void map_slot(bebi32 const storage, uint8_t const *key, size_t key_len, bebi32 slot_out);
50 |
51 | /**
52 | * calculate slot and offset for an array with base slot "slot"
53 | * notice tht short byte-arrays and strings are not stored in base but in
54 | * the "size" slot - see solidity spec
55 | */
56 | int array_slot_offset(bebi32 const base, size_t val_size, uint64_t index, bebi32 slot_out, size_t *offset_out);
57 |
58 | /**
59 | * calculate the base slot for a dynamic array with storage-slot "storage"
60 | * (this is just native keccak of storage into base_out)
61 | */
62 | void dynamic_array_base_slot(bebi32 const storage, bebi32 base_out);
63 |
64 | #ifdef __cplusplus
65 | }
66 | #endif
67 |
68 | #endif
--------------------------------------------------------------------------------
/include/string.h:
--------------------------------------------------------------------------------
1 | #ifndef __SIMPLELIB_STRING_H
2 | #define __SIMPLELIB_STRING_H
3 |
4 | /**
5 | * Not at all a full implementation of string.h,
6 | * just the parts of it supported by simplelib
7 | *
8 | * requirements: -
9 | * c-file: simplelib.c
10 | */
11 |
12 | #include
13 | #include
14 |
15 | #ifdef __cplusplus
16 | extern "C" {
17 | #endif
18 |
19 | inline void *memcpy(void *destination, const void *source, size_t num) {
20 | return __builtin_memcpy(destination, source, num);
21 | }
22 |
23 | inline void *memmove( void *destination, const void * source, size_t num) {
24 | return __builtin_memcpy(destination, source, num);
25 | }
26 |
27 | inline void *memset(void *ptr, int value, size_t num) {
28 | return __builtin_memset(ptr, value, num);
29 | }
30 |
31 | char *strncpy(char *dst, const char *src, size_t num);
32 | size_t strlen(const char *str);
33 |
34 | #ifdef __cplusplus
35 | }
36 | #endif
37 |
38 | #endif // __SIMPLELIB_STRING_H
39 |
--------------------------------------------------------------------------------
/include/stylus_debug.h:
--------------------------------------------------------------------------------
1 | // Copyright 2022-2023, Offchain Labs, Inc.
2 | // For licensing, see https://github.com/stylus-sdk-c/blob/stylus/licenses/COPYRIGHT.md
3 |
4 | #ifndef STYLUS_DEBUG_H
5 | #define STYLUS_DEBUG_H
6 |
7 | /**
8 | * These functions are only usable in a debug-enabled network, which will usually be local-dev environments
9 | * Prints will appear on the dev-node's log.
10 | */
11 |
12 | #include
13 | #include
14 |
15 | #ifdef __cplusplus
16 | extern "C" {
17 | #endif
18 |
19 | #define CONSOLE(name) extern __attribute__((import_module("console"), import_name(#name)))
20 |
21 | /**
22 | * Prints a 32-bit floating point number to the console, Only available in debug mode with
23 | * floating point enabled.
24 | */
25 | CONSOLE(log_f32) void log_f32(float * value);
26 |
27 | /**
28 | * Prints a 64-bit floating point number to the console, Only available in debug mode with
29 | * floating point enabled.
30 | */
31 | CONSOLE(log_f64) void log_f64(double * value);
32 |
33 | /**
34 | * Prints a 32-bit integer to the console, which can be either signed or unsigned.
35 | * Only available in debug mode.
36 | */
37 | CONSOLE(log_i32) void log_i32(int32_t value);
38 |
39 | /**
40 | * Prints a 64-bit integer to the console, which can be either signed or unsigned.
41 | * Only available in debug mode.
42 | */
43 | CONSOLE(log_i64) void log_i64(int64_t value);
44 |
45 | /**
46 | * Prints a UTF-8 encoded string to the console. Only available in debug mode.
47 | */
48 | CONSOLE(log_txt) void log_txt(const uint8_t * text, size_t len);
49 |
50 | #ifdef __cplusplus
51 | }
52 | #endif
53 |
54 | #endif
55 |
--------------------------------------------------------------------------------
/include/stylus_entry.h:
--------------------------------------------------------------------------------
1 | // Copyright 2022-2023, Offchain Labs, Inc.
2 | // For licensing, see https://github.com/stylus-sdk-c/blob/stylus/licenses/COPYRIGHT.md
3 |
4 | #ifndef __STYLUS_ENTRY_H
5 | #define __STYLUS_ENTRY_H
6 |
7 | /**
8 | * This defines the entrypoint to a smart contract.
9 | * Only one file per wasm is expected to have an entrypoint
10 | *
11 | * requires: stylus_types.h
12 | * c-file: -
13 | */
14 |
15 | #include
16 | #include
17 |
18 | #include "hostio.h"
19 | #include "stylus_types.h"
20 |
21 | #ifdef __cplusplus
22 | extern "C" {
23 | #endif
24 |
25 | #define ENTRYPOINT(user_main) \
26 | /* Force the compiler to import these symbols */ \
27 | /* Note: calling these functions will unproductively consume gas */ \
28 | __attribute__((export_name("mark_used"))) \
29 | void mark_used() { \
30 | memory_grow(0); \
31 | } \
32 | \
33 | __attribute__((export_name("user_entrypoint"))) \
34 | int user_entrypoint(size_t args_len) { \
35 | uint8_t args[args_len]; \
36 | read_args(args); \
37 | const ArbResult result = user_main(args, args_len); \
38 | write_result(result.output, result.output_len); \
39 | return result.status; \
40 | }
41 |
42 | #ifdef __cplusplus
43 | }
44 | #endif
45 |
46 | #endif // __STYLUS_ENTRY_H
47 |
--------------------------------------------------------------------------------
/include/stylus_types.h:
--------------------------------------------------------------------------------
1 | // Copyright 2022-2023, Offchain Labs, Inc.
2 | // For licensing, see https://github.com/stylus-sdk-c/blob/stylus/licenses/COPYRIGHT.md
3 |
4 | #ifndef __STYLUS_TYPES_H
5 | #define __STYLUS_TYPES_H
6 |
7 | /**
8 | * stylus_types.h defines types used by generated and entrypoint c- macros
9 | *
10 | * requires: -
11 | * c-file: -
12 | */
13 |
14 | #include
15 | #include
16 |
17 | #ifdef __cplusplus
18 | extern "C" {
19 | #endif
20 |
21 | typedef enum ArbStatus {
22 | Success = 0,
23 | Failure,
24 | } ArbStatus;
25 |
26 | /**
27 | * Status = Failure is used to signify a revert
28 | * Revert or success may both return data to caller
29 | */
30 | typedef struct ArbResult {
31 | const ArbStatus status;
32 | const uint8_t * output;
33 | const size_t output_len;
34 | } ArbResult;
35 |
36 | /**
37 | * This will create a revert by causing a machine error.
38 | * There will be no returned data for this event.
39 | */
40 | inline void revert() {
41 | asm("unreachable");
42 | }
43 |
44 | #ifdef __cplusplus
45 | }
46 | #endif
47 |
48 | #endif
49 |
--------------------------------------------------------------------------------
/include/stylus_utils.h:
--------------------------------------------------------------------------------
1 | #ifndef __STYLUS_UTILS_H
2 | #define __STYLUS_UTILS_H
3 |
4 | /**
5 | * stylus_utils.h defines a few high-level useful utils for stylus smart contracts
6 | *
7 | * requires: bebi.h(string.h), hostio, stylus_types
8 | * c-file: utils.c
9 | */
10 |
11 | #include
12 | #include
13 | #include
14 | #include
15 | #include
16 |
17 | #ifdef __cplusplus
18 | extern "C" {
19 | #endif
20 |
21 | /**
22 | * sets message sender inside a padded 32-byte array
23 | */
24 | inline void msg_sender_padded(bebi sender) {
25 | msg_sender(sender+12);
26 | }
27 |
28 | /**
29 | * Arbresult with no data, can be success or failure
30 | */
31 | ArbResult inline _return_nodata(ArbStatus status) {
32 | ArbResult res = {status, NULL , 0};
33 | return res;
34 | }
35 |
36 | /**
37 | * string must be short (up to 32 bytes)
38 | *
39 | * Success returns the string in a tuple, as returned by functions returning string
40 | * Failure returns an Error string in a tuple, which can encode a revert reason for any function
41 | */
42 | ArbResult _return_short_string(ArbStatus status, char *string);
43 |
44 | #ifdef __cplusplus
45 | }
46 | #endif
47 |
48 | #endif // __STYLUS_UTILS_H
49 |
--------------------------------------------------------------------------------
/licenses/Apache-2.0:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright 2022-2023 Offchain Labs, Inc.
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/licenses/COPYRIGHT.md:
--------------------------------------------------------------------------------
1 | # Licensing Information
2 |
3 | Copyright 2022-2023 Offchain Labs, Inc.
4 |
5 | Copyright assignment and [DCO sign-off](DCO.txt) is required to contribute to this project.
6 |
7 | Except as otherwise noted (below and/or in individual files), this project is licensed under the Apache License, Version 2.0 ([`LICENSE-APACHE`](Apache-2.0) or http://www.apache.org/licenses/LICENSE-2.0) or the MIT license, ([`LICENSE-MIT`](MIT) or http://opensource.org/licenses/MIT), at your option.
8 |
9 | Each Stylus logo is a service mark of Offchain Labs (collectively, the "Offchain Labs Trademarks"). Offchain Labs reserves all rights in the Offchain Labs Trademarks and nothing herein or in these licenses should be construed as granting, by implication, estoppel, or otherwise, any license or right to use any of Offchain Labs Trademarks without Offchain Labs' prior written permission in each instance. All goodwill generated from the use of Offchain Labs Trademarks will inure to our exclusive benefit.
10 |
--------------------------------------------------------------------------------
/licenses/DCO.txt:
--------------------------------------------------------------------------------
1 | Developer Certificate of Origin
2 | Version 1.1
3 |
4 | Copyright (C) 2004, 2006 The Linux Foundation and its contributors.
5 |
6 | Everyone is permitted to copy and distribute verbatim copies of this
7 | license document, but changing it is not allowed.
8 |
9 |
10 | Developer's Certificate of Origin 1.1
11 |
12 | By making a contribution to this project, I certify that:
13 |
14 | (a) The contribution was created in whole or in part by me and I
15 | have the right to submit it under the open source license
16 | indicated in the file; or
17 |
18 | (b) The contribution is based upon previous work that, to the best
19 | of my knowledge, is covered under an appropriate open source
20 | license and I have the right under that license to submit that
21 | work with modifications, whether created in whole or in part
22 | by me, under the same open source license (unless I am
23 | permitted to submit under a different license), as indicated
24 | in the file; or
25 |
26 | (c) The contribution was provided directly to me by some other
27 | person who certified (a), (b) or (c) and I have not modified
28 | it.
29 |
30 | (d) I understand and agree that this project and the contribution
31 | are public and that a record of the contribution (including all
32 | personal information I submit with it, including my sign-off) is
33 | maintained indefinitely and may be redistributed consistent with
34 | this project or the open source license(s) involved.
35 |
--------------------------------------------------------------------------------
/licenses/MIT:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright 2022-2023 Offchain Labs, Inc.
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/src/bebi.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 |
4 | extern inline int bebi_add(bebi lhs, size_t lhs_size, const bebi rhs, size_t rhs_size);
5 | extern inline int bebi_sub(bebi lhs, size_t lhs_size, const bebi rhs, size_t rhs_size);
6 | extern inline int bebi_cmp(const bebi lhs, size_t lhs_size, const bebi rhs, size_t rhs_size);
7 |
8 | extern inline void bebi_set_u8(bebi dst, size_t offset, uint8_t val);
9 | extern inline bool bebi_is_zero(const bebi bebi, size_t size);
10 | extern inline uint8_t bebi_get_u8(const bebi src, size_t offset);
11 | extern inline void bebi_set_u16(bebi dst, size_t offset, uint16_t val);
12 | extern inline uint16_t bebi_get_u16(const bebi src, size_t offset);
13 | extern inline void bebi_set_u32(bebi dst, size_t offset, uint32_t val);
14 | extern inline uint32_t bebi_get_u32(const bebi src, size_t offset);
15 | extern inline void bebi_set_u64(bebi dst, size_t offset, uint64_t val);
16 | extern inline uint64_t bebi_get_u64(const bebi src, size_t offset);
17 |
18 | int bebi32_add(bebi32 lhs, const bebi32 rhs) {
19 | return bebi_add(lhs, 32, rhs, 32);
20 | }
21 |
22 | int bebi32_sub(bebi32 lhs, const bebi32 rhs) {
23 | return bebi_sub(lhs, 32, rhs, 32);
24 | }
25 |
26 | int bebi32_add_u64(bebi32 lhs, uint64_t rhs) {
27 | uint8_t rhs_bebi[8];
28 | bebi_set_u64(rhs_bebi, 0, rhs);
29 | return bebi_add(lhs, 32, rhs_bebi, 8);
30 | }
31 |
32 | void bebi32_set_u8(bebi32 dst, uint8_t val) {
33 | memset(dst, 0, 32-1);
34 | bebi_set_u8(dst, 32-1, val);
35 | }
36 |
37 | void bebi32_set_u16(bebi32 dst, uint16_t val) {
38 | memset(dst, 0, 32-2);
39 | bebi_set_u16(dst, 32-2, val);
40 | }
41 |
42 | void bebi32_set_u32(bebi32 dst, uint32_t val) {
43 | memset(dst, 0, 32-4);
44 | bebi_set_u32(dst, 32-4, val);
45 | }
46 |
47 | void bebi32_set_u64(bebi32 dst, uint64_t val) {
48 | memset(dst, 0, 32-8);
49 | bebi_set_u64(dst, 32-8, val);
50 | }
51 |
52 | bool bebi32_is_u8(const bebi32 dst) {
53 | return bebi_is_zero(dst, 32-8);
54 | }
55 |
56 | bool bebi32_is_u16(const bebi32 dst) {
57 | return bebi_is_zero(dst, 32-2);
58 | }
59 |
60 | bool bebi32_is_u32(const bebi32 dst) {
61 | return bebi_is_zero(dst, 32-4);
62 | }
63 |
64 | bool bebi32_is_u64(const bebi32 dst) {
65 | return bebi_is_zero(dst, 32-8);
66 | }
67 |
68 | bool bebi32_is_u160(const bebi32 dst) {
69 | return bebi_is_zero(dst, 32-20);
70 | }
71 |
72 | uint16_t bebi32_get_u16(const bebi32 dst) {
73 | return bebi_get_u16(dst, 32-2);
74 | }
75 |
76 | uint32_t bebi32_get_u32(const bebi32 dst) {
77 | return bebi_get_u32(dst, 32-4);
78 | }
79 |
80 | uint64_t bebi32_get_u64(const bebi32 dst) {
81 | return bebi_get_u64(dst, 32-8);
82 | }
83 |
84 | bool bebi32_is_zero(const bebi bebi) {
85 | return bebi_is_zero(bebi, 32);
86 | }
87 |
88 | int bebi32_cmp(const bebi32 lhs, const bebi32 rhs) {
89 | return bebi_cmp(lhs, 32, rhs, 32);
90 | }
91 |
--------------------------------------------------------------------------------
/src/simplelib.c:
--------------------------------------------------------------------------------
1 | #include
2 |
3 | extern inline void *memcpy(void *destination, const void *source, size_t num);
4 | extern inline void *memset(void *ptr, int value, size_t num);
5 |
6 | char *strncpy(char *dst, const char *src, size_t num) {
7 | size_t idx=0;
8 | while (idx
2 |
3 | #define PAGE_SIZE 65536
4 |
5 | static size_t next_free;
6 | static size_t heap_end;
7 |
8 | void *malloc(size_t size) {
9 | if (size > heap_end - next_free) {
10 | size_t pages_required = (size - (heap_end - next_free) + PAGE_SIZE - 1) / PAGE_SIZE;
11 | size_t prev_pages = __builtin_wasm_memory_grow(0, pages_required);
12 | if (next_free == 0) {
13 | next_free = prev_pages * PAGE_SIZE;
14 | }
15 | heap_end = (prev_pages + pages_required) * PAGE_SIZE;
16 | }
17 | void *retval = (void *)next_free;
18 | next_free += size;
19 | return retval;
20 | }
21 |
22 | // free does nothing
23 | void free(void *ptr) {}
24 |
--------------------------------------------------------------------------------
/src/storage.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 |
5 | int array_slot_offset(bebi32 const base, size_t val_size, uint64_t index, bebi32 slot_out, size_t *offset_out) {
6 | uint64_t slots;
7 | uint64_t offset;
8 | if (val_size == 0) {
9 | return -1;
10 | }
11 | if (val_size >= 32) {
12 | offset = 0;
13 | slots = index * ((val_size + 31)/ 32);
14 | } else {
15 | uint64_t per_slot = (32 / val_size);
16 | slots = index / per_slot;
17 | offset = index % per_slot;
18 | }
19 | memcpy(slot_out, base, 32);
20 | bebi32_add_u64(slot_out, slots);
21 | if (offset_out != NULL) {
22 | *offset_out = offset;
23 | }
24 | return 0;
25 | }
26 |
27 | void dynamic_array_base_slot(bebi32 const storage, bebi32 base_out) {
28 | native_keccak256(storage, 32, base_out);
29 | }
30 |
31 | void map_slot(bebi32 const storage, uint8_t const *key, size_t key_len, bebi32 slot_out) {
32 | uint8_t buf[32 + key_len];
33 | memcpy(buf, key, key_len);
34 | memcpy(buf+key_len, storage, 32);
35 | native_keccak256(buf, 32 + key_len, slot_out);
36 | }
37 |
38 |
--------------------------------------------------------------------------------
/src/utils.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 |
5 | extern inline void msg_sender_padded(bebi sender);
6 |
7 | extern ArbResult inline _return_nodata(ArbStatus status);
8 |
9 | ArbResult _return_short_string(ArbStatus status, char *string) {
10 | static uint8_t buf_out[100];
11 | size_t len = strlen(string);
12 | if (len > 32) {
13 | len = 32;
14 | }
15 | uint8_t* strlen_out = buf_out+36;
16 | char *str_out = (char *)(buf_out + 68);
17 | bebi32_set_u64(strlen_out, len);
18 | strncpy(str_out, string, 32);
19 | // Tuple encoding: offset, strlen, str
20 | bebi32_set_u64(buf_out + 4, 32);
21 | if (status == Failure) {
22 | // Err encoding: ErrSignature
23 | bebi_set_u32(buf_out, 0, 0x08c379a0);
24 | ArbResult res = {Failure, buf_out, 100};
25 | return res;
26 | }
27 | ArbResult res = {status, buf_out+4, 96};
28 | return res;
29 | }
30 |
--------------------------------------------------------------------------------