diff --git a/docs/docs/migration_notes.md b/docs/docs/migration_notes.md index 2ccbdfc438b..ca535d3a95a 100644 --- a/docs/docs/migration_notes.md +++ b/docs/docs/migration_notes.md @@ -8,6 +8,22 @@ Aztec is in full-speed development. Literally every version breaks compatibility ## TBD +### `U128` type replaced with native `u128` + +The `U128` type has been replaced with the native `u128` type. This means that you can no longer use the `U128` type in your code. Instead, you should use the `u128` type. +Doing the changes is as straightforward as: + +```diff + #[public] + #[view] +- fn balance_of_public(owner: AztecAddress) -> U128 { ++ fn balance_of_public(owner: AztecAddress) -> u128 { + storage.public_balances.at(owner).read() + } +``` + +`UintNote` has also been updated to use the native `u128` type. + ### [aztec-nr] Removed `compute_note_hash_and_optionally_a_nullifer` This function is no longer mandatory for contracts, and the `#[aztec]` macro no longer injects it. @@ -63,7 +79,7 @@ await contract.methods txHash.hash, toBoundedVec(txEffects!.data.noteHashes, MAX_NOTE_HASHES_PER_TX), txEffects!.data.nullifiers[0], - wallet.getAddress(), + wallet.getAddress() ) .simulate(); ``` diff --git a/noir-projects/aztec-nr/aztec/src/macros/notes/mod.nr b/noir-projects/aztec-nr/aztec/src/macros/notes/mod.nr index 90c9ca77b0d..39cf5d01d7d 100644 --- a/noir-projects/aztec-nr/aztec/src/macros/notes/mod.nr +++ b/noir-projects/aztec-nr/aztec/src/macros/notes/mod.nr @@ -412,7 +412,7 @@ comptime fn generate_fixed_generators() -> (Quoted, Quoted) { /// std::hash::from_field_unsafe(npk_m_hash as Field), /// std::hash::from_field_unsafe(randomness as Field) /// ] -/// args_list: [amount: U128, npk_m_hash: Field, randomness: Field] +/// args_list: [amount: u128, npk_m_hash: Field, randomness: Field] /// aux_vars: [] comptime fn generate_multi_scalar_mul( indexed_fields: [(Quoted, Type, u32)], @@ -695,7 +695,7 @@ comptime fn get_setup_log_plaintext_body( /// } /// /// impl TokenNoteFinalizationPayload { -/// fn new(mut self, context: &mut aztec::prelude::PublicContext, slot: Field, amount: U128) -> TokenNoteFinalizationPayload { +/// fn new(mut self, context: &mut aztec::prelude::PublicContext, slot: Field, amount: u128) -> TokenNoteFinalizationPayload { /// self.context = context; /// self.hiding_point_slot = slot; /// self.setup_log_slot = slot + aztec::protocol_types::point::POINT_LENGTH as Field; @@ -978,7 +978,6 @@ comptime fn register_note( /// Separates note struct members into fixed and nullable ones. It also stores the index of where each struct member /// starts in the serialized note. Note that each struct member can occupy multiple fields (as in Field type). -/// An example of a struct member occupying multiple fields is `amount` in `TokenNote` that uses `U128` type. comptime fn index_note_fields( s: StructDefinition, nullable_fields: [Quoted], diff --git a/noir-projects/aztec-nr/aztec/src/state_vars/public_immutable.nr b/noir-projects/aztec-nr/aztec/src/state_vars/public_immutable.nr index bb27e1379b2..7e1e77a575f 100644 --- a/noir-projects/aztec-nr/aztec/src/state_vars/public_immutable.nr +++ b/noir-projects/aztec-nr/aztec/src/state_vars/public_immutable.nr @@ -27,7 +27,7 @@ use dep::protocol_types::{constants::INITIALIZATION_SLOT_SEPARATOR, traits::Pack /// #[derive(Eq, Packable)] /// pub struct Config \{ /// pub address_1: AztecAddress, -/// pub value_1: U128, +/// pub value_1: u128, /// pub value_2: u64, /// ... /// } diff --git a/noir-projects/aztec-nr/uint-note/src/uint_note.nr b/noir-projects/aztec-nr/uint-note/src/uint_note.nr index 3e0517a92e8..23c4e687c49 100644 --- a/noir-projects/aztec-nr/uint-note/src/uint_note.nr +++ b/noir-projects/aztec-nr/uint-note/src/uint_note.nr @@ -10,14 +10,14 @@ use dep::aztec::{ #[derive(Eq, Serialize)] pub struct UintNote { // The amount of tokens in the note - value: U128, + value: u128, owner: AztecAddress, // Randomness of the note to protect against note hash preimage attacks randomness: Field, } // docs:end:UintNote impl UintNote { - pub fn new(value: U128, owner: AztecAddress) -> Self { + pub fn new(value: u128, owner: AztecAddress) -> Self { // Safety: We use the randomness to preserve the privacy of the note recipient by preventing brute-forcing, // so a malicious sender could use non-random values to make the note less private. But they already know // the full note pre-image anyway, and so the recipient already trusts them to not disclose this @@ -26,7 +26,7 @@ impl UintNote { Self { value, owner, randomness } } - pub fn get_value(self) -> U128 { + pub fn get_value(self) -> u128 { self.value } } diff --git a/noir-projects/aztec-nr/value-note/src/filter.nr b/noir-projects/aztec-nr/value-note/src/filter.nr index 11cf2502525..5390712ba85 100644 --- a/noir-projects/aztec-nr/value-note/src/filter.nr +++ b/noir-projects/aztec-nr/value-note/src/filter.nr @@ -1,6 +1,10 @@ use crate::value_note::ValueNote; -use dep::aztec::note::retrieved_note::RetrievedNote; -use dep::aztec::protocol_types::constants::MAX_NOTE_HASH_READ_REQUESTS_PER_CALL; +use aztec::{ + note::retrieved_note::RetrievedNote, + protocol_types::{ + constants::MAX_NOTE_HASH_READ_REQUESTS_PER_CALL, utils::field::full_field_less_than, + }, +}; pub fn filter_notes_min_sum( notes: [Option>; MAX_NOTE_HASH_READ_REQUESTS_PER_CALL], @@ -8,12 +12,12 @@ pub fn filter_notes_min_sum( ) -> [Option>; MAX_NOTE_HASH_READ_REQUESTS_PER_CALL] { let mut selected = [Option::none(); MAX_NOTE_HASH_READ_REQUESTS_PER_CALL]; - let mut sum = U128::from_integer(0); + let mut sum = 0; for i in 0..notes.len() { - if notes[i].is_some() & (sum < U128::from_integer(min_sum)) { + if notes[i].is_some() & full_field_less_than(sum, min_sum) { let retrieved_note = notes[i].unwrap_unchecked(); selected[i] = Option::some(retrieved_note); - sum += U128::from_integer(retrieved_note.note.value); + sum += retrieved_note.note.value; } } diff --git a/noir-projects/noir-contracts/contracts/amm_contract/src/lib.nr b/noir-projects/noir-contracts/contracts/amm_contract/src/lib.nr index d3d72f5ac01..eb77f177330 100644 --- a/noir-projects/noir-contracts/contracts/amm_contract/src/lib.nr +++ b/noir-projects/noir-contracts/contracts/amm_contract/src/lib.nr @@ -1,7 +1,7 @@ /// Given an input amount of an asset and pair balances, returns the maximum output amount of the other asset. -pub fn get_amount_out(amount_in: U128, balance_in: U128, balance_out: U128) -> U128 { - assert(amount_in > U128::zero(), "INSUFFICIENT_INPUT_AMOUNT"); - assert((balance_in > U128::zero()) & (balance_out > U128::zero()), "INSUFFICIENT_LIQUIDITY"); +pub fn get_amount_out(amount_in: u128, balance_in: u128, balance_out: u128) -> u128 { + assert(amount_in > 0 as u128, "INSUFFICIENT_INPUT_AMOUNT"); + assert((balance_in > 0 as u128) & (balance_out > 0 as u128), "INSUFFICIENT_LIQUIDITY"); // The expression below is: // (amount_in * 997 * balance_out) / (balance_in * 10000 + amount_in * 997) @@ -9,16 +9,16 @@ pub fn get_amount_out(amount_in: U128, balance_in: U128, balance_out: U128) -> U // balance_out * ((amount_in * 0.997) / (balance_in + amount_in * 0.997)) // resulting in an implicit 0.3% fee on the amount in, as the fee tokens are not taken into consideration. - let amount_in_with_fee = amount_in * U128::from_integer(997); + let amount_in_with_fee = amount_in * 997 as u128; let numerator = amount_in_with_fee * balance_out; - let denominator = balance_in * U128::from_integer(1000) + amount_in_with_fee; + let denominator = balance_in * 1000 as u128 + amount_in_with_fee; numerator / denominator } /// Given an output amount of an asset and pair balances, returns a required input amount of the other asset. -pub fn get_amount_in(amount_out: U128, balance_in: U128, balance_out: U128) -> U128 { - assert(amount_out > U128::zero(), "INSUFFICIENT_OUTPUT_AMOUNT"); - assert((balance_in > U128::zero()) & (balance_out > U128::zero()), "INSUFFICIENT_LIQUIDITY"); +pub fn get_amount_in(amount_out: u128, balance_in: u128, balance_out: u128) -> u128 { + assert(amount_out > 0 as u128, "INSUFFICIENT_OUTPUT_AMOUNT"); + assert((balance_in > 0 as u128) & (balance_out > 0 as u128), "INSUFFICIENT_LIQUIDITY"); // The expression below is: // (balance_in * amount_out * 1000) / (balance_out - amount_out * 997) + 1 @@ -27,26 +27,26 @@ pub fn get_amount_in(amount_out: U128, balance_in: U128, balance_out: U128) -> U // resulting in an implicit 0.3% fee on the amount in, as the fee tokens are not taken into consideration. The +1 // at the end ensures the rounding error favors the pool. - let numerator = balance_in * amount_out * U128::from_integer(1000); - let denominator = (balance_out - amount_out) * U128::from_integer(997); - (numerator / denominator) + U128::from_integer(1) + let numerator = balance_in * amount_out * 1000 as u128; + let denominator = (balance_out - amount_out) * 997 as u128; + (numerator / denominator) + 1 as u128 } /// Given the desired amounts and balances of token0 and token1 returns the optimal amount of token0 and token1 to be added to the pool. pub fn get_amounts_to_add( - amount0_max: U128, - amount1_max: U128, - amount0_min: U128, - amount1_min: U128, - balance0: U128, - balance1: U128, -) -> (U128, U128) { + amount0_max: u128, + amount1_max: u128, + amount0_min: u128, + amount1_min: u128, + balance0: u128, + balance1: u128, +) -> (u128, u128) { // When adding tokens, both balances must grow by the same ratio, which means that their spot price is unchanged. // Since any swaps would affect these ratios, liquidity providers supply a range of minimum and maximum balances // they are willing to supply for each token (which translates to minimum and maximum relative prices of the // tokens, preventing loss of value outside of this range due to e.g. front-running). - if (balance0 == U128::zero()) | (balance1 == U128::zero()) { + if (balance0 == 0 as u128) | (balance1 == 0 as u128) { // The token balances should only be zero when initializing the pool. In this scenario there is no prior ratio // to follow so we simply transfer the full maximum balance - it is up to the caller to make sure that the ratio // they've chosen results in a a reasonable spot price. @@ -75,11 +75,11 @@ pub fn get_amounts_to_add( /// Returns the amount of tokens to return to a liquidity provider when they remove liquidity from the pool. pub fn get_amounts_on_remove( - to_burn: U128, - total_supply: U128, - balance0: U128, - balance1: U128, -) -> (U128, U128) { + to_burn: u128, + total_supply: u128, + balance0: u128, + balance1: u128, +) -> (u128, u128) { // Since the liquidity token tracks ownership of the pool, the liquidity provider gets a proportional share of each // token. (to_burn * balance0 / total_supply, to_burn * balance1 / total_supply) @@ -87,8 +87,8 @@ pub fn get_amounts_on_remove( /// Given some amount of an asset and pair balances, returns an equivalent amount of the other asset. Tokens should be /// added and removed from the Pool respecting this ratio. -fn get_equivalent_amount(amount0: U128, balance0: U128, balance1: U128) -> U128 { - assert((balance0 > U128::zero()) & (balance1 > U128::zero()), "INSUFFICIENT_LIQUIDITY"); +fn get_equivalent_amount(amount0: u128, balance0: u128, balance1: u128) -> u128 { + assert((balance0 > 0 as u128) & (balance1 > 0 as u128), "INSUFFICIENT_LIQUIDITY"); // This is essentially the Rule of Three, since we're computing proportional ratios. Note we divide at the end to // avoid introducing too much error due to truncation. diff --git a/noir-projects/noir-contracts/contracts/amm_contract/src/main.nr b/noir-projects/noir-contracts/contracts/amm_contract/src/main.nr index c5354e37016..d4e9d65fc63 100644 --- a/noir-projects/noir-contracts/contracts/amm_contract/src/main.nr +++ b/noir-projects/noir-contracts/contracts/amm_contract/src/main.nr @@ -51,9 +51,9 @@ pub contract AMM { /// Amount of liquidity which gets locked when liquidity is provided for the first time. Its purpose is to prevent /// the pool from ever emptying which could lead to undefined behavior. - global MINIMUM_LIQUIDITY: U128 = U128::from_integer(1000); + global MINIMUM_LIQUIDITY: u128 = 1000; /// We set it to 99 times the minimum liquidity. That way the first LP gets 99% of the value of their deposit. - global INITIAL_LIQUIDITY: U128 = U128::from_integer(99000); + global INITIAL_LIQUIDITY: u128 = 99000; // TODO(#9480): Either deploy the liquidity contract in the constructor or verify it that it corresponds to what // this contract expects (i.e. that the AMM has permission to mint and burn). @@ -72,10 +72,10 @@ pub contract AMM { /// The identity of the liquidity provider is not revealed, but the action and amounts are. #[private] fn add_liquidity( - amount0_max: U128, - amount1_max: U128, - amount0_min: U128, - amount1_min: U128, + amount0_max: u128, + amount1_max: u128, + amount0_min: u128, + amount1_min: u128, nonce: Field, ) { assert( @@ -86,10 +86,7 @@ pub contract AMM { (amount1_min < amount1_max) | (amount1_min == amount1_max), "INCORRECT_TOKEN1_LIMITS", ); - assert( - (U128::zero() < amount0_max) & (U128::zero() < amount1_max), - "INSUFFICIENT_INPUT_AMOUNTS", - ); + assert((0 as u128 < amount0_max) & (0 as u128 < amount1_max), "INSUFFICIENT_INPUT_AMOUNTS"); let config = storage.config.read(); @@ -145,10 +142,10 @@ pub contract AMM { refund_token0_hiding_point_slot: Field, refund_token1_hiding_point_slot: Field, liquidity_hiding_point_slot: Field, - amount0_max: U128, - amount1_max: U128, - amount0_min: U128, - amount1_min: U128, + amount0_max: u128, + amount1_max: u128, + amount0_min: u128, + amount1_min: u128, ) { let token0 = Token::at(config.token0); let token1 = Token::at(config.token1); @@ -182,12 +179,12 @@ pub contract AMM { // We can simply skip the refund if the amount to return is 0 in order to save gas: the partial note will // simply stay in public storage and not be completed, but this is not an issue. - if (refund_amount_token0 > U128::zero()) { + if (refund_amount_token0 > 0 as u128) { token0 .finalize_transfer_to_private(refund_amount_token0, refund_token0_hiding_point_slot) .call(&mut context); } - if (refund_amount_token1 > U128::zero()) { + if (refund_amount_token1 > 0 as u128) { token1 .finalize_transfer_to_private(refund_amount_token1, refund_token1_hiding_point_slot) .call(&mut context); @@ -196,7 +193,7 @@ pub contract AMM { // With the deposit amounts known, we can compute the number of liquidity tokens to mint and finalize the // depositor's partial note. let total_supply = liquidity_token.total_supply().view(&mut context); - let liquidity_amount = if total_supply != U128::zero() { + let liquidity_amount = if total_supply != 0 as u128 { // The liquidity token supply increases by the same ratio as the balances. In case one of the token balances // increased with a ratio different from the other one, we simply take the smallest value. std::cmp::min( @@ -219,7 +216,7 @@ pub contract AMM { INITIAL_LIQUIDITY }; - assert(liquidity_amount > U128::zero(), "INSUFFICIENT_LIQUIDITY_MINTED"); + assert(liquidity_amount > 0 as u128, "INSUFFICIENT_LIQUIDITY_MINTED"); liquidity_token .finalize_mint_to_private(liquidity_amount, liquidity_hiding_point_slot) .call(&mut context); @@ -232,7 +229,7 @@ pub contract AMM { /// /// The identity of the liquidity provider is not revealed, but the action and amounts are. #[private] - fn remove_liquidity(liquidity: U128, amount0_min: U128, amount1_min: U128, nonce: Field) { + fn remove_liquidity(liquidity: u128, amount0_min: u128, amount1_min: u128, nonce: Field) { let config = storage.config.read(); let liquidity_token = Token::at(config.liquidity_token); @@ -275,11 +272,11 @@ pub contract AMM { #[internal] fn _remove_liquidity( config: Config, // We could read this in public, but it's cheaper to receive from private - liquidity: U128, + liquidity: u128, token0_hiding_point_slot: Field, token1_hiding_point_slot: Field, - amount0_min: U128, - amount1_min: U128, + amount0_min: u128, + amount1_min: u128, ) { let token0 = Token::at(config.token0); let token1 = Token::at(config.token1); @@ -313,8 +310,8 @@ pub contract AMM { fn swap_exact_tokens_for_tokens( token_in: AztecAddress, token_out: AztecAddress, - amount_in: U128, - amount_out_min: U128, + amount_in: u128, + amount_out_min: u128, nonce: Field, ) { let config = storage.config.read(); @@ -351,8 +348,8 @@ pub contract AMM { fn _swap_exact_tokens_for_tokens( token_in: AztecAddress, token_out: AztecAddress, - amount_in: U128, - amount_out_min: U128, + amount_in: u128, + amount_out_min: u128, token_out_hiding_point_slot: Field, ) { // In order to compute the amount to swap we need the live token balances. Note that at this state the token in @@ -383,8 +380,8 @@ pub contract AMM { fn swap_tokens_for_exact_tokens( token_in: AztecAddress, token_out: AztecAddress, - amount_out: U128, - amount_in_max: U128, + amount_out: u128, + amount_in_max: u128, nonce: Field, ) { let config = storage.config.read(); @@ -429,8 +426,8 @@ pub contract AMM { fn _swap_tokens_for_exact_tokens( token_in: AztecAddress, token_out: AztecAddress, - amount_in_max: U128, - amount_out: U128, + amount_in_max: u128, + amount_out: u128, change_token_in_hiding_point_slot: Field, token_out_hiding_point_slot: Field, ) { @@ -449,7 +446,7 @@ pub contract AMM { assert(amount_in <= amount_in_max, "INSUFFICIENT_OUTPUT_AMOUNT"); let change = amount_in_max - amount_in; - if (change > U128::zero()) { + if (change > 0 as u128) { Token::at(token_in) .finalize_transfer_to_private(change, change_token_in_hiding_point_slot) .call(&mut context); @@ -463,19 +460,19 @@ pub contract AMM { } unconstrained fn get_amount_out_for_exact_in( - balance_in: U128, - balance_out: U128, - amount_in: U128, - ) -> U128 { + balance_in: u128, + balance_out: u128, + amount_in: u128, + ) -> u128 { // Ideally we'd call the token contract in order to read the current balance, but we can't due to #7524. get_amount_out(amount_in, balance_in, balance_out) } unconstrained fn get_amount_in_for_exact_out( - balance_in: U128, - balance_out: U128, - amount_out: U128, - ) -> U128 { + balance_in: u128, + balance_out: u128, + amount_out: u128, + ) -> u128 { // Ideally we'd call the token contract in order to read the current balance, but we can't due to #7524. get_amount_in(amount_out, balance_in, balance_out) } diff --git a/noir-projects/noir-contracts/contracts/app_subscription_contract/src/config.nr b/noir-projects/noir-contracts/contracts/app_subscription_contract/src/config.nr index 908b4bec409..5593efb0fb3 100644 --- a/noir-projects/noir-contracts/contracts/app_subscription_contract/src/config.nr +++ b/noir-projects/noir-contracts/contracts/app_subscription_contract/src/config.nr @@ -8,6 +8,6 @@ pub struct Config { pub target_address: AztecAddress, pub subscription_token_address: AztecAddress, pub subscription_recipient_address: AztecAddress, - pub subscription_price: U128, + pub subscription_price: u128, pub fee_juice_limit_per_tx: Field, } diff --git a/noir-projects/noir-contracts/contracts/app_subscription_contract/src/main.nr b/noir-projects/noir-contracts/contracts/app_subscription_contract/src/main.nr index 369811545d8..dc874784895 100644 --- a/noir-projects/noir-contracts/contracts/app_subscription_contract/src/main.nr +++ b/noir-projects/noir-contracts/contracts/app_subscription_contract/src/main.nr @@ -67,7 +67,7 @@ pub contract AppSubscription { target_address: AztecAddress, subscription_recipient_address: AztecAddress, subscription_token_address: AztecAddress, - subscription_price: U128, + subscription_price: u128, fee_juice_limit_per_tx: Field, ) { storage.config.initialize( diff --git a/noir-projects/noir-contracts/contracts/avm_test_contract/src/main.nr b/noir-projects/noir-contracts/contracts/avm_test_contract/src/main.nr index 57e0ddf6ae2..aa4a66a0a3f 100644 --- a/noir-projects/noir-contracts/contracts/avm_test_contract/src/main.nr +++ b/noir-projects/noir-contracts/contracts/avm_test_contract/src/main.nr @@ -135,7 +135,7 @@ pub contract AvmTest { } #[public] - fn add_u128(a: U128, b: U128) -> U128 { + fn add_u128(a: u128, b: u128) -> u128 { a + b } @@ -193,18 +193,12 @@ pub contract AvmTest { ************************************************************************/ #[public] - fn u128_addition_overflow() -> U128 { - let max_u128: U128 = U128::from_hex("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"); - let one: U128 = U128::from_integer(1); + fn u128_addition_overflow() -> u128 { + let max_u128: u128 = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; + let one: u128 = 1; max_u128 + one } - #[public] - fn u128_from_integer_overflow() -> U128 { - let should_overflow: Field = 2.pow_32(128); // U128::max() + 1; - U128::from_integer(should_overflow) - } - #[public] fn to_radix_le(input: Field) -> [u8; 10] { input.to_le_radix(/*base=*/ 2) diff --git a/noir-projects/noir-contracts/contracts/crowdfunding_contract/src/main.nr b/noir-projects/noir-contracts/contracts/crowdfunding_contract/src/main.nr index 53f3199e60b..6d464737fcb 100644 --- a/noir-projects/noir-contracts/contracts/crowdfunding_contract/src/main.nr +++ b/noir-projects/noir-contracts/contracts/crowdfunding_contract/src/main.nr @@ -31,7 +31,7 @@ pub contract Crowdfunding { #[event] struct WithdrawalProcessed { who: AztecAddress, - amount: U128, + amount: u128, } // docs:start:storage @@ -59,7 +59,7 @@ pub contract Crowdfunding { // docs:start:donate #[private] - fn donate(amount: U128) { + fn donate(amount: u128) { let config = storage.config.read(); // 1) Check that the deadline has not passed --> we do that via the router contract to conceal which contract @@ -91,7 +91,7 @@ pub contract Crowdfunding { // docs:start:operator-withdrawals // Withdraws balance to the operator. Requires that msg_sender() is the operator. #[private] - fn withdraw(amount: U128) { + fn withdraw(amount: u128) { let config = storage.config.read(); let operator_address = config.operator; @@ -109,7 +109,7 @@ pub contract Crowdfunding { #[public] #[internal] - fn _publish_donation_receipts(amount: U128, to: AztecAddress) { + fn _publish_donation_receipts(amount: u128, to: AztecAddress) { WithdrawalProcessed { amount, who: to }.emit(encode_event(&mut context)); } } diff --git a/noir-projects/noir-contracts/contracts/escrow_contract/src/main.nr b/noir-projects/noir-contracts/contracts/escrow_contract/src/main.nr index 03be3686285..f1272a74677 100644 --- a/noir-projects/noir-contracts/contracts/escrow_contract/src/main.nr +++ b/noir-projects/noir-contracts/contracts/escrow_contract/src/main.nr @@ -37,7 +37,7 @@ pub contract Escrow { // Withdraws balance. Requires that msg.sender is the owner. #[private] - fn withdraw(token: AztecAddress, amount: U128, recipient: AztecAddress) { + fn withdraw(token: AztecAddress, amount: u128, recipient: AztecAddress) { let sender = context.msg_sender(); let note = storage.owner.get_note(); diff --git a/noir-projects/noir-contracts/contracts/escrow_contract/src/test.nr b/noir-projects/noir-contracts/contracts/escrow_contract/src/test.nr index ed3337a83ca..4d98ed6fe20 100644 --- a/noir-projects/noir-contracts/contracts/escrow_contract/src/test.nr +++ b/noir-projects/noir-contracts/contracts/escrow_contract/src/test.nr @@ -12,14 +12,14 @@ use aztec::{ pub unconstrained fn get_public_balance( token_contract_address: AztecAddress, address: AztecAddress, -) -> U128 { +) -> u128 { let current_contract_address = get_contract_address(); cheatcodes::set_contract_address(token_contract_address); let block_number = get_block_number(); let balances_slot = Token::storage_layout().public_balances.slot; let address_slot = derive_storage_slot_in_map(balances_slot, address); - let amount: U128 = storage_read(token_contract_address, address_slot, block_number); + let amount: u128 = storage_read(token_contract_address, address_slot, block_number); cheatcodes::set_contract_address(current_contract_address); amount } @@ -27,7 +27,7 @@ pub unconstrained fn get_public_balance( pub unconstrained fn get_private_balance( token_contract_address: AztecAddress, address: AztecAddress, -) -> U128 { +) -> u128 { let current_contract_address = get_contract_address(); cheatcodes::set_contract_address(token_contract_address); // Direct call to unconstrained @@ -36,7 +36,7 @@ pub unconstrained fn get_private_balance( amt } -global MINT_AMOUNT: U128 = U128::from_integer(200000); +global MINT_AMOUNT: u128 = 200000; unconstrained fn deploy_contracts( env: &mut TestEnvironment, @@ -88,7 +88,7 @@ unconstrained fn main() { let (token_contract_address, escrow_contract_address) = deploy_contracts(&mut env, account_1); // We transfer tokens to the escrow contract - let TRANSFER_AMOUNT = U128::from_integer(20000); + let TRANSFER_AMOUNT = 20000 as u128; Token::at(token_contract_address).transfer(escrow_contract_address, TRANSFER_AMOUNT).call( &mut env.private(), ); @@ -102,9 +102,9 @@ unconstrained fn main() { // We then withdraw some escrowed funds to account_2 let balance_of_account_2_before_withdrawal = get_private_balance(token_contract_address, account_2); - assert(balance_of_account_2_before_withdrawal == U128::zero()); + assert(balance_of_account_2_before_withdrawal == 0 as u128); - let WITHDRAWAL_AMOUNT = U128::from_integer(69); + let WITHDRAWAL_AMOUNT = 69 as u128; Escrow::at(escrow_contract_address) .withdraw(token_contract_address, WITHDRAWAL_AMOUNT, account_2) .call(&mut env.private()); diff --git a/noir-projects/noir-contracts/contracts/fee_juice_contract/src/lib.nr b/noir-projects/noir-contracts/contracts/fee_juice_contract/src/lib.nr index 390dc878c25..76ef9bf8a8b 100644 --- a/noir-projects/noir-contracts/contracts/fee_juice_contract/src/lib.nr +++ b/noir-projects/noir-contracts/contracts/fee_juice_contract/src/lib.nr @@ -6,10 +6,10 @@ pub fn calculate_fee(context: PublicContext) -> Field { context.transaction_fee() } -pub fn get_bridge_gas_msg_hash(owner: AztecAddress, amount: U128) -> Field { +pub fn get_bridge_gas_msg_hash(owner: AztecAddress, amount: u128) -> Field { let mut hash_bytes = [0; 68]; let recipient_bytes: [u8; 32] = owner.to_field().to_be_bytes(); - let amount_bytes: [u8; 32] = amount.to_field().to_be_bytes(); + let amount_bytes: [u8; 32] = (amount as Field).to_be_bytes(); // The purpose of including the following selector is to make the message unique to that specific call. Note that // it has nothing to do with calling the function. diff --git a/noir-projects/noir-contracts/contracts/fee_juice_contract/src/main.nr b/noir-projects/noir-contracts/contracts/fee_juice_contract/src/main.nr index d9380bf16c1..abe3f9967ad 100644 --- a/noir-projects/noir-contracts/contracts/fee_juice_contract/src/main.nr +++ b/noir-projects/noir-contracts/contracts/fee_juice_contract/src/main.nr @@ -16,14 +16,14 @@ pub contract FeeJuice { struct Storage { // This map is accessed directly by protocol circuits to check balances for fee payment. // Do not change this storage layout unless you also update the base rollup circuits. - balances: Map, Context>, + balances: Map, Context>, portal_address: PublicImmutable, } // Not flagged as initializer to reduce cost of checking init nullifier in all functions. // This function should be called as entrypoint to initialize the contract by minting itself funds. #[private] - fn initialize(portal_address: EthAddress, initial_mint: U128) { + fn initialize(portal_address: EthAddress, initial_mint: u128) { // Validate contract class parameters are correct let self = context.this_address(); @@ -46,7 +46,7 @@ pub contract FeeJuice { } #[private] - fn claim(to: AztecAddress, amount: U128, secret: Field, message_leaf_index: Field) { + fn claim(to: AztecAddress, amount: u128, secret: Field, message_leaf_index: Field) { let content_hash = get_bridge_gas_msg_hash(to, amount); let portal_address = storage.portal_address.read(); assert(!portal_address.is_zero()); @@ -63,21 +63,21 @@ pub contract FeeJuice { #[public] #[internal] - fn _increase_public_balance(to: AztecAddress, amount: U128) { + fn _increase_public_balance(to: AztecAddress, amount: u128) { let new_balance = storage.balances.at(to).read().add(amount); storage.balances.at(to).write(new_balance); } #[public] #[view] - fn check_balance(fee_limit: U128) { + fn check_balance(fee_limit: u128) { assert(storage.balances.at(context.msg_sender()).read() >= fee_limit, "Balance too low"); } // utility function for testing #[public] #[view] - fn balance_of_public(owner: AztecAddress) -> pub U128 { + fn balance_of_public(owner: AztecAddress) -> pub u128 { storage.balances.at(owner).read() } } diff --git a/noir-projects/noir-contracts/contracts/fpc_contract/src/main.nr b/noir-projects/noir-contracts/contracts/fpc_contract/src/main.nr index 1bba78878d6..a2ebf7506d3 100644 --- a/noir-projects/noir-contracts/contracts/fpc_contract/src/main.nr +++ b/noir-projects/noir-contracts/contracts/fpc_contract/src/main.nr @@ -1,4 +1,5 @@ mod config; +mod utils; use dep::aztec::macros::aztec; @@ -10,13 +11,13 @@ use dep::aztec::macros::aztec; /// be pulled by the admin using the `pull_funds` function. #[aztec] pub contract FPC { - use crate::config::Config; - use dep::aztec::{ + use crate::{config::Config, utils::safe_cast_to_u128}; + use aztec::{ macros::{functions::{initializer, internal, private, public}, storage::storage}, protocol_types::{abis::function_selector::FunctionSelector, address::AztecAddress}, state_vars::PublicImmutable, }; - use dep::token::Token; + use token::Token; #[storage] struct Storage { @@ -75,7 +76,7 @@ pub contract FPC { /// - the asset which was used to make the payment. // docs:start:fee_entrypoint_private #[private] - fn fee_entrypoint_private(max_fee: U128, nonce: Field) { + fn fee_entrypoint_private(max_fee: u128, nonce: Field) { let accepted_asset = storage.config.read().accepted_asset; let user = context.msg_sender(); @@ -91,13 +92,10 @@ pub contract FPC { let refund_slot = token.prepare_private_balance_increase(user, user).call(&mut context); // Set a public teardown function in which the refund will be paid back to the user by finalizing the partial note. - let max_fee_serialized = max_fee.serialize(); context.set_public_teardown_function( context.this_address(), - comptime { - FunctionSelector::from_signature("complete_refund((Field),Field,(Field,Field))") - }, - [accepted_asset.to_field(), refund_slot, max_fee_serialized[0], max_fee_serialized[1]], + comptime { FunctionSelector::from_signature("complete_refund((Field),Field,u128)") }, + [accepted_asset.to_field(), refund_slot, max_fee as Field], ); // Set the FPC as the fee payer of the tx. @@ -110,8 +108,8 @@ pub contract FPC { // docs:start:complete_refund #[public] #[internal] - fn complete_refund(accepted_asset: AztecAddress, refund_slot: Field, max_fee: U128) { - let tx_fee = U128::from_integer(context.transaction_fee()); + fn complete_refund(accepted_asset: AztecAddress, refund_slot: Field, max_fee: u128) { + let tx_fee = safe_cast_to_u128(context.transaction_fee()); // 1. Check that user funded the fee payer contract with at least the transaction fee. // TODO(#10805): Nuke this check once we have a proper max_fee check in the fee_entrypoint_private. @@ -148,7 +146,7 @@ pub contract FPC { /// Protocol-enshrined fee-payment phase: /// 4. The protocol deducts the actual fee denominated in fee juice from the FPC's balance. #[private] - fn fee_entrypoint_public(max_fee: U128, nonce: Field) { + fn fee_entrypoint_public(max_fee: u128, nonce: Field) { let config = storage.config.read(); // We pull the max fee from the user's balance of the accepted asset to this contract. @@ -161,18 +159,10 @@ pub contract FPC { context.set_as_fee_payer(); // TODO(#6277) for improving interface: // FPC::at(context.this_address()).pay_refund(...).set_public_teardown_function(&mut context); - let max_fee_serialized = max_fee.serialize(); context.set_public_teardown_function( context.this_address(), - comptime { - FunctionSelector::from_signature("pay_refund((Field),(Field,Field),(Field))") - }, - [ - context.msg_sender().to_field(), - max_fee_serialized[0], - max_fee_serialized[1], - config.accepted_asset.to_field(), - ], + comptime { FunctionSelector::from_signature("pay_refund((Field),u128,(Field))") }, + [context.msg_sender().to_field(), max_fee as Field, config.accepted_asset.to_field()], ); } @@ -181,8 +171,9 @@ pub contract FPC { /// It's passed as an argument to avoid the need for another read from public storage. #[public] #[internal] - fn pay_refund(refund_recipient: AztecAddress, max_fee: U128, accepted_asset: AztecAddress) { - let actual_fee = U128::from_integer(context.transaction_fee()); + fn pay_refund(refund_recipient: AztecAddress, max_fee: u128, accepted_asset: AztecAddress) { + let actual_fee = safe_cast_to_u128(context.transaction_fee()); + assert(actual_fee <= max_fee, "Max fee paid to the paymaster does not cover actual fee"); // TODO(#10805): Introduce a real exchange rate let refund = max_fee - actual_fee; diff --git a/noir-projects/noir-contracts/contracts/fpc_contract/src/utils.nr b/noir-projects/noir-contracts/contracts/fpc_contract/src/utils.nr new file mode 100644 index 00000000000..6606a03fb39 --- /dev/null +++ b/noir-projects/noir-contracts/contracts/fpc_contract/src/utils.nr @@ -0,0 +1,4 @@ +pub(crate) fn safe_cast_to_u128(field: Field) -> u128 { + field.assert_max_bit_size::<128>(); + field as u128 +} diff --git a/noir-projects/noir-contracts/contracts/lending_contract/src/asset.nr b/noir-projects/noir-contracts/contracts/lending_contract/src/asset.nr index 67a98b0fd2d..d137bd7e0ed 100644 --- a/noir-projects/noir-contracts/contracts/lending_contract/src/asset.nr +++ b/noir-projects/noir-contracts/contracts/lending_contract/src/asset.nr @@ -11,8 +11,8 @@ use std::meta::derive; /// up rewriting all the values. #[derive(Deserialize, Packable, Serialize)] pub struct Asset { - interest_accumulator: U128, + interest_accumulator: u128, last_updated_ts: u64, - loan_to_value: U128, + loan_to_value: u128, oracle: AztecAddress, } diff --git a/noir-projects/noir-contracts/contracts/lending_contract/src/helpers.nr b/noir-projects/noir-contracts/contracts/lending_contract/src/helpers.nr index 0d186db0d60..4736b922681 100644 --- a/noir-projects/noir-contracts/contracts/lending_contract/src/helpers.nr +++ b/noir-projects/noir-contracts/contracts/lending_contract/src/helpers.nr @@ -14,14 +14,14 @@ pub fn compute_identifier(secret: Field, on_behalf_of: Field, self: Field) -> Fi } pub fn covered_by_collateral( - 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); + price: u128, + loan_to_value: u128, + collateral: u128, + increase: u128, + decrease: u128, +) -> u128 { + let price_precision = 1000000000 as u128; + let ltv_precision = 10000 as u128; let collateral = (collateral + increase) - decrease; @@ -32,27 +32,27 @@ pub fn covered_by_collateral( } pub struct DebtReturn { - debt_value: U128, - static_debt: U128, + debt_value: u128, + static_debt: u128, } -fn div_up(a: U128, b: U128) -> U128 { +fn div_up(a: u128, b: u128) -> u128 { let div = a / b; if div * b < a { - div + U128::from_integer(1) + div + (1 as u128) } else { div } } pub fn debt_updates( - interest_accumulator: U128, - static_debt: U128, - increase: U128, - decrease: U128, + interest_accumulator: u128, + static_debt: u128, + increase: u128, + decrease: u128, ) -> DebtReturn { - assert(interest_accumulator > U128::from_integer(0)); - let accumulator_precision = U128::from_integer(1000000000); + assert(interest_accumulator > (0 as u128)); + let accumulator_precision = 1000000000 as u128; let current_debt_value = (static_debt * interest_accumulator) / accumulator_precision; let new_debt_value = current_debt_value.add(increase).sub(decrease); @@ -70,7 +70,7 @@ pub fn debt_updates( DebtReturn { debt_value: new_debt_value, static_debt: new_static_debt } } -pub fn debt_value(static_debt: U128, interest_accumulator: U128) -> U128 { - let accumulator_precision = U128::from_integer(1000000000); +pub fn debt_value(static_debt: u128, interest_accumulator: u128) -> u128 { + let accumulator_precision = 1000000000 as u128; div_up(static_debt * interest_accumulator, accumulator_precision) } diff --git a/noir-projects/noir-contracts/contracts/lending_contract/src/interest_math.nr b/noir-projects/noir-contracts/contracts/lending_contract/src/interest_math.nr index e3e1e2e1d1b..2d0a4e69f43 100644 --- a/noir-projects/noir-contracts/contracts/lending_contract/src/interest_math.nr +++ b/noir-projects/noir-contracts/contracts/lending_contract/src/interest_math.nr @@ -5,15 +5,15 @@ // dividing with 31536000 (seconds per year). // rate must be measured with higher precision than 10^9. // we use e18, and rates >= 4% yearly. Otherwise need more precision -pub fn compute_multiplier(rate_per_second: U128, dt: u64) -> U128 { - let base = U128::from_integer(1000000000); // 1e9 - let WAD = U128::from_integer(1000000000000000000); // 1e18 +pub fn compute_multiplier(rate_per_second: u128, dt: u64) -> u128 { + let base = 1000000000 as u128; // 1e9 + let WAD = 1000000000000000000 as u128; // 1e18 let diff = WAD.div(base); let mut res = base; if dt != 0 { - let exp_minus_one = U128::from_integer(dt - 1); - let exp_minus_two = U128::from_integer(if (dt > 2) { dt - 2 } else { 0 }); - let dt = U128::from_integer(dt); + let exp_minus_one = (dt - 1) as u128; + let exp_minus_two = (if (dt > 2) { dt - 2 } else { 0 }) as u128; + let dt = dt as u128; // if rate_per_second < sqrt(WAD), then base_power_two and base_power_three = 0 let rate = rate_per_second; @@ -21,8 +21,8 @@ pub fn compute_multiplier(rate_per_second: U128, dt: u64) -> U128 { let base_power_three = (base_power_two * rate) / WAD; let temp = dt.mul(exp_minus_one); - let second_term = temp.mul(base_power_two).div(U128::from_integer(2)); - let third_term = temp.mul(exp_minus_two).mul(base_power_three).div(U128::from_integer(6)); + let second_term = temp.mul(base_power_two).div(2 as u128); + let third_term = temp.mul(exp_minus_two).mul(base_power_three).div(6 as u128); // throwing away precision to keep us under u128 :sob: let offset = dt.mul(rate).add(second_term).add(third_term).div(diff); diff --git a/noir-projects/noir-contracts/contracts/lending_contract/src/main.nr b/noir-projects/noir-contracts/contracts/lending_contract/src/main.nr index 49922a06eae..3cf0c298d43 100644 --- a/noir-projects/noir-contracts/contracts/lending_contract/src/main.nr +++ b/noir-projects/noir-contracts/contracts/lending_contract/src/main.nr @@ -34,8 +34,8 @@ pub contract Lending { collateral_asset: PublicMutable, stable_coin: PublicMutable, assets: Map, Context>, - collateral: Map, Context>, - static_debt: Map, Context>, // abusing keys very heavily + collateral: Map, Context>, + static_debt: Map, Context>, // abusing keys very heavily } // Constructs the contract. @@ -46,7 +46,7 @@ pub contract Lending { #[public] fn init( oracle: AztecAddress, - loan_to_value: U128, + loan_to_value: u128, collateral_asset: AztecAddress, stable_coin: AztecAddress, ) { @@ -55,15 +55,15 @@ pub contract Lending { let loan_to_value = loan_to_value; - assert(loan_to_value <= U128::from_integer(10000)); + assert(loan_to_value <= (10000 as u128)); assert(asset.last_updated_ts == 0); - assert(asset.interest_accumulator == U128::zero()); + assert(asset.interest_accumulator == 0 as u128); let last_updated_ts = context.timestamp(); asset_loc.write( Asset { - interest_accumulator: U128::from_integer(1000000000), + interest_accumulator: 1000000000 as u128, last_updated_ts, loan_to_value, oracle, @@ -85,8 +85,8 @@ pub contract Lending { // Only update if time has passed. if !(dt == 0) { - let precision = U128::from_integer(1000000000); - let rate_per_second = U128::from_integer(1268391679); // 4% yearly rate / (60 * 60 * 24 * 365) + let precision = 1000000000 as u128; + let rate_per_second = 1268391679 as u128; // 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); @@ -103,7 +103,7 @@ pub contract Lending { #[private] fn deposit_private( from: AztecAddress, - amount: U128, + amount: u128, nonce: Field, secret: Field, on_behalf_of: Field, @@ -123,7 +123,7 @@ pub contract Lending { #[public] fn deposit_public( - amount: U128, + amount: u128, nonce: Field, on_behalf_of: Field, collateral_asset: AztecAddress, @@ -140,7 +140,7 @@ pub contract Lending { #[public] #[internal] - fn _deposit(owner: AztecAddress, amount: U128, collateral_asset: AztecAddress) { + fn _deposit(owner: AztecAddress, amount: u128, collateral_asset: AztecAddress) { let _asset = Lending::at(context.this_address()).update_accumulator().call(&mut context); let coll_asset = storage.collateral_asset.read(); @@ -152,7 +152,7 @@ pub contract Lending { } #[private] - fn withdraw_private(secret: Field, to: AztecAddress, amount: U128) { + fn withdraw_private(secret: Field, to: AztecAddress, amount: u128) { let on_behalf_of = compute_identifier(secret, 0, context.msg_sender().to_field()); Lending::at(context.this_address()) ._withdraw(AztecAddress::from_field(on_behalf_of), to, amount) @@ -160,7 +160,7 @@ pub contract Lending { } #[public] - fn withdraw_public(to: AztecAddress, amount: U128) { + fn withdraw_public(to: AztecAddress, amount: u128) { let _ = Lending::at(context.this_address()) ._withdraw(context.msg_sender(), to, amount) .call(&mut context); @@ -168,7 +168,7 @@ pub contract Lending { #[public] #[internal] - fn _withdraw(owner: AztecAddress, recipient: AztecAddress, amount: U128) { + fn _withdraw(owner: AztecAddress, recipient: AztecAddress, amount: u128) { let asset = Lending::at(context.this_address()).update_accumulator().call(&mut context); let price = PriceFeed::at(asset.oracle).get_price(0).view(&mut context).price; @@ -181,12 +181,12 @@ pub contract Lending { // debt_covered will revert if decrease would leave insufficient collateral to cover debt. // or trying to remove more collateral than available let debt_covered = - covered_by_collateral(price, asset.loan_to_value, collateral, U128::zero(), amount); + covered_by_collateral(price, asset.loan_to_value, collateral, 0 as u128, amount); let debt_returns = debt_updates( asset.interest_accumulator, static_debt, - U128::zero(), - U128::zero(), + 0 as u128, + 0 as u128, ); assert(debt_returns.debt_value < debt_covered); @@ -201,7 +201,7 @@ pub contract Lending { } #[private] - fn borrow_private(secret: Field, to: AztecAddress, amount: U128) { + fn borrow_private(secret: Field, to: AztecAddress, amount: u128) { let on_behalf_of = compute_identifier(secret, 0, context.msg_sender().to_field()); let _ = Lending::at(context.this_address()) ._borrow(AztecAddress::from_field(on_behalf_of), to, amount) @@ -209,7 +209,7 @@ pub contract Lending { } #[public] - fn borrow_public(to: AztecAddress, amount: U128) { + fn borrow_public(to: AztecAddress, amount: u128) { let _ = Lending::at(context.this_address())._borrow(context.msg_sender(), to, amount).call( &mut context, ); @@ -217,7 +217,7 @@ pub contract Lending { #[public] #[internal] - fn _borrow(owner: AztecAddress, to: AztecAddress, amount: U128) { + fn _borrow(owner: AztecAddress, to: AztecAddress, amount: u128) { let asset = Lending::at(context.this_address()).update_accumulator().call(&mut context); let price = PriceFeed::at(asset.oracle).get_price(0).view(&mut context).price; @@ -225,19 +225,9 @@ pub contract Lending { let collateral = storage.collateral.at(owner).read(); let static_debt = storage.static_debt.at(owner).read(); - let debt_covered = covered_by_collateral( - price, - asset.loan_to_value, - collateral, - U128::zero(), - U128::zero(), - ); - let debt_returns = debt_updates( - asset.interest_accumulator, - static_debt, - amount, - U128::zero(), - ); + let debt_covered = + covered_by_collateral(price, asset.loan_to_value, collateral, 0 as u128, 0 as u128); + let debt_returns = debt_updates(asset.interest_accumulator, static_debt, amount, 0 as u128); assert(debt_returns.debt_value < debt_covered); @@ -251,7 +241,7 @@ pub contract Lending { #[private] fn repay_private( from: AztecAddress, - amount: U128, + amount: u128, nonce: Field, secret: Field, on_behalf_of: Field, @@ -268,7 +258,7 @@ pub contract Lending { } #[public] - fn repay_public(amount: U128, nonce: Field, owner: AztecAddress, stable_coin: AztecAddress) { + fn repay_public(amount: u128, nonce: Field, owner: AztecAddress, stable_coin: AztecAddress) { let _ = Token::at(stable_coin).burn_public(context.msg_sender(), amount, nonce).call( &mut context, ); @@ -279,19 +269,14 @@ pub contract Lending { #[public] #[internal] - fn _repay(owner: AztecAddress, amount: U128, stable_coin: AztecAddress) { + fn _repay(owner: AztecAddress, amount: u128, stable_coin: AztecAddress) { let asset = Lending::at(context.this_address()).update_accumulator().call(&mut context); // To ensure that private is using the correct token. assert(stable_coin.eq(storage.stable_coin.read())); let static_debt = storage.static_debt.at(owner).read(); - let debt_returns = debt_updates( - asset.interest_accumulator, - static_debt, - U128::zero(), - amount, - ); + let debt_returns = debt_updates(asset.interest_accumulator, static_debt, 0 as u128, amount); storage.static_debt.at(owner).write(debt_returns.static_debt); } diff --git a/noir-projects/noir-contracts/contracts/lending_contract/src/position.nr b/noir-projects/noir-contracts/contracts/lending_contract/src/position.nr index d708161133d..610a0ba6a12 100644 --- a/noir-projects/noir-contracts/contracts/lending_contract/src/position.nr +++ b/noir-projects/noir-contracts/contracts/lending_contract/src/position.nr @@ -3,7 +3,7 @@ use std::meta::derive; #[derive(Serialize, Deserialize)] pub struct Position { - collateral: U128, - static_debt: U128, - debt: U128, + collateral: u128, + static_debt: u128, + debt: u128, } diff --git a/noir-projects/noir-contracts/contracts/price_feed_contract/src/asset.nr b/noir-projects/noir-contracts/contracts/price_feed_contract/src/asset.nr index 8a16ce4abfb..a1c0a95e71d 100644 --- a/noir-projects/noir-contracts/contracts/price_feed_contract/src/asset.nr +++ b/noir-projects/noir-contracts/contracts/price_feed_contract/src/asset.nr @@ -3,5 +3,5 @@ use std::meta::derive; #[derive(Deserialize, Packable, Serialize)] pub struct Asset { - price: U128, + price: u128, } diff --git a/noir-projects/noir-contracts/contracts/price_feed_contract/src/main.nr b/noir-projects/noir-contracts/contracts/price_feed_contract/src/main.nr index 5e773817ff1..cddea23ed63 100644 --- a/noir-projects/noir-contracts/contracts/price_feed_contract/src/main.nr +++ b/noir-projects/noir-contracts/contracts/price_feed_contract/src/main.nr @@ -16,7 +16,7 @@ pub contract PriceFeed { } #[public] - fn set_price(asset_id: Field, price: U128) { + fn set_price(asset_id: Field, price: u128) { let asset = storage.assets.at(asset_id); asset.write(Asset { price }); } diff --git a/noir-projects/noir-contracts/contracts/spam_contract/src/main.nr b/noir-projects/noir-contracts/contracts/spam_contract/src/main.nr index 4e3e9302f7c..66390a43630 100644 --- a/noir-projects/noir-contracts/contracts/spam_contract/src/main.nr +++ b/noir-projects/noir-contracts/contracts/spam_contract/src/main.nr @@ -24,13 +24,13 @@ pub contract Spam { #[storage] struct Storage { balances: Map, Context>, - public_balances: Map, Context>, + public_balances: Map, Context>, } #[private] fn spam(nullifier_seed: Field, nullifier_count: u32, call_public: bool) { let caller = context.msg_sender(); - let amount = U128::from_integer(1); + let amount = 1 as u128; for _ in 0..MAX_NOTE_HASHES_PER_CALL { storage.balances.at(caller).add(caller, amount).emit( @@ -63,7 +63,7 @@ pub contract Spam { #[public] #[internal] fn public_spam(start: u32, end: u32) { - let one = U128::from_integer(1); + let one = 1 as u128; for i in start..end { let prev = storage.public_balances.at(i as Field).read(); storage.public_balances.at(i as Field).write(prev + one); diff --git a/noir-projects/noir-contracts/contracts/spam_contract/src/types/balance_set.nr b/noir-projects/noir-contracts/contracts/spam_contract/src/types/balance_set.nr index b5817b639f0..a83c92df7d3 100644 --- a/noir-projects/noir-contracts/contracts/spam_contract/src/types/balance_set.nr +++ b/noir-projects/noir-contracts/contracts/spam_contract/src/types/balance_set.nr @@ -23,18 +23,18 @@ impl BalanceSet { } impl BalanceSet { - pub unconstrained fn balance_of(self: Self) -> U128 + pub unconstrained fn balance_of(self: Self) -> u128 where Note: NoteType + NoteHash + OwnedNote + Packable, { self.balance_of_with_offset(0) } - pub unconstrained fn balance_of_with_offset(self: Self, offset: u32) -> U128 + pub unconstrained fn balance_of_with_offset(self: Self, offset: u32) -> u128 where Note: NoteType + NoteHash + OwnedNote + Packable, { - let mut balance = U128::from_integer(0); + let mut balance = 0 as u128; // docs:start:view_notes let mut options = NoteViewerOptions::new(); let notes = self.set.view_notes(options.set_offset(offset)); @@ -53,11 +53,11 @@ impl BalanceSet { } impl BalanceSet { - pub fn add(self: Self, owner: AztecAddress, addend: U128) -> OuterNoteEmission + pub fn add(self: Self, owner: AztecAddress, addend: u128) -> OuterNoteEmission where Note: NoteType + NoteHash + OwnedNote + Eq + Packable, { - if addend == U128::from_integer(0) { + if addend == 0 as u128 { OuterNoteEmission::new(Option::none()) } else { let mut addend_note = Note::new(addend, owner); @@ -68,7 +68,7 @@ impl BalanceSet { } } - pub fn sub(self: Self, owner: AztecAddress, amount: U128) -> OuterNoteEmission + pub fn sub(self: Self, owner: AztecAddress, amount: u128) -> OuterNoteEmission where Note: NoteType + NoteHash + OwnedNote + Eq + Packable, { @@ -89,7 +89,7 @@ impl BalanceSet { // The `max_notes` parameter is used to fine-tune the number of constraints created by this function. The gate count // scales relatively linearly with `max_notes`, but a lower `max_notes` parameter increases the likelihood of // `try_sub` subtracting an amount smaller than `target_amount`. - pub fn try_sub(self: Self, target_amount: U128, max_notes: u32) -> U128 + pub fn try_sub(self: Self, target_amount: u128, max_notes: u32) -> u128 where Note: NoteType + NoteHash + OwnedNote + Eq + Packable, { @@ -102,7 +102,7 @@ impl BalanceSet { .set_limit(max_notes); let notes = self.set.pop_notes(options); - let mut subtracted = U128::from_integer(0); + let mut subtracted = 0 as u128; for i in 0..options.limit { if i < notes.len() { let note = notes.get_unchecked(i); @@ -121,13 +121,13 @@ impl BalanceSet { // Note that proper usage of this preprocessor requires for notes to be sorted in descending order. pub fn preprocess_notes_min_sum( notes: [Option>; MAX_NOTE_HASH_READ_REQUESTS_PER_CALL], - min_sum: U128, + min_sum: u128, ) -> [Option>; MAX_NOTE_HASH_READ_REQUESTS_PER_CALL] where Note: NoteType + NoteHash + OwnedNote, { let mut selected = [Option::none(); MAX_NOTE_HASH_READ_REQUESTS_PER_CALL]; - let mut sum = U128::from_integer(0); + let mut sum = 0 as u128; for i in 0..notes.len() { // Because we process notes in retrieved order, notes need to be sorted in descending amount order for this // filter to be useful. Consider a 'min_sum' of 4, and a set of notes with amounts [3, 2, 1, 1, 1, 1, 1]. If diff --git a/noir-projects/noir-contracts/contracts/spam_contract/src/types/token_note.nr b/noir-projects/noir-contracts/contracts/spam_contract/src/types/token_note.nr index 54e80a1b931..c33728e5ac9 100644 --- a/noir-projects/noir-contracts/contracts/spam_contract/src/types/token_note.nr +++ b/noir-projects/noir-contracts/contracts/spam_contract/src/types/token_note.nr @@ -3,15 +3,15 @@ use dep::aztec::{ }; trait OwnedNote { - fn new(amount: U128, owner: AztecAddress) -> Self; - fn get_amount(self) -> U128; + fn new(amount: u128, owner: AztecAddress) -> Self; + fn get_amount(self) -> u128; } // docs:start:TokenNote #[note] #[derive(Eq)] pub struct TokenNote { // The amount of tokens in the note - amount: U128, + amount: u128, // The owner of the note owner: AztecAddress, // Randomness of the note to protect against note hash preimage attacks @@ -20,7 +20,7 @@ pub struct TokenNote { // docs:end:TokenNote impl OwnedNote for TokenNote { - fn new(amount: U128, owner: AztecAddress) -> Self { + fn new(amount: u128, owner: AztecAddress) -> Self { // Safety: We use the randomness to preserve the privacy of the note recipient by preventing brute-forcing, // so a malicious sender could use non-random values to make the note less private. But they already know // the full note pre-image anyway, and so the recipient already trusts them to not disclose this @@ -29,7 +29,7 @@ impl OwnedNote for TokenNote { Self { amount, owner, randomness } } - fn get_amount(self) -> U128 { + fn get_amount(self) -> u128 { self.amount } } diff --git a/noir-projects/noir-contracts/contracts/test_contract/src/main.nr b/noir-projects/noir-contracts/contracts/test_contract/src/main.nr index 0fb8600dfcf..ad75d4def0d 100644 --- a/noir-projects/noir-contracts/contracts/test_contract/src/main.nr +++ b/noir-projects/noir-contracts/contracts/test_contract/src/main.nr @@ -377,7 +377,7 @@ pub contract Test { #[public] fn consume_mint_to_public_message( to: AztecAddress, - amount: U128, + amount: u128, secret: Field, message_leaf_index: Field, portal_address: EthAddress, @@ -389,7 +389,7 @@ pub contract Test { #[private] fn consume_mint_to_private_message( - amount: U128, + amount: u128, secret_for_L1_to_L2_message_consumption: Field, portal_address: EthAddress, message_leaf_index: Field, diff --git a/noir-projects/noir-contracts/contracts/token_blacklist_contract/src/main.nr b/noir-projects/noir-contracts/contracts/token_blacklist_contract/src/main.nr index 351f2f1df1f..df6c4e714fa 100644 --- a/noir-projects/noir-contracts/contracts/token_blacklist_contract/src/main.nr +++ b/noir-projects/noir-contracts/contracts/token_blacklist_contract/src/main.nr @@ -46,9 +46,9 @@ pub contract TokenBlacklist { #[storage] struct Storage { balances: BalancesMap, - total_supply: PublicMutable, + total_supply: PublicMutable, pending_shields: PrivateSet, - public_balances: Map, Context>, + public_balances: Map, Context>, roles: Map, Context>, } @@ -87,14 +87,13 @@ pub contract TokenBlacklist { } #[public] - fn mint_public(to: AztecAddress, amount: Field) { + fn mint_public(to: AztecAddress, amount: u128) { let to_roles = storage.roles.at(to).get_current_value(); assert(!to_roles.is_blacklisted, "Blacklisted: Recipient"); let caller_roles = storage.roles.at(context.msg_sender()).get_current_value(); assert(caller_roles.is_minter, "caller is not minter"); - let amount = U128::from_integer(amount); let new_balance = storage.public_balances.at(to).read().add(amount); let supply = storage.total_supply.read().add(amount); @@ -103,13 +102,13 @@ pub contract TokenBlacklist { } #[public] - fn mint_private(amount: Field, secret_hash: Field) { + fn mint_private(amount: u128, secret_hash: Field) { let caller_roles = storage.roles.at(context.msg_sender()).get_current_value(); assert(caller_roles.is_minter, "caller is not minter"); let pending_shields = storage.pending_shields; let note = TransparentNote::new(amount, secret_hash); - let supply = storage.total_supply.read().add(U128::from_integer(amount)); + let supply = storage.total_supply.read().add(amount); storage.total_supply.write(supply); @@ -121,7 +120,7 @@ pub contract TokenBlacklist { } #[public] - fn shield(from: AztecAddress, amount: Field, secret_hash: Field, nonce: Field) { + fn shield(from: AztecAddress, amount: u128, secret_hash: Field, nonce: Field) { let from_roles = storage.roles.at(from).get_current_value(); assert(!from_roles.is_blacklisted, "Blacklisted: Sender"); @@ -132,11 +131,10 @@ pub contract TokenBlacklist { assert(nonce == 0, "invalid nonce"); } - let amount = U128::from_integer(amount); let from_balance = storage.public_balances.at(from).read().sub(amount); let pending_shields = storage.pending_shields; - let note = TransparentNote::new(amount.to_field(), secret_hash); + let note = TransparentNote::new(amount, secret_hash); storage.public_balances.at(from).write(from_balance); @@ -148,7 +146,7 @@ pub contract TokenBlacklist { } #[public] - fn transfer_public(from: AztecAddress, to: AztecAddress, amount: Field, nonce: Field) { + fn transfer_public(from: AztecAddress, to: AztecAddress, amount: u128, nonce: Field) { let from_roles = storage.roles.at(from).get_current_value(); assert(!from_roles.is_blacklisted, "Blacklisted: Sender"); let to_roles = storage.roles.at(to).get_current_value(); @@ -160,7 +158,6 @@ pub contract TokenBlacklist { assert(nonce == 0, "invalid nonce"); } - let amount = U128::from_integer(amount); let from_balance = storage.public_balances.at(from).read().sub(amount); storage.public_balances.at(from).write(from_balance); @@ -169,7 +166,7 @@ pub contract TokenBlacklist { } #[public] - fn burn_public(from: AztecAddress, amount: Field, nonce: Field) { + fn burn_public(from: AztecAddress, amount: u128, nonce: Field) { let from_roles = storage.roles.at(from).get_current_value(); assert(!from_roles.is_blacklisted, "Blacklisted: Sender"); @@ -179,7 +176,6 @@ pub contract TokenBlacklist { assert(nonce == 0, "invalid nonce"); } - let amount = U128::from_integer(amount); let from_balance = storage.public_balances.at(from).read().sub(amount); storage.public_balances.at(from).write(from_balance); @@ -188,7 +184,7 @@ pub contract TokenBlacklist { } #[private] - fn redeem_shield(to: AztecAddress, amount: Field, secret: Field) { + fn redeem_shield(to: AztecAddress, amount: u128, secret: Field) { let to_roles = storage.roles.at(to).get_current_value(); assert(!to_roles.is_blacklisted, "Blacklisted: Recipient"); @@ -206,7 +202,7 @@ pub contract TokenBlacklist { assert(notes.len() == 1, "note not popped"); // Add the token note to user's balances set - storage.balances.add(to, U128::from_integer(amount)).emit(encode_and_encrypt_note( + storage.balances.add(to, amount).emit(encode_and_encrypt_note( &mut context, to, context.msg_sender(), @@ -214,7 +210,7 @@ pub contract TokenBlacklist { } #[private] - fn unshield(from: AztecAddress, to: AztecAddress, amount: Field, nonce: Field) { + fn unshield(from: AztecAddress, to: AztecAddress, amount: u128, nonce: Field) { let from_roles = storage.roles.at(from).get_current_value(); assert(!from_roles.is_blacklisted, "Blacklisted: Sender"); let to_roles = storage.roles.at(to).get_current_value(); @@ -226,11 +222,7 @@ pub contract TokenBlacklist { assert(nonce == 0, "invalid nonce"); } - storage.balances.sub(from, U128::from_integer(amount)).emit(encode_and_encrypt_note( - &mut context, - from, - from, - )); + storage.balances.sub(from, amount).emit(encode_and_encrypt_note(&mut context, from, from)); TokenBlacklist::at(context.this_address())._increase_public_balance(to, amount).enqueue( &mut context, @@ -239,7 +231,7 @@ pub contract TokenBlacklist { // docs:start:transfer_private #[private] - fn transfer(from: AztecAddress, to: AztecAddress, amount: Field, nonce: Field) { + fn transfer(from: AztecAddress, to: AztecAddress, amount: u128, nonce: Field) { let from_roles = storage.roles.at(from).get_current_value(); assert(!from_roles.is_blacklisted, "Blacklisted: Sender"); let to_roles = storage.roles.at(to).get_current_value(); @@ -251,7 +243,6 @@ pub contract TokenBlacklist { assert(nonce == 0, "invalid nonce"); } - let amount = U128::from_integer(amount); storage.balances.sub(from, amount).emit(encode_and_encrypt_note_unconstrained( &mut context, from, @@ -265,7 +256,7 @@ pub contract TokenBlacklist { } #[private] - fn burn(from: AztecAddress, amount: Field, nonce: Field) { + fn burn(from: AztecAddress, amount: u128, nonce: Field) { let from_roles = storage.roles.at(from).get_current_value(); assert(!from_roles.is_blacklisted, "Blacklisted: Sender"); @@ -275,11 +266,7 @@ pub contract TokenBlacklist { assert(nonce == 0, "invalid nonce"); } - storage.balances.sub(from, U128::from_integer(amount)).emit(encode_and_encrypt_note( - &mut context, - from, - from, - )); + storage.balances.sub(from, amount).emit(encode_and_encrypt_note(&mut context, from, from)); TokenBlacklist::at(context.this_address())._reduce_total_supply(amount).enqueue(&mut context); } @@ -287,16 +274,16 @@ pub contract TokenBlacklist { /// Internal /// #[public] #[internal] - fn _increase_public_balance(to: AztecAddress, amount: Field) { - let new_balance = storage.public_balances.at(to).read().add(U128::from_integer(amount)); + fn _increase_public_balance(to: AztecAddress, amount: u128) { + let new_balance = storage.public_balances.at(to).read().add(amount); storage.public_balances.at(to).write(new_balance); } #[public] #[internal] - fn _reduce_total_supply(amount: Field) { + fn _reduce_total_supply(amount: u128) { // Only to be called from burn. - let new_supply = storage.total_supply.read().sub(U128::from_integer(amount)); + let new_supply = storage.total_supply.read().sub(amount); storage.total_supply.write(new_supply); } @@ -308,7 +295,7 @@ pub contract TokenBlacklist { // docs:start:deliver_note_contract_method unconstrained fn deliver_transparent_note( contract_address: AztecAddress, - amount: Field, + amount: u128, secret_hash: Field, tx_hash: Field, unique_note_hashes_in_tx: BoundedVec, diff --git a/noir-projects/noir-contracts/contracts/token_blacklist_contract/src/types/balances_map.nr b/noir-projects/noir-contracts/contracts/token_blacklist_contract/src/types/balances_map.nr index e845cdb4a73..c9e43a93a28 100644 --- a/noir-projects/noir-contracts/contracts/token_blacklist_contract/src/types/balances_map.nr +++ b/noir-projects/noir-contracts/contracts/token_blacklist_contract/src/types/balances_map.nr @@ -27,7 +27,7 @@ impl BalancesMap { } impl BalancesMap { - pub unconstrained fn balance_of(self: Self, owner: AztecAddress) -> U128 + pub unconstrained fn balance_of(self: Self, owner: AztecAddress) -> u128 where Note: NoteType + NoteHash + OwnedNote + Packable, { @@ -38,11 +38,11 @@ impl BalancesMap { self: Self, owner: AztecAddress, offset: u32, - ) -> U128 + ) -> u128 where Note: NoteType + NoteHash + OwnedNote + Packable, { - let mut balance = U128::from_integer(0); + let mut balance = 0 as u128; // docs:start:view_notes let mut options = NoteViewerOptions::new(); let notes = self.map.at(owner).view_notes(options.set_offset(offset)); @@ -62,11 +62,11 @@ impl BalancesMap { impl BalancesMap { - pub fn add(self: Self, owner: AztecAddress, addend: U128) -> OuterNoteEmission + pub fn add(self: Self, owner: AztecAddress, addend: u128) -> OuterNoteEmission where Note: NoteType + NoteHash + OwnedNote + Eq + Packable, { - if addend == U128::from_integer(0) { + if addend == 0 as u128 { OuterNoteEmission::new(Option::none()) } else { let addend_note = Note::new(addend, owner); @@ -80,7 +80,7 @@ impl BalancesMap { pub fn sub( self: Self, owner: AztecAddress, - subtrahend: U128, + subtrahend: u128, ) -> OuterNoteEmission where Note: NoteType + NoteHash + OwnedNote + Eq + Packable, @@ -88,7 +88,7 @@ impl BalancesMap { let options = NoteGetterOptions::with_filter(filter_notes_min_sum, subtrahend); let notes = self.map.at(owner).pop_notes(options); - let mut minuend: U128 = U128::from_integer(0); + let mut minuend: u128 = 0 as u128; for i in 0..options.limit { if i < notes.len() { let note: Note = notes.get_unchecked(i); @@ -107,13 +107,13 @@ impl BalancesMap { pub fn filter_notes_min_sum( retrieved_notes: [Option>; MAX_NOTE_HASH_READ_REQUESTS_PER_CALL], - min_sum: U128, + min_sum: u128, ) -> [Option>; MAX_NOTE_HASH_READ_REQUESTS_PER_CALL] where Note: NoteType + OwnedNote, { let mut selected = [Option::none(); MAX_NOTE_HASH_READ_REQUESTS_PER_CALL]; - let mut sum = U128::from_integer(0); + let mut sum = 0 as u128; for i in 0..retrieved_notes.len() { if retrieved_notes[i].is_some() & sum < min_sum { let retrieved_note = retrieved_notes[i].unwrap_unchecked(); diff --git a/noir-projects/noir-contracts/contracts/token_blacklist_contract/src/types/token_note.nr b/noir-projects/noir-contracts/contracts/token_blacklist_contract/src/types/token_note.nr index 6f64f0f5ffe..f79b797657f 100644 --- a/noir-projects/noir-contracts/contracts/token_blacklist_contract/src/types/token_note.nr +++ b/noir-projects/noir-contracts/contracts/token_blacklist_contract/src/types/token_note.nr @@ -3,22 +3,22 @@ use dep::aztec::{ }; trait OwnedNote { - fn new(amount: U128, owner: AztecAddress) -> Self; - fn get_amount(self) -> U128; + fn new(amount: u128, owner: AztecAddress) -> Self; + fn get_amount(self) -> u128; } #[note] #[derive(Eq)] pub struct TokenNote { // The amount of tokens in the note - amount: U128, + amount: u128, owner: AztecAddress, // Randomness of the note to protect against note hash preimage attacks randomness: Field, } impl OwnedNote for TokenNote { - fn new(amount: U128, owner: AztecAddress) -> Self { + fn new(amount: u128, owner: AztecAddress) -> Self { // Safety: We use the randomness to preserve the privacy of the note recipient by preventing brute-forcing, // so a malicious sender could use non-random values to make the note less private. But they already know // the full note pre-image anyway, and so the recipient already trusts them to not disclose this @@ -27,7 +27,7 @@ impl OwnedNote for TokenNote { Self { amount, owner, randomness } } - fn get_amount(self) -> U128 { + fn get_amount(self) -> u128 { self.amount } } diff --git a/noir-projects/noir-contracts/contracts/token_blacklist_contract/src/types/transparent_note.nr b/noir-projects/noir-contracts/contracts/token_blacklist_contract/src/types/transparent_note.nr index b5a1b72d360..20820383f31 100644 --- a/noir-projects/noir-contracts/contracts/token_blacklist_contract/src/types/transparent_note.nr +++ b/noir-projects/noir-contracts/contracts/token_blacklist_contract/src/types/transparent_note.nr @@ -19,7 +19,7 @@ use dep::std::mem::zeroed; #[custom_note] #[derive(Eq)] pub struct TransparentNote { - amount: Field, + amount: u128, secret_hash: Field, } @@ -67,7 +67,7 @@ impl NoteHash for TransparentNote { impl TransparentNote { // CONSTRUCTORS - pub fn new(amount: Field, secret_hash: Field) -> Self { + pub fn new(amount: u128, secret_hash: Field) -> Self { TransparentNote { amount, secret_hash } } } diff --git a/noir-projects/noir-contracts/contracts/token_bridge_contract/src/main.nr b/noir-projects/noir-contracts/contracts/token_bridge_contract/src/main.nr index aa54d0de062..5454b8eab78 100644 --- a/noir-projects/noir-contracts/contracts/token_bridge_contract/src/main.nr +++ b/noir-projects/noir-contracts/contracts/token_bridge_contract/src/main.nr @@ -57,7 +57,7 @@ pub contract TokenBridge { // docs:start:claim_public // Consumes a L1->L2 message and calls the token contract to mint the appropriate amount publicly #[public] - fn claim_public(to: AztecAddress, amount: U128, secret: Field, message_leaf_index: Field) { + fn claim_public(to: AztecAddress, amount: u128, secret: Field, message_leaf_index: Field) { let content_hash = get_mint_to_public_content_hash(to, amount); let config = storage.config.read(); @@ -76,7 +76,7 @@ pub contract TokenBridge { #[public] fn exit_to_l1_public( recipient: EthAddress, // ethereum address to withdraw to - amount: U128, + amount: u128, caller_on_l1: EthAddress, // ethereum address that can call this function on the L1 portal (0x0 if anyone can call) nonce: Field, // nonce used in the approval message by `msg.sender` to let bridge burn their tokens on L2 ) { @@ -98,7 +98,7 @@ pub contract TokenBridge { #[private] fn claim_private( recipient: AztecAddress, // recipient of the bridged tokens - amount: U128, + amount: u128, secret_for_L1_to_L2_message_consumption: Field, // secret used to consume the L1 to L2 message message_leaf_index: Field, ) { @@ -129,7 +129,7 @@ pub contract TokenBridge { fn exit_to_l1_private( token: AztecAddress, recipient: EthAddress, // ethereum address to withdraw to - amount: U128, + amount: u128, caller_on_l1: EthAddress, // ethereum address that can call this function on the L1 portal (0x0 if anyone can call) nonce: Field, // nonce used in the approval message by `msg.sender` to let bridge burn their tokens on L2 ) { diff --git a/noir-projects/noir-contracts/contracts/token_contract/src/main.nr b/noir-projects/noir-contracts/contracts/token_contract/src/main.nr index 325ab8edf02..d15a524d9a0 100644 --- a/noir-projects/noir-contracts/contracts/token_contract/src/main.nr +++ b/noir-projects/noir-contracts/contracts/token_contract/src/main.nr @@ -61,7 +61,7 @@ pub contract Token { struct Transfer { from: AztecAddress, to: AztecAddress, - amount: U128, + amount: u128, } // docs:start:storage_struct @@ -76,8 +76,8 @@ pub contract Token { // docs:start:storage_balances balances: Map, Context>, // docs:end:storage_balances - total_supply: PublicMutable, - public_balances: Map, Context>, + total_supply: PublicMutable, + public_balances: Map, Context>, symbol: PublicImmutable, name: PublicImmutable, // docs:start:storage_decimals @@ -166,7 +166,7 @@ pub contract Token { // docs:start:total_supply #[public] #[view] - fn total_supply() -> U128 { + fn total_supply() -> u128 { storage.total_supply.read() } // docs:end:total_supply @@ -174,7 +174,7 @@ pub contract Token { // docs:start:balance_of_public #[public] #[view] - fn balance_of_public(owner: AztecAddress) -> U128 { + fn balance_of_public(owner: AztecAddress) -> u128 { storage.public_balances.at(owner).read() } // docs:end:balance_of_public @@ -193,7 +193,7 @@ pub contract Token { // docs:start:mint_to_public #[public] - fn mint_to_public(to: AztecAddress, amount: U128) { + fn mint_to_public(to: AztecAddress, amount: u128) { // docs:start:read_minter assert(storage.minters.at(context.msg_sender()).read(), "caller is not minter"); // docs:end:read_minter @@ -206,7 +206,7 @@ pub contract Token { // docs:start:transfer_in_public #[public] - fn transfer_in_public(from: AztecAddress, to: AztecAddress, amount: U128, nonce: Field) { + fn transfer_in_public(from: AztecAddress, to: AztecAddress, amount: u128, nonce: Field) { if (!from.eq(context.msg_sender())) { assert_current_call_valid_authwit_public(&mut context, from); } else { @@ -221,7 +221,7 @@ pub contract Token { // docs:start:burn_public #[public] - fn burn_public(from: AztecAddress, amount: U128, nonce: Field) { + fn burn_public(from: AztecAddress, amount: u128, nonce: Field) { // docs:start:assert_current_call_valid_authwit_public if (!from.eq(context.msg_sender())) { assert_current_call_valid_authwit_public(&mut context, from); @@ -238,7 +238,7 @@ pub contract Token { // docs:start:transfer_to_public #[private] - fn transfer_to_public(from: AztecAddress, to: AztecAddress, amount: U128, nonce: Field) { + fn transfer_to_public(from: AztecAddress, to: AztecAddress, amount: u128, nonce: Field) { if (!from.eq(context.msg_sender())) { assert_current_call_valid_authwit(&mut context, from); } else { @@ -256,7 +256,7 @@ pub contract Token { // docs:start:transfer #[private] - fn transfer(to: AztecAddress, amount: U128) { + fn transfer(to: AztecAddress, amount: u128) { let from = context.msg_sender(); // We reduce `from`'s balance by amount by recursively removing notes over potentially multiple calls. This @@ -299,15 +299,15 @@ pub contract Token { context: &mut PrivateContext, storage: Storage<&mut PrivateContext>, account: AztecAddress, - amount: U128, + amount: u128, max_notes: u32, - ) -> U128 { + ) -> u128 { let subtracted = storage.balances.at(account).try_sub(amount, max_notes); // Failing to subtract any amount means that the owner was unable to produce more notes that could be nullified. // We could in some cases fail early inside try_sub if we detected that fewer notes than the maximum were // returned and we were still unable to reach the target amount, but that'd make the code more complicated, and // optimizing for the failure scenario is not as important. - assert(subtracted > U128::zero(), "Balance too low"); + assert(subtracted > 0 as u128, "Balance too low"); if subtracted >= amount { // We have achieved our goal of nullifying notes that add up to more than amount, so we return the change subtracted - amount @@ -326,14 +326,14 @@ pub contract Token { fn compute_recurse_subtract_balance_call( context: PrivateContext, account: AztecAddress, - remaining: U128, - ) -> PrivateCallInterface<25, U128> { + remaining: u128, + ) -> PrivateCallInterface<25, u128> { Token::at(context.this_address())._recurse_subtract_balance(account, remaining) } #[internal] #[private] - fn _recurse_subtract_balance(account: AztecAddress, amount: U128) -> U128 { + fn _recurse_subtract_balance(account: AztecAddress, amount: u128) -> u128 { subtract_balance( &mut context, storage, @@ -358,7 +358,7 @@ pub contract Token { // docs:start:transfer_in_private #[private] - fn transfer_in_private(from: AztecAddress, to: AztecAddress, amount: U128, nonce: Field) { + fn transfer_in_private(from: AztecAddress, to: AztecAddress, amount: u128, nonce: Field) { // docs:start:assert_current_call_valid_authwit if (!from.eq(context.msg_sender())) { assert_current_call_valid_authwit(&mut context, from); @@ -382,7 +382,7 @@ pub contract Token { // docs:start:burn_private #[private] - fn burn_private(from: AztecAddress, amount: U128, nonce: Field) { + fn burn_private(from: AztecAddress, amount: u128, nonce: Field) { if (!from.eq(context.msg_sender())) { assert_current_call_valid_authwit(&mut context, from); } else { @@ -400,7 +400,7 @@ pub contract Token { // docs:start:transfer_to_private // Transfers token `amount` from public balance of message sender to a private balance of `to`. #[private] - fn transfer_to_private(to: AztecAddress, amount: U128) { + fn transfer_to_private(to: AztecAddress, amount: u128) { // `from` is the owner of the public balance from which we'll subtract the `amount`. let from = context.msg_sender(); let token = Token::at(context.this_address()); @@ -488,7 +488,7 @@ pub contract Token { /// The transfer must be prepared by calling `prepare_private_balance_increase` first and the resulting /// `hiding_point_slot` must be passed as an argument to this function. #[public] - fn finalize_transfer_to_private(amount: U128, hiding_point_slot: Field) { + fn finalize_transfer_to_private(amount: u128, hiding_point_slot: Field) { let from = context.msg_sender(); _finalize_transfer_to_private(from, amount, hiding_point_slot, &mut context, storage); } @@ -502,7 +502,7 @@ pub contract Token { #[internal] fn _finalize_transfer_to_private_unsafe( from: AztecAddress, - amount: U128, + amount: u128, hiding_point_slot: Field, ) { _finalize_transfer_to_private(from, amount, hiding_point_slot, &mut context, storage); @@ -512,7 +512,7 @@ pub contract Token { #[contract_library_method] fn _finalize_transfer_to_private( from: AztecAddress, - amount: U128, + amount: u128, hiding_point_slot: Field, context: &mut PublicContext, storage: Storage<&mut PublicContext>, @@ -536,7 +536,7 @@ pub contract Token { fn mint_to_private( from: AztecAddress, // sender of the tag: TODO(#9887): this is not great? to: AztecAddress, - amount: U128, + amount: u128, ) { let token = Token::at(context.this_address()); @@ -561,7 +561,7 @@ pub contract Token { /// and `finalize_transfer_to_private`. It is however used very commonly so it makes sense to optimize it /// (e.g. used during token bridging, in AMM liquidity token etc.). #[public] - fn finalize_mint_to_private(amount: U128, hiding_point_slot: Field) { + fn finalize_mint_to_private(amount: u128, hiding_point_slot: Field) { assert(storage.minters.at(context.msg_sender()).read(), "caller is not minter"); _finalize_mint_to_private(amount, hiding_point_slot, &mut context, storage); @@ -573,7 +573,7 @@ pub contract Token { #[internal] fn _finalize_mint_to_private_unsafe( from: AztecAddress, - amount: U128, + amount: u128, hiding_point_slot: Field, ) { // We check the minter permissions as it was not done in `mint_to_private` function. @@ -584,7 +584,7 @@ pub contract Token { #[contract_library_method] fn _finalize_mint_to_private( - amount: U128, + amount: u128, hiding_point_slot: Field, context: &mut PublicContext, storage: Storage<&mut PublicContext>, @@ -623,7 +623,7 @@ pub contract Token { /// function. #[public] #[internal] - fn _increase_public_balance(to: AztecAddress, amount: U128) { + fn _increase_public_balance(to: AztecAddress, amount: u128) { _increase_public_balance_inner(to, amount, storage); } // docs:end:increase_public_balance @@ -631,7 +631,7 @@ pub contract Token { #[contract_library_method] fn _increase_public_balance_inner( to: AztecAddress, - amount: U128, + amount: u128, storage: Storage<&mut PublicContext>, ) { let new_balance = storage.public_balances.at(to).read().add(amount); @@ -641,7 +641,7 @@ pub contract Token { // docs:start:reduce_total_supply #[public] #[internal] - fn _reduce_total_supply(amount: U128) { + fn _reduce_total_supply(amount: u128) { // Only to be called from burn. let new_supply = storage.total_supply.read().sub(amount); storage.total_supply.write(new_supply); @@ -650,7 +650,7 @@ pub contract Token { /// Unconstrained /// // docs:start:balance_of_private - pub(crate) unconstrained fn balance_of_private(owner: AztecAddress) -> pub U128 { + pub(crate) unconstrained fn balance_of_private(owner: AztecAddress) -> pub u128 { storage.balances.at(owner).balance_of() } // docs:end:balance_of_private diff --git a/noir-projects/noir-contracts/contracts/token_contract/src/test/burn_private.nr b/noir-projects/noir-contracts/contracts/token_contract/src/test/burn_private.nr index 3559c851cc4..340421ebf8e 100644 --- a/noir-projects/noir-contracts/contracts/token_contract/src/test/burn_private.nr +++ b/noir-projects/noir-contracts/contracts/token_contract/src/test/burn_private.nr @@ -7,7 +7,7 @@ use dep::aztec::oracle::random::random; unconstrained fn burn_private_on_behalf_of_self() { let (env, token_contract_address, owner, _, mint_amount) = utils::setup_and_mint_to_private(/* with_account_contracts */ false); - let burn_amount = mint_amount / U128::from_integer(10); + let burn_amount = mint_amount / (10 as u128); // Burn less than balance Token::at(token_contract_address).burn_private(owner, burn_amount, 0).call(&mut env.private()); @@ -18,7 +18,7 @@ unconstrained fn burn_private_on_behalf_of_self() { unconstrained fn burn_private_on_behalf_of_other() { let (env, token_contract_address, owner, recipient, mint_amount) = utils::setup_and_mint_to_private(/* with_account_contracts */ true); - let burn_amount = mint_amount / U128::from_integer(10); + let burn_amount = mint_amount / (10 as u128); // Burn on behalf of other let burn_call_interface = @@ -41,7 +41,7 @@ unconstrained fn burn_private_failure_more_than_balance() { utils::setup_and_mint_to_public(/* with_account_contracts */ false); // Burn more than balance - let burn_amount = mint_amount * U128::from_integer(10); + let burn_amount = mint_amount * (10 as u128); Token::at(token_contract_address).burn_private(owner, burn_amount, 0).call(&mut env.private()); } @@ -51,7 +51,7 @@ unconstrained fn burn_private_failure_on_behalf_of_self_non_zero_nonce() { utils::setup_and_mint_to_public(/* with_account_contracts */ false); // Burn more than balance - let burn_amount = mint_amount / U128::from_integer(10); + let burn_amount = mint_amount / (10 as u128); Token::at(token_contract_address).burn_private(owner, burn_amount, random()).call( &mut env.private(), ); @@ -63,7 +63,7 @@ unconstrained fn burn_private_failure_on_behalf_of_other_more_than_balance() { utils::setup_and_mint_to_public(/* with_account_contracts */ true); // Burn more than balance - let burn_amount = mint_amount * U128::from_integer(10); + let burn_amount = mint_amount * (10 as u128); // Burn on behalf of other let burn_call_interface = Token::at(token_contract_address).burn_private(owner, burn_amount, random()); @@ -83,7 +83,7 @@ unconstrained fn burn_private_failure_on_behalf_of_other_without_approval() { utils::setup_and_mint_to_public(/* with_account_contracts */ true); // Burn more than balance - let burn_amount = mint_amount / U128::from_integer(10); + let burn_amount = mint_amount / (10 as u128); // Burn on behalf of other let burn_call_interface = Token::at(token_contract_address).burn_private(owner, burn_amount, 3); // Impersonate recipient to perform the call @@ -97,7 +97,7 @@ unconstrained fn burn_private_failure_on_behalf_of_other_wrong_designated_caller utils::setup_and_mint_to_public(/* with_account_contracts */ true); // Burn more than balance - let burn_amount = mint_amount / U128::from_integer(10); + let burn_amount = mint_amount / (10 as u128); // Burn on behalf of other let burn_call_interface = Token::at(token_contract_address).burn_private(owner, burn_amount, 3); authwit_cheatcodes::add_private_authwit_from_call_interface(owner, owner, burn_call_interface); diff --git a/noir-projects/noir-contracts/contracts/token_contract/src/test/burn_public.nr b/noir-projects/noir-contracts/contracts/token_contract/src/test/burn_public.nr index 075007fdc3b..5306538603e 100644 --- a/noir-projects/noir-contracts/contracts/token_contract/src/test/burn_public.nr +++ b/noir-projects/noir-contracts/contracts/token_contract/src/test/burn_public.nr @@ -7,7 +7,7 @@ use dep::aztec::oracle::random::random; unconstrained fn burn_public_success() { let (env, token_contract_address, owner, recipient, mint_amount) = utils::setup_and_mint_to_public(/* with_account_contracts */ false); - let burn_amount = mint_amount / U128::from_integer(10); + let burn_amount = mint_amount / (10 as u128); // Burn less than balance Token::at(token_contract_address).burn_public(owner, burn_amount, 0).call(&mut env.public()); @@ -18,7 +18,7 @@ unconstrained fn burn_public_success() { unconstrained fn burn_public_on_behalf_of_other() { let (env, token_contract_address, owner, recipient, mint_amount) = utils::setup_and_mint_to_public(/* with_account_contracts */ true); - let burn_amount = mint_amount / U128::from_integer(10); + let burn_amount = mint_amount / (10 as u128); // Burn on behalf of other let burn_call_interface = @@ -35,13 +35,13 @@ unconstrained fn burn_public_on_behalf_of_other() { utils::check_public_balance(token_contract_address, owner, mint_amount - burn_amount); } -#[test(should_fail_with = "attempt to subtract with underflow")] +#[test(should_fail_with = "Assertion failed: attempt to subtract with overflow 'self - other'")] unconstrained fn burn_public_failure_more_than_balance() { let (env, token_contract_address, owner, _, mint_amount) = utils::setup_and_mint_to_public(/* with_account_contracts */ false); // Burn more than balance - let burn_amount = mint_amount * U128::from_integer(10); + let burn_amount = mint_amount * (10 as u128); // Try to burn Token::at(token_contract_address).burn_public(owner, burn_amount, 0).call(&mut env.public()); } @@ -52,7 +52,7 @@ unconstrained fn burn_public_failure_on_behalf_of_self_non_zero_nonce() { utils::setup_and_mint_to_public(/* with_account_contracts */ false); // Burn on behalf of self with non-zero nonce - let burn_amount = mint_amount / U128::from_integer(10); + let burn_amount = mint_amount / (10 as u128); // Try to burn Token::at(token_contract_address).burn_public(owner, burn_amount, random()).call( &mut env.public(), @@ -65,7 +65,7 @@ unconstrained fn burn_public_failure_on_behalf_of_other_without_approval() { utils::setup_and_mint_to_public(/* with_account_contracts */ true); // Burn on behalf of other without approval - let burn_amount = mint_amount / U128::from_integer(10); + let burn_amount = mint_amount / (10 as u128); let burn_call_interface = Token::at(token_contract_address).burn_public(owner, burn_amount, random()); // Impersonate recipient to perform the call @@ -79,7 +79,7 @@ unconstrained fn burn_public_failure_on_behalf_of_other_wrong_caller() { utils::setup_and_mint_to_public(/* with_account_contracts */ true); // Burn on behalf of other, wrong designated caller - let burn_amount = mint_amount / U128::from_integer(10); + let burn_amount = mint_amount / (10 as u128); let burn_call_interface = Token::at(token_contract_address).burn_public(owner, burn_amount, random()); authwit_cheatcodes::add_public_authwit_from_call_interface(owner, owner, burn_call_interface); diff --git a/noir-projects/noir-contracts/contracts/token_contract/src/test/mint_to_public.nr b/noir-projects/noir-contracts/contracts/token_contract/src/test/mint_to_public.nr index 3f073a06d76..b5ef966022a 100644 --- a/noir-projects/noir-contracts/contracts/token_contract/src/test/mint_to_public.nr +++ b/noir-projects/noir-contracts/contracts/token_contract/src/test/mint_to_public.nr @@ -5,7 +5,7 @@ unconstrained fn mint_to_public_success() { // Setup without account contracts. We are not using authwits here, so dummy accounts are enough let (env, token_contract_address, owner, _) = utils::setup(/* with_account_contracts */ false); - let mint_amount = U128::from_integer(10_000); + let mint_amount = 10_000 as u128; Token::at(token_contract_address).mint_to_public(owner, mint_amount).call(&mut env.public()); utils::check_public_balance(token_contract_address, owner, mint_amount); @@ -21,21 +21,21 @@ unconstrained fn mint_to_public_failures() { utils::setup(/* with_account_contracts */ false); // As non-minter - let mint_amount = U128::from_integer(10_000); + let mint_amount = 10_000 as u128; env.impersonate(recipient); let mint_to_public_call_interface = Token::at(token_contract_address).mint_to_public(owner, mint_amount); env.assert_public_call_fails(mint_to_public_call_interface); - utils::check_public_balance(token_contract_address, owner, U128::zero()); + utils::check_public_balance(token_contract_address, owner, 0 as u128); env.impersonate(owner); // Overflow recipient - // We have to do this in 2 steps because we have to pass in a valid U128 - let amount_until_overflow = U128::from_integer(1000); - let mint_amount = U128::from_integer(2.pow_32(128) - amount_until_overflow.to_integer()); + // We have to do this in 2 steps because we have to pass in a valid u128 + let amount_until_overflow = 1000 as u128; + let mint_amount = (2.pow_32(128) - amount_until_overflow as Field) as u128; Token::at(token_contract_address).mint_to_public(recipient, mint_amount).call(&mut env.public()); @@ -43,7 +43,7 @@ unconstrained fn mint_to_public_failures() { Token::at(token_contract_address).mint_to_public(owner, amount_until_overflow); env.assert_public_call_fails(mint_to_public_call_interface); - utils::check_public_balance(token_contract_address, owner, U128::zero()); + utils::check_public_balance(token_contract_address, owner, 0 as u128); utils::check_total_supply(token_contract_address, mint_amount); // Overflow total supply @@ -51,5 +51,5 @@ unconstrained fn mint_to_public_failures() { Token::at(token_contract_address).mint_to_public(owner, mint_amount); env.assert_public_call_fails(mint_to_public_call_interface); - utils::check_public_balance(token_contract_address, owner, U128::zero()); + utils::check_public_balance(token_contract_address, owner, 0 as u128); } diff --git a/noir-projects/noir-contracts/contracts/token_contract/src/test/transfer.nr b/noir-projects/noir-contracts/contracts/token_contract/src/test/transfer.nr index 1b6e40640ba..ccd78378f97 100644 --- a/noir-projects/noir-contracts/contracts/token_contract/src/test/transfer.nr +++ b/noir-projects/noir-contracts/contracts/token_contract/src/test/transfer.nr @@ -10,7 +10,7 @@ unconstrained fn transfer_private() { // docs:start:txe_test_transfer_private // Transfer tokens - let transfer_amount = U128::from_integer(1000); + let transfer_amount = 1000 as u128; Token::at(token_contract_address).transfer(recipient, transfer_amount).call(&mut env.private()); // docs:end:txe_test_transfer_private // Check balances @@ -24,7 +24,7 @@ unconstrained fn transfer_private_to_self() { let (env, token_contract_address, owner, _, mint_amount) = utils::setup_and_mint_to_private(/* with_account_contracts */ false); // Transfer tokens - let transfer_amount = U128::from_integer(1000); + let transfer_amount = 1000 as u128; Token::at(token_contract_address).transfer(owner, transfer_amount).call(&mut env.private()); // Check balances @@ -38,7 +38,7 @@ unconstrained fn transfer_private_to_non_deployed_account() { utils::setup_and_mint_to_private(/* with_account_contracts */ false); let not_deployed = cheatcodes::create_account(999); // Transfer tokens - let transfer_amount = U128::from_integer(1000); + let transfer_amount = 1000 as u128; Token::at(token_contract_address).transfer(not_deployed.address, transfer_amount).call( &mut env.private(), ); @@ -58,6 +58,6 @@ unconstrained fn transfer_private_failure_more_than_balance() { let (env, token_contract_address, _, recipient, mint_amount) = utils::setup_and_mint_to_private(/* with_account_contracts */ false); // Transfer tokens - let transfer_amount = mint_amount + U128::from_integer(1); + let transfer_amount = mint_amount + (1 as u128); Token::at(token_contract_address).transfer(recipient, transfer_amount).call(&mut env.private()); } diff --git a/noir-projects/noir-contracts/contracts/token_contract/src/test/transfer_in_private.nr b/noir-projects/noir-contracts/contracts/token_contract/src/test/transfer_in_private.nr index cfb01d97ab1..679265fbd0d 100644 --- a/noir-projects/noir-contracts/contracts/token_contract/src/test/transfer_in_private.nr +++ b/noir-projects/noir-contracts/contracts/token_contract/src/test/transfer_in_private.nr @@ -9,7 +9,7 @@ unconstrained fn transfer_private_on_behalf_of_other() { utils::setup_and_mint_to_private(/* with_account_contracts */ true); // Add authwit // docs:start:private_authwit - let transfer_amount = U128::from_integer(1000); + let transfer_amount = 1000 as u128; let transfer_private_from_call_interface = Token::at(token_contract_address).transfer_in_private(owner, recipient, transfer_amount, 1); authwit_cheatcodes::add_private_authwit_from_call_interface( @@ -34,7 +34,7 @@ unconstrained fn transfer_private_failure_on_behalf_of_self_non_zero_nonce() { let (env, token_contract_address, owner, recipient, _) = utils::setup_and_mint_to_private(/* with_account_contracts */ false); // Add authwit - let transfer_amount = U128::from_integer(1000); + let transfer_amount = 1000 as u128; let transfer_private_from_call_interface = Token::at(token_contract_address).transfer_in_private(owner, recipient, transfer_amount, 1); authwit_cheatcodes::add_private_authwit_from_call_interface( @@ -53,7 +53,7 @@ unconstrained fn transfer_private_failure_on_behalf_of_more_than_balance() { let (env, token_contract_address, owner, recipient, mint_amount) = utils::setup_and_mint_to_private(/* with_account_contracts */ true); // Add authwit - let transfer_amount = mint_amount + U128::from_integer(1); + let transfer_amount = mint_amount + (1 as u128); let transfer_private_from_call_interface = Token::at(token_contract_address).transfer_in_private(owner, recipient, transfer_amount, 1); authwit_cheatcodes::add_private_authwit_from_call_interface( @@ -73,7 +73,7 @@ unconstrained fn transfer_private_failure_on_behalf_of_other_without_approval() let (env, token_contract_address, owner, recipient, _) = utils::setup_and_mint_to_private(/* with_account_contracts */ true); // Add authwit - let transfer_amount = U128::from_integer(1000); + let transfer_amount = 1000 as u128; let transfer_private_from_call_interface = Token::at(token_contract_address).transfer_in_private(owner, recipient, transfer_amount, 1); // Impersonate recipient to perform the call @@ -88,7 +88,7 @@ unconstrained fn transfer_private_failure_on_behalf_of_other_wrong_caller() { let (env, token_contract_address, owner, recipient, _) = utils::setup_and_mint_to_private(/* with_account_contracts */ true); // Add authwit - let transfer_amount = U128::from_integer(1000); + let transfer_amount = 1000 as u128; let transfer_private_from_call_interface = Token::at(token_contract_address).transfer_in_private(owner, recipient, transfer_amount, 1); authwit_cheatcodes::add_private_authwit_from_call_interface( diff --git a/noir-projects/noir-contracts/contracts/token_contract/src/test/transfer_in_public.nr b/noir-projects/noir-contracts/contracts/token_contract/src/test/transfer_in_public.nr index 5b60b28f8e9..fb9ffa49c92 100644 --- a/noir-projects/noir-contracts/contracts/token_contract/src/test/transfer_in_public.nr +++ b/noir-projects/noir-contracts/contracts/token_contract/src/test/transfer_in_public.nr @@ -9,7 +9,7 @@ unconstrained fn public_transfer() { let (env, token_contract_address, owner, recipient, mint_amount) = utils::setup_and_mint_to_public(/* with_account_contracts */ false); // Transfer tokens - let transfer_amount = mint_amount / U128::from_integer(10); + let transfer_amount = mint_amount / (10 as u128); Token::at(token_contract_address).transfer_in_public(owner, recipient, transfer_amount, 0).call( &mut env.public(), ); @@ -25,7 +25,7 @@ unconstrained fn public_transfer_to_self() { let (env, token_contract_address, owner, _, mint_amount) = utils::setup_and_mint_to_public(/* with_account_contracts */ false); // Transfer tokens - let transfer_amount = mint_amount / U128::from_integer(10); + let transfer_amount = mint_amount / (10 as u128); // docs:start:call_public Token::at(token_contract_address).transfer_in_public(owner, owner, transfer_amount, 0).call( &mut env.public(), @@ -40,7 +40,7 @@ unconstrained fn public_transfer_on_behalf_of_other() { // Setup with account contracts. Slower since we actually deploy them, but needed for authwits. let (env, token_contract_address, owner, recipient, mint_amount) = utils::setup_and_mint_to_public(/* with_account_contracts */ true); - let transfer_amount = mint_amount / U128::from_integer(10); + let transfer_amount = mint_amount / (10 as u128); let public_transfer_in_private_call_interface = Token::at(token_contract_address).transfer_in_public(owner, recipient, transfer_amount, 1); authwit_cheatcodes::add_public_authwit_from_call_interface( @@ -57,13 +57,13 @@ unconstrained fn public_transfer_on_behalf_of_other() { utils::check_public_balance(token_contract_address, recipient, transfer_amount); } -#[test(should_fail_with = "attempt to subtract with underflow")] +#[test(should_fail_with = "Assertion failed: attempt to subtract with overflow 'self - other'")] unconstrained fn public_transfer_failure_more_than_balance() { // Setup without account contracts. We are not using authwits here, so dummy accounts are enough let (env, token_contract_address, owner, recipient, mint_amount) = utils::setup_and_mint_to_public(/* with_account_contracts */ false); // Transfer tokens - let transfer_amount = mint_amount + U128::from_integer(1); + let transfer_amount = mint_amount + (1 as u128); let public_transfer_call_interface = Token::at(token_contract_address).transfer_in_public(owner, recipient, transfer_amount, 0); // Try to transfer tokens @@ -76,7 +76,7 @@ unconstrained fn public_transfer_failure_on_behalf_of_self_non_zero_nonce() { let (env, token_contract_address, owner, recipient, mint_amount) = utils::setup_and_mint_to_public(/* with_account_contracts */ false); // Transfer tokens - let transfer_amount = mint_amount / U128::from_integer(10); + let transfer_amount = mint_amount / (10 as u128); let public_transfer_call_interface = Token::at(token_contract_address).transfer_in_public( owner, recipient, @@ -97,7 +97,7 @@ unconstrained fn public_transfer_failure_on_behalf_of_other_without_approval() { // Setup with account contracts. Slower since we actually deploy them, but needed for authwits. let (env, token_contract_address, owner, recipient, mint_amount) = utils::setup_and_mint_to_public(/* with_account_contracts */ true); - let transfer_amount = mint_amount / U128::from_integer(10); + let transfer_amount = mint_amount / (10 as u128); let public_transfer_in_private_call_interface = Token::at(token_contract_address).transfer_in_public(owner, recipient, transfer_amount, 1); // Impersonate recipient to perform the call @@ -106,12 +106,12 @@ unconstrained fn public_transfer_failure_on_behalf_of_other_without_approval() { public_transfer_in_private_call_interface.call(&mut env.public()); } -#[test(should_fail_with = "attempt to subtract with underflow")] +#[test(should_fail_with = "Assertion failed: attempt to subtract with overflow 'self - other'")] unconstrained fn public_transfer_failure_on_behalf_of_other_more_than_balance() { // Setup with account contracts. Slower since we actually deploy them, but needed for authwits. let (env, token_contract_address, owner, recipient, mint_amount) = utils::setup_and_mint_to_public(/* with_account_contracts */ true); - let transfer_amount = mint_amount + U128::from_integer(1); + let transfer_amount = mint_amount + (1 as u128); // docs:start:public_authwit let public_transfer_in_private_call_interface = Token::at(token_contract_address).transfer_in_public(owner, recipient, transfer_amount, 1); @@ -132,7 +132,7 @@ unconstrained fn public_transfer_failure_on_behalf_of_other_wrong_caller() { // Setup with account contracts. Slower since we actually deploy them, but needed for authwits. let (env, token_contract_address, owner, recipient, mint_amount) = utils::setup_and_mint_to_public(/* with_account_contracts */ true); - let transfer_amount = mint_amount / U128::from_integer(10); + let transfer_amount = mint_amount / (10 as u128); let public_transfer_in_private_call_interface = Token::at(token_contract_address).transfer_in_public(owner, recipient, transfer_amount, 1); authwit_cheatcodes::add_public_authwit_from_call_interface( diff --git a/noir-projects/noir-contracts/contracts/token_contract/src/test/transfer_to_private.nr b/noir-projects/noir-contracts/contracts/token_contract/src/test/transfer_to_private.nr index b71e9ef5f42..0f9e64693a6 100644 --- a/noir-projects/noir-contracts/contracts/token_contract/src/test/transfer_to_private.nr +++ b/noir-projects/noir-contracts/contracts/token_contract/src/test/transfer_to_private.nr @@ -62,7 +62,7 @@ unconstrained fn transfer_to_private_transfer_not_prepared() { ); } -#[test(should_fail_with = "Assertion failed: attempt to subtract with underflow 'hi == high'")] +#[test(should_fail_with = "Assertion failed: attempt to subtract with overflow 'self - other'")] unconstrained fn transfer_to_private_failure_not_an_owner() { // Setup without account contracts. We are not using authwits here, so dummy accounts are enough let (env, token_contract_address, owner, not_owner, amount) = diff --git a/noir-projects/noir-contracts/contracts/token_contract/src/test/transfer_to_public.nr b/noir-projects/noir-contracts/contracts/token_contract/src/test/transfer_to_public.nr index 8d958d29dcf..13f9ba3c238 100644 --- a/noir-projects/noir-contracts/contracts/token_contract/src/test/transfer_to_public.nr +++ b/noir-projects/noir-contracts/contracts/token_contract/src/test/transfer_to_public.nr @@ -9,7 +9,7 @@ unconstrained fn transfer_to_public_on_behalf_of_self() { let (env, token_contract_address, owner, _, mint_amount) = utils::setup_and_mint_to_private(/* with_account_contracts */ false); - let transfer_to_public_amount = mint_amount / U128::from_integer(10); + let transfer_to_public_amount = mint_amount / (10 as u128); Token::at(token_contract_address) .transfer_to_public(owner, owner, transfer_to_public_amount, 0) .call(&mut env.private()); @@ -26,7 +26,7 @@ unconstrained fn transfer_to_public_on_behalf_of_other() { let (env, token_contract_address, owner, recipient, mint_amount) = utils::setup_and_mint_to_private(/* with_account_contracts */ true); - let transfer_to_public_amount = mint_amount / U128::from_integer(10); + let transfer_to_public_amount = mint_amount / (10 as u128); let transfer_to_public_call_interface = Token::at(token_contract_address).transfer_to_public( owner, recipient, @@ -56,7 +56,7 @@ unconstrained fn transfer_to_public_failure_more_than_balance() { let (env, token_contract_address, owner, _, mint_amount) = utils::setup_and_mint_to_private(/* with_account_contracts */ false); - let transfer_to_public_amount = mint_amount + U128::one(); + let transfer_to_public_amount = mint_amount + (1 as u128); Token::at(token_contract_address) .transfer_to_public(owner, owner, transfer_to_public_amount, 0) .call(&mut env.private()); @@ -68,7 +68,7 @@ unconstrained fn transfer_to_public_failure_on_behalf_of_self_non_zero_nonce() { let (env, token_contract_address, owner, _, mint_amount) = utils::setup_and_mint_to_private(/* with_account_contracts */ false); - let transfer_to_public_amount = mint_amount + U128::one(); + let transfer_to_public_amount = mint_amount + (1 as u128); Token::at(token_contract_address) .transfer_to_public(owner, owner, transfer_to_public_amount, random()) .call(&mut env.private()); @@ -79,7 +79,7 @@ unconstrained fn transfer_to_public_failure_on_behalf_of_other_more_than_balance let (env, token_contract_address, owner, recipient, mint_amount) = utils::setup_and_mint_to_private(/* with_account_contracts */ true); - let transfer_to_public_amount = mint_amount + U128::one(); + let transfer_to_public_amount = mint_amount + (1 as u128); let transfer_to_public_call_interface = Token::at(token_contract_address).transfer_to_public( owner, recipient, @@ -102,7 +102,7 @@ unconstrained fn transfer_to_public_failure_on_behalf_of_other_invalid_designate let (env, token_contract_address, owner, recipient, mint_amount) = utils::setup_and_mint_to_private(/* with_account_contracts */ true); - let transfer_to_public_amount = mint_amount + U128::one(); + let transfer_to_public_amount = mint_amount + (1 as u128); let transfer_to_public_call_interface = Token::at(token_contract_address).transfer_to_public( owner, recipient, @@ -125,7 +125,7 @@ unconstrained fn transfer_to_public_failure_on_behalf_of_other_no_approval() { let (env, token_contract_address, owner, recipient, mint_amount) = utils::setup_and_mint_to_private(/* with_account_contracts */ true); - let transfer_to_public_amount = mint_amount + U128::one(); + let transfer_to_public_amount = mint_amount + (1 as u128); let transfer_to_public_call_interface = Token::at(token_contract_address).transfer_to_public( owner, recipient, diff --git a/noir-projects/noir-contracts/contracts/token_contract/src/test/utils.nr b/noir-projects/noir-contracts/contracts/token_contract/src/test/utils.nr index e9626da1747..60e038f0791 100644 --- a/noir-projects/noir-contracts/contracts/token_contract/src/test/utils.nr +++ b/noir-projects/noir-contracts/contracts/token_contract/src/test/utils.nr @@ -46,10 +46,10 @@ pub unconstrained fn setup( pub unconstrained fn setup_and_mint_to_public( with_account_contracts: bool, -) -> (&mut TestEnvironment, AztecAddress, AztecAddress, AztecAddress, U128) { +) -> (&mut TestEnvironment, AztecAddress, AztecAddress, AztecAddress, u128) { // Setup let (env, token_contract_address, owner, recipient) = setup(with_account_contracts); - let mint_amount = U128::from_integer(10000); + let mint_amount = 10000 as u128; // Mint some tokens Token::at(token_contract_address).mint_to_public(owner, mint_amount).call(&mut env.public()); @@ -58,8 +58,8 @@ pub unconstrained fn setup_and_mint_to_public( pub unconstrained fn setup_and_mint_amount_to_private( with_account_contracts: bool, - mint_amount: U128, -) -> (&mut TestEnvironment, AztecAddress, AztecAddress, AztecAddress, U128) { + mint_amount: u128, +) -> (&mut TestEnvironment, AztecAddress, AztecAddress, AztecAddress, u128) { // Setup the tokens and mint public balance let (env, token_contract_address, owner, recipient) = setup(with_account_contracts); @@ -71,8 +71,8 @@ pub unconstrained fn setup_and_mint_amount_to_private( pub unconstrained fn setup_and_mint_to_private( with_account_contracts: bool, -) -> (&mut TestEnvironment, AztecAddress, AztecAddress, AztecAddress, U128) { - let mint_amount = U128::from_integer(10000); +) -> (&mut TestEnvironment, AztecAddress, AztecAddress, AztecAddress, u128) { + let mint_amount = 10000 as u128; setup_and_mint_amount_to_private(with_account_contracts, mint_amount) } @@ -80,7 +80,7 @@ pub unconstrained fn mint_to_private( env: &mut TestEnvironment, token_contract_address: AztecAddress, recipient: AztecAddress, - amount: U128, + amount: u128, ) { let note_randomness = random(); let _ = OracleMock::mock("getRandomField").returns(note_randomness); @@ -97,7 +97,7 @@ pub unconstrained fn mint_to_private( pub unconstrained fn check_public_balance( token_contract_address: AztecAddress, address: AztecAddress, - address_amount: U128, + address_amount: u128, ) { let current_contract_address = get_contract_address(); cheatcodes::set_contract_address(token_contract_address); @@ -105,7 +105,7 @@ pub unconstrained fn check_public_balance( let balances_slot = Token::storage_layout().public_balances.slot; let address_slot = derive_storage_slot_in_map(balances_slot, address); - let amount: U128 = storage_read(token_contract_address, address_slot, block_number); + let amount: u128 = storage_read(token_contract_address, address_slot, block_number); assert(amount == address_amount, "Public balance is not correct"); cheatcodes::set_contract_address(current_contract_address); } @@ -114,28 +114,28 @@ pub unconstrained fn check_public_balance( pub unconstrained fn get_public_balance( token_contract_address: AztecAddress, address: AztecAddress, -) -> U128 { +) -> u128 { let current_contract_address = get_contract_address(); cheatcodes::set_contract_address(token_contract_address); let block_number = get_block_number(); let balances_slot = Token::storage_layout().public_balances.slot; let address_slot = derive_storage_slot_in_map(balances_slot, address); - let amount: U128 = storage_read(token_contract_address, address_slot, block_number); + let amount: u128 = storage_read(token_contract_address, address_slot, block_number); cheatcodes::set_contract_address(current_contract_address); amount } pub unconstrained fn check_total_supply( token_contract_address: AztecAddress, - expected_total_supply: U128, + expected_total_supply: u128, ) { let current_contract_address = get_contract_address(); cheatcodes::set_contract_address(token_contract_address); let block_number = get_block_number(); let total_supply_slot = Token::storage_layout().total_supply.slot; - let total_supply: U128 = storage_read(token_contract_address, total_supply_slot, block_number); + let total_supply: u128 = storage_read(token_contract_address, total_supply_slot, block_number); assert(total_supply == expected_total_supply, "Total supply is not correct"); cheatcodes::set_contract_address(current_contract_address); } @@ -144,7 +144,7 @@ pub unconstrained fn check_total_supply( pub unconstrained fn check_private_balance( token_contract_address: AztecAddress, address: AztecAddress, - address_amount: U128, + address_amount: u128, ) { let current_contract_address = get_contract_address(); cheatcodes::set_contract_address(token_contract_address); @@ -158,7 +158,7 @@ pub unconstrained fn check_private_balance( pub unconstrained fn get_private_balance( token_contract_address: AztecAddress, address: AztecAddress, -) -> U128 { +) -> u128 { let current_contract_address = get_contract_address(); cheatcodes::set_contract_address(token_contract_address); // Direct call to unconstrained @@ -172,7 +172,7 @@ pub unconstrained fn add_token_note( env: &mut TestEnvironment, token_contract_address: AztecAddress, owner: AztecAddress, - amount: U128, + amount: u128, note_randomness: Field, ) { // docs:start:txe_test_add_note diff --git a/noir-projects/noir-contracts/contracts/token_contract/src/types/balance_set.nr b/noir-projects/noir-contracts/contracts/token_contract/src/types/balance_set.nr index 1fecee449db..5a9f77c3cd5 100644 --- a/noir-projects/noir-contracts/contracts/token_contract/src/types/balance_set.nr +++ b/noir-projects/noir-contracts/contracts/token_contract/src/types/balance_set.nr @@ -18,12 +18,12 @@ impl BalanceSet { } impl BalanceSet { - pub unconstrained fn balance_of(self: Self) -> U128 { + pub unconstrained fn balance_of(self: Self) -> u128 { self.balance_of_with_offset(0) } - pub unconstrained fn balance_of_with_offset(self: Self, offset: u32) -> U128 { - let mut balance = U128::from_integer(0); + pub unconstrained fn balance_of_with_offset(self: Self, offset: u32) -> u128 { + let mut balance = 0 as u128; // docs:start:view_notes let mut options = NoteViewerOptions::new(); let notes = self.set.view_notes(options.set_offset(offset)); @@ -42,8 +42,8 @@ impl BalanceSet { } impl BalanceSet<&mut PrivateContext> { - pub fn add(self: Self, owner: AztecAddress, addend: U128) -> OuterNoteEmission { - if addend == U128::from_integer(0) { + pub fn add(self: Self, owner: AztecAddress, addend: u128) -> OuterNoteEmission { + if addend == 0 as u128 { OuterNoteEmission::new(Option::none()) } else { // We fetch the nullifier public key hash from the registry / from our PXE @@ -55,7 +55,7 @@ impl BalanceSet<&mut PrivateContext> { } } - pub fn sub(self: Self, owner: AztecAddress, amount: U128) -> OuterNoteEmission { + pub fn sub(self: Self, owner: AztecAddress, amount: u128) -> OuterNoteEmission { let subtracted = self.try_sub(amount, MAX_NOTE_HASH_READ_REQUESTS_PER_CALL); // try_sub may have substracted more or less than amount. We must ensure that we subtracted at least as much as @@ -73,7 +73,7 @@ impl BalanceSet<&mut PrivateContext> { // The `max_notes` parameter is used to fine-tune the number of constraints created by this function. The gate count // scales relatively linearly with `max_notes`, but a lower `max_notes` parameter increases the likelihood of // `try_sub` subtracting an amount smaller than `target_amount`. - pub fn try_sub(self: Self, target_amount: U128, max_notes: u32) -> U128 { + pub fn try_sub(self: Self, target_amount: u128, max_notes: u32) -> u128 { // We are using a preprocessor here (filter applied in an unconstrained context) instead of a filter because // we do not need to prove correct execution of the preprocessor. // Because the `min_sum` notes is not constrained, users could choose to e.g. not call it. However, all this @@ -83,7 +83,7 @@ impl BalanceSet<&mut PrivateContext> { .set_limit(max_notes); let notes = self.set.pop_notes(options); - let mut subtracted = U128::from_integer(0); + let mut subtracted = 0 as u128; for i in 0..options.limit { if i < notes.len() { let note = notes.get_unchecked(i); @@ -102,10 +102,10 @@ impl BalanceSet<&mut PrivateContext> { // Note that proper usage of this preprocessor requires for notes to be sorted in descending order. pub fn preprocess_notes_min_sum( notes: [Option>; MAX_NOTE_HASH_READ_REQUESTS_PER_CALL], - min_sum: U128, + min_sum: u128, ) -> [Option>; MAX_NOTE_HASH_READ_REQUESTS_PER_CALL] { let mut selected = [Option::none(); MAX_NOTE_HASH_READ_REQUESTS_PER_CALL]; - let mut sum = U128::from_integer(0); + let mut sum = 0 as u128; for i in 0..notes.len() { // Because we process notes in retrieved order, notes need to be sorted in descending amount order for this // filter to be useful. Consider a 'min_sum' of 4, and a set of notes with amounts [3, 2, 1, 1, 1, 1, 1]. If diff --git a/noir-projects/noir-contracts/contracts/token_portal_content_hash_lib/src/lib.nr b/noir-projects/noir-contracts/contracts/token_portal_content_hash_lib/src/lib.nr index 32039dfb512..cc2b8e9b082 100644 --- a/noir-projects/noir-contracts/contracts/token_portal_content_hash_lib/src/lib.nr +++ b/noir-projects/noir-contracts/contracts/token_portal_content_hash_lib/src/lib.nr @@ -4,10 +4,10 @@ use dep::aztec::protocol_types::{hash::sha256_to_field, traits::ToField}; // Computes a content hash of a deposit/mint_to_public message. // Refer TokenPortal.sol for reference on L1. -pub fn get_mint_to_public_content_hash(owner: AztecAddress, amount: U128) -> Field { +pub fn get_mint_to_public_content_hash(owner: AztecAddress, amount: u128) -> Field { let mut hash_bytes = [0; 68]; let recipient_bytes:[u8; 32] = owner.to_field().to_be_bytes(); - let amount_bytes:[u8; 32] = amount.to_field().to_be_bytes(); + let amount_bytes:[u8; 32] = (amount as Field).to_be_bytes(); // The purpose of including the following selector is to make the message unique to that specific call. Note that // it has nothing to do with calling the function. @@ -30,9 +30,9 @@ pub fn get_mint_to_public_content_hash(owner: AztecAddress, amount: U128) -> Fie // docs:start:get_mint_to_private_content_hash // Computes a content hash of a deposit/mint_to_private message. // Refer TokenPortal.sol for reference on L1. -pub fn get_mint_to_private_content_hash(amount: U128) -> Field { +pub fn get_mint_to_private_content_hash(amount: u128) -> Field { let mut hash_bytes = [0; 36]; - let amount_bytes:[u8; 32] = amount.to_field().to_be_bytes(); + let amount_bytes:[u8; 32] = (amount as Field).to_be_bytes(); // The purpose of including the following selector is to make the message unique to that specific call. Note that // it has nothing to do with calling the function. @@ -53,14 +53,14 @@ pub fn get_mint_to_private_content_hash(amount: U128) -> Field { // docs:start:get_withdraw_content_hash // Computes a content hash of a withdraw message. -pub fn get_withdraw_content_hash(recipient: EthAddress, amount: U128, caller_on_l1: EthAddress) -> Field { +pub fn get_withdraw_content_hash(recipient: EthAddress, amount: u128, caller_on_l1: EthAddress) -> Field { // Compute the content hash // Compute sha256(selector || amount || recipient) // then convert to a single field element // add that to the l2 to l1 messages let mut hash_bytes: [u8; 100] = [0; 100]; let recipient_bytes: [u8; 32] = recipient.to_field().to_be_bytes(); - let amount_bytes: [u8; 32] = amount.to_field().to_be_bytes(); + let amount_bytes: [u8; 32] = (amount as Field).to_be_bytes(); let caller_on_l1_bytes: [u8; 32] = caller_on_l1.to_field().to_be_bytes(); // The purpose of including the following selector is to make the message unique to that specific call. Note that diff --git a/noir-projects/noir-contracts/contracts/uniswap_contract/src/main.nr b/noir-projects/noir-contracts/contracts/uniswap_contract/src/main.nr index 664c34ef286..11e8c504ff8 100644 --- a/noir-projects/noir-contracts/contracts/uniswap_contract/src/main.nr +++ b/noir-projects/noir-contracts/contracts/uniswap_contract/src/main.nr @@ -37,13 +37,13 @@ pub contract Uniswap { fn swap_public( sender: AztecAddress, input_asset_bridge: AztecAddress, - input_amount: U128, + input_amount: u128, output_asset_bridge: AztecAddress, // params for using the transfer approval nonce_for_transfer_approval: Field, // params for the swap uniswap_fee_tier: Field, - minimum_output_amount: U128, + minimum_output_amount: u128, // params for the depositing output_asset back to Aztec recipient: AztecAddress, secret_hash_for_L1_to_l2_message: Field, @@ -112,13 +112,13 @@ pub contract Uniswap { fn swap_private( input_asset: AztecAddress, // since private, we pass here and later assert that this is as expected by input_bridge input_asset_bridge: AztecAddress, - input_amount: U128, + input_amount: u128, output_asset_bridge: AztecAddress, // params for using the transfer_to_public approval nonce_for_transfer_to_public_approval: Field, // params for the swap uniswap_fee_tier: Field, // which uniswap tier to use (eg 3000 for 0.3% fee) - minimum_output_amount: U128, // minimum output amount to receive (slippage protection for the swap) + minimum_output_amount: u128, // minimum output amount to receive (slippage protection for the swap) // params for the depositing output_asset back to Aztec secret_hash_for_L1_to_l2_message: Field, // for when l1 uniswap portal inserts the message to consume output assets on L2 caller_on_L1: EthAddress, // ethereum address that can call this function on the L1 portal (0x0 if anyone can call) @@ -191,7 +191,7 @@ pub contract Uniswap { fn _approve_bridge_and_exit_input_asset_to_L1( token: AztecAddress, token_bridge: AztecAddress, - amount: U128, + amount: u128, ) { // Since we will authorize and instantly spend the funds, all in public, we can use the same nonce // every interaction. In practice, the authwit should be squashed, so this is also cheap! diff --git a/noir-projects/noir-contracts/contracts/uniswap_contract/src/util.nr b/noir-projects/noir-contracts/contracts/uniswap_contract/src/util.nr index b1d5a4d30fa..85709b15065 100644 --- a/noir-projects/noir-contracts/contracts/uniswap_contract/src/util.nr +++ b/noir-projects/noir-contracts/contracts/uniswap_contract/src/util.nr @@ -6,10 +6,10 @@ use dep::aztec::protocol_types::hash::sha256_to_field; // refer `l1-contracts/test/portals/UniswapPortal.sol` on how L2 to L1 message is expected pub fn compute_swap_public_content_hash( input_asset_bridge_portal_address: EthAddress, - input_amount: U128, + input_amount: u128, uniswap_fee_tier: Field, output_asset_bridge_portal_address: EthAddress, - minimum_output_amount: U128, + minimum_output_amount: u128, aztec_recipient: AztecAddress, secret_hash_for_L1_to_l2_message: Field, caller_on_L1: EthAddress, @@ -62,10 +62,10 @@ pub fn compute_swap_public_content_hash( // refer `l1-contracts/test/portals/UniswapPortal.sol` on how L2 to L1 message is expected pub fn compute_swap_private_content_hash( input_asset_bridge_portal_address: EthAddress, - input_amount: U128, + input_amount: u128, uniswap_fee_tier: Field, output_asset_bridge_portal_address: EthAddress, - minimum_output_amount: U128, + minimum_output_amount: u128, secret_hash_for_L1_to_l2_message: Field, caller_on_L1: EthAddress, ) -> Field { diff --git a/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/abis/base_or_merge_rollup_public_inputs.nr b/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/abis/base_or_merge_rollup_public_inputs.nr index c84653d848f..14c3e48e7bc 100644 --- a/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/abis/base_or_merge_rollup_public_inputs.nr +++ b/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/abis/base_or_merge_rollup_public_inputs.nr @@ -25,8 +25,8 @@ pub struct BaseOrMergeRollupPublicInputs { pub(crate) end_sponge_blob: SpongeBlob, // We hash public inputs to make them constant-sized (to then be opened on-chain) - // U128 isn't safe if it's an input to the circuit (it won't automatically constrain the witness) - // So we want to constrain it when casting these fields to U128 + // u128 isn't safe if it's an input to the circuit (it won't automatically constrain the witness) + // So we want to constrain it when casting these fields to u128 pub(crate) out_hash: Field, diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/hash.nr b/noir-projects/noir-protocol-circuits/crates/types/src/hash.nr index 78f1b38318c..eb3666a4e7b 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/hash.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/hash.nr @@ -183,7 +183,7 @@ pub fn silo_l2_to_l1_message( // pub fn accumulate_sha256(input: [Field; 2]) -> Field { // This is a note about the cpp code, since it takes an array of Fields - // instead of a U128. + // instead of a u128. // 4 Field elements when converted to bytes will usually // occupy 4 * 32 = 128 bytes. // However, this function is making the assumption that each Field diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/meta/mod.nr b/noir-projects/noir-protocol-circuits/crates/types/src/meta/mod.nr index c24fb685603..a06be877c54 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/meta/mod.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/meta/mod.nr @@ -39,16 +39,11 @@ comptime fn get_trait_impl_method( /// Given the following setup: /// ``` /// struct UintNote { -/// value: U128, +/// value: u128, /// owner: AztecAddress, /// randomness: Field, /// } /// -/// struct U128 { -/// lo: Field, -/// hi: Field, -/// } -/// /// struct AztecAddress { /// inner: Field, /// } @@ -57,18 +52,15 @@ comptime fn get_trait_impl_method( /// If `UintNote` is the input type, the function will generate the following deserialization code: /// ``` /// UintNote { -/// value: U128 { -/// lo: fields[0], // First field becomes low part of U128 -/// hi: fields[1], // Second field becomes high part of U128 -/// }, +/// value: fields[0] as u128, /// owner: AztecAddress { -/// inner: fields[2], // Third field becomes inner address +/// inner: fields[1], /// }, -/// randomness: fields[3], // Fourth field as randomness +/// randomness: fields[2], /// } /// ``` /// # Nested Struct Example with Unpacking -/// - given the same setup as above and given that U128, AztecAddress and Field implement the `Packable` trait +/// - given the same setup as above and given that u128, AztecAddress and Field implement the `Packable` trait /// the result we get is: /// ``` /// UintNote { @@ -140,7 +132,7 @@ pub comptime fn generate_deserialize_from_fields( // We increment the consumed counter by the number of fields consumed in the recursion consumed_counter += num_consumed_in_recursion; // We add the deserialized field to the list of deserialized fields. - // E.g. `value: U128 { lo: fields[0], hi: fields[1] }` + // E.g. `value: u128 { lo: fields[0], hi: fields[1] }` deserialized_fields_list = deserialized_fields_list.push_back(quote { $field_name: $deserialized_field }); } @@ -244,33 +236,33 @@ pub comptime fn generate_deserialize_from_fields( /// ## Struct /// Given the following struct: /// ```rust -/// struct U128 { -/// lo: Field, -/// hi: Field, +/// struct MockStruct { +/// a: Field, +/// b: Field, /// } /// ``` /// /// Serializing the struct: /// ```rust -/// generate_serialize_to_fields(quote { my_u128 }, U128, &[], false) +/// generate_serialize_to_fields(quote { my_mock_struct }, MockStruct, &[], false) /// // Returns: -/// // ([`my_u128.lo`, `my_u128.hi`], []) +/// // ([`my_mock_struct.a`, `my_mock_struct.b`], []) /// ``` /// /// ## Nested Struct /// For a more complex struct: /// ```rust -/// struct UintNote { -/// value: U128, -/// randomness: Field, +/// struct NestedStruct { +/// m1: MockStruct, +/// m2: MockStruct, /// } /// ``` /// /// Serialization output: /// ```rust -/// generate_serialize_to_fields(quote { self }, UintNote, &[\], false) +/// generate_serialize_to_fields(quote { self }, NestedStruct, &[], false) /// // Returns: -/// // ([`self.value.lo`, `self.value.hi`, `self.randomness`], []) +/// // ([`self.m1.a`, `self.m1.b`, `self.m2.a`, `self.m2.b`], []) /// ``` /// /// ## Array @@ -291,12 +283,12 @@ pub comptime fn generate_deserialize_from_fields( /// ``` /// /// ## Nested Struct with Omitted Field and packing enabled -/// - U128 has a `Packable` implementation hence it will be packed. +/// - u128 has a `Packable` implementation hence it will be packed. /// /// For a more complex struct: /// ```rust /// struct MyStruct { -/// value: U128, +/// value: u128, /// value2: Field, /// } /// ``` @@ -540,12 +532,6 @@ pub struct Fancier { d: str<16>, } -#[derive(Eq, Packable)] -pub struct ContainsU128 { - a: U128, - b: Field, -} - fn main() { assert(false); } @@ -588,13 +574,3 @@ fn fancier_test() { let deserialized = Fancier::deserialize(serialized); assert(deserialized == fancier); } - -#[test] -fn contains_u128_test() { - let contains_u128 = ContainsU128 { a: U128::from_integer(5), b: 3 }; - let packed = contains_u128.pack(); - assert_eq(packed, [5, 3], "Packed does not match the expected"); - - let unpacked = ContainsU128::unpack(packed); - assert_eq(unpacked, contains_u128, "Unpacked does not match the original"); -} diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/tests/merkle_tree_utils.nr b/noir-projects/noir-protocol-circuits/crates/types/src/tests/merkle_tree_utils.nr index 97ae46c48c4..e4f94ee8580 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/tests/merkle_tree_utils.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/tests/merkle_tree_utils.nr @@ -104,8 +104,8 @@ impl Self { - U128::from_integer(0) + 0 } } @@ -116,9 +116,9 @@ impl ToField for u64 { self as Field } } -impl ToField for U128 { +impl ToField for u128 { fn to_field(self) -> Field { - self.to_integer() + self as Field } } impl ToField for str { @@ -163,9 +163,9 @@ impl FromField for u64 { value as u64 } } -impl FromField for U128 { +impl FromField for u128 { fn from_field(value: Field) -> Self { - U128::from_integer(value) + value as u128 } } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/type_packing.nr b/noir-projects/noir-protocol-circuits/crates/types/src/type_packing.nr index 56486e92e5d..be32a12cc83 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/type_packing.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/type_packing.nr @@ -1,4 +1,4 @@ -use crate::traits::{Packable, ToField}; +use crate::traits::Packable; global BOOL_PACKED_LEN: u32 = 1; global U8_PACKED_LEN: u32 = 1; @@ -62,13 +62,13 @@ impl Packable for u64 { } } -impl Packable for U128 { +impl Packable for u128 { fn pack(self) -> [Field; U128_PACKED_LEN] { - [self.to_field()] + [self as Field] } fn unpack(fields: [Field; U128_PACKED_LEN]) -> Self { - U128::from_integer(fields[0]) + fields[0] as u128 } } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/type_serialization.nr b/noir-projects/noir-protocol-circuits/crates/types/src/type_serialization.nr index 1a6d2b7f84a..1c005aa9675 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/type_serialization.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/type_serialization.nr @@ -5,7 +5,7 @@ global U8_SERIALIZED_LEN: u32 = 1; global U16_SERIALIZED_LEN: u32 = 1; global U32_SERIALIZED_LEN: u32 = 1; global U64_SERIALIZED_LEN: u32 = 1; -global U128_SERIALIZED_LEN: u32 = 2; +global U128_SERIALIZED_LEN: u32 = 1; global FIELD_SERIALIZED_LEN: u32 = 1; global I8_SERIALIZED_LEN: u32 = 1; global I16_SERIALIZED_LEN: u32 = 1; @@ -72,24 +72,15 @@ impl Deserialize for u64 { } } -impl Serialize for U128 { +impl Serialize for u128 { fn serialize(self) -> [Field; U128_SERIALIZED_LEN] { - // We use little-endian ordering to match the order in which U128 defines its limbs. - // This is necessary because of how Noir handles serialization: - // - When calling a contract function from TypeScript, the serialization in encoder.ts gets used and then Noir - // deserializes using its intrinsic serialization logic (based on the limb order in the struct). - // - When calling a contract function from another function, the `serialize` method is invoked on the type - // first. - // For this reason if we didn't use the ordering of U128 limbs here and in encoder.ts we would get an arguments - // hash mismatch. - // The below warning is due to visibility in noir stdlib. - [self.lo, self.hi] + [self as Field] } } -impl Deserialize for U128 { +impl Deserialize for u128 { fn deserialize(fields: [Field; U128_SERIALIZED_LEN]) -> Self { - U128::from_u64s_le(fields[0] as u64, fields[1] as u64) + fields[0] as u128 } } diff --git a/playground/src/components/common/fnParameter.tsx b/playground/src/components/common/fnParameter.tsx index bdb2bd3789b..404ed2d3a5b 100644 --- a/playground/src/components/common/fnParameter.tsx +++ b/playground/src/components/common/fnParameter.tsx @@ -2,7 +2,6 @@ import { type ABIParameter, type AbiType, isAddressStruct, - isU128Struct, } from "@aztec/stdlib/abi"; import { Autocomplete, @@ -48,10 +47,6 @@ export function FunctionParameter({ break; } case "struct": { - if (isU128Struct(type)) { - onParameterChange(BigInt(value)); - break; - } // Otherwise fall through } default: { @@ -125,7 +120,7 @@ export function FunctionParameter({ variant="outlined" disabled={ ["array", "struct", "tuple"].includes(parameter.type.kind) && - !(isAddressStruct(parameter.type) || isU128Struct(parameter.type)) + !(isAddressStruct(parameter.type)) } key={parameter.name} type="text" diff --git a/yarn-project/aztec.js/src/fee/fee_juice_payment_method_with_claim.ts b/yarn-project/aztec.js/src/fee/fee_juice_payment_method_with_claim.ts index b702ee70b60..f5b7ae02006 100644 --- a/yarn-project/aztec.js/src/fee/fee_juice_payment_method_with_claim.ts +++ b/yarn-project/aztec.js/src/fee/fee_juice_payment_method_with_claim.ts @@ -2,7 +2,7 @@ import { Fr } from '@aztec/foundation/fields'; import { ProtocolContractAddress } from '@aztec/protocol-contracts'; import { getCanonicalFeeJuice } from '@aztec/protocol-contracts/fee-juice'; import type { FunctionCall } from '@aztec/stdlib/abi'; -import { FunctionSelector, FunctionType, U128 } from '@aztec/stdlib/abi'; +import { FunctionSelector, FunctionType } from '@aztec/stdlib/abi'; import type { AztecAddress } from '@aztec/stdlib/aztec-address'; import type { L2AmountClaim } from '../api/ethereum/portal_manager.js'; @@ -37,7 +37,7 @@ export class FeeJuicePaymentMethodWithClaim extends FeeJuicePaymentMethod { isStatic: false, args: [ this.sender.toField(), - ...new U128(this.claim.claimAmount).toFields(), + new Fr(this.claim.claimAmount), this.claim.claimSecret, new Fr(this.claim.messageLeafIndex), ], diff --git a/yarn-project/aztec.js/src/fee/private_fee_payment_method.ts b/yarn-project/aztec.js/src/fee/private_fee_payment_method.ts index ac731cf0264..a4d0d6752f2 100644 --- a/yarn-project/aztec.js/src/fee/private_fee_payment_method.ts +++ b/yarn-project/aztec.js/src/fee/private_fee_payment_method.ts @@ -1,5 +1,5 @@ import { Fr } from '@aztec/foundation/fields'; -import { type FunctionCall, FunctionSelector, FunctionType, U128 } from '@aztec/stdlib/abi'; +import { type FunctionCall, FunctionSelector, FunctionType } from '@aztec/stdlib/abi'; import type { AztecAddress } from '@aztec/stdlib/aztec-address'; import type { GasSettings } from '@aztec/stdlib/gas'; @@ -87,15 +87,15 @@ export class PrivateFeePaymentMethod implements FeePaymentMethod { async getFunctionCalls(gasSettings: GasSettings): Promise { // We assume 1:1 exchange rate between fee juice and token. But in reality you would need to convert feeLimit // (maxFee) to be in token denomination. - const maxFee = new U128(this.setMaxFeeToOne ? 1n : gasSettings.getFeeLimit().toBigInt()); + const maxFee = this.setMaxFeeToOne ? Fr.ONE : gasSettings.getFeeLimit(); const nonce = Fr.random(); await this.wallet.createAuthWit({ caller: this.paymentContract, action: { name: 'transfer_to_public', - args: [this.wallet.getAddress().toField(), this.paymentContract.toField(), ...maxFee.toFields(), nonce], - selector: await FunctionSelector.fromSignature('transfer_to_public((Field),(Field),(Field,Field),Field)'), + args: [this.wallet.getAddress().toField(), this.paymentContract.toField(), maxFee, nonce], + selector: await FunctionSelector.fromSignature('transfer_to_public((Field),(Field),u128,Field)'), type: FunctionType.PRIVATE, isStatic: false, to: await this.getAsset(), @@ -107,10 +107,10 @@ export class PrivateFeePaymentMethod implements FeePaymentMethod { { name: 'fee_entrypoint_private', to: this.paymentContract, - selector: await FunctionSelector.fromSignature('fee_entrypoint_private((Field,Field),Field)'), + selector: await FunctionSelector.fromSignature('fee_entrypoint_private(u128,Field)'), type: FunctionType.PRIVATE, isStatic: false, - args: [...maxFee.toFields(), nonce], + args: [maxFee, nonce], returnTypes: [], }, ]; diff --git a/yarn-project/aztec.js/src/fee/public_fee_payment_method.ts b/yarn-project/aztec.js/src/fee/public_fee_payment_method.ts index 7d42ae76726..8acae43925a 100644 --- a/yarn-project/aztec.js/src/fee/public_fee_payment_method.ts +++ b/yarn-project/aztec.js/src/fee/public_fee_payment_method.ts @@ -1,6 +1,6 @@ import { Fr } from '@aztec/foundation/fields'; import type { FunctionCall } from '@aztec/stdlib/abi'; -import { FunctionSelector, FunctionType, U128 } from '@aztec/stdlib/abi'; +import { FunctionSelector, FunctionType } from '@aztec/stdlib/abi'; import type { AztecAddress } from '@aztec/stdlib/aztec-address'; import type { GasSettings } from '@aztec/stdlib/gas'; @@ -80,15 +80,15 @@ export class PublicFeePaymentMethod implements FeePaymentMethod { */ async getFunctionCalls(gasSettings: GasSettings): Promise { const nonce = Fr.random(); - const maxFee = new U128(gasSettings.getFeeLimit().toBigInt()); + const maxFee = gasSettings.getFeeLimit(); const setPublicAuthWitInteraction = await this.wallet.setPublicAuthWit( { caller: this.paymentContract, action: { name: 'transfer_in_public', - args: [this.wallet.getAddress().toField(), this.paymentContract.toField(), ...maxFee.toFields(), nonce], - selector: await FunctionSelector.fromSignature('transfer_in_public((Field),(Field),(Field,Field),Field)'), + args: [this.wallet.getAddress().toField(), this.paymentContract.toField(), maxFee, nonce], + selector: await FunctionSelector.fromSignature('transfer_in_public((Field),(Field),u128,Field)'), type: FunctionType.PUBLIC, isStatic: false, to: await this.getAsset(), @@ -103,10 +103,10 @@ export class PublicFeePaymentMethod implements FeePaymentMethod { { name: 'fee_entrypoint_public', to: this.paymentContract, - selector: await FunctionSelector.fromSignature('fee_entrypoint_public((Field,Field),Field)'), + selector: await FunctionSelector.fromSignature('fee_entrypoint_public(u128,Field)'), type: FunctionType.PRIVATE, isStatic: false, - args: [...maxFee.toFields(), nonce], + args: [maxFee, nonce], returnTypes: [], }, ]; diff --git a/yarn-project/bb-prover/src/avm_proving_tests/avm_proven_token.test.ts b/yarn-project/bb-prover/src/avm_proving_tests/avm_proven_token.test.ts index a3e06963bd9..23ebfe7a04a 100644 --- a/yarn-project/bb-prover/src/avm_proving_tests/avm_proven_token.test.ts +++ b/yarn-project/bb-prover/src/avm_proving_tests/avm_proven_token.test.ts @@ -108,7 +108,7 @@ describe('AVM Witgen & Circuit apps tests: TokenContract', () => { ], ); expect(balResult.revertCode.isOK()).toBe(true); - expectAppCall0Output(balResult, [new Fr(expectedBalance), Fr.zero()]); + expectAppCall0Output(balResult, [new Fr(expectedBalance)]); }; }); diff --git a/yarn-project/builder/src/contract-interface-gen/typescript.ts b/yarn-project/builder/src/contract-interface-gen/typescript.ts index d62a2a4315c..426e59ae9b2 100644 --- a/yarn-project/builder/src/contract-interface-gen/typescript.ts +++ b/yarn-project/builder/src/contract-interface-gen/typescript.ts @@ -9,7 +9,6 @@ import { isAztecAddressStruct, isEthAddressStruct, isFunctionSelectorStruct, - isU128Struct, isWrappedFieldStruct, } from '@aztec/stdlib/abi'; @@ -40,9 +39,6 @@ function abiTypeToTypescript(type: ABIParameter['type']): string { if (isFunctionSelectorStruct(type)) { return 'FunctionSelectorLike'; } - if (isU128Struct(type)) { - return 'U128Like'; - } if (isWrappedFieldStruct(type)) { return 'WrappedFieldLike'; } diff --git a/yarn-project/cli/src/utils/encoding.ts b/yarn-project/cli/src/utils/encoding.ts index f01acfd5bc3..11b342de9e5 100644 --- a/yarn-project/cli/src/utils/encoding.ts +++ b/yarn-project/cli/src/utils/encoding.ts @@ -1,5 +1,5 @@ import { Fr } from '@aztec/foundation/fields'; -import { type ABIParameter, type AbiType, type StructType, isU128Struct } from '@aztec/stdlib/abi'; +import type { ABIParameter, AbiType, StructType } from '@aztec/stdlib/abi'; /** * Parses a hex string into an ABI struct type. @@ -85,19 +85,13 @@ function encodeArg(arg: string, abiType: AbiType, name: string): any { throw Error(`Array passed for arg ${name}. Expected a struct.`); } const res: any = {}; - if (isU128Struct(abiType)) { - // When dealing with U128 we don't expect to receive limbs from the user but instead just a normal number. - // Also encoder.ts expects a normal number so we just return it as such. - return obj; - } else { - for (const field of abiType.fields) { - // Remove field name from list as it's present - const arg = obj[field.name]; - if (!arg) { - throw Error(`Expected field ${field.name} not found in struct ${name}.`); - } - res[field.name] = encodeArg(obj[field.name], field.type, field.name); + for (const field of abiType.fields) { + // Remove field name from list as it's present + const arg = obj[field.name]; + if (!arg) { + throw Error(`Expected field ${field.name} not found in struct ${name}.`); } + res[field.name] = encodeArg(obj[field.name], field.type, field.name); } return res; } diff --git a/yarn-project/end-to-end/src/composed/e2e_persistence.test.ts b/yarn-project/end-to-end/src/composed/e2e_persistence.test.ts index 8f9f1b032f8..cbe98f55a29 100644 --- a/yarn-project/end-to-end/src/composed/e2e_persistence.test.ts +++ b/yarn-project/end-to-end/src/composed/e2e_persistence.test.ts @@ -347,7 +347,7 @@ async function addPendingShieldNoteToPXE( await contract.methods .deliver_transparent_note( contract.address, - new Fr(amount), + amount, secretHash, txHash.hash, toBoundedVec(txEffects!.data.noteHashes, MAX_NOTE_HASHES_PER_TX), diff --git a/yarn-project/end-to-end/src/e2e_blacklist_token_contract/blacklist_token_contract_test.ts b/yarn-project/end-to-end/src/e2e_blacklist_token_contract/blacklist_token_contract_test.ts index 69ecf3950bf..7ce2a70455a 100644 --- a/yarn-project/end-to-end/src/e2e_blacklist_token_contract/blacklist_token_contract_test.ts +++ b/yarn-project/end-to-end/src/e2e_blacklist_token_contract/blacklist_token_contract_test.ts @@ -173,7 +173,7 @@ export class BlacklistTokenContractTest { await contract.methods .deliver_transparent_note( contract.address, - new Fr(amount), + amount, secretHash, txHash.hash, this.#toBoundedVec(txEffects!.data.noteHashes, MAX_NOTE_HASHES_PER_TX), diff --git a/yarn-project/end-to-end/src/e2e_blacklist_token_contract/minting.test.ts b/yarn-project/end-to-end/src/e2e_blacklist_token_contract/minting.test.ts index c3742500d0a..af941a30432 100644 --- a/yarn-project/end-to-end/src/e2e_blacklist_token_contract/minting.test.ts +++ b/yarn-project/end-to-end/src/e2e_blacklist_token_contract/minting.test.ts @@ -43,8 +43,9 @@ describe('e2e_blacklist_token_contract mint', () => { ).rejects.toThrow('Assertion failed: caller is not minter'); }); - it('mint >u128 tokens to overflow', async () => { - const amount = 2n ** 128n; // U128::max() + 1; + // TODO(#12221): re-enable this test once we have proper unsigned integer overflow checks + it.skip('mint >u128 tokens to overflow', async () => { + const amount = 2n ** 128n; // u128::max() + 1; await expect(asset.methods.mint_public(wallets[0].getAddress(), amount).prove()).rejects.toThrow( BITSIZE_TOO_BIG_ERROR, ); @@ -108,7 +109,7 @@ describe('e2e_blacklist_token_contract mint', () => { it('try to redeem as recipient again (double-spend) [REVERTS]', async () => { // We have another wallet add the note to their PXE and then try to spend it. They will be able to successfully // add it, but PXE will realize that the note has been nullified already and not inject it into the circuit - // during execution of redeem_shield, resulting in a simulaton failure. + // during execution of redeem_shield, resulting in a simulation failure. await t.addPendingShieldNoteToPXE(asset, wallets[1], amount, secretHash, txHash); @@ -123,8 +124,9 @@ describe('e2e_blacklist_token_contract mint', () => { ); }); - it('mint >u128 tokens to overflow', async () => { - const amount = 2n ** 128n; // U128::max() + 1; + // TODO(#12221): re-enable this test once we have proper unsigned integer overflow checks + it.skip('mint >u128 tokens to overflow', async () => { + const amount = 2n ** 128n; // u128::max() + 1; await expect(asset.methods.mint_private(amount, secretHash).prove()).rejects.toThrow(BITSIZE_TOO_BIG_ERROR); }); diff --git a/yarn-project/end-to-end/src/e2e_fees/failures.test.ts b/yarn-project/end-to-end/src/e2e_fees/failures.test.ts index 5cd06d8adbb..5f64fd8dd77 100644 --- a/yarn-project/end-to-end/src/e2e_fees/failures.test.ts +++ b/yarn-project/end-to-end/src/e2e_fees/failures.test.ts @@ -10,9 +10,10 @@ import { } from '@aztec/aztec.js'; import type { FPCContract } from '@aztec/noir-contracts.js/FPC'; import type { TokenContract as BananaCoin } from '@aztec/noir-contracts.js/Token'; -import { FunctionType, U128 } from '@aztec/stdlib/abi'; +import { FunctionType } from '@aztec/stdlib/abi'; import { Gas, GasSettings } from '@aztec/stdlib/gas'; +import { U128_UNDERFLOW_ERROR } from '../fixtures/fixtures.js'; import { expectMapping } from '../fixtures/utils.js'; import { FeesTest } from './fees_test.js'; @@ -65,7 +66,7 @@ describe('e2e_fees failures', () => { }, }) .wait(), - ).rejects.toThrow(/attempt to subtract with underflow 'hi == high'/); + ).rejects.toThrow(U128_UNDERFLOW_ERROR); // we did not pay the fee, because we did not submit the TX await expectMapping( @@ -161,7 +162,7 @@ describe('e2e_fees failures', () => { }, }) .wait(), - ).rejects.toThrow(/attempt to subtract with underflow 'hi == high'/); + ).rejects.toThrow(U128_UNDERFLOW_ERROR); // we did not pay the fee, because we did not submit the TX await expectMapping( @@ -324,10 +325,10 @@ describe('e2e_fees failures', () => { class BuggedSetupFeePaymentMethod extends PublicFeePaymentMethod { override async getFunctionCalls(gasSettings: GasSettings): Promise { - const maxFee = new U128(gasSettings.getFeeLimit().toBigInt()); + const maxFee = gasSettings.getFeeLimit(); const nonce = Fr.random(); - const tooMuchFee = new U128(maxFee.toInteger() * 2n); + const tooMuchFee = new Fr(maxFee.toBigInt() * 2n); const asset = await this.getAsset(); @@ -336,8 +337,8 @@ class BuggedSetupFeePaymentMethod extends PublicFeePaymentMethod { caller: this.paymentContract, action: { name: 'transfer_in_public', - args: [this.wallet.getAddress().toField(), this.paymentContract.toField(), ...maxFee.toFields(), nonce], - selector: await FunctionSelector.fromSignature('transfer_in_public((Field),(Field),(Field,Field),Field)'), + args: [this.wallet.getAddress().toField(), this.paymentContract.toField(), maxFee, nonce], + selector: await FunctionSelector.fromSignature('transfer_in_public((Field),(Field),u128,Field)'), type: FunctionType.PUBLIC, isStatic: false, to: asset, @@ -352,10 +353,10 @@ class BuggedSetupFeePaymentMethod extends PublicFeePaymentMethod { { name: 'fee_entrypoint_public', to: this.paymentContract, - selector: await FunctionSelector.fromSignature('fee_entrypoint_public((Field,Field),Field)'), + selector: await FunctionSelector.fromSignature('fee_entrypoint_public(u128,Field)'), type: FunctionType.PRIVATE, isStatic: false, - args: [...tooMuchFee.toFields(), nonce], + args: [tooMuchFee, nonce], returnTypes: [], }, ]; diff --git a/yarn-project/end-to-end/src/e2e_fees/gas_estimation.test.ts b/yarn-project/end-to-end/src/e2e_fees/gas_estimation.test.ts index 19f9251fc46..0ea40d7195c 100644 --- a/yarn-project/end-to-end/src/e2e_fees/gas_estimation.test.ts +++ b/yarn-project/end-to-end/src/e2e_fees/gas_estimation.test.ts @@ -52,10 +52,12 @@ describe('e2e_fees gas_estimation', () => { const makeTransferRequest = () => bananaCoin.methods.transfer_in_public(aliceAddress, bobAddress, 1n, 0n); // Sends two tx with transfers of public tokens: one with estimateGas on, one with estimateGas off - const sendTransfers = (paymentMethod: FeePaymentMethod, estimatedGasPadding: number) => + const sendTransfers = (paymentMethod: FeePaymentMethod) => Promise.all( [true, false].map(estimateGas => - makeTransferRequest().send({ fee: { estimateGas, gasSettings, paymentMethod, estimatedGasPadding } }).wait(), + makeTransferRequest() + .send({ fee: { estimateGas, gasSettings, paymentMethod, estimatedGasPadding: 0 } }) + .wait(), ), ); @@ -66,11 +68,9 @@ describe('e2e_fees gas_estimation', () => { }); it('estimates gas with Fee Juice payment method', async () => { - const estimatedGasPadding = 0; - const paymentMethod = new FeeJuicePaymentMethod(aliceAddress); const estimatedGas = await makeTransferRequest().estimateGas({ - fee: { gasSettings, paymentMethod, estimatedGasPadding }, + fee: { gasSettings, paymentMethod, estimatedGasPadding: 0 }, }); logGasEstimate(estimatedGas); @@ -78,7 +78,7 @@ describe('e2e_fees gas_estimation', () => { .getSequencer()! .updateSequencerConfig({ minTxsPerBlock: 2, maxTxsPerBlock: 2 }); - const [withEstimate, withoutEstimate] = await sendTransfers(paymentMethod, estimatedGasPadding); + const [withEstimate, withoutEstimate] = await sendTransfers(paymentMethod); // This is the interesting case, which we hit most of the time. const block = await t.pxe.getBlock(withEstimate.blockNumber!); @@ -96,17 +96,14 @@ describe('e2e_fees gas_estimation', () => { }); it('estimates gas with public payment method', async () => { - // TODO(#11324): Reset this value back to zero. - const estimatedGasPadding = 0.1; - const teardownFixedFee = gasSettings.teardownGasLimits.computeFee(gasSettings.maxFeesPerGas).toBigInt(); const paymentMethod = new PublicFeePaymentMethod(bananaFPC.address, aliceWallet); const estimatedGas = await makeTransferRequest().estimateGas({ - fee: { gasSettings, paymentMethod, estimatedGasPadding }, + fee: { gasSettings, paymentMethod, estimatedGasPadding: 0 }, }); logGasEstimate(estimatedGas); - const [withEstimate, withoutEstimate] = await sendTransfers(paymentMethod, estimatedGasPadding); + const [withEstimate, withoutEstimate] = await sendTransfers(paymentMethod); // Actual teardown gas used is less than the limits. expect(estimatedGas.teardownGasLimits.l2Gas).toBeLessThan(gasSettings.teardownGasLimits.l2Gas); @@ -119,19 +116,15 @@ describe('e2e_fees gas_estimation', () => { // Check that estimated gas for teardown are not zero since we're doing work there expect(estimatedGas.teardownGasLimits.l2Gas).toBeGreaterThan(0); - // TODO(#11324): Figure out why this does not match no more - // const estimatedFee = estimatedGas.gasLimits.computeFee(gasSettings.maxFeesPerGas).toBigInt(); - // expect(estimatedFee).toEqual(withEstimate.transactionFee!); + const estimatedFee = estimatedGas.gasLimits.computeFee(gasSettings.maxFeesPerGas).toBigInt(); + expect(estimatedFee).toEqual(withEstimate.transactionFee!); }); it('estimates gas for public contract initialization with Fee Juice payment method', async () => { - // TODO(#11324): Reset this value back to zero. - const estimatedGasPadding = 0.1; - const paymentMethod = new FeeJuicePaymentMethod(aliceAddress); const deployMethod = () => BananaCoin.deploy(aliceWallet, aliceAddress, 'TKN', 'TKN', 8); const deployOpts = (estimateGas = false) => ({ - fee: { gasSettings, paymentMethod, estimateGas, estimatedGasPadding }, + fee: { gasSettings, paymentMethod, estimateGas, estimatedGasPadding: 0 }, skipClassRegistration: true, }); const estimatedGas = await deployMethod().estimateGas(deployOpts()); @@ -149,8 +142,7 @@ describe('e2e_fees gas_estimation', () => { expect(estimatedGas.teardownGasLimits.l2Gas).toEqual(0); expect(estimatedGas.teardownGasLimits.daGas).toEqual(0); - // TODO(#11324): Figure out why this does not match no more - // const estimatedFee = estimatedGas.gasLimits.computeFee(gasSettings.maxFeesPerGas).toBigInt(); - // expect(estimatedFee).toEqual(withEstimate.transactionFee!); + const estimatedFee = estimatedGas.gasLimits.computeFee(gasSettings.maxFeesPerGas).toBigInt(); + expect(estimatedFee).toEqual(withEstimate.transactionFee!); }); }); diff --git a/yarn-project/end-to-end/src/e2e_token_contract/minting.test.ts b/yarn-project/end-to-end/src/e2e_token_contract/minting.test.ts index 96c2a4da392..2e6c8a1b0da 100644 --- a/yarn-project/end-to-end/src/e2e_token_contract/minting.test.ts +++ b/yarn-project/end-to-end/src/e2e_token_contract/minting.test.ts @@ -39,20 +39,6 @@ describe('e2e_token_contract minting', () => { ).rejects.toThrow('Assertion failed: caller is not minter'); }); - it('mint >u128 tokens to overflow', async () => { - const maxAmountWithoutOverflow = 2n ** 128n - 1n - tokenSim.balanceOfPublic(accounts[0].address); - - // First we send a valid tx because if we minted with "amount > U128::max()" we would get an error in U128 - // in encoder.ts - await asset.methods.mint_to_public(accounts[0].address, maxAmountWithoutOverflow).send().wait(); - tokenSim.mintPublic(accounts[0].address, maxAmountWithoutOverflow); - - // Then we try to mint 1 to cause the U128 overflow inside the contract - await expect(asset.methods.mint_to_public(accounts[0].address, 1n).simulate()).rejects.toThrow( - U128_OVERFLOW_ERROR, - ); - }); - it('mint u128', async () => { const amount = 2n ** 128n - tokenSim.balanceOfPublic(accounts[0].address); await expect(asset.methods.mint_to_public(accounts[0].address, amount).simulate()).rejects.toThrow( @@ -68,4 +54,51 @@ describe('e2e_token_contract minting', () => { }); }); }); + + describe('Private', () => { + it('as minter', async () => { + const amount = 10000n; + await asset.methods.mint_to_private(accounts[0].address, accounts[0].address, amount).send().wait(); + + tokenSim.mintPrivate(accounts[0].address, amount); + expect(await asset.methods.balance_of_private(accounts[0].address).simulate()).toEqual( + tokenSim.balanceOfPrivate(accounts[0].address), + ); + expect(await asset.methods.total_supply().simulate()).toEqual(tokenSim.totalSupply); + }); + + describe('failure cases', () => { + it('as non-minter', async () => { + const amount = 10000n; + await expect( + asset + .withWallet(wallets[1]) + .methods.mint_to_private(accounts[1].address, accounts[0].address, amount) + .simulate(), + ).rejects.toThrow('Assertion failed: caller is not minter'); + }); + + it('mint >u128 tokens to overflow', async () => { + const overflowAmount = 2n ** 128n; + + await expect( + asset.methods.mint_to_private(accounts[0].address, accounts[0].address, overflowAmount).simulate(), + ).rejects.toThrow('Cannot satisfy constraint'); + }); + + it('mint u128', async () => { + const amount = 2n ** 128n - tokenSim.balanceOfPrivate(accounts[0].address); + await expect( + asset.methods.mint_to_private(accounts[0].address, accounts[0].address, amount).simulate(), + ).rejects.toThrow(U128_OVERFLOW_ERROR); + }); + + it('mint u128', async () => { + const amount = 2n ** 128n - tokenSim.balanceOfPrivate(accounts[0].address); + await expect( + asset.methods.mint_to_private(accounts[0].address, accounts[1].address, amount).simulate(), + ).rejects.toThrow(U128_OVERFLOW_ERROR); + }); + }); + }); }); diff --git a/yarn-project/end-to-end/src/fixtures/fixtures.ts b/yarn-project/end-to-end/src/fixtures/fixtures.ts index 48980db0e21..e4241b665dc 100644 --- a/yarn-project/end-to-end/src/fixtures/fixtures.ts +++ b/yarn-project/end-to-end/src/fixtures/fixtures.ts @@ -14,8 +14,8 @@ export const privateKey = Buffer.from('ac0974bec39a17e36ba4a6b4d238ff944bacb478c export const privateKey2 = Buffer.from('59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d', 'hex'); /// Common errors -export const U128_UNDERFLOW_ERROR = "Assertion failed: attempt to subtract with underflow 'hi == high'"; -export const U128_OVERFLOW_ERROR = "Assertion failed: attempt to add with overflow 'hi == high'"; +export const U128_UNDERFLOW_ERROR = "Assertion failed: attempt to subtract with overflow 'self - other'"; +export const U128_OVERFLOW_ERROR = "Assertion failed: attempt to add with overflow 'self + other'"; export const BITSIZE_TOO_BIG_ERROR = "Assertion failed: call to assert_max_bit_size 'self.__assert_max_bit_size'"; // TODO(https://github.com/AztecProtocol/aztec-packages/issues/5818): Make these a fixed error after transition. export const DUPLICATE_NULLIFIER_ERROR = /dropped|duplicate nullifier|reverted|Nullifier collision/; diff --git a/yarn-project/noir-bb-bench/src/index.ts b/yarn-project/noir-bb-bench/src/index.ts index b14877a23d2..83b837bd8b9 100644 --- a/yarn-project/noir-bb-bench/src/index.ts +++ b/yarn-project/noir-bb-bench/src/index.ts @@ -1,6 +1,6 @@ /* eslint-disable camelcase */ import { type ForeignCallOutput, Noir } from '@noir-lang/noir_js'; -import { type InputValue } from '@noir-lang/noirc_abi'; +import type { InputValue } from '@noir-lang/noirc_abi'; import createDebug from 'debug'; // these files are generated diff --git a/yarn-project/sequencer-client/src/sequencer/allowed.ts b/yarn-project/sequencer-client/src/sequencer/allowed.ts index 450c5ae9c83..7afa2fb5a59 100644 --- a/yarn-project/sequencer-client/src/sequencer/allowed.ts +++ b/yarn-project/sequencer-client/src/sequencer/allowed.ts @@ -17,13 +17,13 @@ export async function getDefaultAllowedSetupFunctions(): Promise { it('allows fee paying txs if fee payer claims enough balance during setup', async () => { mockBalance(feeLimit - 1n); - const selector = await FunctionSelector.fromSignature('_increase_public_balance((Field),(Field,Field))'); + const selector = await FunctionSelector.fromSignature('_increase_public_balance((Field),u128)'); await patchNonRevertibleFn(tx, 0, { address: ProtocolContractAddress.FeeJuice, selector: FunctionSelector.fromField(new Fr(PUBLIC_DISPATCH_SELECTOR)), - args: [selector.toField(), payer.toField(), ...new U128(1n).toFields()], + args: [selector.toField(), payer.toField(), new Fr(1n)], msgSender: ProtocolContractAddress.FeeJuice, }); await expectValid(tx); @@ -92,8 +92,8 @@ describe('GasTxValidator', () => { it('rejects txs if fee payer claims balance outside setup', async () => { mockBalance(feeLimit - 1n); await patchRevertibleFn(tx, 0, { - selector: await FunctionSelector.fromSignature('_increase_public_balance((Field),(Field,Field))'), - args: [payer.toField(), ...new U128(1n).toFields()], + selector: await FunctionSelector.fromSignature('_increase_public_balance((Field),u128)'), + args: [payer.toField(), new Fr(1n)], }); await expectInvalid(tx, 'Insufficient fee payer balance'); }); diff --git a/yarn-project/sequencer-client/src/tx_validator/gas_validator.ts b/yarn-project/sequencer-client/src/tx_validator/gas_validator.ts index 626c8ed21bb..a5364f2cdaa 100644 --- a/yarn-project/sequencer-client/src/tx_validator/gas_validator.ts +++ b/yarn-project/sequencer-client/src/tx_validator/gas_validator.ts @@ -2,7 +2,7 @@ import { Fr } from '@aztec/foundation/fields'; import { createLogger } from '@aztec/foundation/log'; import { computeFeePayerBalanceStorageSlot } from '@aztec/protocol-contracts/fee-juice'; import { getExecutionRequestsByPhase } from '@aztec/simulator/server'; -import { FunctionSelector, U128 } from '@aztec/stdlib/abi'; +import { FunctionSelector } from '@aztec/stdlib/abi'; import type { AztecAddress } from '@aztec/stdlib/aztec-address'; import type { GasFees } from '@aztec/stdlib/gas'; import { type Tx, TxExecutionPhase, type TxValidationResult, type TxValidator } from '@aztec/stdlib/tx'; @@ -33,7 +33,7 @@ export class GasTxValidator implements TxValidator { /** * Check whether the tx's max fees are valid for the current block, and skip if not. - * We skip instead of invalidating since the tx may become elligible later. + * We skip instead of invalidating since the tx may become eligible later. * Note that circuits check max fees even if fee payer is unset, so we * keep this validation even if the tx does not pay fees. */ @@ -67,7 +67,7 @@ export class GasTxValidator implements TxValidator { // If there is a claim in this tx that increases the fee payer balance in Fee Juice, add it to balance const setupFns = getExecutionRequestsByPhase(tx, TxExecutionPhase.SETUP); const increasePublicBalanceSelector = await FunctionSelector.fromSignature( - '_increase_public_balance((Field),(Field,Field))', + '_increase_public_balance((Field),u128)', ); const claimFunctionCall = setupFns.find( fn => @@ -80,10 +80,11 @@ export class GasTxValidator implements TxValidator { !fn.callContext.isStaticCall, ); - // `amount` in the claim function call arguments occupies 2 fields as it is represented as U128. - const balance = claimFunctionCall - ? initialBalance.add(new Fr(U128.fromFields(claimFunctionCall.args.slice(2, 4)).toInteger())) - : initialBalance; + // The claim amount is at index 2 in the args array because: + // - Index 0: Target function selector (due to dispatch routing) + // - Index 1: Amount recipient + // - Index 2: Amount being claimed + const balance = claimFunctionCall ? initialBalance.add(claimFunctionCall.args[2]) : initialBalance; if (balance.lt(feeLimit)) { this.#log.warn(`Rejecting transaction due to not enough fee payer balance`, { feePayer, diff --git a/yarn-project/simulator/src/avm/apps_tests/token.test.ts b/yarn-project/simulator/src/avm/apps_tests/token.test.ts index c04fabf20d5..51e5ec5e0ab 100644 --- a/yarn-project/simulator/src/avm/apps_tests/token.test.ts +++ b/yarn-project/simulator/src/avm/apps_tests/token.test.ts @@ -72,6 +72,6 @@ describe('AVM simulator apps tests: TokenContract', () => { /*isStaticCall=*/ true, ); expect(balResult.reverted).toBe(false); - expect(balResult.output).toEqual([new Fr(expectedBalance), Fr.zero()]); + expect(balResult.output).toEqual([new Fr(expectedBalance)]); }; }); diff --git a/yarn-project/simulator/src/avm/avm_simulator.test.ts b/yarn-project/simulator/src/avm/avm_simulator.test.ts index d6984e5fe50..57d99f4e0fc 100644 --- a/yarn-project/simulator/src/avm/avm_simulator.test.ts +++ b/yarn-project/simulator/src/avm/avm_simulator.test.ts @@ -366,10 +366,8 @@ describe('AVM simulator: transpiled Noir contracts', () => { const calldata: Fr[] = [ // First U128 new Fr(1), - new Fr(2), // Second U128 - new Fr(3), - new Fr(4), + new Fr(2), ]; const context = initContext({ env: initExecutionEnvironment({ calldata }) }); @@ -377,7 +375,7 @@ describe('AVM simulator: transpiled Noir contracts', () => { const results = await new AvmSimulator(context).executeBytecode(bytecode); expect(results.reverted).toBe(false); - expect(results.output).toEqual([new Fr(4), new Fr(6)]); + expect(results.output).toEqual([new Fr(3)]); }); it('Expect failure on U128::add() overflow', async () => { @@ -389,16 +387,6 @@ describe('AVM simulator: transpiled Noir contracts', () => { resolveAvmTestContractAssertionMessage('u128_addition_overflow', results.revertReason!, results.output), ).toMatch('attempt to add with overflow'); }); - - it('Expect failure on U128::from_integer() overflow', async () => { - const bytecode = getAvmTestContractBytecode('u128_from_integer_overflow'); - const results = await new AvmSimulator(initContext()).executeBytecode(bytecode); - expect(results.reverted).toBe(true); - expect(results.revertReason).toBeDefined(); - expect( - resolveAvmTestContractAssertionMessage('u128_from_integer_overflow', results.revertReason!, results.output), - ).toMatch('call to assert_max_bit_size'); - }); }); it('Logging', async () => { diff --git a/yarn-project/simulator/src/public/apps_tests/token.test.ts b/yarn-project/simulator/src/public/apps_tests/token.test.ts index 909da0ec6e0..bb0bc15a1ab 100644 --- a/yarn-project/simulator/src/public/apps_tests/token.test.ts +++ b/yarn-project/simulator/src/public/apps_tests/token.test.ts @@ -105,7 +105,7 @@ describe('Public TX simulator apps tests: TokenContract', () => { ], ); expect(balResult.revertCode.isOK()).toBe(true); - expectAppCall0Output(balResult, [new Fr(expectedBalance), Fr.zero()]); + expectAppCall0Output(balResult, [new Fr(expectedBalance)]); }; }); diff --git a/yarn-project/stdlib/src/abi/decoder.ts b/yarn-project/stdlib/src/abi/decoder.ts index f50bcd8afe3..c7d75e93e2d 100644 --- a/yarn-project/stdlib/src/abi/decoder.ts +++ b/yarn-project/stdlib/src/abi/decoder.ts @@ -2,8 +2,7 @@ import { Fr } from '@aztec/foundation/fields'; import { AztecAddress } from '../aztec-address/index.js'; import type { ABIParameter, ABIVariable, AbiType } from './abi.js'; -import { U128 } from './u128.js'; -import { isAztecAddressStruct, isU128Struct, parseSignedInt } from './utils.js'; +import { isAztecAddressStruct, parseSignedInt } from './utils.js'; /** * The type of our decoded ABI. @@ -45,14 +44,6 @@ class AbiDecoder { return array; } case 'struct': { - if (isU128Struct(abiType)) { - const fields = [ - new Fr(this.decodeNext({ kind: 'field' }) as bigint), - new Fr(this.decodeNext({ kind: 'field' }) as bigint), - ]; - return U128.fromFields(fields).toInteger(); - } - const struct: { [key: string]: AbiDecoded } = {}; if (isAztecAddressStruct(abiType)) { return new AztecAddress(this.getNextField().toBuffer()); diff --git a/yarn-project/stdlib/src/abi/encoder.ts b/yarn-project/stdlib/src/abi/encoder.ts index 885f0222a53..c4bae6f0f23 100644 --- a/yarn-project/stdlib/src/abi/encoder.ts +++ b/yarn-project/stdlib/src/abi/encoder.ts @@ -1,8 +1,7 @@ import { Fr } from '@aztec/foundation/fields'; import type { AbiType, FunctionAbi } from './abi.js'; -import { U128 } from './u128.js'; -import { isAddressStruct, isFunctionSelectorStruct, isU128Struct, isWrappedFieldStruct } from './utils.js'; +import { isAddressStruct, isFunctionSelectorStruct, isWrappedFieldStruct } from './utils.js'; /** * Encodes arguments for a function call. @@ -107,15 +106,6 @@ class ArgumentEncoder { this.encodeArgument({ kind: 'integer', sign: 'unsigned', width: 32 }, arg.value ?? arg, `${name}.inner`); break; } - if (isU128Struct(abiType)) { - // U128 struct has low and high limbs - so we first convert the value to the 2 limbs and then we encode them - const value = new U128(arg); - const limbs = value.toFields(); - const limbNames = U128.getLimbNames(); - this.encodeArgument({ kind: 'field' }, limbs[0], `${name}.${limbNames[0]}`); - this.encodeArgument({ kind: 'field' }, limbs[1], `${name}.${limbNames[1]}`); - break; - } if (isWrappedFieldStruct(abiType)) { this.encodeArgument({ kind: 'field' }, arg.inner ?? arg, `${name}.inner`); break; diff --git a/yarn-project/stdlib/src/abi/index.ts b/yarn-project/stdlib/src/abi/index.ts index da5eb01d0d6..4287723582f 100644 --- a/yarn-project/stdlib/src/abi/index.ts +++ b/yarn-project/stdlib/src/abi/index.ts @@ -6,6 +6,5 @@ export * from './event_selector.js'; export * from './function_selector.js'; export * from './note_selector.js'; export * from './utils.js'; -export * from './u128.js'; export * from './contract_artifact.js'; export * from './function_call.js'; diff --git a/yarn-project/stdlib/src/abi/u128.test.ts b/yarn-project/stdlib/src/abi/u128.test.ts deleted file mode 100644 index df41b3cbe13..00000000000 --- a/yarn-project/stdlib/src/abi/u128.test.ts +++ /dev/null @@ -1,102 +0,0 @@ -import { U128 } from './u128.js'; - -describe('U128', () => { - describe('constructor', () => { - it('accepts valid number inputs', () => { - const small = new U128(42); - expect(small.toInteger()).toBe(42n); - - const large = new U128(Number.MAX_SAFE_INTEGER); - expect(large.toInteger()).toBe(BigInt(Number.MAX_SAFE_INTEGER)); - }); - - it('accepts valid bigint inputs', () => { - const small = new U128(42n); - expect(small.toInteger()).toBe(42n); - - const max = new U128(2n ** 128n - 1n); - expect(max.toInteger()).toBe(2n ** 128n - 1n); - }); - - it('throws for negative values', () => { - expect(() => new U128(-1)).toThrow('Value -1 is not within 128 bits'); - expect(() => new U128(-1n)).toThrow('Value -1 is not within 128 bits'); - }); - - it('throws for values >= 2^128', () => { - const tooLarge = 2n ** 128n; - expect(() => new U128(tooLarge)).toThrow(`Value ${tooLarge} is not within 128 bits`); - }); - }); - - describe('fromU64sLE', () => { - it('correctly combines valid limbs', () => { - const lo = 0xdeadbeefn; - const hi = 0xcafebaben; - const combined = U128.fromU64sLE(lo, hi); - - expect(combined.lo).toBe(lo); - expect(combined.hi).toBe(hi); - expect(combined.toInteger()).toBe((hi << 64n) | lo); - }); - - it('accepts maximum valid limb values', () => { - const maxLimb = 2n ** 64n - 1n; - const value = U128.fromU64sLE(maxLimb, maxLimb); - - expect(value.lo).toBe(maxLimb); - expect(value.hi).toBe(maxLimb); - expect(value.toInteger()).toBe(2n ** 128n - 1n); - }); - - it('throws for invalid lower limb', () => { - const invalid = 2n ** 64n; - expect(() => U128.fromU64sLE(invalid, 0n)).toThrow(`Lower limb ${invalid} is not within valid range`); - - expect(() => U128.fromU64sLE(-1n, 0n)).toThrow('Lower limb -1 is not within valid range'); - }); - - it('throws for invalid higher limb', () => { - const invalid = 2n ** 64n; - expect(() => U128.fromU64sLE(0n, invalid)).toThrow(`Higher limb ${invalid} is not within valid range`); - - expect(() => U128.fromU64sLE(0n, -1n)).toThrow('Higher limb -1 is not within valid range'); - }); - }); - - describe('getters', () => { - it('correctly extracts lo and hi components', () => { - const testCases = [ - { lo: 0xdeadbeefn, hi: 0xcafebaben }, - { lo: 0n, hi: 1n }, - { lo: 1n, hi: 0n }, - { lo: 2n ** 64n - 1n, hi: 2n ** 64n - 1n }, - ]; - - for (const { lo, hi } of testCases) { - const value = U128.fromU64sLE(lo, hi); - expect(value.lo).toBe(lo); - expect(value.hi).toBe(hi); - } - }); - }); - - it('round-trips through field conversion', () => { - const testCases = [ - U128.fromU64sLE(0xdeadbeefn, 0xcafebaben), - new U128(0), - new U128(2n ** 128n - 1n), - U128.fromU64sLE(2n ** 64n - 1n, 0n), - U128.fromU64sLE(0n, 2n ** 64n - 1n), - ]; - - for (const original of testCases) { - const fields = original.toFields(); - const reconstructed = U128.fromFields(fields); - - expect(reconstructed.lo).toBe(original.lo); - expect(reconstructed.hi).toBe(original.hi); - expect(reconstructed.toInteger()).toBe(original.toInteger()); - } - }); -}); diff --git a/yarn-project/stdlib/src/abi/u128.ts b/yarn-project/stdlib/src/abi/u128.ts deleted file mode 100644 index f8a63b9e1ad..00000000000 --- a/yarn-project/stdlib/src/abi/u128.ts +++ /dev/null @@ -1,71 +0,0 @@ -import { Fr } from '@aztec/foundation/fields'; - -// A typescript version of noir::std::U128 -export class U128 { - private readonly value: bigint; - - constructor(value: bigint | number) { - if (typeof value !== 'bigint') { - value = BigInt(value); - } - - // Check value is within 128 bits - if (value < 0n || value >= 2n ** 128n) { - throw new Error(`Value ${value} is not within 128 bits and hence cannot be converted to U128.`); - } - - this.value = value; - } - - static fromU64sLE(lo: bigint, hi: bigint): U128 { - // Validate limbs are within valid ranges - if (lo < 0n || lo >= 2n ** 64n) { - throw new Error(`Lower limb ${lo} is not within valid range (0 to 2^64-1)`); - } - if (hi < 0n || hi >= 2n ** 64n) { - throw new Error(`Higher limb ${hi} is not within valid range (0 to 2^64-1)`); - } - - // Combine limbs into full value and create new instance - const value = (hi << 64n) | lo; - return new U128(value); - } - - get lo(): bigint { - return this.value & 0xffffffffffffffffn; - } - - get hi(): bigint { - return this.value >> 64n; - } - - toInteger(): bigint { - return this.value; - } - - // We use little-endian ordering to match the order in which U128 defines its limbs. - // This is necessary because of how Noir handles serialization: - // - When calling a contract function from TypeScript, the serialization below gets used and then Noir - // deserializes using its intrinsic serialization logic (based on the limb order in the struct). - // - When calling a contract function from another function, the `serialize` method is invoked - // on the type first. - // For this reason if we didn't use the ordering of U128 limbs here and in the implementation of Serialize - // trait for U128 we would get an arguments hash mismatch. - toFields(): Fr[] { - return [new Fr(this.lo), new Fr(this.hi)]; - } - - // Has to follow ordering of `toFields()` - static fromFields(fields: Fr[]): U128 { - if (fields.length !== 2) { - throw new Error(`Expected 2 fields for U128, got ${fields.length}`); - } - - return U128.fromU64sLE(fields[0].toBigInt(), fields[1].toBigInt()); - } - - // Has to follow ordering of `toFields()` - static getLimbNames(): string[] { - return ['lo', 'hi']; - } -} diff --git a/yarn-project/stdlib/src/abi/utils.ts b/yarn-project/stdlib/src/abi/utils.ts index efb8576c9d2..71fe43d4b41 100644 --- a/yarn-project/stdlib/src/abi/utils.ts +++ b/yarn-project/stdlib/src/abi/utils.ts @@ -36,14 +36,6 @@ export function isFunctionSelectorStruct(abiType: AbiType) { return abiType.kind === 'struct' && abiType.path.endsWith('types::abis::function_selector::FunctionSelector'); } -/** - * Returns whether the ABI type is the U128 defined in noir::std. - * @param abiType - Type to check. - */ -export function isU128Struct(abiType: AbiType) { - return abiType.kind === 'struct' && abiType.path.endsWith('U128'); -} - /** * Returns whether the ABI type is a struct with a single `inner` field. * @param abiType - Type to check.