Author SHA1 Message Date
zjkree b4e723fd2c Minimal working example. Can run programs in CL. 2024-12-25 08:59:48 +01:00
zjkree 73f3bca656 Make some progress on ASTs. 2024-12-24 07:05:17 +01:00
zjkree ae908ee23d Offchain scaffolding. 2024-12-24 06:32:46 +01:00
18 changed files with 5527 additions and 309 deletions
+1
View File
@@ -0,0 +1 @@
use flake
+4 -3
View File
@@ -1,5 +1,6 @@
onchain/cache/
onchain/out/
out/
cache/
lib/forge-std
offchain/target/
.direnv
-47
View File
@@ -1,47 +0,0 @@
me: Bounty
about: Bounty
title: ''
labels: bounty
assignees: ''
---
# Bounty
## Scope
<!-- A list of specific things which should be done to deliver the bounty. These could be seen as requirements to verify/review bounty against -->
-
-
-
## Deliverables
<!-- Artifacts produced as the result of this bounty. Something that could be verified/reviewed. Some examples: updated code, deployment made, blog post published, public event conducted etc -->
-
-
## Bounty Owner/Gardener
<!-- The Role who is responsible for the bounty. -->
<@your github username> as **<Role>**
## Gain for the Role
<!-- How the completion of this bounty helps to pursue the Role's purpose -->
## Roles
bounty gardener: <@your git username> / X DAI <!-- likely shouldn't be a % but rather flat -->
bounty worker: name / share
bounty reviewer: name / share
## Gardener checklist
- [ ] I have attached one of the `size-` labels to this bounty
<!--
# Bounty sizes
XS / 200 DAI / effort ~ 3h
S / 350 DAI / effort ~5h
M / 550 DAI / effort ~8h
L / 900 DAI / effort ~13h
XL / 1400 DAI / effort ~21h
-->
+124
View File
@@ -0,0 +1,124 @@
# Interpreter.md
## Overview
This repository provides a **Push3-like interpreter** implemented in Solidity. It uses a _token-based bytecode_ approach to parse programs from a `bytes` array (the `code`) into typed **descriptors**, which are then executed by the interpreter.
**Push3** is a stack-based language originally designed for genetic programming and autoconstructive evolution. Each data type (e.g. `INT_LITERAL`, `FLOAT`, `BOOLEAN`, etc.) has its own stack. The **`EXEC`** stack manages the flow of execution.
**In this implementation**:
- We store code in a single `bytes` array (`code`).
- We parse sublists and integer literals from that array.
- We push instructions and literals onto an execution stack.
- We pop them in LIFO order and execute them.
### Key Features
1. **Token-Based Parsing**: We define small tokens (`0x00` => NOOP, `0x01` => INTEGER_PLUS, `0x02` => INT_LITERAL, `0x03` => SUBLIST). If we see `INT_LITERAL`, we read 4 bytes for a 32-bit integer; if we see `SUBLIST`, we read 2 bytes for the sublist length, then parse it recursively.
2. **Descriptor System**: We represent instructions, literals, and sublists using 256-bit “descriptors.” Each descriptor encodes:
- A `tag` (top 8 bits): e.g. `INT_LITERAL`, `INSTRUCTION`, `SUBLIST`.
- `offset` and `length` for sublists.
- A leftover field (e.g. for storing integer data).
3. **Reversing Items**: When we pop a sublist descriptor, we parse it into descriptors and then push them onto the `EXEC` stack in reverse order. This ensures the list’s leftmost token executes first, consistent with the Push3 spec.
4. **Separation of Parsing and Execution**:
- **Parsing**: Transforms raw byte tokens into typed descriptors (instructions, literals, or nested sublists).
- **Execution**: The `runInterpreter` function repeatedly pops from `EXEC`, decides if it’s an instruction or literal or sublist, and acts accordingly.
## Code Structure
### 1. **Enums**
- **`CodeTag`**:
- `NO_TAG` (unused),
- `INSTRUCTION`,
- `INT_LITERAL`,
- `SUBLIST`.
- **`OpCode`**:
- `NOOP`,
- `INTEGER_PLUS`.
### 2. **Descriptor Layout**
A **256-bit** word has:
```
[ top 8 bits | offset(32 bits) | length(32 bits) | leftover(184 bits) ]
```
- `tag`: The top 8 bits (e.g. `INT_LITERAL`).
- `offset, length`: If `tag = SUBLIST`, these define which bytes in `code` represent the sub-sublists.
- `leftover`: If `tag = INT_LITERAL`, we store the 32-bit integer in the bottom 32 bits of leftover. If `tag = INSTRUCTION`, we store the opcode (`NOOP`, `INTEGER_PLUS`) in the lowest 8 bits of leftover.
### 3. **Helper Reads**
- **`readUint32(code, start)`**: Copies 4 bytes from calldata into a small buffer, returns the final `uint32`. By shifting bits if needed, we ensure we get the integer from the correct part of the loaded word.
- **`readUint16(code, start)`**: Similar logic for 2 bytes.
### 4. **`parseSublist` Function**
When we see a sublist descriptor (`tag=SUBLIST`), we parse the slice `[off..off+len]` in the `bytes code`. We iterate token by token:
- `0x00` => `NOOP`
- `0x01` => `INTEGER_PLUS`
- `0x02` => read 4 bytes => `INT_LITERAL`
- `0x03` => read 2 bytes => sub-sublist length => build a sub-descriptor
We accumulate these descriptors in an array. Then, later, we push them _in reverse_ onto the `EXEC` stack.
### 5. **`runInterpreter` Function**
1. Loads initial CODE, EXEC, and INT stacks from the provided arrays.
2. While `EXEC` is non-empty:
- Pop the top descriptor.
- If `INSTRUCTION`, decode the opcode (e.g. `INTEGER_PLUS`) and do it (pop top 2 ints, push their sum).
- If `INT_LITERAL`, push that integer onto the int stack.
- If `SUBLIST`, parse that sublist into descriptors, then push those in reverse.
## How to Contribute
1. **Add New Instructions**
- Expand `OpCode` enum (e.g. `INTEGER_MINUS`, `INTEGER_MUL`, etc.).
- Write a `makeInstruction` or `makeIntLiteral` function to build the descriptor for it.
- In the main loop, implement the logic (pop the correct number of integers, do the operation, push the result).
2. **Support More Data Types**
- For instance, a `FLOAT` or `BOOLEAN` stack.
- Add a new tag (`FLOAT_LITERAL`?), new instructions (`FLOAT.PLUS`?), etc.
3. **Improve Parsing**
- If you want 256-bit literals, define a new token that reads 32 bytes, or do other expansions (like `CODE` type).
- Or define advanced sublist structures (like nested `( ( ) )` expansions).
4. **Gas Optimization**
- Check how large arrays are allocated (like in `parseSublist`).
- Possibly implement step-by-step execution if large code exceeds block gas limits.
5. **Add Logging & Debug Tools**
- Use `console.log(...)` to trace tokens, track final states, or measure performance.
6. **Test Coverage**
- Provide more unit tests in Foundry for advanced instructions, nested sublists, edge cases with zero-length sublists, etc.
## Next Steps
### A. Extending the VM
A “full” Push3 VM might include:
- **Multiple Data Stacks**: `BOOLEAN`, `FLOAT`, `NAME`, etc.
- **NAME Binding**: Let `NAME`s reference values or code.
- **Control Structures**: `EXEC.IF`, `EXEC.DO*COUNT`, or combinators like `EXEC.Y`.
### B. Example Project
You could use this interpreter in:
- A genetic programming environment, where random code is generated and mutated.
- A puzzle solver that runs tiny “scripts” in EVM-like constraints.
## Conclusion
This `Push3Interpreter` is a **minimal** scaffold for a token-based, list-expanding interpreter with typed descriptors. By following the patterns for instructions, sublists, and typed stacks, you can easily expand it into a more complete VM. We welcome contributions in the form of new instructions, data types, and performance optimizations.
1. **Clone** this repo.
2. **Check** the `test/` folder for Foundry-based tests.
3. **Add** or modify instructions & sublists in `parseSublist` and `runInterpreter`.
4. **Run** `forge test --via-ir -vv` to see logs and confirm your changes.
Enjoy exploring the **Push3** style VM in Solidity!
+9 -95
View File
@@ -1,14 +1,6 @@
# **SoLUSH**: A Push 3 Virtual Machine in Solidity
Welcome to **SoLUSH 3** (pronounced like **"slush"** without the "o", composed from **S**o**L**idity and p**USH** 3), a **Push3-like interpreter** implemented in Solidity. It uses a _token-based bytecode_ approach to parse programs from a `bytes` array (the `code`) into typed **descriptors**, which are then executed by the interpreter.
**Push3** is a stack-based language originally designed for genetic programming and autoconstructive evolution. Each data type (e.g. `INT_LITERAL`, `FLOAT`, `BOOLEAN`, etc.) has its own stack. The **`EXEC`** stack manages the flow of execution.
**In this implementation**:
- We store code in a single `bytes` array (`code`).
- We parse sublists and integer literals from that array.
- We push instructions and literals onto an execution stack.
- We pop them in LIFO order and execute them.
Welcome to **SoLUSH 3** (pronounced like **"slush"** without the "o", composed from **S**o**L**idity and p**USH** 3), a Solidity implementation of the [Push 3 stack machine](http://faculty.hampshire.edu/lspector/push3-description.html), designed to bring evolved genetic algorithms on-chain. By enabling the execution of Push 3 programs directly within Ethereum smart contracts, SoLush 3 paves the way for decentralized, adaptive systems to address complex optimization problems.
## 🌟 Vision
@@ -20,97 +12,19 @@ SoLUSH is a key step toward realizing the vision of running decentralized evolut
To understand the broader vision, check out the [Vision Document](vision.md).
### Key Features
1. **Token-Based Parsing**: We define small tokens (`0x00` => NOOP, `0x01` => INTEGER_PLUS, `0x02` => INT_LITERAL, `0x03` => SUBLIST). If we see `INT_LITERAL`, we read 4 bytes for a 32-bit integer; if we see `SUBLIST`, we read 2 bytes for the sublist length, then parse it recursively.
2. **Descriptor System**: We represent instructions, literals, and sublists using 256-bit “descriptors.” Each descriptor encodes:
- A `tag` (top 8 bits): e.g. `INT_LITERAL`, `INSTRUCTION`, `SUBLIST`.
- `offset` and `length` for sublists.
- A leftover field (e.g. for storing integer data).
3. **Reversing Items**: When we pop a sublist descriptor, we parse it into descriptors and then push them onto the `EXEC` stack in reverse order. This ensures the list’s leftmost token executes first, consistent with the Push3 spec.
4. **Separation of Parsing and Execution**:
- **Parsing**: Transforms raw byte tokens into typed descriptors (instructions, literals, or nested sublists).
- **Execution**: The `runInterpreter` function repeatedly pops from `EXEC`, decides if it’s an instruction or literal or sublist, and acts accordingly.
## Code Structure
### 1. **Enums**
- **`CodeTag`**:
- `NO_TAG` (unused),
- `INSTRUCTION`,
- `INT_LITERAL`,
- `SUBLIST`.
- **`OpCode`**:
- `NOOP`,
- `INTEGER_PLUS`.
### 2. **Descriptor Layout**
A **256-bit** word has:
```
[ top 8 bits | offset(32 bits) | length(32 bits) | leftover(184 bits) ]
```
- `tag`: The top 8 bits (e.g. `INT_LITERAL`).
- `offset, length`: If `tag = SUBLIST`, these define which bytes in `code` represent the sub-sublists.
- `leftover`: If `tag = INT_LITERAL`, we store the 32-bit integer in the bottom 32 bits of leftover. If `tag = INSTRUCTION`, we store the opcode (`NOOP`, `INTEGER_PLUS`) in the lowest 8 bits of leftover.
### 3. **Helper Reads**
- **`readUint32(code, start)`**: Copies 4 bytes from calldata into a small buffer, returns the final `uint32`. By shifting bits if needed, we ensure we get the integer from the correct part of the loaded word.
- **`readUint16(code, start)`**: Similar logic for 2 bytes.
### 4. **`parseSublist` Function**
When we see a sublist descriptor (`tag=SUBLIST`), we parse the slice `[off..off+len]` in the `bytes code`. We iterate token by token:
- `0x00` => `NOOP`
- `0x01` => `INTEGER_PLUS`
- `0x02` => read 4 bytes => `INT_LITERAL`
- `0x03` => read 2 bytes => sub-sublist length => build a sub-descriptor
We accumulate these descriptors in an array. Then, later, we push them _in reverse_ onto the `EXEC` stack.
### 5. **`runInterpreter` Function**
1. Loads initial CODE, EXEC, and INT stacks from the provided arrays.
2. While `EXEC` is non-empty:
- Pop the top descriptor.
- If `INSTRUCTION`, decode the opcode (e.g. `INTEGER_PLUS`) and do it (pop top 2 ints, push their sum).
- If `INT_LITERAL`, push that integer onto the int stack.
- If `SUBLIST`, parse that sublist into descriptors, then push those in reverse.
## Next Steps
### A. Extending the VM
A “full” Push3 VM might include:
- **Multiple Data Stacks**: `BOOLEAN`, `FLOAT`, `NAME`, etc.
- **NAME Binding**: Let `NAME`s reference values or code.
- **Control Structures**: `EXEC.IF`, `EXEC.DO*COUNT`, or combinators like `EXEC.Y`.
### B. Example Project
You could use this interpreter in:
- A genetic programming environment, where random code is generated and mutated.
- A puzzle solver that runs tiny “scripts” in EVM-like constraints.
## 🚀 Getting Started
This `Push3Interpreter` is a **minimal** scaffold for a token-based, list-expanding interpreter with typed descriptors. By following the patterns for instructions, sublists, and typed stacks, you can easily expand it into a more complete VM. We welcome contributions in the form of new instructions, data types, and performance optimizations.
SoLUSH 3 is in active development. To contribute or test the functionality, follow these steps:
1. **Clone** this repo.
2. **Check** the `test/` folder for Foundry-based tests.
3. **Add** or modify instructions & sublists in `parseSublist` and `runInterpreter`.
4. **Run** `forge test --via-ir -vv` to see logs and confirm your changes.
1. Clone the repository:
```bash
git clone https://github.com/your-username/SoLUSH.git
cd SoLUSH
```
2. Install dependencies (if applicable).
3. Review the examples and test cases to understand how Push 3 programs are executed on the VM.
### How to contribute
Check the [Issues](../../../issues) section to find tasks to tackle.
## 🛠️ Roadmap
- **Core Features:**
+3
View File
@@ -23,6 +23,9 @@
# ... any other dependencies we need
solc
cargo
rustc
rust-analyzer
];
# Decorative prompt override so we know when we're in a dev shell
+4627
View File
File diff suppressed because it is too large Load Diff
+18
View File
@@ -0,0 +1,18 @@
[package]
name = "offchain"
version = "0.1.0"
edition = "2021"
[dependencies]
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
rand = "0.8"
hex = "0.4"
# ethers = { version = "2.0", features = ["abi"] }
anyhow = "1.0"
revm = { git = "https://github.com/bluealloy/revm.git", rev = "03ea24bd9550e93b08f343e0b410725557c1adb4", features = ["std"] }
database = { git = "https://github.com/bluealloy/revm.git", rev = "03ea24bd9550e93b08f343e0b410725557c1adb4", package = "revm-database" }
ethers = "2.0"
+530
View File
@@ -0,0 +1,530 @@
// pub trait Push3Ast {
// /// Convert this AST into a bytecode array (Push3 tokens).
// fn to_bytecode(&self) -> Vec<u8>;
// // Parse an AST from bytecode (the "decompiler"), if possible.
// // Possibly returns a Result in case of partial/invalid parse.
// // fn from_bytecode(data: &[u8]) -> Self
// // where
// // Self: Sized;
// // Randomly mutate this AST in-place (GP mutation).
// // fn mutate(&mut self, rng: &mut impl rand::Rng);
// // Possibly a "crossover" method, or we do it externally.
// // fn crossover(&self, other: &Self, rng: &mut impl rand::Rng) -> Self;
// // Evaluate the AST with some input(s).
// // Optionally do we want this or do we always run in EVM?
// // We can stub it or do an interpret approach for local test.
// // fn interpret_locally(&self, inputs: &[i32]) -> Vec<i32>;
// }
// #[derive(Debug, Clone)]
// pub enum TypedAst {
// IntLiteral(i32),
// Instruction(InstructionKind),
// }
// #[derive(Debug, Clone)]
// pub enum InstructionKind {
// Plus(Box<TypedAst>, Box<TypedAst>),
// Minus(Box<TypedAst>, Box<TypedAst>),
// Mult(Box<TypedAst>, Box<TypedAst>),
// Dup, // 0 children
// Pop, // 0 children
// }
// impl Push3Ast for TypedAst {
// fn to_bytecode(&self) -> Vec<u8> {
// // do typed encoding:
// // - for Plus(e1, e2): e1 -> bytecode, e2 -> bytecode, then PLUS opcode
// unimplemented!()
// }
// // fn from_bytecode(data: &[u8]) -> Self {
// // // parse in a strictly typed manner; might fail or panic
// // // if the code doesn't line up properly
// // unimplemented!()
// // }
// // fn mutate(&mut self, rng: &mut impl rand::Rng) {
// // // e.g. randomly pick a node, replace it with something
// // // that respects the typed structure
// // unimplemented!()
// // }
// // fn interpret_locally(&self, inputs: &[i32]) -> Vec<i32> {
// // // do a normal expression evaluation. If a node is "Plus(a,b)",
// // // interpret (a) + interpret(b).
// // unimplemented!()
// // }
// }
// #[derive(Debug, Clone)]
// pub enum UntypedAst {
// /// A single token in a list-based approach, e.g. "Integer literal"
// IntLiteral(i32),
// /// "Instruction" might be a simple variant with no children,
// /// because the stack-based evaluation decides how many arguments it consumes.
// Instruction(OpCode),
// /// A sublist of tokens, e.g. "( 2 3 DUP + )"
// Sublist(Vec<UntypedAst>),
// }
// /// Possibly an enum for OpCode:
// #[derive(Debug, Clone)]
// pub enum OpCode {
// Noop,
// Plus,
// Minus,
// Mult,
// Dup,
// Pop,
// // maybe Unknown => treat as no-op
// }
// // impl Push3Ast for UntypedAst {
// // fn to_bytecode(&self) -> Vec<u8> {
// // // flatten out sublists vs instructions
// // unimplemented!()
// // }
// // // fn from_bytecode(data: &[u8]) -> Self {
// // // // parse "0x02 => INT_LITERAL => read next 4 bytes"
// // // // instructions might have no subchildren
// // // unimplemented!()
// // // }
// // // fn mutate(&mut self, rng: &mut impl rand::Rng) {
// // // // can randomly insert unknown tokens, reorder sublists, etc.
// // // // possibly produce "invalid ops => noops"
// // // unimplemented!()
// // // }
// // // fn interpret_locally(&self, inputs: &[i32]) -> Vec<i32> {
// // // // push-based interpretation:
// // // // sublist => interpret each item in sequence
// // // // if an instruction sees insufficient args => no-op
// // // unimplemented!()
// // // }
// // }
// use crate::compiler::ast::Push3Ast;
// /// An untyped AST node, matching your Push3 structure.
// #[derive(Debug, Clone)]
// pub enum UntypedAst {
// /// A single integer literal.
// IntLiteral(i32),
// /// A single push instruction (no subchildren).
// Instruction(OpCode),
// /// A sublist of items, each of which is another UntypedAst.
// Sublist(Vec<UntypedAst>),
// }
// /// Your Push3 opcodes in an untyped form.
// #[derive(Debug, Clone)]
// pub enum OpCode {
// Noop,
// Plus,
// Minus,
// Mult,
// Dup,
// Pop,
// }
// /// Implementation of `Push3Ast` for `UntypedAst`.
// ///
// /// This will produce **bytecode** compatible with your Solidity `Push3Interpreter`:
// ///
// /// - `0x00` => NOOP
// /// - `0x01` => INTEGER_PLUS
// /// - `0x02` => INT_LITERAL => next 4 bytes (little-endian i32)
// /// - `0x03` => SUBLIST => next 2 bytes (big-endian `u16` length), then the sublist contents
// /// - `0x04` => INTEGER_MINUS
// /// - `0x05` => INTEGER_MULT
// /// - `0x06` => INTEGER_DUP
// /// - `0x07` => INTEGER_POP
// ///
// /// In the Solidity parser, `SUBLIST (0x03)` consumes two bytes to determine
// /// how many bytes of tokens to read in that sublist.
// impl Push3Ast for UntypedAst {
// /// Convert this untyped AST into a flattened push3 bytecode sequence.
// fn to_bytecode(&self) -> Vec<u8> {
// match self {
// UntypedAst::IntLiteral(val) => {
// // 0x02 followed by 4 bytes of i32 (little-endian)
// let mut bytes = Vec::with_capacity(1 + 4);
// bytes.push(0x02);
// bytes.extend_from_slice(&val.to_le_bytes());
// bytes
// }
// UntypedAst::Instruction(op) => {
// // Single opcode byte
// let opcode_byte = match op {
// OpCode::Noop => 0x00,
// OpCode::Plus => 0x01,
// OpCode::Minus => 0x04,
// OpCode::Mult => 0x05,
// OpCode::Dup => 0x06,
// OpCode::Pop => 0x07,
// };
// vec![opcode_byte]
// }
// UntypedAst::Sublist(children) => {
// // 0x03 => SUBLIST
// // Then 2 bytes for length (big-endian u16),
// // Then the concatenated bytecode for all children.
// let mut payload = Vec::new();
// for child in children {
// let child_bytes = child.to_bytecode();
// payload.extend_from_slice(&child_bytes);
// }
// let sub_len = payload.len() as u16; // assume it fits in 65535
// let mut bytes = Vec::with_capacity(1 + 2 + payload.len());
// bytes.push(0x03);
// // Store the sublist length as big-endian, because readUint16 in solidity
// // does `val = uint16(word >> 240)` (effectively big-endian).
// bytes.extend_from_slice(&sub_len.to_be_bytes());
// // Then the actual sublist payload
// bytes.extend_from_slice(&payload);
// bytes
// }
// }
// }
// }
// #[derive(Debug, Clone, PartialEq)]
// pub enum SExpr {
// Atom(String), // e.g. "3", "DUP", "+"
// List(Vec<SExpr>), // e.g. (3 5 +)
// }
// fn tokenize(s: &str) -> Vec<String> {
// let mut tokens = Vec::new();
// let mut current = String::new();
// for c in s.chars() {
// match c {
// '(' | ')' => {
// // If we were building up an atom, push it first
// if !current.trim().is_empty() {
// tokens.push(current.trim().to_string());
// }
// current.clear();
// // Then push the single-char token
// tokens.push(c.to_string());
// }
// ' ' | '\t' | '\n' | '\r' => {
// // Whitespace => if we have an atom, finish it
// if !current.trim().is_empty() {
// tokens.push(current.trim().to_string());
// current.clear();
// }
// }
// _ => {
// // Part of an atom
// current.push(c);
// }
// }
// }
// // If something is left in 'current' at the end
// if !current.trim().is_empty() {
// tokens.push(current.trim().to_string());
// }
// tokens
// }
// fn parse_sexpr(tokens: &[String], pos: &mut usize) -> Result<SExpr, String> {
// // If we’re out of tokens, error
// if *pos >= tokens.len() {
// return Err("Unexpected end of tokens".into());
// }
// let token = &tokens[*pos];
// match token.as_str() {
// "(" => {
// // Parse a list
// *pos += 1; // consume '('
// let mut list_items = Vec::new();
// while *pos < tokens.len() && tokens[*pos] != ")" {
// let expr = parse_sexpr(tokens, pos)?;
// list_items.push(expr);
// }
// if *pos >= tokens.len() {
// return Err("Missing closing parenthesis".into());
// }
// // consume ")"
// *pos += 1;
// Ok(SExpr::List(list_items))
// }
// ")" => {
// // Should never parse_sexpr starting with ')'
// Err("Unexpected ')'".into())
// }
// _ => {
// // Atom
// let atom_str = token.clone();
// *pos += 1;
// Ok(SExpr::Atom(atom_str))
// }
// }
// }
// /// Parse an entire string into a single top-level `SExpr`.
// fn parse_string_to_sexpr(s: &str) -> Result<SExpr, String> {
// let tokens = tokenize(s);
// let mut pos = 0;
// let expr = parse_sexpr(&tokens, &mut pos)?;
// // If there's leftover tokens, optionally check
// if pos < tokens.len() {
// return Err(format!("Extra tokens after parse: {:?}", &tokens[pos..]));
// }
// Ok(expr)
// }
// fn sexpr_to_untyped(expr: &SExpr) -> Result<UntypedAst, String> {
// match expr {
// SExpr::Atom(text) => {
// // 1) try to parse as i32
// if let Ok(val) = text.parse::<i32>() {
// Ok(UntypedAst::IntLiteral(val))
// } else {
// // 2) otherwise parse as OpCode symbol
// match text.to_uppercase().as_str() {
// "+" => Ok(UntypedAst::Instruction(OpCode::Plus)),
// "-" => Ok(UntypedAst::Instruction(OpCode::Minus)),
// "*" => Ok(UntypedAst::Instruction(OpCode::Mult)),
// "DUP" => Ok(UntypedAst::Instruction(OpCode::Dup)),
// "POP" => Ok(UntypedAst::Instruction(OpCode::Pop)),
// // more opcodes ...
// _ => Ok(UntypedAst::Instruction(OpCode::Noop))
// }
// }
// }
// SExpr::List(list) => {
// // parse each child into UntypedAst
// let mut result = Vec::new();
// for child in list {
// result.push(sexpr_to_untyped(child)?);
// }
// Ok(UntypedAst::Sublist(result))
// }
// }
// }
// src/compiler/ast.rs
pub trait Push3Ast {
/// Convert this AST into a bytecode array (Push3 tokens).
fn to_bytecode(&self) -> Vec<u8>;
}
/* --------------------------------------------
1) TypedAst stubs (optional)
-------------------------------------------- */
#[derive(Debug, Clone)]
pub enum TypedAst {
IntLiteral(i32),
Instruction(InstructionKind),
}
#[derive(Debug, Clone)]
pub enum InstructionKind {
Plus(Box<TypedAst>, Box<TypedAst>),
Minus(Box<TypedAst>, Box<TypedAst>),
Mult(Box<TypedAst>, Box<TypedAst>),
Dup,
Pop,
}
// Example stub; not fully implemented
impl Push3Ast for TypedAst {
fn to_bytecode(&self) -> Vec<u8> {
unimplemented!("TypedAst::to_bytecode not yet implemented");
}
}
/* --------------------------------------------
2) UntypedAst + OpCode
-------------------------------------------- */
#[derive(Debug, Clone)]
pub enum UntypedAst {
IntLiteral(i32),
Instruction(OpCode),
Sublist(Vec<UntypedAst>),
}
#[derive(Debug, Clone)]
pub enum OpCode {
Noop,
Plus,
Minus,
Mult,
Dup,
Pop,
}
/// Implementation of `Push3Ast` for `UntypedAst`.
/// Matches the Solidity-based Push3Interpreter token IDs.
impl Push3Ast for UntypedAst {
fn to_bytecode(&self) -> Vec<u8> {
match self {
UntypedAst::IntLiteral(val) => {
// 0x02 => INT_LITERAL => next 4 bytes (little-endian i32)
let mut bytes = Vec::with_capacity(1 + 4);
bytes.push(0x02);
bytes.extend_from_slice(&val.to_be_bytes());
bytes
}
UntypedAst::Instruction(op) => {
let opcode_byte = match op {
OpCode::Noop => 0x00,
OpCode::Plus => 0x01,
OpCode::Minus => 0x04,
OpCode::Mult => 0x05,
OpCode::Dup => 0x06,
OpCode::Pop => 0x07,
};
vec![opcode_byte]
}
UntypedAst::Sublist(children) => {
// 0x03 => SUBLIST => next 2 bytes = big-endian length, then sub-payload
let mut payload = Vec::new();
for child in children {
payload.extend(child.to_bytecode());
}
let sub_len = payload.len() as u16;
let mut bytes = Vec::with_capacity(1 + 2 + payload.len());
bytes.push(0x03);
bytes.extend_from_slice(&sub_len.to_be_bytes()); // big-endian
bytes.extend_from_slice(&payload);
bytes
}
}
}
}
/* --------------------------------------------
3) S-expression parsing helpers
-------------------------------------------- */
#[derive(Debug, Clone, PartialEq)]
pub enum SExpr {
Atom(String),
List(Vec<SExpr>),
}
pub fn tokenize(s: &str) -> Vec<String> {
let mut tokens = Vec::new();
let mut current = String::new();
for c in s.chars() {
match c {
'(' | ')' => {
if !current.trim().is_empty() {
tokens.push(current.trim().to_string());
}
current.clear();
tokens.push(c.to_string());
}
' ' | '\t' | '\n' | '\r' => {
if !current.trim().is_empty() {
tokens.push(current.trim().to_string());
current.clear();
}
}
_ => {
current.push(c);
}
}
}
if !current.trim().is_empty() {
tokens.push(current.trim().to_string());
}
tokens
}
fn parse_sexpr_internal(tokens: &[String], pos: &mut usize) -> Result<SExpr, String> {
if *pos >= tokens.len() {
return Err("Unexpected end of tokens".into());
}
let token = &tokens[*pos];
match token.as_str() {
"(" => {
*pos += 1; // consume '('
let mut items = Vec::new();
while *pos < tokens.len() && tokens[*pos] != ")" {
let expr = parse_sexpr_internal(tokens, pos)?;
items.push(expr);
}
if *pos >= tokens.len() {
return Err("Missing closing parenthesis".into());
}
*pos += 1; // consume ')'
Ok(SExpr::List(items))
}
")" => {
Err("Unexpected ')'".into())
}
_ => {
let atom = token.clone();
*pos += 1;
Ok(SExpr::Atom(atom))
}
}
}
/// Parse an entire string into a single top-level `SExpr`.
pub fn parse_string_to_sexpr(s: &str) -> Result<SExpr, String> {
let tokens = tokenize(s);
let mut pos = 0;
let expr = parse_sexpr_internal(&tokens, &mut pos)?;
if pos < tokens.len() {
return Err(format!("Extra tokens after parse: {:?}", &tokens[pos..]));
}
Ok(expr)
}
/// Convert an SExpr => UntypedAst
pub fn sexpr_to_untyped(expr: &SExpr) -> Result<UntypedAst, String> {
match expr {
SExpr::Atom(text) => {
if let Ok(val) = text.parse::<i32>() {
Ok(UntypedAst::IntLiteral(val))
} else {
match text.to_uppercase().as_str() {
"+" => Ok(UntypedAst::Instruction(OpCode::Plus)),
"-" => Ok(UntypedAst::Instruction(OpCode::Minus)),
"*" => Ok(UntypedAst::Instruction(OpCode::Mult)),
"DUP" => Ok(UntypedAst::Instruction(OpCode::Dup)),
"POP" => Ok(UntypedAst::Instruction(OpCode::Pop)),
_ => Ok(UntypedAst::Instruction(OpCode::Noop)),
}
}
}
SExpr::List(items) => {
let mut sub_asts = Vec::new();
for child in items {
sub_asts.push(sexpr_to_untyped(child)?);
}
Ok(UntypedAst::Sublist(sub_asts))
}
}
}
+1
View File
@@ -0,0 +1 @@
pub mod ast;
+1
View File
@@ -0,0 +1 @@
pub mod revm_runner;
+10
View File
@@ -0,0 +1,10 @@
// use crate::compiler::ast::{Expr};
// pub fn crossover(a: &Expr, b: &Expr) -> (Expr, Expr) {
// // stub
// (a.clone(), b.clone())
// }
// pub fn mutate(expr: &mut Expr) {
// // stub
// }
+13
View File
@@ -0,0 +1,13 @@
pub mod population;
pub mod genetic_ops;
// pub mod fitness;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_dummy() {
assert_eq!(2+2, 4);
}
}
+9
View File
@@ -0,0 +1,9 @@
#[derive(Debug, Clone)]
pub struct Individual {
pub fitness: f64,
// your Expr or bytecode or both
}
pub struct Population {
pub individuals: Vec<Individual>,
}
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -43,7 +43,7 @@ contract Push3InterpreterTest is Test {
// [9..12] = 0x00000020 => 32
// [13] = 0x01 => plus
bytes memory code = hex"03000B020000000A020000002001";
bytes memory code = hex"03000B020000000A020000002001";
// Or fully concatenated:
// 0x03 00 0B 02 00 00 00 0A 02 00 00 00 20 01
-163
View File
@@ -1,163 +0,0 @@
# Home of Dumplings / \$DPL Tokenomics
## 1. Overview
The Home of Dumplings protocol deploys AI agents that solve optimization problems for DeFi users and protocols, addressing tasks such as liquidity management and parameter tuning. The ecosystem operates through **Tasks** hosted on-chain and populations of solution programs evolved off-chain by the Optimizer Pool.
**\$DPL** is the native token powering this ecosystem. Its primary roles include:
1. **Payment**: Clients pay invocation or subscription fees in \$DPL.
2. **Staking and Governance**: Token holders stake \$DPL to secure the protocol, join the optimizer pool or participate in governance.
3. **Rewards**: Optimizer Pool nodes earn \$DPL for validated contributions to the evolution of programs.
---
## 2. Token Supply and Distribution
### Fixed Supply
- **Total Supply**: \$DPL has a fixed supply (e.g., 100M tokens), minted at genesis.
- **No Inflation**: No further token minting or emission beyond the initial allocation.
### Allocation of Supply
1. **Uniswap V3 Liquidity Pool**
- All of the supply is allocated to a Uniswap V3 liquidity pool over a wide price range.
- Multiple price ranges hold extra liquidity to ensure stable price discovery.
2. **Team**
- A vesting contract purchases a small portion (e.g., 10-15%) of the cheapest tokens from the pool right after deployment and allocates them to the team.
3. **Treasury**
- An NFT minting contract purchases a small portion (e.g., 5-10%) right after the vesting contract before other buyers come in. The tokens are packaged into nice-looking NFTs.
- These NFTs are sold on marketplaces like OpenSea, redeemable for tokens. The proceeds are transferred to the team multisig, forming the treasury.
---
## 3. Revenue Model
### Fee Structure
1. **Invocation Fees**
- Charged for AI agents evolved with synthetic data.
- Paid in \$DPL or other currencies auto-converted into \$DPL and routed to the protocol reward pools.
2. **Subscription Fees**
- Charged for AI agents evolved with synthetic data initially, but are continuously improved by backtesting with real data.
- Periodic payment in \$DPL or other currencies auto-converted into \$DPL and routed to the protocol reward pools.
### Reward Allocation
- A portion of the fees collected funds rewards for the Optimizer Pool nodes that contribute validated solutions to Tasks.
- Governance determines the exact split between:
- Optimizer Pool rewards.
- Treasury for operational funding.
- Potential staking rewards.
---
## 4. Staking
### Types of Stakers
1. **Council Node Stakers**
- Nodes in the Optimizer Pool stake \$DPL to become eligible for selection to the Council.
- Council members validate and vote on improved solutions to Tasks.
- **Slashing Mechanism**: If a Council member votes against the majority decision, they are penalized by slashing a portion of their staked tokens.
2. **Investor Stakers**
- Investors stake \$DPL to earn a share of the protocol’s revenue.
- Revenue is comprised of invocation and subscription fees, a part is distributed as staking rewards.
### Risk Backstop
- Stakers collectively backstop potential risks associated with the AI agents.
- If an AI agent malfunctions (e.g., outputs suboptimal or incorrect decisions due to flaws in the algorithm), affected users may be compensated via the staking pool, reducing the system’s reputational and financial risk.
- Governance defines the conditions for such compensations, ensuring fairness and transparency.
---
## 5. Governance
Voting weight is proportional to the amount of \$DPL staked.
### Governance Mechanics
1. **Voting Rights**
- All stakers can participate in governance, regardless of whether they are nodes or investors.
- Proposals focus on:
- Adjusting fee parameters (e.g., invocation and subscription fees).
- Allocating Optimizer Pool rewards.
- Defining compensation rules for Risk Backstop events.
2. **Council Randomness**
- Optimizer Pool nodes with staked \$DPL can be selected for the Council via a verifiable random selection process.
- The Council validates and votes on improved solutions to Tasks.
---
## 6. NFT-Based Early Bird Mechanism
1. **Purpose**
- Raise initial funding and incentivize early supporters.
2. **Mechanics**
- NFTs represent the right to claim a specified quantity of \$DPL at a discounted rate.
- Sold on marketplaces like OpenSea.
3. **Redemption**
- Upon redemption, the NFT is burned, and the holder receives their allocated \$DPL.
- Vesting or time locks may apply to align with protocol growth.
---
## 7. Fee Usage and Distribution
- **Optimizer Pool Rewards**: A fraction of collected fees funds rewards for Optimizer Pool nodes.
- **Treasury**: Supports operations, development, and marketing initiatives.
- **Stakers**: Receive a share of fees as staking rewards, subject to governance decisions.
---
## 8. Launch and Go-to-Market Strategy
### Initial Liquidity Deployment
- Deploy a majority of \$DPL supply into Uniswap V3 pools.
- Use multiple concentrated price ranges to establish liquidity depth and facilitate market stability.
### Early Bird NFT Sale
- Launch a curated NFT collection for discounted \$DPL rights.
- Drive initial funding and engage early adopters.
### Target Customers
- Position DeFi protocols as key customers for SoLUSH’s optimization services.
- Focus marketing on showcasing cost-saving and performance-enhancing use cases.
---
## 9. Conclusion
The \$DPL tokenomics framework is designed to:
- Provide immediate utility through payment and staking mechanisms.
- Incentivize Optimizer Pool participation via rewards for validated solutions.
- Ensure sustainable growth through fixed supply, governance, and clear fee allocation.
This structure ensures the long-term viability and scalability of the SoLUSH ecosystem, while fostering community involvement and alignment with protocol goals.