-
Notifications
You must be signed in to change notification settings - Fork 607
feat: make token transfer be recursive #7730
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 4 commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -16,7 +16,7 @@ contract Token { | |
| use dep::compressed_string::FieldCompressedString; | ||
|
|
||
| use dep::aztec::{ | ||
| hash::compute_secret_hash, | ||
| context::{PrivateContext, PrivateCallInterface}, hash::compute_secret_hash, | ||
| prelude::{NoteGetterOptions, Map, PublicMutable, SharedImmutable, PrivateSet, AztecAddress}, | ||
| encrypted_logs::{ | ||
| encrypted_note_emission::{ | ||
|
|
@@ -34,6 +34,15 @@ contract Token { | |
| use crate::types::{transparent_note::TransparentNote, token_note::{TokenNote, TOKEN_NOTE_LEN}, balances_map::BalancesMap}; | ||
| // docs:end::imports | ||
|
|
||
| // In the first transfer iteration we are computing a lot of additional information (validating inputs, retrieving | ||
| // keys, etc.), so the gate count is already relatively high. We therefore only read a few notes to keep the happy | ||
| // case with few constraints. | ||
| global INITIAL_TRANSFER_CALL_MAX_NOTES = 2; | ||
| // All the recursive call does is nullify notes, meaning the gate count is low, but it is all constant overhead. We | ||
| // therefore read more notes than in the base case to increase the efficiency of the overhead, since this results in | ||
| // an overall small circuit regardless. | ||
| global RECURISVE_TRANSFER_CALL_MAX_NOTES = 8; | ||
|
|
||
| #[aztec(event)] | ||
| struct Transfer { | ||
| from: AztecAddress, | ||
|
|
@@ -335,13 +344,74 @@ contract Token { | |
| let to_ivpk = header.get_ivpk_m(&mut context, to); | ||
|
|
||
| let amount = U128::from_integer(amount); | ||
| storage.balances.sub(from, amount).emit(encode_and_encrypt_note_with_keys_unconstrained(&mut context, from_ovpk, from_ivpk, from)); | ||
|
|
||
| // We reduce `from`'s balance by amount by recursively removing notes over potentially multiple calls. This | ||
| // method keeps the gate count for each individual call low - reading too many notes at once could result in | ||
| // circuits in which proving is not feasible. | ||
| // Since the sum of the amounts in the notes we nullified was potentially larger than amount, we create a new | ||
| // note for `from` with the change amount, e.g. if `amount` is 10 and two notes are nullified with amounts 8 and | ||
| // 5, then the change will be 3 (since 8 + 5 - 10 = 3). | ||
| let change = subtract_balance( | ||
| &mut context, | ||
| storage, | ||
| from, | ||
| amount, | ||
| INITIAL_TRANSFER_CALL_MAX_NOTES | ||
| ); | ||
|
|
||
| storage.balances.add(from, change).emit(encode_and_encrypt_note_with_keys_unconstrained(&mut context, from_ovpk, from_ivpk, from)); | ||
|
|
||
| storage.balances.add(to, amount).emit(encode_and_encrypt_note_with_keys_unconstrained(&mut context, from_ovpk, to_ivpk, to)); | ||
|
|
||
| // We don't constrain encryption of the note log in `transfer` (unlike in `transfer_from`) because the transfer | ||
| // function is only designed to be used in situations where the event is not strictly necessary (e.g. payment to | ||
| // another person where the payment is considered to be successful when the other party successfully decrypts a | ||
| // note). | ||
| Transfer { from, to, amount: amount.to_field() }.emit(encode_and_encrypt_event_with_keys_unconstrained(&mut context, from_ovpk, to_ivpk, to)); | ||
| } | ||
| // docs:end:transfer | ||
|
|
||
| #[contract_library_method] | ||
| fn subtract_balance( | ||
| context: &mut PrivateContext, | ||
| storage: Storage<&mut PrivateContext>, | ||
| account: AztecAddress, | ||
| amount: U128, | ||
| max_notes: u32 | ||
| ) -> U128 { | ||
| let subtracted = storage.balances.try_sub(account, 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::from_integer(0), "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 | ||
| } else { | ||
| // try_sub failed to nullify enough notes to reach the target amount, so we compute the amount remaining | ||
| // and try again. | ||
| let remaining = amount - subtracted; | ||
| Token::at(context.this_address())._recurse_subtract_balance(account, remaining.to_field()).call(context) | ||
| } | ||
| } | ||
|
|
||
| // TODO(#7728): even though the amount should be a U128, we can't have that type in a contract interface due to | ||
| // serialization issues. | ||
| #[aztec(internal)] | ||
| #[aztec(private)] | ||
| fn _recurse_subtract_balance(account: AztecAddress, amount: Field) -> U128 { | ||
| subtract_balance( | ||
| &mut context, | ||
| storage, | ||
| account, | ||
| U128::from_integer(amount), | ||
| RECURISVE_TRANSFER_CALL_MAX_NOTES | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. It's quite cool that in the recursive case we can afford to have a larger amount of notes which will probably result in the notes being consolidated for future cases as well --> so user will be less likely to fall into the recursive case soon. In the future it might make sense to try make note getter return as many notes as possible such that it sums at least to the target amount.
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. There's some discussion about this in #7731 - consuming more notes results in larger DA costs, but consuming only the largest notes can lead to excessive change notes being created. |
||
| ) | ||
| } | ||
|
|
||
| /** | ||
| * Cancel a private authentication witness. | ||
| * @param inner_hash The inner hash of the authwit to cancel. | ||
|
|
@@ -427,4 +497,5 @@ contract Token { | |
| } | ||
| // docs:end:balance_of_private | ||
| } | ||
| // docs:end:token_all | ||
|
|
||
| // docs:end:token_all | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,90 @@ | ||
| import { BatchCall, EventType, Fr } from '@aztec/aztec.js'; | ||
| import { TokenContract } from '@aztec/noir-contracts.js'; | ||
|
|
||
| import { TokenContractTest } from './token_contract_test.js'; | ||
|
|
||
| describe('e2e_token_contract private transfer recursion', () => { | ||
| const t = new TokenContractTest('odd_transfer_private'); | ||
| let { asset, accounts, wallets } = t; | ||
|
|
||
| beforeAll(async () => { | ||
| await t.applyBaseSnapshots(); | ||
| await t.setup(); | ||
| ({ asset, accounts, wallets } = t); | ||
| }); | ||
|
|
||
| afterAll(async () => { | ||
| await t.teardown(); | ||
| }); | ||
|
|
||
| async function mintNotes(noteAmounts: bigint[]): Promise<bigint> { | ||
| // Mint all notes, 4 at a time | ||
| for (let mintedNotes = 0; mintedNotes < noteAmounts.length; mintedNotes += 4) { | ||
| const toMint = noteAmounts.slice(mintedNotes, mintedNotes + 4); // We mint 4 notes at a time | ||
| const actions = toMint.map(amt => asset.methods.privately_mint_private_note(amt).request()); | ||
| await new BatchCall(wallets[0], actions).send().wait(); | ||
| } | ||
|
|
||
| return noteAmounts.reduce((prev, curr) => prev + curr, 0n); | ||
| } | ||
|
|
||
| it('transfer full balance', async () => { | ||
| // We insert 16 notes, which is large enough to guarantee that the token will need to do two recursive calls to | ||
| // itself to consume them all (since it retrieves 2 notes on the first pass and 8 in each subsequent pass). | ||
| const totalNotes = 16; | ||
| const totalBalance = await mintNotes(Array(totalNotes).fill(10n)); | ||
| const tx = await asset.methods.transfer(accounts[1].address, totalBalance).send().wait({ debug: true }); | ||
|
|
||
| // We should have nullified all notes, plus an extra nullifier for the transaction | ||
| expect(tx.debugInfo?.nullifiers.length).toBe(totalNotes + 1); | ||
| // We should have created a single new note, for the recipient | ||
| expect(tx.debugInfo?.noteHashes.length).toBe(1); | ||
|
|
||
| const events = await wallets[1].getEvents(EventType.Encrypted, TokenContract.events.Transfer, tx.blockNumber!, 1); | ||
|
|
||
| expect(events[0]).toEqual({ | ||
| from: accounts[0].address, | ||
| to: accounts[1].address, | ||
| amount: new Fr(totalBalance), | ||
| }); | ||
| }); | ||
|
|
||
| it('transfer less than full balance and get change', async () => { | ||
| const noteAmounts = [10n, 10n, 10n, 10n]; | ||
| const expectedChange = 3n; // This will result in one of the notes being partially used | ||
|
|
||
| const totalBalance = await mintNotes(noteAmounts); | ||
| const toSend = totalBalance - expectedChange; | ||
|
|
||
| const tx = await asset.methods.transfer(accounts[1].address, toSend).send().wait({ debug: true }); | ||
|
|
||
| // We should have nullified all notes, plus an extra nullifier for the transaction | ||
| expect(tx.debugInfo?.nullifiers.length).toBe(noteAmounts.length + 1); | ||
| // We should have created two new notes, one for the recipient and one for the sender (with the change) | ||
| expect(tx.debugInfo?.noteHashes.length).toBe(2); | ||
|
|
||
| const senderBalance = await asset.methods.balance_of_private(accounts[0].address).simulate(); | ||
| expect(senderBalance).toEqual(expectedChange); | ||
|
|
||
| const events = await wallets[1].getEvents(EventType.Encrypted, TokenContract.events.Transfer, tx.blockNumber!, 1); | ||
|
|
||
| expect(events[0]).toEqual({ | ||
| from: accounts[0].address, | ||
| to: accounts[1].address, | ||
| amount: new Fr(toSend), | ||
| }); | ||
| }); | ||
|
|
||
| describe('failure cases', () => { | ||
| it('transfer more than balance', async () => { | ||
| const balance0 = await asset.methods.balance_of_private(accounts[0].address).simulate(); | ||
|
|
||
| const amount = balance0 + 1n; | ||
| expect(amount).toBeGreaterThan(0n); | ||
|
|
||
| await expect(asset.methods.transfer(accounts[1].address, amount).simulate()).rejects.toThrow( | ||
| 'Assertion failed: Balance too low', | ||
| ); | ||
| }); | ||
| }); | ||
| }); |
Uh oh!
There was an error while loading. Please reload this page.