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:
#[aztec(note)]
struct ValueNote {
value: Field,
// The nullifying public key hash is used with the nsk_app to ensure that the note can be privately spent.
npk_m_hash: Field,
randomness: Field,
}
Source code: noir-projects/aztec-nr/value-note/src/value_note.nr#L16-L24
Importing ValueNote
In Nargo.toml
value_note = { git="https://github.com/AztecProtocol/aztec-packages/", tag="aztec-packages-v0.54.0", directory="noir-projects/aztec-nr/value-note" }
In your contract
use dep::value_note::value_note::ValueNote;
Source code: noir-projects/noir-contracts/contracts/crowdfunding_contract/src/main.nr#L12-L14
Working with ValueNote
Creating a new note
Creating a new ValueNote
takes the following args:
value
(Field
): the value of the ValueNotenpk_m_hash
(Field
): the master nullifier public key hash of the user
let mut note = ValueNote::new(amount as Field, donor_keys.npk_m.hash());
Source code: noir-projects/noir-contracts/contracts/crowdfunding_contract/src/main.nr#L74-L76
In this example, amount
is the value
and the npk_m_hash
of the donor was computed earlier.
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#L94-L97
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,
recipient: AztecAddress,
Source code: noir-projects/aztec-nr/value-note/src/utils.nr#L16-L20
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, outgoing_viewer);
Source code: noir-projects/noir-contracts/contracts/benchmarking_contract/src/main.nr#L21-L23
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.