Chia BASIC Language Specification
Version 1.0 - A BASIC-syntax language that compiles to ChiaLisp/CLVM
Document Purpose and Structure
This specification defines Chia BASIC, a structured BASIC-syntax language that compiles to ChiaLisp/CLVM. It serves as both implementation guide and AI training reference. The design prioritizes direct mapping to ChiaLisp functionality while maintaining BASIC's readability.
1. Language Overview
1.1 Design Philosophy
- Functional Paradigm: All operations are pure functions, no mutable state
- Direct Mapping: Each BASIC construct maps clearly to ChiaLisp equivalent
- Blockchain Focus: Built-in support for cryptocurrency operations
- Type Safety: Static typing with ChiaLisp-compatible types
1.2 Compilation Target
Chia BASIC compiles directly to ChiaLisp source code, which then compiles to CLVM bytecode for execution on the Chia blockchain.
2. Lexical Structure
2.1 Keywords (Reserved Words)
AND, AS, ASSERT, BASIC, BYTES, CALL, CASE, COIN, CONDITION, CONST, DIM, ELSE, ELSEIF, END, EXIT, FALSE, FOR, FUNCTION, G1ELEMENT, G2ELEMENT, IF, INTEGER, LIST, MOD, NEXT, NIL, NOT, OR, PRIVATE, PUBLIC, PUZZLE, RETURN, SELECT, STEP, STRING, SUB, THEN, TO, TRUE, WHILE
2.2 Identifiers
- Start with letter or underscore
- Contain letters, digits, underscores
- Case insensitive
- Maximum 64 characters
2.3 Literals
' Integer literals 42 -17 0xFF00 ' Hexadecimal 0b1010 ' Binary ' String literals "Hello World" 'Single line comment ' Boolean literals TRUE FALSE ' Hex byte literals 0xDEADBEEF
3. Type System
3.1 Primitive Types
Chia BASIC Type | ChiaLisp Equivalent | Description |
---|---|---|
INTEGER |
Signed integer atom | Arbitrary precision signed integers |
BYTES |
Byte atom | Raw byte sequences, puzzle hashes |
STRING |
Byte atom (UTF-8) | Text data |
BOOLEAN |
Integer (0/1) | True/false values |
LIST |
Cons pair chain | Linked lists |
ATOM |
Atom | Generic atomic value |
G1ELEMENT |
BLS G1 point | Public keys |
G2ELEMENT |
BLS G2 point | Signatures |
3.2 Type Declarations
DIM variableName AS TypeName DIM CONST constantName AS TypeName = value
3.3 Special Types
' Condition types for blockchain operations DIM condition AS CONDITION DIM coinInfo AS COIN ' (parent_id, puzzle_hash, amount) DIM puzzleHash AS PUZZLE ' 32-byte puzzle hash
4. Program Structure
4.1 Module Declaration
MODULE ModuleName ' Module contents END MODULE
4.2 Include System
INCLUDE "condition_codes.chi" ' Maps to ChiaLisp include INCLUDE "sha256tree.chi"
4.3 Function Definition
FUNCTION FunctionName(param1 AS Type1, param2 AS Type2) AS ReturnType ' Function body FunctionName = returnValue END FUNCTION SUB SubroutineName(param1 AS Type1, param2 AS Type2) ' Subroutine body (no return value) END SUB
5. Operators and Expressions
5.1 Arithmetic Operators
+ ' Addition (maps to ChiaLisp +) - ' Subtraction (maps to ChiaLisp -) * ' Multiplication (maps to ChiaLisp *) / ' Division (maps to ChiaLisp /) MOD ' Modulo (maps to ChiaLisp divmod)
5.2 Comparison Operators
= ' Equal (maps to ChiaLisp =) <> ' Not equal (maps to ChiaLisp not =) < ' Less than (maps to ChiaLisp >s with swapped args) > ' Greater than (maps to ChiaLisp >) <= ' Less or equal >= ' Greater or equal
5.3 Logical Operators
AND ' Logical and (maps to ChiaLisp all) OR ' Logical or (maps to ChiaLisp any) NOT ' Logical not (maps to ChiaLisp not)
5.4 Bitwise Operators
BAND ' Bitwise and (maps to ChiaLisp logand) BOR ' Bitwise or (maps to ChiaLisp logior) BXOR ' Bitwise xor (maps to ChiaLisp logxor) BNOT ' Bitwise not (maps to ChiaLisp lognot) LSH ' Left shift (maps to ChiaLisp lsh) RSH ' Right shift (maps to ChiaLisp ash with negative)
6. Control Flow Statements
6.1 Conditional Statements
' Simple if-then-else (maps to ChiaLisp if) IF condition THEN statements ELSE statements END IF ' Multi-condition if IF condition1 THEN statements ELSEIF condition2 THEN statements ELSE statements END IF
6.2 Select Case Statement
' Maps to nested ChiaLisp if statements SELECT CASE expression CASE value1 statements CASE value2, value3 statements CASE ELSE statements END SELECT
6.3 Assert Statement
' Maps to ChiaLisp assert macro ASSERT condition, "Error message"
7. List Operations (ChiaLisp Core)
7.1 List Construction
DIM myList AS LIST myList = CONS(element, existingList) ' Maps to ChiaLisp c myList = LIST(elem1, elem2, elem3) ' Maps to ChiaLisp list macro
7.2 List Access
first = CAR(myList) ' Maps to ChiaLisp f (first) rest = CDR(myList) ' Maps to ChiaLisp r (rest) isEmpty = ISNIL(myList) ' Maps to ChiaLisp not length = LEN(myList) ' Maps to ChiaLisp l (list predicate)
7.3 Environment Access
' Direct environment access (ChiaLisp @ operator) value = ENV(pathNumber) ' Maps to ChiaLisp @ pathNumber
8. Built-in Functions (ChiaLisp Operators)
8.1 Cryptographic Functions
' Hash functions result = SHA256(data1, data2, ...) ' Maps to ChiaLisp sha256 result = KECCAK256(data1, data2, ...) ' Maps to ChiaLisp keccak256 result = SHA256TREE(tree) ' Maps to sha256tree library ' BLS Operations pubkey = PUBKEY_FOR_EXP(privateKey) ' Maps to ChiaLisp pubkey_for_exp result = G1_ADD(point1, point2, ...) ' Maps to ChiaLisp g1_add result = G1_MULTIPLY(point, scalar) ' Maps to ChiaLisp g1_multiply result = G2_ADD(sig1, sig2, ...) ' Maps to ChiaLisp g2_add isValid = BLS_VERIFY(sig, pubkey, msg) ' Maps to ChiaLisp bls_verify ' Coin operations coinId = COINID(parent, puzzle, amount) ' Maps to ChiaLisp coinid
8.2 String/Byte Operations
length = STRLEN(byteString) ' Maps to ChiaLisp strlen result = CONCAT(bytes1, bytes2, ...) ' Maps to ChiaLisp concat substr = SUBSTR(bytes, start, length) ' Maps to ChiaLisp substr
8.3 Program Execution
result = APPLY(program, environment) ' Maps to ChiaLisp a quoted = QUOTE(expression) ' Maps to ChiaLisp q
9. Blockchain-Specific Constructs
9.1 Condition Creation
' Create coin condition (maps to condition 51) condition = CREATE_COIN(puzzleHash, amount, memos) ' Signature conditions (maps to conditions 49/50) condition = AGG_SIG_UNSAFE(pubkey, message) condition = AGG_SIG_ME(pubkey, message) ' Assertion conditions condition = ASSERT_COIN_ANNOUNCEMENT(announcementId) condition = ASSERT_MY_COIN_ID(coinId) condition = ASSERT_HEIGHT_ABSOLUTE(height) ' Announcement conditions condition = CREATE_COIN_ANNOUNCEMENT(message) condition = CREATE_PUZZLE_ANNOUNCEMENT(message) ' Fee condition condition = RESERVE_FEE(amount)
9.2 Condition Lists
DIM conditions AS LIST conditions = NIL conditions = CONS(CREATE_COIN(hash, amount), conditions) conditions = CONS(AGG_SIG_ME(pubkey, msg), conditions)
9.3 Message Passing (CHIP-25)
' Send and receive messages condition = SEND_MESSAGE(mode, message, destination) condition = RECEIVE_MESSAGE(mode, message, source)
10. Constants and Condition Codes
10.1 Built-in Constants
' Condition codes (from condition_codes.clib) CONST CREATE_COIN = 51 CONST AGG_SIG_ME = 50 CONST AGG_SIG_UNSAFE = 49 CONST ASSERT_COIN_ANNOUNCEMENT = 61 CONST ASSERT_MY_COIN_ID = 70 CONST RESERVE_FEE = 52 ' Special values CONST NIL = 0 CONST TRUE = 1 CONST FALSE = 0
11. Error Handling
11.1 Error Termination
' Maps to ChiaLisp x operator RAISE "Error message" RAISE_ERROR("Error message") EXIT FUNCTION ' Early return with error
12. Module System and Currying
12.1 Module Definition
MODULE PuzzleName(CURRIED_PARAM1 AS Type, CURRIED_PARAM2 AS Type) ' Maps to ChiaLisp (mod (CURRIED_PARAM1 CURRIED_PARAM2 solution_params) ...) FUNCTION Main(solutionParam AS Type) AS LIST ' Main puzzle logic Main = conditions END FUNCTION END MODULE
12.2 Constants and Inline Functions
' Maps to ChiaLisp defconstant DIM CONST MAGIC_NUMBER = 42 ' Maps to ChiaLisp defun-inline INLINE FUNCTION DoubleFast(x AS INTEGER) AS INTEGER DoubleFast = x * 2 END FUNCTION ' Maps to ChiaLisp defun (regular function) FUNCTION CalculateSquare(x AS INTEGER) AS INTEGER CalculateSquare = x * x END FUNCTION
13. Standard Patterns
13.1 Puzzle Template
Basic Puzzle Structure
MODULE StandardPuzzle(PUBKEY AS G1ELEMENT) INCLUDE "condition_codes.chi" FUNCTION SpendCoin(conditions AS LIST) AS LIST DIM result AS LIST ' Add signature requirement result = CONS(AGG_SIG_ME(PUBKEY, SHA256TREE(conditions)), conditions) SpendCoin = result END FUNCTION END MODULE
13.2 Inner Puzzle Pattern
Outer Puzzle with Inner Puzzle
MODULE OuterPuzzle(INNER_PUZZLE AS PUZZLE) FUNCTION ProcessInner(innerSolution AS LIST) AS LIST DIM innerConditions AS LIST DIM wrappedConditions AS LIST ' Execute inner puzzle innerConditions = APPLY(INNER_PUZZLE, innerSolution) ' Wrap create_coin conditions wrappedConditions = WrapCreateCoins(innerConditions) ProcessInner = wrappedConditions END FUNCTION FUNCTION WrapCreateCoins(conditions AS LIST) AS LIST ' Implementation to wrap CREATE_COIN conditions ' Maps to ChiaLisp condition morphing pattern END FUNCTION END MODULE
14. Compilation Mapping
14.1 Function Compilation
FUNCTION Add(a AS INTEGER, b AS INTEGER) AS INTEGER Add = a + b END FUNCTION
(defun Add (a b) (+ a b) )
14.2 Module Compilation
MODULE SimpleWallet(PUBKEY AS G1ELEMENT) FUNCTION Spend(amount AS INTEGER, dest AS BYTES) AS LIST DIM conditions AS LIST conditions = LIST(CREATE_COIN(dest, amount), AGG_SIG_ME(PUBKEY, amount)) Spend = conditions END FUNCTION END MODULE
(mod (PUBKEY amount dest) (include condition_codes.clib) (defun Spend (amount dest) (list (list CREATE_COIN dest amount) (list AGG_SIG_ME PUBKEY amount) ) ) (Spend amount dest) )
14.3 Control Flow Compilation
IF amount > 1000 THEN result = "large" ELSE result = "small" END IF
(if (> amount 1000) "large" "small")
15. Type Conversion and Compatibility
15.1 Automatic Conversions
STRING
toBYTES
: UTF-8 encodingINTEGER
toBYTES
: Big-endian representationBOOLEAN
toINTEGER
: TRUE=1, FALSE=0
15.2 Explicit Conversion Functions
bytes = TOBYTES(integerValue) int = TOINT(byteValue) str = TOSTRING(byteValue) hex = TOHEX(byteValue)
16. Standard Library Functions
16.1 List Utilities
FUNCTION APPEND(list1 AS LIST, list2 AS LIST) AS LIST FUNCTION REVERSE(inputList AS LIST) AS LIST FUNCTION FILTER(inputList AS LIST, predicate AS FUNCTION) AS LIST FUNCTION MAP(inputList AS LIST, transform AS FUNCTION) AS LIST
16.2 Math Utilities
FUNCTION ABS(value AS INTEGER) AS INTEGER FUNCTION MIN(a AS INTEGER, b AS INTEGER) AS INTEGER FUNCTION MAX(a AS INTEGER, b AS INTEGER) AS INTEGER FUNCTION DIVMOD(dividend AS INTEGER, divisor AS INTEGER) AS LIST
17. Error Handling and Debugging
17.1 Compile-time Errors
- Type mismatches
- Undefined variables/functions
- Invalid ChiaLisp mapping
17.2 Runtime Debugging
' Debug output (removed in production) DEBUG "Variable value:", variableName TRACE "Entering function:", functionName
18. Example Programs
18.1 Simple Payment Puzzle
Basic Payment Implementation
MODULE PaymentPuzzle(RECIPIENT_HASH AS BYTES) INCLUDE "condition_codes.chi" FUNCTION MakePayment(amount AS INTEGER, signature AS G2ELEMENT) AS LIST DIM conditions AS LIST ASSERT amount > 0, "Amount must be positive" conditions = LIST( CREATE_COIN(RECIPIENT_HASH, amount), AGG_SIG_UNSAFE(RECIPIENT_HASH, amount) ) MakePayment = conditions END FUNCTION END MODULE
18.2 Multi-signature Puzzle
Multi-Signature Implementation
MODULE MultiSig(PUBKEY1 AS G1ELEMENT, PUBKEY2 AS G1ELEMENT, THRESHOLD AS INTEGER) FUNCTION AuthorizeSpend(amount AS INTEGER, dest AS BYTES, sigs AS LIST) AS LIST DIM conditions AS LIST DIM sigCount AS INTEGER sigCount = LEN(sigs) ASSERT sigCount >= THRESHOLD, "Insufficient signatures" conditions = LIST(CREATE_COIN(dest, amount)) ' Add signature requirements IF NOT ISNIL(CAR(sigs)) THEN conditions = CONS(AGG_SIG_ME(PUBKEY1, amount), conditions) END IF IF NOT ISNIL(CAR(CDR(sigs))) THEN conditions = CONS(AGG_SIG_ME(PUBKEY2, amount), conditions) END IF AuthorizeSpend = conditions END FUNCTION END MODULE
19. Implementation Notes for AI Training
19.1 Parsing Priority
- Keywords and operators are case-insensitive
- String literals preserve case and whitespace
- Comments start with ' and continue to end of line
- Block structure requires matching keywords (IF/END IF, etc.)
19.2 Semantic Analysis
- All variables must be declared before use
- Function parameters are immutable within function scope
- All functions must have explicit return type or be SUB
- Type checking enforced at compile time
19.3 Code Generation Strategy
- Each Chia BASIC construct maps to exactly one ChiaLisp pattern
- Preserve functional programming semantics throughout
- Generate readable ChiaLisp code for debugging
- Optimize for CLVM cost efficiency in final output
19.4 Standard Library Implementation
Core functions should be implemented as ChiaLisp libraries that are automatically included and provide the built-in functionality described in this specification.
Appendices
Appendix A: Reserved Word Complete List
ABS, AGG_SIG_ME, AGG_SIG_UNSAFE, AND, APPEND, APPLY, AS, ASSERT, ASSERT_COIN_ANNOUNCEMENT, ASSERT_HEIGHT_ABSOLUTE, ASSERT_MY_COIN_ID, BAND, BLS_VERIFY, BNOT, BOOLEAN, BOR, BXOR, BYTES, CAR, CASE, CDR, COINID, CONCAT, CONDITION, CONS, CONST, CREATE_COIN, CREATE_COIN_ANNOUNCEMENT, CREATE_PUZZLE_ANNOUNCEMENT, DEBUG, DIM, DIVMOD, ELSE, ELSEIF, END, ENV, EXIT, FALSE, FILTER, FOR, FUNCTION, G1_ADD, G1_MULTIPLY, G1ELEMENT, G2_ADD, G2ELEMENT, IF, INCLUDE, INLINE, INTEGER, ISNIL, KECCAK256, LEN, LIST, LSH, MAP, MAX, MIN, MOD, MODULE, NEXT, NIL, NOT, OR, PRIVATE, PUBLIC, PUBKEY_FOR_EXP, PUZZLE, QUOTE, RAISE, RAISE_ERROR, RECEIVE_MESSAGE, RESERVE_FEE, RETURN, REVERSE, RSH, SELECT, SEND_MESSAGE, SHA256, SHA256TREE, STEP, STRING, STRLEN, SUB, SUBSTR, THEN, TO, TOBYTES, TOHEX, TOINT, TOSTRING, TRACE, TRUE, WHILE
Appendix B: Operator Precedence (Highest to Lowest)
- Function calls, array access
- Unary operators (NOT, BNOT, -)
- Multiplication, division (*, /, MOD)
- Addition, subtraction (+, -)
- Bitwise shifts (LSH, RSH)
- Relational operators (<, >, <=, >=)
- Equality operators (=, <>)
- Bitwise AND (BAND)
- Bitwise XOR (BXOR)
- Bitwise OR (BOR)
- Logical AND (AND)
- Logical OR (OR)
This specification provides a complete foundation for implementing Chia BASIC as a ChiaLisp frontend, with clear mappings between BASIC constructs and their ChiaLisp equivalents, suitable for AI training and human implementation.