Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Pull noir with restricted bit sizes (WIP) #4681

Closed
wants to merge 4 commits into from
Closed
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
wip: restricting bit sizes
sirasistant committed Feb 15, 2024
commit 518ec4151111c2879ae2466ebdda34c0cebfe14a
1 change: 0 additions & 1 deletion docs/docs/developers/contracts/references/storage/main.md
Original file line number Diff line number Diff line change
@@ -59,7 +59,6 @@ type = "contract"

[dependencies]
aztec = { git="https://github.com/AztecProtocol/aztec-packages/", tag="#include_aztec_version", directory="noir-projects/aztec-nr/aztec" }
safe_math = { git="https://github.com/AztecProtocol/aztec-packages/", tag="#include_aztec_version", directory="noir-projects/aztec-nr/safe-math"}
authwit={ git="https://github.com/AztecProtocol/aztec-packages/", tag="#include_aztec_version", directory="noir-projects/aztec-nr/authwit"}
compressed_string = {git="https://github.com/AztecProtocol/aztec-packages/", tag="#include_aztec_version", directory="noir-projects/aztec-nr/compressed-string"}
```
8 changes: 0 additions & 8 deletions docs/docs/developers/contracts/resources/dependencies.md
Original file line number Diff line number Diff line change
@@ -44,14 +44,6 @@ protocol_types = { git="https://github.com/AztecProtocol/aztec-packages/", tag="

This library contains types that are used in the Aztec protocol. Find it on [GitHub](https://github.com/AztecProtocol/aztec-packages/tree/master/noir-projects/noir-protocol-circuits/src/crates/types/src).

## Safe math

```toml
safe_math = { git="https://github.com/AztecProtocol/aztec-packages/", tag="#include_aztec_version", directory="noir-projects/aztec-nr/safe-math" }
```

This is a library for safe arithmetic, similar to OpenZeppelin's safe math library. Find it on [GitHub](https://github.com/AztecProtocol/aztec-packages/tree/master/noir-projects/aztec-nr/safe-math).

## Value note

```toml
3 changes: 1 addition & 2 deletions docs/docs/developers/contracts/setup.md
Original file line number Diff line number Diff line change
@@ -57,7 +57,7 @@ Your folder should look like:

Before writing the contracts, we must add the aztec.nr library. This adds smart contract utility functions for interacting with the Aztec network.

3. Finally, add relevant aztec-nr dependencies that you might use such as `aztec.nr`, `value_note` and `safe_math` libraries.
3. Finally, add relevant aztec-nr dependencies that you might use such as `aztec.nr` and `value_note` libraries.

Open Nargo.toml that is in the `contracts/example_contract` folder, and add the dependency section as follows

@@ -74,7 +74,6 @@ aztec = { git="https://github.com/AztecProtocol/aztec-packages/", tag="#include_

# Utility dependencies
value_note = { git="https://github.com/AztecProtocol/aztec-packages/", tag="#include_aztec_version", directory="noir-projects/aztec-nr/value-note"}
safe_math = { git="https://github.com/AztecProtocol/aztec-packages/", tag="#include_aztec_version", directory="noir-projects/aztec-nr/safe-math"}
```

:::info
Original file line number Diff line number Diff line change
@@ -21,7 +21,6 @@ Then, open the `contracts/token/Nargo.toml` configuration file, and add the `azt
[dependencies]
aztec = { git="https://github.com/AztecProtocol/aztec-packages/", tag="#include_aztec_version", directory="noir-projects/aztec-nr/aztec" }
authwit = { git="https://github.com/AztecProtocol/aztec-packages/", tag="#include_aztec_version", directory="noir-projects/aztec-nr/authwit"}
safe_math = { git="https://github.com/AztecProtocol/aztec-packages/", tag="#include_aztec_version", directory="noir-projects/aztec-nr/safe-math"}
compressed_string = {git="https://github.com/AztecProtocol/aztec-packages/", tag="#include_aztec_version", directory="noir-projects/aztec-nr/compressed-string"}
```

1 change: 0 additions & 1 deletion docs/docs/developers/tutorials/writing_token_contract.md
Original file line number Diff line number Diff line change
@@ -59,7 +59,6 @@ type = "contract"

[dependencies]
aztec = { git="https://github.com/AztecProtocol/aztec-packages/", tag="#include_aztec_version", directory="noir-projects/aztec-nr/aztec" }
safe_math = { git="https://github.com/AztecProtocol/aztec-packages/", tag="#include_aztec_version", directory="noir-projects/aztec-nr/safe-math"}
authwit={ git="https://github.com/AztecProtocol/aztec-packages/", tag="#include_aztec_version", directory="noir-projects/aztec-nr/authwit"}
compressed_string = {git="https://github.com/AztecProtocol/aztec-packages/", tag="#include_aztec_version", directory="noir-projects/aztec-nr/compressed-string"}
```
1 change: 0 additions & 1 deletion noir-projects/aztec-nr/README.md
Original file line number Diff line number Diff line change
@@ -44,7 +44,6 @@ aztec = { git = "https://github.com/AztecProtocol/aztec-nr", tag = "master" , di

# Optional libraries
easy_private_state = { git = "https://github.com/AztecProtocol/aztec-nr", tag = "master" , directory = "easy-private-state" }
safe_math = { git = "https://github.com/AztecProtocol/aztec-nr", tag = "master" , directory = "safe-math" }
value_note = { git = "https://github.com/AztecProtocol/aztec-nr", tag = "master" , directory = "value-note" }
```

18 changes: 7 additions & 11 deletions noir-projects/aztec-nr/aztec/src/note/note_getter.nr
Original file line number Diff line number Diff line change
@@ -1,19 +1,15 @@
use dep::std::option::Option;
use dep::protocol_types::{
constants::{
MAX_READ_REQUESTS_PER_CALL,
GET_NOTE_ORACLE_RETURN_LENGTH,
GET_NOTES_ORACLE_RETURN_LENGTH,
MAX_NOTES_PER_PAGE,
VIEW_NOTE_ORACLE_RETURN_LENGTH,
},
MAX_READ_REQUESTS_PER_CALL, GET_NOTE_ORACLE_RETURN_LENGTH, GET_NOTES_ORACLE_RETURN_LENGTH,
MAX_NOTES_PER_PAGE, VIEW_NOTE_ORACLE_RETURN_LENGTH
}
};
use crate::context::PrivateContext;
use crate::note::{
note_getter_options::{NoteGetterOptions, Select, Sort, SortOrder, Comparator, NoteStatus},
note_interface::NoteInterface,
note_viewer_options::NoteViewerOptions,
utils::compute_note_hash_for_consumption,
note_interface::NoteInterface, note_viewer_options::NoteViewerOptions,
utils::compute_note_hash_for_consumption
};
use crate::oracle;

@@ -60,7 +56,7 @@ fn check_notes_order<N>(
for i in 0..sorts.len {
let sort = sorts.get_unchecked(i).unwrap_unchecked();
let eq = fields_0[sort.field_index] == fields_1[sort.field_index];
let lt = fields_0[sort.field_index] as u120 < fields_1[sort.field_index] as u120;
let lt = fields_0[sort.field_index].lt(fields_1[sort.field_index]);
if sort.order == SortOrder.ASC {
assert(eq | lt, "Return notes not sorted in ascending order.");
} else if !eq {
@@ -195,7 +191,7 @@ unconstrained pub fn view_notes<Note, N>(
unconstrained fn flatten_options<Note, N>(
selects: BoundedVec<Option<Select>, N>,
sorts: BoundedVec<Option<Sort>, N>
) -> (u8, [u8; N], [Field; N], [u3; N], [u8; N], [u2; N]) {
) -> (u8, [u8; N], [Field; N], [u8; N], [u8; N], [u8; N]) {
let mut num_selects = 0;
let mut select_by = [0; N];
let mut select_values = [0; N];
50 changes: 24 additions & 26 deletions noir-projects/aztec-nr/aztec/src/note/note_getter_options.nr
Original file line number Diff line number Diff line change
@@ -1,16 +1,14 @@
use dep::std::option::Option;
use dep::protocol_types::{
constants::MAX_READ_REQUESTS_PER_CALL,
};
use dep::protocol_types::{constants::MAX_READ_REQUESTS_PER_CALL};
use crate::note::note_interface::NoteInterface;

struct ComparatorEnum {
EQ: u3,
NEQ: u3,
LT: u3,
LTE: u3,
GT: u3,
GTE: u3,
EQ: u8,
NEQ: u8,
LT: u8,
LTE: u8,
GT: u8,
GTE: u8,
}

global Comparator = ComparatorEnum {
@@ -25,18 +23,18 @@ global Comparator = ComparatorEnum {
struct Select {
field_index: u8,
value: Field,
comparator: u3,
comparator: u8,
}

impl Select {
pub fn new(field_index: u8, value: Field, comparator: u3) -> Self {
pub fn new(field_index: u8, value: Field, comparator: u8) -> Self {
Select { field_index, value, comparator }
}
}

struct SortOrderEnum {
DESC: u2,
ASC: u2,
DESC: u8,
ASC: u8,
}

global SortOrder = SortOrderEnum {
@@ -46,18 +44,18 @@ global SortOrder = SortOrderEnum {

struct Sort {
field_index: u8,
order: u2,
order: u8,
}

impl Sort {
pub fn new(field_index: u8, order: u2) -> Self {
pub fn new(field_index: u8, order: u8) -> Self {
Sort { field_index, order }
}
}

struct NoteStatusEnum {
ACTIVE: u2,
ACTIVE_OR_NULLIFIED: u2,
ACTIVE: u8,
ACTIVE_OR_NULLIFIED: u8,
}

global NoteStatus = NoteStatusEnum {
@@ -81,7 +79,7 @@ struct NoteGetterOptions<Note, N, FILTER_ARGS> {
offset: u32,
filter: fn ([Option<Note>; MAX_READ_REQUESTS_PER_CALL], FILTER_ARGS) -> [Option<Note>; MAX_READ_REQUESTS_PER_CALL],
filter_args: FILTER_ARGS,
status: u2,
status: u8,
}
// docs:end:NoteGetterOptions

@@ -99,39 +97,39 @@ impl<Note, N, FILTER_ARGS> NoteGetterOptions<Note, N, FILTER_ARGS> {
offset: 0,
filter: return_all_notes,
filter_args: 0,
status: NoteStatus.ACTIVE,
status: NoteStatus.ACTIVE
}
}

// This function initializes a NoteGetterOptions with a filter, which takes the notes returned from the database and filter_args as its parameters.
// `filter_args` allows you to provide additional data or context to the custom filter.
pub fn with_filter(
filter: fn ([Option<Note>; MAX_READ_REQUESTS_PER_CALL], FILTER_ARGS) -> [Option<Note>; MAX_READ_REQUESTS_PER_CALL],
filter_args: FILTER_ARGS,
filter: fn([Option<Note>; MAX_READ_REQUESTS_PER_CALL], FILTER_ARGS) -> [Option<Note>; MAX_READ_REQUESTS_PER_CALL],
filter_args: FILTER_ARGS
) -> Self where Note: NoteInterface<N> {
NoteGetterOptions {
NoteGetterOptions {
selects: BoundedVec::new(Option::none()),
sorts: BoundedVec::new(Option::none()),
limit: MAX_READ_REQUESTS_PER_CALL as u32,
offset: 0,
filter,
filter_args,
status: NoteStatus.ACTIVE,
status: NoteStatus.ACTIVE
}
}

// This method adds a `Select` criterion to the options.
// It takes a field_index indicating which field to select,
// a value representing the specific value to match in that field, and
// a comparator (For possible values of comparators, please see the Comparator enum above)
pub fn select(&mut self, field_index: u8, value: Field, comparator: Option<u3>) -> Self {
pub fn select(&mut self, field_index: u8, value: Field, comparator: Option<u8>) -> Self {
self.selects.push(Option::some(Select::new(field_index, value, comparator.unwrap_or(Comparator.EQ))));
*self
}

// This method adds a `Sort` criterion to the options.
// It takes a field_index indicating which field to sort by and an order (SortOrder) to determine the sorting direction.
pub fn sort(&mut self, field_index: u8, order: u2) -> Self {
pub fn sort(&mut self, field_index: u8, order: u8) -> Self {
self.sorts.push(Option::some(Sort::new(field_index, order)));
*self
}
@@ -150,7 +148,7 @@ impl<Note, N, FILTER_ARGS> NoteGetterOptions<Note, N, FILTER_ARGS> {
}

// This method sets the status value, which determines whether to retrieve active or nullified notes.
pub fn set_status(&mut self, status: u2) -> Self {
pub fn set_status(&mut self, status: u8) -> Self {
self.status = status;
*self
}
14 changes: 6 additions & 8 deletions noir-projects/aztec-nr/aztec/src/note/note_viewer_options.nr
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
use dep::std::option::Option;
use crate::note::note_getter_options::{Select, Sort, Comparator, NoteStatus};
use dep::protocol_types::{
constants::MAX_NOTES_PER_PAGE,
};
use dep::protocol_types::{constants::MAX_NOTES_PER_PAGE};
use crate::note::note_interface::NoteInterface;

// docs:start:NoteViewerOptions
@@ -11,7 +9,7 @@ struct NoteViewerOptions<Note, N> {
sorts: BoundedVec<Option<Sort>, N>,
limit: u32,
offset: u32,
status: u2,
status: u8,
}
// docs:end:NoteViewerOptions

@@ -22,20 +20,20 @@ impl<Note, N> NoteViewerOptions<Note, N> {
sorts: BoundedVec::new(Option::none()),
limit: MAX_NOTES_PER_PAGE as u32,
offset: 0,
status: NoteStatus.ACTIVE,
status: NoteStatus.ACTIVE
}
}

// This method adds a `Select` criterion to the options.
// It takes a field_index indicating which field to select,
// a value representing the specific value to match in that field, and
// a comparator (For possible values of comparators, please see the Comparator enum from note_getter_options)
pub fn select(&mut self, field_index: u8, value: Field, comparator: Option<u3>) -> Self {
pub fn select(&mut self, field_index: u8, value: Field, comparator: Option<u8>) -> Self {
self.selects.push(Option::some(Select::new(field_index, value, comparator.unwrap_or(Comparator.EQ))));
*self
}

pub fn sort(&mut self, field_index: u8, order: u2) -> Self {
pub fn sort(&mut self, field_index: u8, order: u8) -> Self {
self.sorts.push(Option::some(Sort::new(field_index, order)));
*self
}
@@ -52,7 +50,7 @@ impl<Note, N> NoteViewerOptions<Note, N> {
}

// This method sets the status value, which determines whether to retrieve active or nullified notes.
pub fn set_status(&mut self, status: u2) -> Self {
pub fn set_status(&mut self, status: u8) -> Self {
self.status = status;
*self
}
28 changes: 11 additions & 17 deletions noir-projects/aztec-nr/aztec/src/oracle/notes.nr
Original file line number Diff line number Diff line change
@@ -1,13 +1,7 @@
use dep::std::option::Option;
use crate::note::{
note_header::NoteHeader,
note_interface::NoteInterface,
};
use crate::note::{note_header::NoteHeader, note_interface::NoteInterface};

use dep::protocol_types::{
address::AztecAddress,
utils::arr_copy_slice,
};
use dep::protocol_types::{address::AztecAddress, utils::arr_copy_slice};

#[oracle(notifyCreatedNote)]
fn notify_created_note_oracle<N>(
@@ -39,12 +33,12 @@ fn get_notes_oracle<N, S>(
_num_selects: u8,
_select_by: [u8; N],
_select_values: [Field; N],
_select_comparators: [u3; N],
_select_comparators: [u8; N],
_sort_by: [u8; N],
_sort_order: [u2; N],
_sort_order: [u8; N],
_limit: u32,
_offset: u32,
_status: u2,
_status: u8,
_return_size: u32,
_placeholder_fields: [Field; S]
) -> [Field; S] {}
@@ -54,12 +48,12 @@ unconstrained fn get_notes_oracle_wrapper<N, S>(
num_selects: u8,
select_by: [u8; N],
select_values: [Field; N],
select_comparators: [u3; N],
select_comparators: [u8; N],
sort_by: [u8; N],
sort_order: [u2; N],
sort_order: [u8; N],
limit: u32,
offset: u32,
status: u2,
status: u8,
mut placeholder_fields: [Field; S]
) -> [Field; S] {
let return_size = placeholder_fields.len() as u32;
@@ -84,12 +78,12 @@ unconstrained pub fn get_notes<Note, N, M, S, NS>(
num_selects: u8,
select_by: [u8; M],
select_values: [Field; M],
select_comparators: [u3; M],
select_comparators: [u8; M],
sort_by: [u8; M],
sort_order: [u2; M],
sort_order: [u8; M],
limit: u32,
offset: u32,
status: u2,
status: u8,
mut placeholder_opt_notes: [Option<Note>; S], // TODO: Remove it and use `limit` to initialize the note array.
placeholder_fields: [Field; NS], // TODO: Remove it and use `limit` to initialize the note array.
_placeholder_note_length: [Field; N] // Turbofish hack? Compiler breaks calculating read_offset unless we add this parameter
35 changes: 10 additions & 25 deletions noir-projects/aztec-nr/easy-private-state/src/easy_private_state.nr
Original file line number Diff line number Diff line change
@@ -1,13 +1,8 @@
use dep::aztec::{
protocol_types::address::AztecAddress,
context::Context,
note::note_getter_options::NoteGetterOptions,
state_vars::set::Set,
};
use dep::value_note::{
filter::filter_notes_min_sum,
value_note::ValueNote,
protocol_types::address::AztecAddress, context::Context,
note::note_getter_options::NoteGetterOptions, state_vars::set::Set
};
use dep::value_note::{filter::filter_notes_min_sum, value_note::ValueNote};

struct EasyPrivateUint {
context: Context,
@@ -16,24 +11,14 @@ struct EasyPrivateUint {
}

impl EasyPrivateUint {
pub fn new(
context: Context,
storage_slot: Field,
) -> Self {
pub fn new(context: Context, storage_slot: Field) -> Self {
assert(storage_slot != 0, "Storage slot 0 not allowed. Storage slots must start from 1.");
let set = Set {
context,
storage_slot
};
EasyPrivateUint {
context,
set,
storage_slot,
}
let set = Set { context, storage_slot };
EasyPrivateUint { context, set, storage_slot }
}

// Very similar to `value_note::utils::increment`.
pub fn add(self, addend: u120, owner: AztecAddress) {
pub fn add(self, addend: u64, owner: AztecAddress) {
// Creates new note for the owner.
let mut addend_note = ValueNote::new(addend as Field, owner);

@@ -44,13 +29,13 @@ impl EasyPrivateUint {
}

// Very similar to `value_note::utils::decrement`.
pub fn sub(self, subtrahend: u120, owner: AztecAddress) {
pub fn sub(self, subtrahend: u64, owner: AztecAddress) {
// docs:start:get_notes
let options = NoteGetterOptions::with_filter(filter_notes_min_sum, subtrahend as Field);
let maybe_notes = self.set.get_notes(options);
// docs:end:get_notes

let mut minuend: u120 = 0;
let mut minuend: u64 = 0;
for i in 0..maybe_notes.len() {
if maybe_notes[i].is_some() {
let note = maybe_notes[i].unwrap_unchecked();
@@ -64,7 +49,7 @@ impl EasyPrivateUint {
self.set.remove(note);
// docs:end:remove

minuend += note.value as u120;
minuend += note.value as u64;
}
}

8 changes: 0 additions & 8 deletions noir-projects/aztec-nr/safe-math/Nargo.toml

This file was deleted.

3 changes: 0 additions & 3 deletions noir-projects/aztec-nr/safe-math/src/lib.nr

This file was deleted.

340 changes: 0 additions & 340 deletions noir-projects/aztec-nr/safe-math/src/safe_u120.nr

This file was deleted.

6 changes: 3 additions & 3 deletions noir-projects/aztec-nr/value-note/src/filter.nr
Original file line number Diff line number Diff line change
@@ -7,12 +7,12 @@ pub fn filter_notes_min_sum(
min_sum: Field
) -> [Option<ValueNote>; MAX_READ_REQUESTS_PER_CALL] {
let mut selected = [Option::none(); MAX_READ_REQUESTS_PER_CALL];
let mut sum = 0;
let mut sum = U128::from_integer(0);
for i in 0..notes.len() {
if notes[i].is_some() & (sum < min_sum as u120) {
if notes[i].is_some() & (sum < U128::from_integer(min_sum)) {
let note = notes[i].unwrap_unchecked();
selected[i] = Option::some(note);
sum += note.value as u120;
sum += U128::from_integer(note.value);
}
}
selected
7 changes: 2 additions & 5 deletions noir-projects/aztec-nr/value-note/src/utils.nr
Original file line number Diff line number Diff line change
@@ -3,10 +3,7 @@ use dep::aztec::context::PrivateContext;
use dep::aztec::note::note_getter_options::{NoteGetterOptions, SortOrder};
use dep::aztec::oracle::get_public_key::get_public_key;
use dep::aztec::state_vars::set::Set;
use crate::{
filter::filter_notes_min_sum,
value_note::{ValueNote, VALUE_NOTE_LEN},
};
use crate::{filter::filter_notes_min_sum, value_note::{ValueNote, VALUE_NOTE_LEN}};
use dep::aztec::protocol_types::address::AztecAddress;

// Sort the note values (0th field) in descending order.
@@ -53,7 +50,7 @@ pub fn decrement_by_at_most(balance: Set<ValueNote>, max_amount: Field, owner: A

// Add the change value back to the owner's balance.
let mut change_value = 0;
if decremented as u120 > max_amount as u120 {
if max_amount.lt(decremented) {
change_value = decremented - max_amount;
decremented -= change_value;
}
101 changes: 34 additions & 67 deletions noir-projects/noir-contracts/contracts/card_game_contract/src/cards.nr
Original file line number Diff line number Diff line change
@@ -1,45 +1,32 @@
use dep::aztec::{
protocol_types::{
address::AztecAddress,
constants::{
MAX_NOTES_PER_PAGE,
MAX_READ_REQUESTS_PER_CALL,
},
},
protocol_types::{address::AztecAddress, constants::{MAX_NOTES_PER_PAGE, MAX_READ_REQUESTS_PER_CALL}},
context::{PrivateContext, PublicContext, Context},
note::{
note_getter_options::NoteGetterOptions,
note_viewer_options::NoteViewerOptions,
note_getter::view_notes,
},
state_vars::set::Set,
note_getter_options::NoteGetterOptions, note_viewer_options::NoteViewerOptions,
note_getter::view_notes
},
state_vars::set::Set
};
use dep::std;
use dep::std::{
option::Option,
};
use dep::value_note::{
value_note::{ValueNote, VALUE_NOTE_LEN},
};
use dep::std::{option::Option};
use dep::value_note::{value_note::{ValueNote, VALUE_NOTE_LEN}};

struct Card {
strength: u16,
points: u16,
// We use u32s since u16s are unsupported
strength: u32,
points: u32,
}

impl Card {
pub fn from_field(field: Field) -> Card {
let value_bytes = field.to_le_bytes(32);
let strength = (value_bytes[0] as u16) + (value_bytes[1] as u16) * 256;
let points = (value_bytes[2] as u16) + (value_bytes[3] as u16) * 256;
Card {
strength,
points,
}
let strength = (value_bytes[0] as u32) + (value_bytes[1] as u32) * 256;
let points = (value_bytes[2] as u32) + (value_bytes[3] as u32) * 256;
Card { strength, points }
}

pub fn to_field(self) -> Field {
self.strength as Field + (self.points as Field)*65536
self.strength as Field + (self.points as Field) * 65536
}

pub fn serialize(self) -> [Field; 2] {
@@ -60,30 +47,17 @@ struct CardNote {
}

impl CardNote {
fn new(
strength: u16,
points: u16,
owner: AztecAddress,
) -> Self {
let card = Card {
strength,
points,
};
fn new(strength: u32, points: u32, owner: AztecAddress) -> Self {
let card = Card { strength, points };
CardNote::from_card(card, owner)
}

pub fn from_card(card: Card, owner: AztecAddress) -> CardNote {
CardNote {
card,
note: ValueNote::new(card.to_field(), owner),
}
CardNote { card, note: ValueNote::new(card.to_field(), owner) }
}

pub fn from_note(note: ValueNote) -> CardNote {
CardNote {
card: Card::from_field(note.value),
note,
}
CardNote { card: Card::from_field(note.value), note }
}
}

@@ -118,21 +92,13 @@ pub fn filter_cards<N>(
}

impl Deck {
pub fn new(
context: Context,
storage_slot: Field,
) -> Self {
let set = Set {
context,
storage_slot,
};
Deck {
set
}
pub fn new(context: Context, storage_slot: Field) -> Self {
let set = Set { context, storage_slot };
Deck { set }
}

pub fn add_cards<N>(&mut self, cards: [Card; N], owner: AztecAddress) -> [CardNote]{
let context = self.set.context.private.unwrap();
pub fn add_cards<N>(&mut self, cards: [Card; N], owner: AztecAddress) -> [CardNote] {
let _context = self.set.context.private.unwrap();

let mut inserted_cards = [];
for card in cards {
@@ -150,25 +116,27 @@ impl Deck {
let mut found_cards = [Option::none(); N];
for i in 0..maybe_notes.len() {
if maybe_notes[i].is_some() {
let card_note = CardNote::from_note(
maybe_notes[i].unwrap_unchecked()
);
let card_note = CardNote::from_note(maybe_notes[i].unwrap_unchecked());
// Ensure the notes are actually owned by the owner (to prevent user from generating a valid proof while
// spending someone else's notes).
assert(card_note.note.owner.eq(owner));

for j in 0..cards.len() {
if found_cards[j].is_none() & (cards[j].strength == card_note.card.strength) & (cards[j].points == card_note.card.points) {
if found_cards[j].is_none()
& (cards[j].strength == card_note.card.strength)
& (cards[j].points == card_note.card.points) {
found_cards[j] = Option::some(card_note);
}
}
}
}

found_cards.map(|card_note: Option<CardNote>| {
found_cards.map(
|card_note: Option<CardNote>| {
assert(card_note.is_some(), "Card not found");
card_note.unwrap_unchecked()
})
}
)
}

pub fn remove_cards<N>(&mut self, cards: [Card; N], owner: AztecAddress) {
@@ -182,14 +150,13 @@ impl Deck {
let options = NoteViewerOptions::new().set_offset(offset);
let opt_notes = self.set.view_notes(options);
let mut opt_cards = [Option::none(); MAX_NOTES_PER_PAGE];

for i in 0..opt_notes.len() {
opt_cards[i] = opt_notes[i].map(|note: ValueNote| Card::from_field(note.value));
}

opt_cards
}

}

global PACK_CARDS = 3; // Limited by number of write requests (max 4)
@@ -204,8 +171,8 @@ pub fn get_pack_cards(seed: Field, owner: AztecAddress, context: &mut PrivateCon
// we generate PACK_CARDS cards
assert((PACK_CARDS as u64) < 8, "Cannot generate more than 8 cards");
for i in 0..PACK_CARDS {
let strength = (random_bytes[i] as u16) + (random_bytes[i + 1] as u16) * 256;
let points = (random_bytes[i + 2] as u16) + (random_bytes[i + 3] as u16) * 256;
let strength = (random_bytes[i] as u32) + (random_bytes[i + 1] as u32) * 256;
let points = (random_bytes[i + 2] as u32) + (random_bytes[i + 3] as u32) * 256;
cards[i] = Card {
strength, points
};
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
use dep::aztec::protocol_types::{
address::AztecAddress,
traits::{Serialize, Deserialize},
};
use dep::aztec::protocol_types::{address::AztecAddress, traits::{Serialize, Deserialize}};
use crate::cards::Card;

global NUMBER_OF_PLAYERS = 2;
@@ -10,7 +7,7 @@ global NUMBER_OF_CARDS_DECK = 2;
struct PlayerEntry {
address: AztecAddress,
deck_strength: u32,
points: u120,
points: u64,
}

impl PlayerEntry {
@@ -25,7 +22,7 @@ impl Deserialize<PLAYER_SERIALIZED_LEN> for PlayerEntry {
fn deserialize(fields: [Field; PLAYER_SERIALIZED_LEN]) -> PlayerEntry {
let address = AztecAddress::from_field(fields[0]);
let deck_strength = fields[1] as u32;
let points = fields[2] as u120;
let points = fields[2] as u64;

PlayerEntry {
address,
@@ -163,7 +160,7 @@ impl Game {

for i in 0..NUMBER_OF_PLAYERS {
let card = self.rounds_cards[round_offset + i];
round_points += (card.points as u120);
round_points += (card.points as u64);
if card.strength > winner_strength {
winner_strength = card.strength;
winner_index = i;
Original file line number Diff line number Diff line change
@@ -2,20 +2,10 @@ contract Counter {
// docs:start:imports
use dep::aztec::protocol_types::address::AztecAddress;
use dep::aztec::{
context::{PrivateContext, Context},
note::{
note_header::NoteHeader,
utils as note_utils,
},
state_vars::map::Map,
};
use dep::value_note::{
balance_utils,
value_note::{
ValueNote,
VALUE_NOTE_LEN,
},
context::{PrivateContext, Context}, note::{note_header::NoteHeader, utils as note_utils},
state_vars::map::Map
};
use dep::value_note::{balance_utils, value_note::{ValueNote, VALUE_NOTE_LEN}};
use dep::easy_private_state::easy_private_state::EasyPrivateUint;
// docs:end:imports

@@ -27,7 +17,7 @@ contract Counter {

// docs:start:constructor
#[aztec(private)]
fn constructor(headstart: u120, owner: AztecAddress) {
fn constructor(headstart: u64, owner: AztecAddress) {
let counters = storage.counters;
counters.at(owner).add(headstart, owner);
}
Original file line number Diff line number Diff line change
@@ -13,26 +13,21 @@ mod types;

contract DocsExample {
// how to import dependencies defined in your workspace
use dep::aztec::protocol_types::{
abis::function_selector::FunctionSelector,
address::AztecAddress,
};
use dep::aztec::protocol_types::{abis::function_selector::FunctionSelector, address::AztecAddress};
use dep::aztec::{
note::{
note_header::NoteHeader,
note_getter_options::{NoteGetterOptions, Comparator},
note_viewer_options::{NoteViewerOptions},
utils as note_utils,
},
note_header::NoteHeader, note_getter_options::{NoteGetterOptions, Comparator},
note_viewer_options::{NoteViewerOptions}, utils as note_utils
},
context::{PrivateContext, PublicContext, Context},
state_vars::{map::Map, public_state::PublicState,singleton::Singleton, immutable_singleton::ImmutableSingleton, set::Set, stable_public_state::StablePublicState},
state_vars::{
map::Map, public_state::PublicState, singleton::Singleton,
immutable_singleton::ImmutableSingleton, set::Set, stable_public_state::StablePublicState
}
};
// how to import methods from other files/folders within your workspace
use crate::options::create_account_card_getter_options;
use crate::types::{
card_note::{CardNote, CARD_NOTE_LEN},
leader::Leader,
};
use crate::types::{card_note::{CardNote, CARD_NOTE_LEN}, leader::Leader};

struct Storage {
// Shows how to create a custom struct in PublicState
@@ -64,10 +59,7 @@ contract DocsExample {
fn init(context: Context) -> Self {
Storage {
// docs:start:storage-leader-init
leader: PublicState::new(
context,
1
),
leader: PublicState::new(context, 1),
// docs:end:storage-leader-init
// docs:start:start_vars_singleton
legendary_card: Singleton::new(context, 3),
@@ -79,7 +71,7 @@ contract DocsExample {
4,
|context, slot| {
Singleton::new(context, slot)
},
}
),
// docs:end:state_vars-MapSingleton
// docs:start:storage-set-init
@@ -95,9 +87,8 @@ contract DocsExample {
8,
|context, slot| {
PublicState::new(context, slot)
},
),
// docs:end:storage-minters-init
}
)// docs:end:storage-minters-init
}
}
}
@@ -155,7 +146,7 @@ contract DocsExample {
}

// docs:start:state_vars-NoteGetterOptionsComparatorExampleNoir
unconstrained fn read_note(amount: Field, comparator: u3) -> pub [Option<CardNote>; 10] {
unconstrained fn read_note(amount: Field, comparator: u8) -> pub [Option<CardNote>; 10] {
let options = NoteViewerOptions::new().select(0, amount, Option::some(comparator));
let notes = storage.set.view_notes(options);

Original file line number Diff line number Diff line change
@@ -4,19 +4,9 @@ contract EasyPrivateToken {
use dep::std::option::Option;
use dep::aztec::{
context::{PrivateContext, PublicContext, Context},
note::{
note_header::NoteHeader,
utils as note_utils,
},
state_vars::map::Map,
};
use dep::value_note::{
balance_utils,
value_note::{
ValueNote,
VALUE_NOTE_LEN,
},
note::{note_header::NoteHeader, utils as note_utils}, state_vars::map::Map
};
use dep::value_note::{balance_utils, value_note::{ValueNote, VALUE_NOTE_LEN}};
use dep::easy_private_state::easy_private_state::EasyPrivateUint;

struct Storage {
@@ -27,23 +17,23 @@ contract EasyPrivateToken {
* initialize the contract's initial state variables.
*/
#[aztec(private)]
fn constructor(initial_supply: u120, owner: AztecAddress) {
fn constructor(initial_supply: u64, owner: AztecAddress) {
let balances = storage.balances;

balances.at(owner).add(initial_supply, owner);
}

// Mints `amount` of tokens to `owner`.
#[aztec(private)]
fn mint(amount: u120, owner: AztecAddress) {
fn mint(amount: u64, owner: AztecAddress) {
let balances = storage.balances;

balances.at(owner).add(amount, owner);
}

// Transfers `amount` of tokens from `sender` to a `recipient`.
#[aztec(private)]
fn transfer(amount: u120, sender: AztecAddress, recipient: AztecAddress) {
fn transfer(amount: u64, sender: AztecAddress, recipient: AztecAddress) {
let balances = storage.balances;

balances.at(sender).sub(amount, sender);
Original file line number Diff line number Diff line change
@@ -6,4 +6,3 @@ type = "contract"

[dependencies]
aztec = { path = "../../../aztec-nr/aztec" }
safe_math = { path = "../../../aztec-nr/safe-math" }
Original file line number Diff line number Diff line change
@@ -1,17 +1,14 @@
use dep::aztec::protocol_types::{
address::AztecAddress,
traits::{Deserialize, Serialize}
};
use dep::aztec::protocol_types::{address::AztecAddress, traits::{Deserialize, Serialize}};

// Struct to be used to represent "totals". Generally, there should be one per asset.
// It stores the global values that are shared among all users, such as an accumulator
// and last time it was updated.
// In practice, it should also point to an oracle and have more fields related to
// loan to value ratios and other things, but we did not have enough reads/writes for this.
struct Asset {
interest_accumulator: u120,
last_updated_ts: u120,
loan_to_value: u120,
interest_accumulator: U128,
last_updated_ts: u64,
loan_to_value: U128,
oracle: AztecAddress,
}

@@ -20,9 +17,9 @@ global ASSET_SERIALIZED_LEN: Field = 4;
impl Serialize<ASSET_SERIALIZED_LEN> for Asset {
fn serialize(asset: Asset) -> [Field; ASSET_SERIALIZED_LEN] {
[
asset.interest_accumulator as Field,
asset.interest_accumulator.to_integer(),
asset.last_updated_ts as Field,
asset.loan_to_value as Field,
asset.loan_to_value.to_integer(),
asset.oracle.to_field()
]
}
@@ -32,9 +29,9 @@ impl Deserialize<ASSET_SERIALIZED_LEN> for Asset {
// Right now we are wasting so many writes. If changing last_updated_ts
// we will end up rewriting all of them, wasting writes.
fn deserialize(fields: [Field; ASSET_SERIALIZED_LEN]) -> Asset {
let interest_accumulator = fields[0] as u120;
let last_updated_ts = fields[1] as u120;
let loan_to_value = fields[2] as u120;
let interest_accumulator = U128::from_integer(fields[0]);
let last_updated_ts = fields[1] as u64;
let loan_to_value = U128::from_integer(fields[2]);
let oracle = AztecAddress::from_field(fields[3]);

Asset {
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use crate::interest_math::compute_multiplier;
use dep::safe_math::SafeU120;
use dep::aztec::hash::pedersen_hash;

// Utility used to easily get a "id" for a private user that sits in the same
@@ -16,45 +15,38 @@ pub fn compute_identifier(secret: Field, on_behalf_of: Field, self: Field) -> Fi
}

pub fn covered_by_collateral(
price: u120,
loan_to_value: u120,
collateral: u120,
increase: u120,
decrease: u120
) -> u120 {
let price_precision = SafeU120 { value: 1000000000 };
let ltv_precision = SafeU120 { value: 10000 };
price: U128,
loan_to_value: U128,
collateral: U128,
increase: U128,
decrease: U128
) -> U128 {
let price_precision = U128::from_integer(1000000000);
let ltv_precision = U128::from_integer(10000);

let price = SafeU120 { value: price };
let collateral = SafeU120 { value: collateral }.add(SafeU120 { value: increase }).sub(SafeU120 { value: decrease });
let loan_to_value = SafeU120 { value: loan_to_value };
let collateral = (collateral + increase) - decrease;

let collateral_value = collateral.mul_div(price, price_precision);
let debt_covered = collateral_value.mul_div(loan_to_value, ltv_precision);
let collateral_value = (collateral* price) / price_precision;
let debt_covered = (collateral_value * loan_to_value) / ltv_precision;

debt_covered.value
debt_covered
}

struct DebtReturn {
debt_value: u120,
static_debt: u120,
debt_value: U128,
static_debt: U128,
}

pub fn debt_updates(
interest_accumulator: u120,
static_debt: u120,
increase: u120,
decrease: u120
interest_accumulator: U128,
static_debt: U128,
increase: U128,
decrease: U128
) -> DebtReturn {
assert(interest_accumulator > 0);
let accumulator_precision = SafeU120 { value: 1000000000 };

let static_debt = SafeU120 { value: static_debt };
let interest_accumulator = SafeU120 { value: interest_accumulator };
let increase = SafeU120 { value: increase };
let decrease = SafeU120 { value: decrease };
assert(interest_accumulator > U128::from_integer(0));
let accumulator_precision = U128::from_integer(1000000000);

let current_debt_value = static_debt.mul_div(interest_accumulator, accumulator_precision);
let current_debt_value = (static_debt * interest_accumulator) / accumulator_precision;
let new_debt_value = current_debt_value.add(increase).sub(decrease);

// static_debt_increase = amount / accumulator
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
use dep::safe_math::SafeU120;

// Binomial approximation of exponential
// using lower than desired precisions for everything due to u120 limit
// (1+x)^n = 1+n*x+[n/2*(n-1)]*x^2+[n/6*(n-1)*(n-2)*x^3]...
Original file line number Diff line number Diff line change
@@ -1,101 +1,120 @@
use dep::aztec::context::{
PrivateContext,
PublicContext
};
use dep::aztec::context::{PrivateContext, PublicContext};

use crate::asset::Asset;
use dep::aztec::protocol_types::{
abis::function_selector::FunctionSelector,
address::AztecAddress,
constants::RETURN_VALUES_LENGTH,
};
use dep::aztec::protocol_types::{abis::function_selector::FunctionSelector, address::AztecAddress, constants::RETURN_VALUES_LENGTH};

struct PriceFeed {
address: AztecAddress,
}

impl PriceFeed {
pub fn at(address: AztecAddress) -> Self {
Self { address }
}

pub fn get_price(self: Self, context: PublicContext) -> u120 {
let return_values = context.call_public_function(
self.address,
FunctionSelector::from_signature("get_price(Field)"),
[0]
);

return_values[0] as u120
}
pub fn at(address: AztecAddress) -> Self {
Self { address }
}

pub fn get_price(self: Self, context: PublicContext) -> U128 {
let return_values = context.call_public_function(
self.address,
FunctionSelector::from_signature("get_price(Field)"),
[0]
);

U128::from_integer(return_values[0])
}
}

struct Token {
address: AztecAddress,
}

impl Token {
pub fn at(address: AztecAddress) -> Self {
Self { address }
}

pub fn transfer_public(self: Self, context: PublicContext, from: AztecAddress, to: AztecAddress, amount: Field, nonce: Field) {
context.call_public_function(
self.address,
FunctionSelector::from_signature("transfer_public((Field),(Field),Field,Field)"),
[from.to_field(), to.to_field(), amount, nonce]
);
}

pub fn mint_public(self: Self, context: PublicContext, to: AztecAddress, amount: Field) {
context.call_public_function(
self.address,
FunctionSelector::from_signature("mint_public((Field),Field)"),
[to.to_field(), amount]
);
}

pub fn burn_public(self: Self, context: PublicContext, from: AztecAddress, amount: Field, nonce: Field) {
context.call_public_function(
self.address,
FunctionSelector::from_signature("burn_public((Field),Field,Field)"),
[from.to_field(), amount, nonce]
);
}

// Private
pub fn unshield(self: Self, context: &mut PrivateContext, from: AztecAddress, to: AztecAddress, amount: Field, nonce: Field) -> [Field; RETURN_VALUES_LENGTH] {
context.call_private_function(
self.address,
FunctionSelector::from_signature("unshield((Field),(Field),Field,Field)"),
[from.to_field(), to.to_field(), amount, nonce]
)
}

pub fn burn(self: Self, context: &mut PrivateContext, from: AztecAddress, amount: Field, nonce: Field) -> [Field; RETURN_VALUES_LENGTH] {
context.call_private_function(
self.address,
FunctionSelector::from_signature("burn((Field),Field,Field)"),
[from.to_field(), amount, nonce]
)
}
pub fn at(address: AztecAddress) -> Self {
Self { address }
}

pub fn transfer_public(
self: Self,
context: PublicContext,
from: AztecAddress,
to: AztecAddress,
amount: Field,
nonce: Field
) {
context.call_public_function(
self.address,
FunctionSelector::from_signature("transfer_public((Field),(Field),Field,Field)"),
[from.to_field(), to.to_field(), amount, nonce]
);
}

pub fn mint_public(self: Self, context: PublicContext, to: AztecAddress, amount: Field) {
context.call_public_function(
self.address,
FunctionSelector::from_signature("mint_public((Field),Field)"),
[to.to_field(), amount]
);
}

pub fn burn_public(
self: Self,
context: PublicContext,
from: AztecAddress,
amount: Field,
nonce: Field
) {
context.call_public_function(
self.address,
FunctionSelector::from_signature("burn_public((Field),Field,Field)"),
[from.to_field(), amount, nonce]
);
}

// Private
pub fn unshield(
self: Self,
context: &mut PrivateContext,
from: AztecAddress,
to: AztecAddress,
amount: Field,
nonce: Field
) -> [Field; RETURN_VALUES_LENGTH] {
context.call_private_function(
self.address,
FunctionSelector::from_signature("unshield((Field),(Field),Field,Field)"),
[from.to_field(), to.to_field(), amount, nonce]
)
}

pub fn burn(
self: Self,
context: &mut PrivateContext,
from: AztecAddress,
amount: Field,
nonce: Field
) -> [Field; RETURN_VALUES_LENGTH] {
context.call_private_function(
self.address,
FunctionSelector::from_signature("burn((Field),Field,Field)"),
[from.to_field(), amount, nonce]
)
}
}

struct Lending {
address: AztecAddress,
}

impl Lending {
pub fn at(address: AztecAddress) -> Self {
Self { address }
}

pub fn update_accumulator(self: Self, context: PublicContext) -> Asset {
let return_values = context.call_public_function_no_args(
self.address,
FunctionSelector::from_signature("update_accumulator()"),
);

Asset::deserialize(return_values)
}
pub fn at(address: AztecAddress) -> Self {
Self { address }
}

pub fn update_accumulator(self: Self, context: PublicContext) -> Asset {
let return_values = context.call_public_function_no_args(
self.address,
FunctionSelector::from_signature("update_accumulator()")
);

Asset::deserialize(return_values)
}
}
26 changes: 13 additions & 13 deletions noir-projects/noir-contracts/contracts/lending_contract/src/main.nr
Original file line number Diff line number Diff line change
@@ -15,7 +15,6 @@ contract Lending {
abis::function_selector::FunctionSelector,
address::AztecAddress,
};
use dep::safe_math::SafeU120;
use dep::std::option::Option;
use dep::aztec::{
context::{PrivateContext, PublicContext, Context},
@@ -59,16 +58,17 @@ contract Lending {
let asset_loc = storage.assets.at(0);
let asset = asset_loc.read();

assert(loan_to_value as u120 <= 10000);
let loan_to_value = U128::from_integer(loan_to_value);

assert(loan_to_value <= U128::from_integer(10000));
assert(asset.last_updated_ts == 0);
assert(asset.interest_accumulator == 0);
assert(asset.interest_accumulator == U128::from_integer(0));

let last_updated_ts = context.timestamp() as u120;
let loan_to_value = loan_to_value as u120;
let last_updated_ts = context.timestamp() as u64;

asset_loc.write(
Asset {
interest_accumulator: 1000000000,
interest_accumulator: U128::from_integer(1000000000),
last_updated_ts,
loan_to_value,
oracle
@@ -85,19 +85,19 @@ contract Lending {
let asset_loc = storage.assets.at(0);
let mut asset = asset_loc.read();

let timestamp = context.timestamp() as u120;
let dt: SafeU120 = SafeU120 { value: timestamp }.sub(SafeU120 { value: asset.last_updated_ts });
let timestamp = context.timestamp() as u64;
let dt = timestamp - asset.last_updated_ts;

// Only update if time has passed.
if (!dt.is_zero()) {
let precision: SafeU120 = SafeU120 { value: 1000000000 };
let rate_per_second: u120 = 1268391679; // 4% yearly rate / (60 * 60 * 24 * 365)
if !(dt == 0) {
let precision = U128::from_integer(1000000000);
let rate_per_second = U128::from_integer(1268391679); // 4% yearly rate / (60 * 60 * 24 * 365)
// if rate_per_second < sqrt(WAD) our approx is eq precision + rate * dt
let multiplier = compute_multiplier(rate_per_second, dt);

// accumulator *= multiplier, and multiplier >= 1
asset.interest_accumulator = SafeU120{value: asset.interest_accumulator}.mul_div(multiplier, precision).value;
asset.last_updated_ts = context.timestamp() as u120;
asset.interest_accumulator = (asset.interest_accumulator * multiplier) / precision;
asset.last_updated_ts = context.timestamp() as u64;

asset_loc.write(asset);
}
Original file line number Diff line number Diff line change
@@ -6,6 +6,5 @@ type = "contract"

[dependencies]
aztec = { path = "../../../aztec-nr/aztec" }
safe_math = { path = "../../../aztec-nr/safe-math" }
field_note = { path = "../../../aztec-nr/field-note" }
authwit = { path = "../../../aztec-nr/authwit" }
Original file line number Diff line number Diff line change
@@ -16,7 +16,6 @@ contract TokenBlacklist {
// Libs
use dep::std::option::Option;

use dep::safe_math::SafeU120;
use dep::aztec::protocol_types::{
abis::function_selector::FunctionSelector,
address::AztecAddress,
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use dep::std::option::Option;
use dep::safe_math::SafeU120;
use dep::aztec::{
context::Context, protocol_types::{address::AztecAddress, constants::MAX_READ_REQUESTS_PER_CALL},
state_vars::{set::Set, map::Map},
Original file line number Diff line number Diff line change
@@ -4,7 +4,6 @@ use dep::aztec::{
context::PrivateContext, state_vars::set::Set, log::emit_encrypted_log, hash::pedersen_hash
};
use dep::aztec::oracle::{rand::rand, nullifier_key::get_nullifier_secret_key, get_public_key::get_public_key};
use dep::safe_math::SafeU120;
use dep::std::option::Option;

trait OwnedNote {
Original file line number Diff line number Diff line change
@@ -6,6 +6,5 @@ type = "contract"

[dependencies]
aztec = { path = "../../../aztec-nr/aztec" }
safe_math = { path = "../../../aztec-nr/safe-math" }
compressed_string = { path = "../../../aztec-nr/compressed-string" }
authwit = { path = "../../../aztec-nr/authwit" }
Original file line number Diff line number Diff line change
@@ -13,7 +13,6 @@ contract Token {
// Libs
use dep::std::option::Option;

use dep::safe_math::SafeU120;
use dep::compressed_string::FieldCompressedString;

use dep::aztec::{
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use dep::std::option::Option;
use dep::safe_math::SafeU120;
use dep::aztec::{
context::{PrivateContext, PublicContext, Context}, hash::pedersen_hash,
protocol_types::{address::AztecAddress, constants::MAX_READ_REQUESTS_PER_CALL},
Original file line number Diff line number Diff line change
@@ -4,7 +4,6 @@ use dep::aztec::{
context::PrivateContext, state_vars::set::Set, log::emit_encrypted_log, hash::pedersen_hash
};
use dep::aztec::oracle::{rand::rand, nullifier_key::get_nullifier_secret_key, get_public_key::get_public_key};
use dep::safe_math::SafeU120;
use dep::std::option::Option;

trait OwnedNote {
Original file line number Diff line number Diff line change
@@ -19,9 +19,9 @@ impl Empty for Field { fn empty() -> Self {0} }

impl Empty for u1 { fn empty() -> Self {0} }
impl Empty for u8 { fn empty() -> Self {0} }
impl Empty for u16 { fn empty() -> Self {0} }
impl Empty for u32 { fn empty() -> Self {0} }
impl Empty for u64 { fn empty() -> Self {0} }
impl Empty for U128 { fn empty() -> Self {U128::from_integer(0)} }

pub fn is_empty<T>(item: T) -> bool where T: Empty + Eq {
item.eq(T::empty())
@@ -45,6 +45,12 @@ impl ToField for Field {
}
}

impl ToField for U128 {
fn to_field(self) -> Field {
self.to_integer()
}
}

// docs:start:serialize
trait Serialize<N> {
fn serialize(self) -> [Field; N];
Original file line number Diff line number Diff line change
@@ -54,3 +54,16 @@ impl Deserialize<BOOL_SERIALIZED_LEN> for bool {
fields[0] as bool
}
}

impl Serialize<2> for U128 {
fn serialize(self) -> [Field; 2] {
[self.lo, self.hi]
}

}

impl Deserialize<2> for U128 {
fn deserialize(fields: [Field; 2]) -> Self {
U128 {lo: fields[0], hi: fields[1]}
}
}