Skip to content

Commit

Permalink
feat: Add contracts table and UDF
Browse files Browse the repository at this point in the history
  • Loading branch information
WillPapper committed Jan 5, 2025
1 parent c147077 commit cff0e13
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ hex = "0.4.3"
# That said, it's not ideal for all scenarios and in particular, generic
# libraries built around `rusqlite` should probably not enable it, which
# is why it is not a default feature -- it could become hard to disable.
rusqlite = { version = "0.32", features = ["bundled"] }
rusqlite = { version = "0.32", features = ["bundled", "functions"] }
serde = { version = "1.0", features = ["derive"] }
strum = { version = "0.26", features = ["derive", "std"] }
thiserror = "2.0.9"
Expand Down
29 changes: 29 additions & 0 deletions src/sqlite.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,20 @@ fn main() -> Result<(), DatabaseError> {

fn initialize_db() -> Result<Connection, DatabaseError> {
let conn = Connection::open_in_memory()?;

// Register custom functions first
conn.create_scalar_function(
"derive_contract_address",
1,
rusqlite::functions::FunctionFlags::SQLITE_DETERMINISTIC,
|ctx| {
let transaction_id: i64 = ctx.get::<i64>(0)?;
// Example: Create a deterministic address from transaction_id
let mut address = [0u8; 20];
address[0..8].copy_from_slice(&transaction_id.to_le_bytes());
Ok(address.to_vec())
}
)?;

// Change ID to use the ID from the smart contract once written
// For now we'll auto-increment for testing purposes, but later on we'll use
Expand Down Expand Up @@ -120,6 +134,21 @@ fn initialize_db() -> Result<Connection, DatabaseError> {
(),
)?;

// Create a trigger to automatically create a new contract when a
// TransactionType of CreateToken is inserted. Uses a custom function to
// derive the contract address from the transaction ID
// Down the road, this can be updated with a salt so that the contract is
// synced with CREATE2
conn.execute(
"CREATE TRIGGER create_contract_trigger AFTER INSERT ON transactions
WHEN NEW.transaction_type = 'CreateToken'
BEGIN
INSERT INTO contracts (address, signers, transaction_id)
VALUES (derive_contract_address(NEW.id), NEW.sender, NEW.id);
END",
(),
)?;

Ok(conn)
}

Expand Down

0 comments on commit cff0e13

Please sign in to comment.