Skip to content

Commit

Permalink
feat!: moving compute_selector to FunctionSelector (AztecProtocol…
Browse files Browse the repository at this point in the history
  • Loading branch information
benesjan authored Jan 3, 2024
1 parent df581f0 commit bbaebf4
Show file tree
Hide file tree
Showing 31 changed files with 204 additions and 163 deletions.
12 changes: 7 additions & 5 deletions boxes/token/src/contracts/src/main.nr
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,11 @@ contract Token {
bool_serialization::{BoolSerializationMethods, BOOL_SERIALIZED_LEN},
address_serialization::{AddressSerializationMethods, AZTEC_ADDRESS_SERIALIZED_LEN},
},
selector::compute_selector,
};
use dep::protocol_types::address::AztecAddress;
use dep::protocol_types::{
abis::function_selector::FunctionSelector,
address::AztecAddress,
};

// docs:start:import_authwit
use dep::authwit::{
Expand Down Expand Up @@ -123,7 +125,7 @@ contract Token {
// docs:start:constructor
#[aztec(private)]
fn constructor(admin: AztecAddress) {
let selector = compute_selector("_initialize((Field))");
let selector = FunctionSelector::from_signature("_initialize((Field))");
context.call_public_function(context.this_address(), selector, [admin.to_field()]);
}
// docs:end:constructor
Expand Down Expand Up @@ -268,7 +270,7 @@ contract Token {

storage.balances.at(from).sub(SafeU120::new(amount));

let selector = compute_selector("_increase_public_balance((Field),Field)");
let selector = FunctionSelector::from_signature("_increase_public_balance((Field),Field)");
let _void = context.call_public_function(context.this_address(), selector, [to.to_field(), amount]);
}
// docs:end:unshield
Expand Down Expand Up @@ -303,7 +305,7 @@ contract Token {

storage.balances.at(from).sub(SafeU120::new(amount));

let selector = compute_selector("_reduce_total_supply(Field)");
let selector = FunctionSelector::from_signature("_reduce_total_supply(Field)");
let _void = context.call_public_function(context.this_address(), selector, [amount]);
}
// docs:end:burn
Expand Down
1 change: 0 additions & 1 deletion docs/docs/dev_docs/contracts/syntax/functions.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,6 @@ Oracles introduce **non-determinism** into a circuit, and thus are `unconstraine

### A few useful inbuilt oracles

- [`compute_selector`](https://github.com/AztecProtocol/aztec-packages/blob/master/yarn-project/aztec-nr/aztec/src/selector.nr) - Computes the selector of a function. This is useful for when you want to call a function from within a circuit, but don't have an interface at hand and don't want to hardcode the selector in hex.
- [`debug_log`](https://github.com/AztecProtocol/aztec-packages/blob/master/yarn-project/aztec-nr/aztec/src/oracle/debug_log.nr) - Provides a couple of debug functions that can be used to log information to the console.
- [`auth_witness`](https://github.com/AztecProtocol/aztec-packages/blob/master/yarn-project/aztec-nr/authwit/src/auth_witness.nr) - Provides a way to fetch the authentication witness for a given address. This is useful when building account contracts to support approve-like functionality.
- [`get_l1_to_l2_message`](https://github.com/AztecProtocol/aztec-packages/blob/master/yarn-project/aztec-nr/aztec/src/oracle/get_l1_to_l2_message.nr) - Useful for application that receive messages from L1 to be consumed on L2, such as token bridges or other cross-chain applications.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ We are using various utils within the Aztec library:

* `context` - exposes things such as the contract address, msg_sender, etc
* `oracle::get_secret_key` - get your secret key to help us create a randomized nullifier
* `selector::compute_selector` - compute a function selector so we can call functions from other functions
* `FunctionSelector::from_signature` - compute a function selector from signature so we can call functions from other functions
* `state_vars::{ map::Map, public_state::PublicState, }` - we will use a Map to store the votes (key = voteId, value = number of votes), and PublicState to hold our public values that we mentioned earlier
* `types::type_serialization::{..}` - various serialization methods for defining how to use these types
* `types::address::{AztecAddress},` - our admin will be held as an address
Expand Down Expand Up @@ -113,7 +113,7 @@ Therefore our constructor must call a public function by using `context.call_pub

`context.call_public_function()` takes three arguments:
1. The contract address whose method we want to call
2. The selector of the function to call (we can use `compute_selector()` for this)
2. The selector of the function to call (we can use `FunctionSelector::from_signature(...)` for this)
3. The arguments of the function (we pass the `admin`)

We now need to write the `_initialize()` function:
Expand Down
14 changes: 9 additions & 5 deletions noir/aztec_macros/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -483,11 +483,12 @@ const SIGNATURE_PLACEHOLDER: &str = "SIGNATURE_PLACEHOLDER";

/// Generates the impl for an event selector
///
/// TODO(https://github.com/AztecProtocol/aztec-packages/issues/3590): Make this point to aztec-nr once the issue is fixed.
/// Inserts the following code:
/// ```noir
/// impl SomeStruct {
/// fn selector() -> FunctionSelector {
/// aztec::selector::compute_selector("SIGNATURE_PLACEHOLDER")
/// protocol_types::abis::function_selector::FunctionSelector::from_signature("SIGNATURE_PLACEHOLDER")
/// }
/// }
/// ```
Expand All @@ -498,15 +499,18 @@ const SIGNATURE_PLACEHOLDER: &str = "SIGNATURE_PLACEHOLDER";
fn generate_selector_impl(structure: &NoirStruct) -> TypeImpl {
let struct_type = make_type(UnresolvedTypeData::Named(path(structure.name.clone()), vec![]));

// TODO(https://github.com/AztecProtocol/aztec-packages/issues/3590): Make this point to aztec-nr once the issue is fixed.
let selector_path = chained_path!("protocol_types", "abis", "function_selector", "FunctionSelector");
let mut from_signature_path = selector_path.clone();
from_signature_path.segments.push(ident("from_signature"));

let selector_fun_body = BlockExpression(vec![make_statement(StatementKind::Expression(call(
variable_path(chained_path!("aztec", "selector", "compute_selector")),
variable_path(from_signature_path),
vec![expression(ExpressionKind::Literal(Literal::Str(SIGNATURE_PLACEHOLDER.to_string())))],
)))]);

// Define `FunctionSelector` return type
// TODO(https://github.com/AztecProtocol/aztec-packages/issues/3590): Make this point to aztec-nr once the issue is fixed.
let return_type_path = chained_path!("protocol_types", "abis", "function_selector", "FunctionSelector");
let return_type = FunctionReturnType::Ty(make_type(UnresolvedTypeData::Named(return_type_path, vec![])));
let return_type = FunctionReturnType::Ty(make_type(UnresolvedTypeData::Named(selector_path, vec![])));

let mut selector_fn_def = FunctionDefinition::normal(
&ident("selector"),
Expand Down
5 changes: 3 additions & 2 deletions noir/tooling/nargo_fmt/tests/expected/contract.nr
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
// Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
// Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
contract Benchmarking {
use dep::protocol_types::abis::function_selector::FunctionSelector;

use dep::value_note::{
utils::{increment, decrement},
value_note::{VALUE_NOTE_LEN, ValueNote, ValueNoteMethods},
Expand All @@ -11,7 +13,6 @@ contract Benchmarking {
use dep::aztec::{
context::{Context},
note::{utils as note_utils, note_getter_options::NoteGetterOptions, note_header::NoteHeader},
selector::compute_selector,
log::emit_unencrypted_log,
state_vars::{map::Map, public_state::PublicState, set::Set},
types::type_serialization::field_serialization::{FieldSerializationMethods, FIELD_SERIALIZED_LEN},
Expand Down Expand Up @@ -59,7 +60,7 @@ contract Benchmarking {
storage.balances.at(owner).write(current + value);
let _callStackItem1 = context.call_public_function(
context.this_address(),
compute_selector("broadcast(Field)"),
FunctionSelector::from_signature("broadcast(Field)"),
[owner]
);
}
Expand Down
5 changes: 3 additions & 2 deletions noir/tooling/nargo_fmt/tests/input/contract.nr
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
// Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
// Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
contract Benchmarking {
use dep::protocol_types::abis::function_selector::FunctionSelector;

use dep::value_note::{
utils::{increment, decrement},
value_note::{VALUE_NOTE_LEN, ValueNote, ValueNoteMethods},
Expand All @@ -11,7 +13,6 @@ contract Benchmarking {
use dep::aztec::{
context::{Context},
note::{utils as note_utils, note_getter_options::NoteGetterOptions, note_header::NoteHeader},
selector::compute_selector,
log::emit_unencrypted_log,
state_vars::{map::Map, public_state::PublicState, set::Set},
types::type_serialization::field_serialization::{FieldSerializationMethods, FIELD_SERIALIZED_LEN},
Expand Down Expand Up @@ -57,7 +58,7 @@ contract Benchmarking {
fn increment_balance(owner: Field, value: Field) {
let current = storage.balances.at(owner).read();
storage.balances.at(owner).write(current + value);
let _callStackItem1 = context.call_public_function(context.this_address(), compute_selector("broadcast(Field)"), [owner]);
let _callStackItem1 = context.call_public_function(context.this_address(), FunctionSelector::from_signature("broadcast(Field)"), [owner]);
}

// Est ultricies integer quis auctor elit sed. In nibh mauris cursus mattis molestie a iaculis.
Expand Down
1 change: 0 additions & 1 deletion yarn-project/aztec-nr/authwit/src/account.nr
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use dep::aztec::context::{PrivateContext, PublicContext, Context};
use dep::aztec::selector::compute_selector;
use dep::aztec::state_vars::{map::Map, public_state::PublicState};
use dep::aztec::types::type_serialization::bool_serialization::{BoolSerializationMethods,BOOL_SERIALIZED_LEN};

Expand Down
1 change: 0 additions & 1 deletion yarn-project/aztec-nr/aztec/src/lib.nr
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ mod log;
mod messaging;
mod note;
mod oracle;
mod selector;
mod state_vars;
mod types;
mod utils;
17 changes: 0 additions & 17 deletions yarn-project/aztec-nr/aztec/src/selector.nr

This file was deleted.

16 changes: 0 additions & 16 deletions yarn-project/aztec-nr/aztec/src/utils.nr
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,6 @@ pub fn arr_copy_slice<T, N, M>(src: [T; N], mut dst: [T; M], offset: Field) -> [
dst
}

pub fn field_from_bytes<N>(bytes: [u8; N], big_endian: bool) -> Field {
assert(bytes.len() as u32 < 32, "field_from_bytes: N must be less than 32");
let mut as_field = 0;
let mut offset = 1;
for i in 0..N {
let mut index = i;
if big_endian {
index = N - i - 1;
}
as_field += (bytes[index] as Field) * offset;
offset *= 256;
}

as_field
}

// TODO(#3470): Copied over from https://github.com/AztecProtocol/aztec-packages/blob/a07c4bd47313be6aa604a63f37857eb0136b41ba/yarn-project/noir-protocol-circuits/src/crates/rollup-lib/src/base/base_rollup_inputs.nr#L599
// move to a shared place?

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,10 @@ export function addNoirCompilerCommanderActions(program: Command, log: LogFn = (
.option('--artifacts <path>', 'Folder containing the compiled artifacts, relative to the project path', 'target')
.option(
'-o, --outdir <path>',
'Output folder for the generated noir interfaces, relative to the project path',
'Output folder for the generated typescript interfaces, relative to the project path',
'interfaces',
)
.description('Generates Noir interfaces from the artifacts in the given project')
.description('Generates typescript interfaces from the artifacts in the given project')

.action(async (projectPath: string, options) => {
const { generateTypescriptInterface } = await import('./generate_typescript_interface.js');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,15 @@ contract Benchmarking {
use dep::aztec::{
context::{Context},
note::{utils as note_utils, note_getter_options::NoteGetterOptions, note_header::NoteHeader},
selector::compute_selector,
log::emit_unencrypted_log,
state_vars::{map::Map, public_state::PublicState, set::Set},
types::type_serialization::field_serialization::{FieldSerializationMethods, FIELD_SERIALIZED_LEN},
};

use dep::protocol_types::address::AztecAddress;
use dep::protocol_types::{
abis::function_selector::FunctionSelector,
address::AztecAddress,
};

struct Storage {
notes: Map<Set<ValueNote, VALUE_NOTE_LEN>>,
Expand Down Expand Up @@ -66,7 +68,7 @@ contract Benchmarking {
storage.balances.at(owner.to_field()).write(current + value);
let _callStackItem1 = context.call_public_function(
context.this_address(),
compute_selector("broadcast((Field))"),
FunctionSelector::from_signature("broadcast((Field))"),
[owner.to_field()]
);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ mod game;

contract CardGame {
use dep::protocol_types::{
abis::function_selector::FunctionSelector,
address::AztecAddress,
constants::MAX_NOTES_PER_PAGE,
};
Expand Down Expand Up @@ -33,7 +34,6 @@ contract CardGame {
note_header::NoteHeader,
utils as note_utils,
},
selector::compute_selector
};

use crate::cards::{
Expand Down Expand Up @@ -128,7 +128,7 @@ contract CardGame {
collection.remove_cards(cards, player);
let mut game_deck = storage.game_decks.at(game as Field).at(player.to_field());
let _added_to_game_deck = game_deck.add_cards(cards, player);
let selector = compute_selector("on_game_joined(u32,(Field),u32)");
let selector = FunctionSelector::from_signature("on_game_joined(u32,(Field),u32)");
let strength = compute_deck_strength(cards);
context.call_public_function(
context.this_address(),
Expand Down Expand Up @@ -163,7 +163,7 @@ contract CardGame {
let mut game_deck = storage.game_decks.at(game as Field).at(player.to_field());
game_deck.remove_cards([card], player);

let selector = compute_selector("on_card_played(u32,(Field),Field)");
let selector = FunctionSelector::from_signature("on_card_played(u32,(Field),Field)");
// docs:start:call_public_function
context.call_public_function(
context.this_address(),
Expand Down Expand Up @@ -195,7 +195,7 @@ contract CardGame {
let mut collection = storage.collections.at(player.to_field());
let _inserted_cards = collection.add_cards(cards, player);

let selector = compute_selector("on_cards_claimed(u32,(Field),Field)");
let selector = FunctionSelector::from_signature("on_cards_claimed(u32,(Field),Field)");
context.call_public_function(
context.this_address(),
selector,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,14 @@ contract Child {
use dep::aztec::{
abi::CallContext,
context::{PrivateContext, PublicContext, Context},
selector::compute_selector,
log::emit_unencrypted_log,
state_vars::public_state::PublicState,
types::type_serialization::field_serialization::{FieldSerializationMethods, FIELD_SERIALIZED_LEN},
};
use dep::protocol_types::address::AztecAddress;
use dep::protocol_types::{
abis::function_selector::FunctionSelector,
address::AztecAddress,
};

struct Storage {
current_value: PublicState<Field, FIELD_SERIALIZED_LEN>,
Expand Down Expand Up @@ -93,7 +95,7 @@ contract Child {

#[aztec(public)]
fn setValueTwiceWithNestedFirst() {
let pubSetValueSelector = compute_selector("pubSetValue(Field)");
let pubSetValueSelector = FunctionSelector::from_signature("pubSetValue(Field)");
let _ret = context.call_public_function(context.this_address(), pubSetValueSelector, [10]);

storage.current_value.write(20);
Expand All @@ -105,7 +107,7 @@ contract Child {
storage.current_value.write(20);
emit_unencrypted_log(&mut context, 20);

let pubSetValueSelector = compute_selector("pubSetValue(Field)");
let pubSetValueSelector = FunctionSelector::from_signature("pubSetValue(Field)");
let _ret = context.call_public_function(context.this_address(), pubSetValueSelector, [10]);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
contract EasyPrivateVoting {
// docs:start:imports
use dep::protocol_types::{
abis::function_selector::FunctionSelector,
address::AztecAddress,
constants::EMPTY_NULLIFIED_COMMITMENT,
};
use dep::aztec::{
context::{PrivateContext, Context},
oracle::get_secret_key::get_secret_key, // used to compute nullifier
selector::compute_selector, // used to compute function selector for calling a function
state_vars::{ map::Map, public_state::PublicState,},
types::type_serialization::{ // serialization methods for using booleans and aztec addresses
bool_serialization::{BoolSerializationMethods, BOOL_SERIALIZED_LEN},
Expand Down Expand Up @@ -57,7 +57,7 @@ contract EasyPrivateVoting {
context.call_public_function(
// we cannot update public state directly from private function but we can call public function (which queues it)
context.this_address(),// contract address whose method we want to call
compute_selector("_initialize((Field))"), // function selector
FunctionSelector::from_signature("_initialize((Field))"), // function selector
[admin.to_field()] // parameters
);
}
Expand All @@ -77,7 +77,7 @@ contract EasyPrivateVoting {
context.push_new_nullifier(nullifier, EMPTY_NULLIFIED_COMMITMENT); // push nullifier
context.call_public_function(
context.this_address(),
compute_selector("add_to_tally_public(Field)"),
FunctionSelector::from_signature("add_to_tally_public(Field)"),
[candidate]
);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@
contract Escrow {
use dep::std::option::Option;

use dep::protocol_types::address::AztecAddress;
use dep::protocol_types::{
abis::function_selector::FunctionSelector,
address::AztecAddress,
};

use dep::aztec::{
context::{PrivateContext, PublicContext, Context},
Expand All @@ -12,7 +15,6 @@ contract Escrow {
utils as note_utils,
},
oracle::get_public_key::get_public_key,
selector::compute_selector,
state_vars::set::Set,
};

Expand Down Expand Up @@ -59,7 +61,7 @@ contract Escrow {
let notes = storage.owners.get_notes(options);
assert(notes[0].is_some(), "Sender is not an owner.");

let selector = compute_selector("transfer((Field),(Field),Field,Field)");
let selector = FunctionSelector::from_signature("transfer((Field),(Field),Field,Field)");
let _callStackItem = context.call_private_function(
token,
selector,
Expand Down
Loading

0 comments on commit bbaebf4

Please sign in to comment.