Using Value Notes in Aztec.nr
ValueNotes hold one main property - a value
- and have utils useful for manipulating this value, such as incrementing and decrementing it similarly to an integer.
ValueNote
This is the ValueNote struct:
#[note]
pub struct ValueNote {
value: Field,
owner: AztecAddress,
randomness: Field,
}
Source code: noir-projects/aztec-nr/value-note/src/value_note.nr#L20-L27
Importing ValueNote
In Nargo.toml
value_note = { git="https://github.com/AztecProtocol/aztec-packages/", tag="aztec-packages-v0.76.4", directory="noir-projects/aztec-nr/value-note" }
In your contract
use dep::value_note::value_note::ValueNote;
Source code: noir-projects/noir-contracts/contracts/child_contract/src/main.nr#L14-L16
Working with ValueNote
Creating a new note
Creating a new ValueNote
takes the following args:
value
(Field
): the value of the ValueNoteowner
(AztecAddress
): owner is the party whose nullifying key can be used to spend the note
let mut note = ValueNote::new(new_value, owner);
Source code: noir-projects/noir-contracts/contracts/child_contract/src/main.nr#L60-L62
Getting a balance
A user may have multiple notes in a set that all refer to the same content (e.g. a set of notes representing a single token balance). By using the ValueNote
type to represent token balances, you do not have to manually add each of these notes and can instead use a helper function get_balance()
.
It takes one argument - the set of notes.
// Return the sum of all notes in the set.
balance_utils::get_balance(owner_balance)
Source code: noir-projects/noir-contracts/contracts/stateful_test_contract/src/main.nr#L104-L107
This can only be used in an unconstrained function.
Incrementing and decrementing
Both increment
and decrement
functions take the same args:
balance: PrivateSet<ValueNote, &mut PrivateContext>,
amount: Field,
Source code: noir-projects/aztec-nr/value-note/src/utils.nr#L20-L23
Note that this will create a new note in the set of notes passed as the first argument. For example:
increment(storage.notes.at(owner), value, owner, sender);
Source code: noir-projects/noir-contracts/contracts/benchmarking_contract/src/main.nr#L24-L26
The decrement
function works similarly except the amount
is the number that the value will be decremented by, and it will fail if the sum of the selected notes is less than the amount.