@aztec/txe 5.0.0-nightly.20260706 → 5.0.0-nightly.20260708
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dest/AuthRegistry-D774QM2G.js +3 -0
- package/dest/AuthRegistry-D774QM2G.js.map +7 -0
- package/dest/HandshakeRegistry-4AIT55KH.js +3 -0
- package/dest/HandshakeRegistry-4AIT55KH.js.map +7 -0
- package/dest/{MultiCallEntrypoint-L4TYDBCW.js → MultiCallEntrypoint-WICVQACI.js} +1 -1
- package/dest/{MultiCallEntrypoint-L4TYDBCW.js.map → MultiCallEntrypoint-WICVQACI.js.map} +2 -2
- package/dest/SchnorrAccount-Y2WZTBJF.js +3 -0
- package/dest/SchnorrAccount-Y2WZTBJF.js.map +7 -0
- package/dest/{SchnorrInitializerlessAccount-U2A3DVSR.js → SchnorrInitializerlessAccount-3AKXYJQI.js} +1 -1
- package/dest/{SchnorrInitializerlessAccount-U2A3DVSR.js.map → SchnorrInitializerlessAccount-3AKXYJQI.js.map} +1 -1
- package/dest/bin/index.js +1 -1
- package/dest/{chunk-6JTAVPZJ.js → chunk-2LYGEVHI.js} +2 -2
- package/dest/{chunk-6JTAVPZJ.js.map → chunk-2LYGEVHI.js.map} +3 -3
- package/dest/{chunk-SJX3LB7U.js → chunk-HLH2NBQI.js} +9 -9
- package/dest/{chunk-SJX3LB7U.js.map → chunk-HLH2NBQI.js.map} +4 -4
- package/dest/index.d.ts +1 -1
- package/dest/index.d.ts.map +1 -1
- package/dest/index.js +5 -3
- package/dest/metafile.json +226 -183
- package/dest/oracle/interfaces.d.ts +5 -5
- package/dest/oracle/interfaces.d.ts.map +1 -1
- package/dest/oracle/test-resolver/default_fixtures.d.ts +3 -3
- package/dest/oracle/test-resolver/default_fixtures.d.ts.map +1 -1
- package/dest/oracle/test-resolver/default_fixtures.js +54 -11
- package/dest/oracle/test-resolver/resolver.js +38 -1
- package/dest/oracle/txe_oracle_public_context.d.ts +5 -5
- package/dest/oracle/txe_oracle_public_context.d.ts.map +1 -1
- package/dest/oracle/txe_oracle_public_context.js +13 -8
- package/dest/oracle/txe_oracle_registry.d.ts +10 -10
- package/dest/oracle/txe_oracle_registry.d.ts.map +1 -1
- package/dest/oracle/txe_oracle_registry.js +21 -12
- package/dest/oracle/txe_oracle_version.d.ts +2 -2
- package/dest/oracle/txe_oracle_version.js +2 -2
- package/dest/rpc_translator.d.ts +2 -2
- package/dest/rpc_translator.d.ts.map +1 -1
- package/dest/rpc_translator.js +3 -3
- package/dest/server.bundle.js +1 -1
- package/dest/state_machine/synchronizer.d.ts +3 -1
- package/dest/state_machine/synchronizer.d.ts.map +1 -1
- package/dest/state_machine/synchronizer.js +3 -0
- package/dest/worker.bundle.js +1 -1
- package/package.json +17 -17
- package/src/index.ts +5 -3
- package/src/oracle/interfaces.ts +4 -4
- package/src/oracle/test-resolver/default_fixtures.ts +73 -17
- package/src/oracle/test-resolver/resolver.ts +48 -1
- package/src/oracle/txe_oracle_public_context.ts +8 -7
- package/src/oracle/txe_oracle_registry.ts +14 -4
- package/src/oracle/txe_oracle_version.ts +2 -2
- package/src/rpc_translator.ts +3 -3
- package/src/state_machine/synchronizer.ts +5 -0
- package/dest/AuthRegistry-HBL4YLHF.js +0 -3
- package/dest/AuthRegistry-HBL4YLHF.js.map +0 -7
- package/dest/HandshakeRegistry-RLXDBPFJ.js +0 -3
- package/dest/HandshakeRegistry-RLXDBPFJ.js.map +0 -7
- package/dest/SchnorrAccount-TM347UJ7.js +0 -3
- package/dest/SchnorrAccount-TM347UJ7.js.map +0 -7
|
@@ -85,7 +85,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
85
85
|
else
|
|
86
86
|
return fromCharCode(${previous})
|
|
87
87
|
}
|
|
88
|
-
`,previous.push(v),i==1e6&&finishUtf8()}return stringBuildCode+=`return fromCharCode(${previous}) + readString(source)}`,stringBuildCode}__name(makeStringBuilder,"makeStringBuilder");var pendingSurrogate;function finishUtf8(byte1,src2){if((byte1&224)===192){let byte2=src2[position++]&63;return(byte1&31)<<6|byte2}else if((byte1&240)===224){let byte2=src2[position++]&63,byte3=src2[position++]&63;return(byte1&31)<<12|byte2<<6|byte3}else if((byte1&248)===240){if(pendingSurrogate)return byte1=pendingSurrogate,pendingSurrogate=null,position+=3,byte1;let byte2=src2[position++]&63,byte3=src2[position++]&63,byte4=src2[position++]&63,unit=(byte1&7)<<18|byte2<<12|byte3<<6|byte4;return unit>65535&&(pendingSurrogate=56320|unit&1023,unit=unit-65536>>>10&1023|55296,position-=4),unit}else return byte1}__name(finishUtf8,"finishUtf8");var readString=typeof process<"u"&&process.isBun?(function(reading){let{setPosition,getPosition,readString:readString3}=reading;return source=>{setPosition(position);let value=readString3(source);return position=getPosition(),value}})(new Function("fromCharCode","let position; let readString = "+makeStringBuilder()+";return {setPosition(p) { position = p },getPosition() { return position },readString }")(fromCharCode)):eval(makeStringBuilder());function readStringSafely(source,end){if(source[end]>0){let previous=source[end];try{return source[end]=0,readString(source)}finally{source[end]=previous}}else return readString(source)}__name(readStringSafely,"readStringSafely");function compareKeys(a,b){if(typeof a=="object"){if(!a)return b==null?0:-1;if(a.compare)return b==null?1:b.compare?a.compare(b):-1;let arrayComparison;if(b instanceof Array){let i=0;for(;(arrayComparison=compareKeys(a[i],b[i]))==0&&i<=a.length;)i++;return arrayComparison}return arrayComparison=compareKeys(a[0],b),arrayComparison==0&&a.length>1?1:arrayComparison}else return typeof a==typeof b?(typeof a=="symbol"&&(a=Symbol.keyFor(a),b=Symbol.keyFor(b)),a<b?-1:a===b?0:1):typeof b=="object"?b instanceof Array?-compareKeys(b,a):1:typeOrder[typeof a]<typeOrder[typeof b]?-1:1}__name(compareKeys,"compareKeys");var typeOrder={symbol:0,undefined:1,boolean:2,number:3,string:4},MINIMUM_KEY=null,MAXIMUM_KEY=new Uint8Array([255]);function keyCmp(a,b){return Buffer.compare(a[0],b[0])}__name(keyCmp,"keyCmp");function singleKeyCmp(a,b){return Buffer.compare(a[0],b)}__name(singleKeyCmp,"singleKeyCmp");function minKey(prefix){return toBufferKey([prefix])}__name(minKey,"minKey");function maxKey(prefix){return toBufferKey([prefix,MAXIMUM_KEY])}__name(maxKey,"maxKey");function serializeKey(prefix,key){return toBufferKey([prefix,key])}__name(serializeKey,"serializeKey");function deserializeKey(prefix,key){let buf=Buffer.from(key),parsed=fromBufferKey(buf);return!Array.isArray(parsed)||parsed[0]!==prefix?!1:parsed[1]}__name(deserializeKey,"deserializeKey");var _computedKey2;_computedKey2=Symbol.asyncIterator;var LMDBArray=class{static{__name(this,"LMDBArray")}store;length;encoder;prefix;constructor(store,name){this.store=store,this.encoder=new Encoder,this.length=store.openSingleton(name+":length"),this.prefix=`array:${name}`}pop(){return execInWriteTx(this.store,async tx=>{let length=await this.lengthAsync();if(length===0)return;let val=await tx.get(serializeKey(this.prefix,length-1));return await tx.remove(serializeKey(this.prefix,length-1)),await this.length.set(length-1),val?this.encoder.unpack(val):void 0})}push(...vals){return execInWriteTx(this.store,async tx=>{let length=await this.lengthAsync();for(let val of vals)await tx.set(serializeKey(this.prefix,length++),this.encoder.pack(val));return await this.length.set(length),length})}setAt(index,val){return execInWriteTx(this.store,async tx=>{let length=await this.lengthAsync();return index<0&&(index+=length),index<0||index>=length?!1:(await tx.set(serializeKey(this.prefix,index),this.encoder.pack(val)),!0)})}atAsync(index){return execInReadTx(this.store,async tx=>{let length=await this.lengthAsync();if(index<0&&(index+=length),index<0||index>=length)return;let val=await tx.get(serializeKey(this.prefix,index));return val?this.encoder.unpack(val):void 0})}async lengthAsync(){return await this.length.getAsync()??0}async*entriesAsync(){let length=await this.lengthAsync();if(length===0)return;let tx=this.store.getCurrentWriteTx(),shouldClose=!tx;tx??=this.store.getReadTx();try{for await(let[key,val]of tx.iterate(serializeKey(this.prefix,0),void 0,!1,length)){let deserializedKey=deserializeKey(this.prefix,key);if(deserializedKey===!1)break;yield[deserializedKey,this.encoder.unpack(val)]}}finally{shouldClose&&tx.close()}}async*valuesAsync(){for await(let[_,value]of this.entriesAsync())yield value}[_computedKey2](){return this.valuesAsync()}};import{Encoder as Encoder2}from"msgpackr";var LMDBMap=class{static{__name(this,"LMDBMap")}store;prefix;encoder;constructor(store,name){this.store=store,this.encoder=new Encoder2,this.prefix=`map:${name}`}set(key,val){return execInWriteTx(this.store,tx=>tx.set(serializeKey(this.prefix,key),this.encoder.pack(val)))}async setMany(entries){await execInWriteTx(this.store,async tx=>{for(let{key,value}of entries)await tx.set(serializeKey(this.prefix,key),this.encoder.pack(value))})}setIfNotExists(key,val){return execInWriteTx(this.store,async tx=>{let strKey=serializeKey(this.prefix,key);return!await tx.get(strKey)?(await tx.set(strKey,this.encoder.pack(val)),!0):!1})}delete(key){return execInWriteTx(this.store,tx=>tx.remove(serializeKey(this.prefix,key)))}getAsync(key){return execInReadTx(this.store,async tx=>{let val=await tx.get(serializeKey(this.prefix,key));return val?this.encoder.unpack(val):void 0})}hasAsync(key){return execInReadTx(this.store,async tx=>!!await tx.get(serializeKey(this.prefix,key)))}sizeAsync(){return execInReadTx(this.store,tx=>tx.countEntries(minKey(this.prefix),maxKey(this.prefix),!1))}async*entriesAsync(range){let reverse=range?.reverse??!1,startKey=range?.start!==void 0?serializeKey(this.prefix,range.start):minKey(this.prefix),endKey=range?.end!==void 0?serializeKey(this.prefix,range.end):reverse?maxKey(this.prefix):void 0,tx=this.store.getCurrentWriteTx(),shouldClose=!tx;tx??=this.store.getReadTx();try{for await(let[key,val]of tx.iterate(reverse?endKey:startKey,reverse?startKey:endKey,reverse,range?.limit)){let deserializedKey=deserializeKey(this.prefix,key);if(deserializedKey===!1)break;yield[deserializedKey,this.encoder.unpack(val)]}}finally{shouldClose&&tx.close()}}async*valuesAsync(range){for await(let[_,value]of this.entriesAsync(range))yield value}async*keysAsync(range){for await(let[key,_]of this.entriesAsync(range))yield key}};var Database=(function(Database2){return Database2.DATA="data",Database2.INDEX="index",Database2})({}),CURSOR_PAGE_SIZE=10,LMDBMessageType=(function(LMDBMessageType2){return LMDBMessageType2[LMDBMessageType2.OPEN_DATABASE=100]="OPEN_DATABASE",LMDBMessageType2[LMDBMessageType2.GET=101]="GET",LMDBMessageType2[LMDBMessageType2.HAS=102]="HAS",LMDBMessageType2[LMDBMessageType2.START_CURSOR=103]="START_CURSOR",LMDBMessageType2[LMDBMessageType2.ADVANCE_CURSOR=104]="ADVANCE_CURSOR",LMDBMessageType2[LMDBMessageType2.ADVANCE_CURSOR_COUNT=105]="ADVANCE_CURSOR_COUNT",LMDBMessageType2[LMDBMessageType2.CLOSE_CURSOR=106]="CLOSE_CURSOR",LMDBMessageType2[LMDBMessageType2.BATCH=107]="BATCH",LMDBMessageType2[LMDBMessageType2.STATS=108]="STATS",LMDBMessageType2[LMDBMessageType2.CLOSE=109]="CLOSE",LMDBMessageType2[LMDBMessageType2.COPY_STORE=110]="COPY_STORE",LMDBMessageType2})({});import{Encoder as Encoder3}from"msgpackr/pack";var LMDBMultiMap=class{static{__name(this,"LMDBMultiMap")}store;prefix;encoder;constructor(store,name){this.store=store,this.encoder=new Encoder3,this.prefix=`multimap:${name}`}set(key,val){return execInWriteTx(this.store,tx=>tx.setIndex(serializeKey(this.prefix,key),this.encoder.pack(val)))}async setMany(entries){await execInWriteTx(this.store,async tx=>{for(let{key,value}of entries)await tx.setIndex(serializeKey(this.prefix,key),this.encoder.pack(value))})}setIfNotExists(key,val){return execInWriteTx(this.store,async tx=>!await this.getAsync(key)?(await tx.setIndex(serializeKey(this.prefix,key),this.encoder.pack(val)),!0):!1)}delete(key){return execInWriteTx(this.store,tx=>tx.removeIndex(serializeKey(this.prefix,key)))}getAsync(key){return execInReadTx(this.store,async tx=>{let val=await tx.getIndex(serializeKey(this.prefix,key));return val.length>0?this.encoder.unpack(val[0]):void 0})}hasAsync(key){return execInReadTx(this.store,async tx=>(await tx.getIndex(serializeKey(this.prefix,key))).length>0)}sizeAsync(){return execInReadTx(this.store,tx=>tx.countEntriesIndex(minKey(this.prefix),maxKey(this.prefix),!1))}async*entriesAsync(range){let reverse=range?.reverse??!1,startKey=range?.start?serializeKey(this.prefix,range.start):minKey(this.prefix),endKey=range?.end?serializeKey(this.prefix,range.end):reverse?maxKey(this.prefix):void 0,tx=this.store.getCurrentWriteTx(),shouldClose=!tx;tx??=this.store.getReadTx();try{for await(let[key,vals]of tx.iterateIndex(reverse?endKey:startKey,reverse?startKey:endKey,reverse,range?.limit)){let deserializedKey=deserializeKey(this.prefix,key);if(!deserializedKey)break;for(let val of vals)yield[deserializedKey,this.encoder.unpack(val)]}}finally{shouldClose&&tx.close()}}async*valuesAsync(range){for await(let[_,value]of this.entriesAsync(range))yield value}async*keysAsync(range){for await(let[key,_]of this.entriesAsync(range))yield key}deleteValue(key,val){return execInWriteTx(this.store,tx=>tx.removeIndex(serializeKey(this.prefix,key),this.encoder.pack(val)))}async*getValuesAsync(key){let values=await execInReadTx(this.store,tx=>tx.getIndex(serializeKey(this.prefix,key)));for(let value of values)yield this.encoder.unpack(value)}getValueCountAsync(key){let startKey=serializeKey(this.prefix,key),endKey=toBufferKey([this.prefix,key,MAXIMUM_KEY]);return execInReadTx(this.store,tx=>tx.countEntriesIndex(startKey,endKey,!1))}};var ReadTransaction=class{static{__name(this,"ReadTransaction")}channel;open;constructor(channel){this.channel=channel,this.open=!0}close(){this.open&&(this.open=!1)}assertIsOpen(){if(!this.open)throw new Error("Transaction is closed")}async get(key){return this.assertIsOpen(),(await this.channel.sendMessage(LMDBMessageType.GET,{keys:[key],db:Database.DATA})).values[0]?.[0]??void 0}async getIndex(key){return this.assertIsOpen(),(await this.channel.sendMessage(LMDBMessageType.GET,{keys:[key],db:Database.INDEX})).values[0]??[]}async*iterate(startKey,endKey,reverse=!1,limit){yield*this.#iterate(Database.DATA,startKey,endKey,reverse,limit,vals=>vals[0])}async*iterateIndex(startKey,endKey,reverse=!1,limit){yield*this.#iterate(Database.INDEX,startKey,endKey,reverse,limit,vals=>vals)}countEntries(startKey,endKey,reverse){return this.#countEntries(Database.DATA,startKey,endKey,reverse)}countEntriesIndex(startKey,endKey,reverse){return this.#countEntries(Database.INDEX,startKey,endKey,reverse)}async*#iterate(db,startKey,endKey,reverse,limit,map2){this.assertIsOpen();let cursor;try{let response=await this.channel.sendMessage(LMDBMessageType.START_CURSOR,{key:startKey,reverse,count:typeof limit=="number"?Math.min(limit,CURSOR_PAGE_SIZE):CURSOR_PAGE_SIZE,onePage:typeof limit=="number"&&limit<CURSOR_PAGE_SIZE,db});cursor=response.cursor??void 0;let entries=response.entries,done=typeof cursor!="number",count2=0;for(;entries.length>0;){for(let[key,values]of entries){if(typeof limit=="number"&&count2>=limit){done=!0;break}if(endKey){let cmp=Buffer.compare(key,endKey);if(!reverse&&cmp>=0||reverse&&cmp<=0){done=!0;break}}count2++,yield[key,map2(values)]}if(typeof cursor!="number"||done)break;let response2=await this.channel.sendMessage(LMDBMessageType.ADVANCE_CURSOR,{cursor,count:CURSOR_PAGE_SIZE});done=response2.done,entries=response2.entries}}finally{typeof cursor=="number"&&await this.channel.sendMessage(LMDBMessageType.CLOSE_CURSOR,{cursor})}}async#countEntries(db,startKey,endKey,reverse){this.assertIsOpen();let cursor;try{return cursor=(await this.channel.sendMessage(LMDBMessageType.START_CURSOR,{key:startKey,reverse,count:0,onePage:!1,db})).cursor??void 0,cursor?(await this.channel.sendMessage(LMDBMessageType.ADVANCE_CURSOR_COUNT,{cursor,endKey})).count:0}finally{typeof cursor=="number"&&await this.channel.sendMessage(LMDBMessageType.CLOSE_CURSOR,{cursor})}}};var LMDBSet=class{static{__name(this,"LMDBSet")}map;constructor(store,mapName){this.map=new LMDBMap(store,mapName)}hasAsync(key){return this.map.hasAsync(key)}add(key){return this.map.set(key,!0)}delete(key){return this.map.delete(key)}async*entriesAsync(range={}){for await(let key of this.map.keysAsync(range))yield key}};import{Encoder as Encoder4}from"msgpackr";var LMDBSingleValue=class{static{__name(this,"LMDBSingleValue")}store;key;encoder;constructor(store,name){this.store=store,this.encoder=new Encoder4,this.key=serializeKey(`singleton:${name}`,"value")}getAsync(){return execInReadTx(this.store,async tx=>{let val=await tx.get(this.key);return val?this.encoder.unpack(val):void 0})}set(val){return execInWriteTx(this.store,async tx=>(await tx.set(this.key,this.encoder.pack(val)),!0))}delete(){return execInWriteTx(this.store,async tx=>(await tx.remove(this.key),!0))}};function makeTuple(length,fn,offset=0){return Array.from({length},(_,i)=>fn(i+offset))}__name(makeTuple,"makeTuple");async function makeTupleAsync(length,fn,offset=0){return await Promise.all(Array(length).fill(0).map(async(_,i)=>await fn(i+offset)))}__name(makeTupleAsync,"makeTupleAsync");function assertMemberLength(obj,member,length){if(obj[member].length!==length)throw new Error(`Expected ${member} to have length ${length} but was ${obj[member].length}`)}__name(assertMemberLength,"assertMemberLength");function dedupeSortedArray(arr,cmp){for(let i=0;i<arr.length;i++){let j=i+1;for(;j<arr.length;j++){let res=cmp(arr[i],arr[j]);if(res!==0){if(res<0)break;throw new Error("Array not sorted")}}j-i>1&&arr.splice(i+1,j-i-1)}}__name(dedupeSortedArray,"dedupeSortedArray");function insertIntoSortedArray(arr,item,cmp,allowDuplicates=!0){let index=findInsertionIndexInSortedArray(arr,item,cmp);return!allowDuplicates&&index>0&&cmp(arr[index-1],item)===0?!1:(arr.splice(index,0,item),!0)}__name(insertIntoSortedArray,"insertIntoSortedArray");function findInsertionIndexInSortedArray(values,needle,cmp){let start=0,end=values.length;for(;start<end;){let mid=start+((end-start)/2|0);cmp(values[mid],needle)<=0?start=mid+1:end=mid}return start}__name(findInsertionIndexInSortedArray,"findInsertionIndexInSortedArray");function findIndexInSortedArray(values,needle,cmp){let start=0,end=values.length-1;for(;start<=end;){let mid=start+((end-start)/2|0),comparison=cmp(values[mid],needle);if(comparison===0)return mid;comparison>0?end=mid-1:start=mid+1}return-1}__name(findIndexInSortedArray,"findIndexInSortedArray");function findInSortedArray(values,needle,cmp){let idx=findIndexInSortedArray(values,needle,cmp);return idx>-1?values[idx]:void 0}__name(findInSortedArray,"findInSortedArray");function removeAnyOf(arr,vals,cmp){let writeIdx=0,readIdx=0,valIdx=0;for(;readIdx<arr.length&&valIdx<vals.length;){let comparison=cmp(arr[readIdx],vals[valIdx]);comparison<0?arr[writeIdx++]=arr[readIdx++]:comparison>0?valIdx++:readIdx++}for(;readIdx<arr.length;)arr[writeIdx++]=arr[readIdx++];arr.length=writeIdx}__name(removeAnyOf,"removeAnyOf");function removeFromSortedArray(arr,val,cmp){let idx=findIndexInSortedArray(arr,val,cmp);idx>-1&&arr.splice(idx,1)}__name(removeFromSortedArray,"removeFromSortedArray");function merge2(arr,toInsert,cmp){let result=new Array(arr.length+toInsert.length),i=0,j=0,k=0;for(;i<arr.length&&j<toInsert.length;)result[k++]=cmp(arr[i],toInsert[j])<=0?arr[i++]:toInsert[j++];for(;i<arr.length;)result[k++]=arr[i++];for(;j<toInsert.length;)result[k++]=toInsert[j++];for(i=0;i<result.length;i++)arr[i]=result[i];arr.length=result.length}__name(merge2,"merge");var WriteTransaction=class extends ReadTransaction{static{__name(this,"WriteTransaction")}dataBatch={addEntries:[],removeEntries:[]};indexBatch={addEntries:[],removeEntries:[]};set(key,value){this.assertIsOpen();let addEntry=findInSortedArray(this.dataBatch.addEntries,key,singleKeyCmp);addEntry?addEntry[1]=[value]:insertIntoSortedArray(this.dataBatch.addEntries,[key,[value]],keyCmp);let removeEntryIndex=findIndexInSortedArray(this.dataBatch.removeEntries,key,singleKeyCmp);return removeEntryIndex>-1&&this.dataBatch.removeEntries.splice(removeEntryIndex,1),Promise.resolve()}remove(key){findIndexInSortedArray(this.dataBatch.removeEntries,key,singleKeyCmp)===-1&&insertIntoSortedArray(this.dataBatch.removeEntries,[key,null],keyCmp);let addEntryIndex=findIndexInSortedArray(this.dataBatch.addEntries,key,singleKeyCmp);return addEntryIndex>-1&&this.dataBatch.addEntries.splice(addEntryIndex,1),Promise.resolve()}async get(key){this.assertIsOpen();let addEntry=findInSortedArray(this.dataBatch.addEntries,key,singleKeyCmp);if(addEntry)return addEntry[1][0];if(!(findIndexInSortedArray(this.dataBatch.removeEntries,key,singleKeyCmp)>-1))return await super.get(key)}setIndex(key,...values){this.assertIsOpen();let addEntries=findInSortedArray(this.indexBatch.addEntries,key,singleKeyCmp),removeEntries=findInSortedArray(this.indexBatch.removeEntries,key,singleKeyCmp);return removeEntries&&(removeEntries[1]&&removeAnyOf(removeEntries[1],values,Buffer.compare),(!removeEntries[1]||removeEntries[1].length===0)&&removeFromSortedArray(this.indexBatch.removeEntries,removeEntries,keyCmp)),addEntries?(merge2(addEntries[1],values,Buffer.compare),dedupeSortedArray(addEntries[1],Buffer.compare)):insertIntoSortedArray(this.indexBatch.addEntries,[key,values],keyCmp),Promise.resolve()}removeIndex(key,...values){this.assertIsOpen();let addEntries=findInSortedArray(this.indexBatch.addEntries,key,singleKeyCmp),removeEntries=findInSortedArray(this.indexBatch.removeEntries,key,singleKeyCmp);return values.length===0?(addEntries&&removeFromSortedArray(this.indexBatch.addEntries,addEntries,keyCmp),removeEntries?removeEntries[1]=null:insertIntoSortedArray(this.indexBatch.removeEntries,[key,null],keyCmp),Promise.resolve()):(addEntries&&(removeAnyOf(addEntries[1],values,Buffer.compare),addEntries[1].length===0&&removeFromSortedArray(this.indexBatch.addEntries,addEntries,keyCmp)),removeEntries?(removeEntries[1]??=[],merge2(removeEntries[1],values,Buffer.compare),dedupeSortedArray(removeEntries[1],Buffer.compare)):insertIntoSortedArray(this.indexBatch.removeEntries,[key,values],keyCmp),Promise.resolve())}async getIndex(key){this.assertIsOpen();let removeEntries=findInSortedArray(this.indexBatch.removeEntries,key,singleKeyCmp);if(removeEntries&&removeEntries[1]===null)return[];let addEntries=findInSortedArray(this.indexBatch.addEntries,key,singleKeyCmp),results=await super.getIndex(key);return addEntries&&(merge2(results,addEntries[1],Buffer.compare),dedupeSortedArray(results,Buffer.compare)),removeEntries&&Array.isArray(removeEntries[1])&&removeAnyOf(results,removeEntries[1],Buffer.compare),results}async*iterate(startKey,endKey,reverse,limit){yield*this.#iterate(super.iterate(startKey,endKey,reverse),this.dataBatch,startKey,endKey,reverse,limit,(committed,toAdd)=>toAdd.length>0?toAdd[0]:committed,vals=>vals[0])}async*iterateIndex(startKey,endKey,reverse,limit){yield*this.#iterate(super.iterateIndex(startKey,endKey,reverse),this.indexBatch,startKey,endKey,reverse,limit,(committed,toAdd,toRemove)=>(toAdd.length>0&&(merge2(committed,toAdd,Buffer.compare),dedupeSortedArray(committed,Buffer.compare)),toRemove.length>0&&removeAnyOf(committed,toRemove,Buffer.compare),committed),vals=>vals)}async*#iterate(iterator,batch,startKey,endKey,reverse=!1,limit,merge3,map2){this.assertIsOpen();let uncommittedEntries=[...batch.addEntries],removeEntries=[...batch.removeEntries],cmpDirection=-1;reverse&&(cmpDirection=1,uncommittedEntries.reverse());let uncommittedEntriesIdx=0;for(;uncommittedEntriesIdx<uncommittedEntries.length;){let entry=uncommittedEntries[uncommittedEntriesIdx];if(Buffer.compare(entry[0],startKey)!==cmpDirection)break;uncommittedEntriesIdx++}let count2=0,checkLimit=typeof limit=="number"?()=>count2<limit:()=>!0;for await(let[key,values]of iterator){for(;uncommittedEntriesIdx<uncommittedEntries.length&&checkLimit();){let entry=uncommittedEntries[uncommittedEntriesIdx];if(endKey&&Buffer.compare(entry[0],endKey)!==cmpDirection)break;if(Buffer.compare(entry[0],key)===cmpDirection)count2++,yield[entry[0],map2(entry[1])];else break;uncommittedEntriesIdx++}if(!checkLimit())break;let toRemove=findInSortedArray(removeEntries,key,singleKeyCmp),toAdd=[];if(uncommittedEntriesIdx<uncommittedEntries.length&&Buffer.compare(uncommittedEntries[uncommittedEntriesIdx][0],key)===0&&(toAdd=uncommittedEntries[uncommittedEntriesIdx][1],uncommittedEntriesIdx++),!(toRemove&&!toRemove[1])){let mergedValues=merge3(values,toAdd,toRemove?.[1]??[]);mergedValues&&(count2++,yield[key,mergedValues])}}for(;uncommittedEntriesIdx<uncommittedEntries.length&&checkLimit();){let entry=uncommittedEntries[uncommittedEntriesIdx];if(endKey&&Buffer.compare(entry[0],endKey)!==cmpDirection)break;count2++,yield[entry[0],map2(entry[1])],uncommittedEntriesIdx++}}async commit(){this.assertIsOpen(),this.close(),await this.channel.sendMessage(LMDBMessageType.BATCH,{batches:new Map([[Database.DATA,this.dataBatch],[Database.INDEX,this.indexBatch]])})}};var AztecLMDBStoreV2=class _AztecLMDBStoreV2{static{__name(this,"AztecLMDBStoreV2")}dataDir;log;cleanup;open;channel;writerCtx;writerQueue;availableCursors;constructor(dataDir,mapSize,maxReaders,log2,cleanup,ephemeral=!1){this.dataDir=dataDir,this.log=log2,this.cleanup=cleanup,this.open=!1,this.writerCtx=new AsyncLocalStorage,this.writerQueue=new SerialQueue,this.log.info(`Starting data store with maxReaders ${maxReaders}`),this.channel=new MsgpackChannel(new NativeLMDBStore(dataDir,mapSize,maxReaders,ephemeral)),this.availableCursors=new Semaphore(maxReaders-1)}get dataDirectory(){return this.dataDir}async start(){this.writerQueue.start(),await this.channel.sendMessage(LMDBMessageType.OPEN_DATABASE,{db:Database.DATA,uniqueKeys:!0}),await this.channel.sendMessage(LMDBMessageType.OPEN_DATABASE,{db:Database.INDEX,uniqueKeys:!1}),this.open=!0}static async new(dataDir,dbMapSizeKb=10*1024*1024,maxReaders=16,cleanup,bindings,ephemeral=!1){let log2=createLogger("kv-store:lmdb-v2",bindings),db=new _AztecLMDBStoreV2(dataDir,dbMapSizeKb,maxReaders,log2,cleanup,ephemeral);return await db.start(),db}async backupTo(dstPath,compact2=!0){await mkdir(dstPath,{recursive:!0}),await this.channel.sendMessage(LMDBMessageType.COPY_STORE,{dstPath,compact:compact2})}getReadTx(){if(!this.open)throw new Error("Store is closed");return new ReadTransaction(this)}getCurrentWriteTx(){if(!this.open)throw new Error("Store is closed");return this.writerCtx.getStore()}openMap(name){return new LMDBMap(this,name)}openMultiMap(name){return new LMDBMultiMap(this,name)}openSingleton(name){return new LMDBSingleValue(this,name)}openArray(name){return new LMDBArray(this,name)}openSet(name){return new LMDBSet(this,name)}openCounter(_name){throw new Error("Not implemented")}async transactionAsync(callback){if(!this.open)throw new Error("Store is closed");let currentTx=this.getCurrentWriteTx();return currentTx?await callback(currentTx):this.writerQueue.put(async()=>{let tx=new WriteTransaction(this);try{let res=await this.writerCtx.run(tx,callback,tx);return await tx.commit(),res}catch(err){throw this.log.error("Failed to commit transaction",err),err}finally{tx.close()}})}clear(){return Promise.resolve()}async delete(){await this.close(),await rm(this.dataDir,{recursive:!0,force:!0,maxRetries:3}),this.log.verbose(`Deleted database files at ${this.dataDir}`),await this.cleanup?.()}async close(){this.open&&(this.open=!1,await this.writerQueue.cancel(),await this.channel.sendMessage(LMDBMessageType.CLOSE,void 0))}async sendMessage(msgType,body){if(!this.open)throw new Error("Store is closed");msgType===LMDBMessageType.START_CURSOR&&await this.availableCursors.acquire();let response;try{return{response}=await this.channel.sendMessage(msgType,body),response}finally{(msgType===LMDBMessageType.START_CURSOR&&response===void 0||msgType===LMDBMessageType.CLOSE_CURSOR||msgType===LMDBMessageType.START_CURSOR&&typeof response.cursor!="number")&&this.availableCursors.release()}}async estimateSize(){let resp=await this.sendMessage(LMDBMessageType.STATS,void 0);return{mappingSize:Number(resp.dbMapSizeBytes),physicalFileSize:Number(resp.dbPhysicalFileSizeBytes),actualSize:resp.stats.reduce((s2,db)=>Number(db.totalUsedSize)+s2,0),numItems:resp.stats.reduce((s2,db)=>Number(db.numDataItems)+s2,0)}}};import{inspect as inspect4}from"util";var import_sha3=__toESM(require_sha3(),1);import{inspect as inspect3}from"util";var _computedKey3;_computedKey3=inspect3.custom;var BaseBuffer32=class _BaseBuffer32{static{__name(this,"BaseBuffer32")}buffer;static SIZE=32;constructor(buffer){if(this.buffer=buffer,buffer.length!==_BaseBuffer32.SIZE)throw new Error(`Expected buffer to have length ${_BaseBuffer32.SIZE} but was ${buffer.length}`)}toBuffer(){return this.buffer}equals(hash5){return this.buffer.equals(hash5.buffer)}isZero(){return this.buffer.equals(Buffer.alloc(32,0))}toString(){return bufferToHex(this.buffer)}[_computedKey3](){return`Buffer32<${this.toString()}>`}toJSON(){return this.toString()}toBigInt(){return deserializeBigInt(this.buffer,0,_BaseBuffer32.SIZE).elem}},Buffer32=class _Buffer32 extends BaseBuffer32{static{__name(this,"Buffer32")}static ZERO=new _Buffer32(Buffer.alloc(_Buffer32.SIZE));static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _Buffer32(reader.readBytes(_Buffer32.SIZE))}static fromBigInt(hash5){return new _Buffer32(serializeBigInt(hash5,_Buffer32.SIZE))}static fromField(hash5){return new _Buffer32(serializeBigInt(hash5.toBigInt()))}static fromBuffer28(buffer){if(buffer.length!=28)throw new Error("Expected Buffer32 input buffer to be 28 bytes");let padded=Buffer.concat([Buffer.alloc(_Buffer32.SIZE-28),buffer]);return new _Buffer32(padded)}static fromString(str){if(str.startsWith("0x")&&(str=str.slice(2)),str.length!==_Buffer32.SIZE*2)throw new Error(`Expected string to be ${_Buffer32.SIZE*2} characters long, but was ${str.length}`);return new _Buffer32(Buffer.from(str,"hex"))}static fromNumber(num){return new _Buffer32(serializeBigInt(BigInt(num),_Buffer32.SIZE))}static random(){return new _Buffer32(Buffer.from(randomBytes(_Buffer32.SIZE)))}};function keccak256(input){return input instanceof Buffer32&&(input=input.buffer),new import_sha3.Keccak(256).update(input).digest()}__name(keccak256,"keccak256");function keccak256String(input){let hash5=new import_sha3.Keccak(256);return hash5.reset(),hash5.update(input),hash5.digest("hex")}__name(keccak256String,"keccak256String");function keccakf1600(state){let Eba,Ebe,Ebi,Ebo,Ebu,Ega,Ege,Egi,Ego,Egu,Eka,Eke,Eki,Eko,Eku,Ema,Eme,Emi,Emo,Emu,Esa,Ese,Esi,Eso,Esu,Ba,Be,Bi,Bo,Bu,Da,De,Di,Do,Du,Aba=state[0],Abe=state[1],Abi=state[2],Abo=state[3],Abu=state[4],Aga=state[5],Age=state[6],Agi=state[7],Ago=state[8],Agu=state[9],Aka=state[10],Ake=state[11],Aki=state[12],Ako=state[13],Aku=state[14],Ama=state[15],Ame=state[16],Ami=state[17],Amo=state[18],Amu=state[19],Asa=state[20],Ase=state[21],Asi=state[22],Aso=state[23],Asu=state[24];for(let round=0;round<24;round+=2)Ba=Aba^Aga^Aka^Ama^Asa,Be=Abe^Age^Ake^Ame^Ase,Bi=Abi^Agi^Aki^Ami^Asi,Bo=Abo^Ago^Ako^Amo^Aso,Bu=Abu^Agu^Aku^Amu^Asu,Da=Bu^rol(Be,1n),De=Ba^rol(Bi,1n),Di=Be^rol(Bo,1n),Do=Bi^rol(Bu,1n),Du=Bo^rol(Ba,1n),Ba=Aba^Da,Be=rol(Age^De,44n),Bi=rol(Aki^Di,43n),Bo=rol(Amo^Do,21n),Bu=rol(Asu^Du,14n),Eba=Ba^~Be&Bi^roundConstants[round],Ebe=Be^~Bi&Bo,Ebi=Bi^~Bo&Bu,Ebo=Bo^~Bu&Ba,Ebu=Bu^~Ba&Be,Ba=rol(Abo^Do,28n),Be=rol(Agu^Du,20n),Bi=rol(Aka^Da,3n),Bo=rol(Ame^De,45n),Bu=rol(Asi^Di,61n),Ega=Ba^~Be&Bi,Ege=Be^~Bi&Bo,Egi=Bi^~Bo&Bu,Ego=Bo^~Bu&Ba,Egu=Bu^~Ba&Be,Ba=rol(Abe^De,1n),Be=rol(Agi^Di,6n),Bi=rol(Ako^Do,25n),Bo=rol(Amu^Du,8n),Bu=rol(Asa^Da,18n),Eka=Ba^~Be&Bi,Eke=Be^~Bi&Bo,Eki=Bi^~Bo&Bu,Eko=Bo^~Bu&Ba,Eku=Bu^~Ba&Be,Ba=rol(Abu^Du,27n),Be=rol(Aga^Da,36n),Bi=rol(Ake^De,10n),Bo=rol(Ami^Di,15n),Bu=rol(Aso^Do,56n),Ema=Ba^~Be&Bi,Eme=Be^~Bi&Bo,Emi=Bi^~Bo&Bu,Emo=Bo^~Bu&Ba,Emu=Bu^~Ba&Be,Ba=rol(Abi^Di,62n),Be=rol(Ago^Do,55n),Bi=rol(Aku^Du,39n),Bo=rol(Ama^Da,41n),Bu=rol(Ase^De,2n),Esa=Ba^~Be&Bi,Ese=Be^~Bi&Bo,Esi=Bi^~Bo&Bu,Eso=Bo^~Bu&Ba,Esu=Bu^~Ba&Be,Ba=Eba^Ega^Eka^Ema^Esa,Be=Ebe^Ege^Eke^Eme^Ese,Bi=Ebi^Egi^Eki^Emi^Esi,Bo=Ebo^Ego^Eko^Emo^Eso,Bu=Ebu^Egu^Eku^Emu^Esu,Da=Bu^rol(Be,1n),De=Ba^rol(Bi,1n),Di=Be^rol(Bo,1n),Do=Bi^rol(Bu,1n),Du=Bo^rol(Ba,1n),Ba=Eba^Da,Be=rol(Ege^De,44n),Bi=rol(Eki^Di,43n),Bo=rol(Emo^Do,21n),Bu=rol(Esu^Du,14n),Aba=Ba^~Be&Bi^roundConstants[round+1],Abe=Be^~Bi&Bo,Abi=Bi^~Bo&Bu,Abo=Bo^~Bu&Ba,Abu=Bu^~Ba&Be,Ba=rol(Ebo^Do,28n),Be=rol(Egu^Du,20n),Bi=rol(Eka^Da,3n),Bo=rol(Eme^De,45n),Bu=rol(Esi^Di,61n),Aga=Ba^~Be&Bi,Age=Be^~Bi&Bo,Agi=Bi^~Bo&Bu,Ago=Bo^~Bu&Ba,Agu=Bu^~Ba&Be,Ba=rol(Ebe^De,1n),Be=rol(Egi^Di,6n),Bi=rol(Eko^Do,25n),Bo=rol(Emu^Du,8n),Bu=rol(Esa^Da,18n),Aka=Ba^~Be&Bi,Ake=Be^~Bi&Bo,Aki=Bi^~Bo&Bu,Ako=Bo^~Bu&Ba,Aku=Bu^~Ba&Be,Ba=rol(Ebu^Du,27n),Be=rol(Ega^Da,36n),Bi=rol(Eke^De,10n),Bo=rol(Emi^Di,15n),Bu=rol(Eso^Do,56n),Ama=Ba^~Be&Bi,Ame=Be^~Bi&Bo,Ami=Bi^~Bo&Bu,Amo=Bo^~Bu&Ba,Amu=Bu^~Ba&Be,Ba=rol(Ebi^Di,62n),Be=rol(Ego^Do,55n),Bi=rol(Eku^Du,39n),Bo=rol(Ema^Da,41n),Bu=rol(Ese^De,2n),Asa=Ba^~Be&Bi,Ase=Be^~Bi&Bo,Asi=Bi^~Bo&Bu,Aso=Bo^~Bu&Ba,Asu=Bu^~Ba&Be;return state[0]=Aba,state[1]=Abe,state[2]=Abi,state[3]=Abo,state[4]=Abu,state[5]=Aga,state[6]=Age,state[7]=Agi,state[8]=Ago,state[9]=Agu,state[10]=Aka,state[11]=Ake,state[12]=Aki,state[13]=Ako,state[14]=Aku,state[15]=Ama,state[16]=Ame,state[17]=Ami,state[18]=Amo,state[19]=Amu,state[20]=Asa,state[21]=Ase,state[22]=Asi,state[23]=Aso,state[24]=Asu,state}__name(keccakf1600,"keccakf1600");function rol(x,s2){return BigInt.asUintN(64,x<<s2)|x>>64n-s2}__name(rol,"rol");var roundConstants=[0x0000000000000001n,0x0000000000008082n,0x800000000000808an,0x8000000080008000n,0x000000000000808bn,0x0000000080000001n,0x8000000080008081n,0x8000000000008009n,0x000000000000008an,0x0000000000000088n,0x0000000080008009n,0x000000008000000an,0x000000008000808bn,0x800000000000008bn,0x8000000000008089n,0x8000000000008003n,0x8000000000008002n,0x8000000000000080n,0x000000000000800an,0x800000008000000an,0x8000000080008081n,0x8000000000008080n,0x0000000080000001n,0x8000000080008008n];var _computedKey4;_computedKey4=inspect4.custom;var EthAddress=class _EthAddress{static{__name(this,"EthAddress")}buffer;static SIZE_IN_BYTES=20;static ZERO=new _EthAddress(Buffer.alloc(_EthAddress.SIZE_IN_BYTES));constructor(buffer){if(this.buffer=buffer,buffer.length!==_EthAddress.SIZE_IN_BYTES)throw new Error(`Expect buffer size to be ${_EthAddress.SIZE_IN_BYTES}. Got ${buffer.length}.`)}static fromString(address){if(!_EthAddress.isAddress(address))throw new Error(`Invalid address string: ${address}`);return new _EthAddress(Buffer.from(address.replace(/^0x/i,""),"hex"))}static fromPlainObject(obj){return obj instanceof _EthAddress?obj:obj instanceof Buffer||Buffer.isBuffer(obj)?obj.length===20?new _EthAddress(obj):_EthAddress.fromField(new Fr(obj)):_EthAddress.fromString(obj)}static random(){return new _EthAddress(randomBytes(20))}static isAddress(address){return/^(0x)?[0-9a-f]{40}$/i.test(address)?/^(0x|0X)?[0-9a-f]{40}$/.test(address)||/^(0x|0X)?[0-9A-F]{40}$/.test(address)?!0:_EthAddress.checkAddressChecksum(address):!1}isZero(){return this.equals(_EthAddress.ZERO)}static checkAddressChecksum(address){address=address.replace(/^0x/i,"");let addressHash=keccak256String(address.toLowerCase());for(let i=0;i<40;i++)if(parseInt(addressHash[i],16)>7&&address[i].toUpperCase()!==address[i]||parseInt(addressHash[i],16)<=7&&address[i].toLowerCase()!==address[i])return!1;return!0}static toChecksumAddress(address){if(!_EthAddress.isAddress(address))throw new Error("Invalid address string.");address=address.toLowerCase().replace(/^0x/i,"");let addressHash=keccak256String(address),checksumAddress="0x";for(let i=0;i<address.length;i++)parseInt(addressHash[i],16)>7?checksumAddress+=address[i].toUpperCase():checksumAddress+=address[i];return checksumAddress}equals(rhs){return this.buffer.equals(rhs.buffer)}toString(){return bufferToHex(this.buffer)}[_computedKey4](){return`EthAddress<${this.toString()}>`}toChecksumString(){return _EthAddress.toChecksumAddress(this.buffer.toString("hex"))}toBuffer(){return this.buffer}toBuffer32(){let buffer=Buffer.alloc(32);return this.buffer.copy(buffer,12),buffer}toField(){return Fr.fromBuffer(this.toBuffer32())}static fromField(fr){return new _EthAddress(fr.toBuffer().slice(-_EthAddress.SIZE_IN_BYTES))}static fromFields(fields){let reader=FieldReader.asReader(fields);return _EthAddress.fromField(reader.readField())}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _EthAddress(reader.readBytes(_EthAddress.SIZE_IN_BYTES))}static fromNumber(num){let buffer=Buffer.alloc(_EthAddress.SIZE_IN_BYTES);return buffer.writeBigUInt64BE(BigInt(num),_EthAddress.SIZE_IN_BYTES-8),new _EthAddress(buffer)}toJSON(){return this.toString()}static get schema(){return hexSchemaFor(_EthAddress,_EthAddress.isAddress)}static areEqual(a,b){let addrA=typeof a=="string"?_EthAddress.fromString(a):a,addrB=typeof b=="string"?_EthAddress.fromString(b):b;return addrA.equals(addrB)}};import fs from"fs/promises";import{join}from"path";import{Buffer as Buffer2}from"buffer";function jsonParseWithSchema(json2,schema){return schema.parse(JSON.parse(json2))}__name(jsonParseWithSchema,"jsonParseWithSchema");function jsonStringify(obj,prettify){return JSON.stringify(obj,(_key,value)=>typeof value=="bigint"?value.toString():typeof value=="object"&&value&&value.type==="Buffer"&&Array.isArray(value.data)?Buffer2.from(value.data).toString("base64"):typeof value=="object"&&value&&Buffer2.isBuffer(value)?value.toString("base64"):typeof value=="object"&&value instanceof Map?Array.from(value.entries()):typeof value=="object"&&value instanceof Set?Array.from(value.values()):value,prettify?2:0)}__name(jsonStringify,"jsonStringify");var BadRequestError=class extends Error{static{__name(this,"BadRequestError")}constructor(message){super(message),this.name="BadRequestError"}};var inspectCustomSymbol=Symbol.for("nodejs.util.inspect.custom"),DatabaseVersion=class _DatabaseVersion{static{__name(this,"DatabaseVersion")}schemaVersion;rollupAddress;constructor(schemaVersion,rollupAddress){this.schemaVersion=schemaVersion,this.rollupAddress=rollupAddress}toBuffer(){return Buffer.from(jsonStringify(this))}static fromBuffer(buf){try{return jsonParseWithSchema(buf.toString("utf-8"),_DatabaseVersion.schema)}catch(err){throw new Error(`Failed to deserialize version information: ${err}`,{cause:err})}}cmp(other){if(this.rollupAddress.equals(other.rollupAddress))return this.schemaVersion<other.schemaVersion?-1:this.schemaVersion>other.schemaVersion?1:0}equals(other){return this.cmp(other)===0}static get schema(){return external_exports.object({schemaVersion:external_exports.number(),rollupAddress:EthAddress.schema}).transform(({schemaVersion,rollupAddress})=>new _DatabaseVersion(schemaVersion,rollupAddress))}[inspectCustomSymbol](){return this.toString()}toString(){return`DatabaseVersion{schemaVersion=${this.schemaVersion},rollupAddress=${this.rollupAddress}"}`}static empty(){return new _DatabaseVersion(0,EthAddress.ZERO)}};var DATABASE_VERSION_FILE_NAME="db_version",DatabaseVersionManager=class _DatabaseVersionManager{static{__name(this,"DatabaseVersionManager")}static VERSION_FILE=DATABASE_VERSION_FILE_NAME;versionFile;currentVersion;dataDirectory;onOpen;onUpgrade;schemaVersionMismatchPolicy;fileSystem;log;constructor({schemaVersion,rollupAddress,dataDirectory,onOpen,onUpgrade,schemaVersionMismatchPolicy="reset",fileSystem=fs,log:log2=createLogger("foundation:version-manager")}){if(schemaVersion<1)throw new TypeError(`Invalid schema version received: ${schemaVersion}`);this.versionFile=join(dataDirectory,_DatabaseVersionManager.VERSION_FILE),this.currentVersion=new DatabaseVersion(schemaVersion,rollupAddress),this.dataDirectory=dataDirectory,this.onOpen=onOpen,this.onUpgrade=onUpgrade,this.schemaVersionMismatchPolicy=schemaVersionMismatchPolicy,this.fileSystem=fileSystem,this.log=log2}static async writeVersion(version2,dataDir,fileSystem=fs){return await fileSystem.mkdir(dataDir,{recursive:!0}),fileSystem.writeFile(join(dataDir,_DatabaseVersionManager.VERSION_FILE),version2.toBuffer())}async open(){let storedVersion,shouldLogDataReset=!0;try{let versionBuf=await this.fileSystem.readFile(this.versionFile);storedVersion=DatabaseVersion.fromBuffer(versionBuf)}catch(err){err&&err.code==="ENOENT"?(storedVersion=DatabaseVersion.empty(),shouldLogDataReset=!1):(this.log.warn(`Failed to read stored version information: ${err}. Defaulting to empty version`),storedVersion=DatabaseVersion.empty())}let cmp=storedVersion.cmp(this.currentVersion),needsReset=!1;if(typeof cmp=="number"){if(cmp===-1&&this.onUpgrade){this.log.info(`Upgrading from version ${storedVersion.schemaVersion} to ${this.currentVersion.schemaVersion}`);try{await this.onUpgrade(this.dataDirectory,storedVersion.schemaVersion,this.currentVersion.schemaVersion)}catch(error2){if(this.schemaVersionMismatchPolicy==="throw")throw new Error(`Failed to upgrade database at ${this.dataDirectory} from schema version ${storedVersion.schemaVersion} to ${this.currentVersion.schemaVersion}`,{cause:error2});this.log.error(`Failed to upgrade: ${error2}. Falling back to reset.`),needsReset=!0}}else if(cmp!==0){if(this.schemaVersionMismatchPolicy==="throw")throw new Error(`Cannot open database at ${this.dataDirectory}: stored schema version ${storedVersion.schemaVersion} is incompatible with expected schema version ${this.currentVersion.schemaVersion}`);shouldLogDataReset&&this.log.info(`Can't upgrade from version ${storedVersion} to ${this.currentVersion}. Resetting database at ${this.dataDirectory}`),needsReset=!0}}else shouldLogDataReset&&this.log.warn("Rollup address has changed, resetting data directory",{versionFile:this.versionFile,storedVersion,currentVersion:this.currentVersion}),needsReset=!0;return needsReset&&await this.resetDataDirectory(),await this.writeVersion(),[await this.onOpen(this.dataDirectory),needsReset]}writeVersion(dir){return _DatabaseVersionManager.writeVersion(this.currentVersion,dir??this.dataDirectory,this.fileSystem)}async resetDataDirectory(){try{await this.fileSystem.rm(this.dataDirectory,{recursive:!0,force:!0,maxRetries:3}),await this.fileSystem.mkdir(this.dataDirectory,{recursive:!0})}catch(err){throw this.log.error(`Failed to reset data directory: ${err}`),new Error(`Failed to reset data directory: ${err}`,{cause:err})}}getDataDirectory(){return this.dataDirectory}getSchemaVersion(){return this.currentVersion.schemaVersion}};import{copyFile,mkdir as mkdir2,mkdtemp,rm as rm2}from"fs/promises";import{tmpdir}from"os";import{join as join2}from"path";var MAX_READERS=16;async function openEphemeralStore(name,dbMapSizeKb=10*1024*1024,maxReaders=MAX_READERS,bindings){let log2=createLogger("kv-store:lmdb-v2:"+name,bindings),dataDir=await mkdtemp(join2(tmpdir(),name+"-"));log2.debug(`Created ephemeral data store at: ${dataDir} with size: ${dbMapSizeKb} KB (LMDB v2)`);let cleanup=__name(async()=>{try{await rm2(dataDir,{recursive:!0,force:!0,maxRetries:3}),log2.debug(`Deleted ephemeral data store: ${dataDir}`)}catch(err){log2.warn(`Failed to delete ephemeral data directory (LMDB v2) ${dataDir}: ${err}`)}},"cleanup");return AztecLMDBStoreV2.new(dataDir,dbMapSizeKb,maxReaders,cleanup,bindings,!0)}__name(openEphemeralStore,"openEphemeralStore");async function cloneEphemeralStoreFrom(srcDataMdbPath,name,dbMapSizeKb=10*1024*1024,maxReaders=MAX_READERS,bindings){let log2=createLogger("kv-store:lmdb-v2:"+name,bindings),dataDir=await mkdtemp(join2(tmpdir(),name+"-"));await copyFile(srcDataMdbPath,join2(dataDir,"data.mdb")),log2.debug(`Cloned ephemeral data store at: ${dataDir} from ${srcDataMdbPath} (LMDB v2)`);let cleanup=__name(async()=>{try{await rm2(dataDir,{recursive:!0,force:!0,maxRetries:3}),log2.debug(`Deleted ephemeral data store: ${dataDir}`)}catch(err){log2.warn(`Failed to delete ephemeral data directory (LMDB v2) ${dataDir}: ${err}`)}},"cleanup");return AztecLMDBStoreV2.new(dataDir,dbMapSizeKb,maxReaders,cleanup,bindings,!0)}__name(cloneEphemeralStoreFrom,"cloneEphemeralStoreFrom");var DateProvider=class{static{__name(this,"DateProvider")}now(){return Date.now()}nowInSeconds(){return Math.floor(this.now()/1e3)}nowAsDate(){return new Date(this.now())}},TestDateProvider=class extends DateProvider{static{__name(this,"TestDateProvider")}logger;offset;constructor(logger3=createLogger("foundation:test-date-provider")){super(),this.logger=logger3,this.offset=0}now(){return Date.now()+this.offset}setTime(timeMs){this.offset=timeMs-Date.now(),this.logger.warn(`Time set to ${new Date(timeMs).toISOString()}`,{offset:this.offset,timeMs})}reset(){this.offset=0,this.logger.warn("Time reset to real time")}advanceTime(seconds){this.offset+=seconds*1e3}};var Timer=class{static{__name(this,"Timer")}start;constructor(){this.start=performance?performance.now():Date.now()}us(){return this.ms()*1e3}ms(){return(performance?performance.now():Date.now())-this.start}s(){return this.ms()/1e3}};async function elapsed(fn){let timer=new Timer,result=await(typeof fn=="function"?fn():fn);return[timer.ms(),result]}__name(elapsed,"elapsed");function defaultSignalError(signal){return signal.reason instanceof Error?signal.reason:new Error(signal.reason?String(signal.reason):"Operation aborted")}__name(defaultSignalError,"defaultSignalError");async function execWithSignal(fn,signal,errorFn=defaultSignalError){if(signal.aborted)throw errorFn(signal);let abortPromise=promiseWithResolvers(),abortListener=__name(()=>abortPromise.reject(errorFn(signal)),"abortListener");signal.addEventListener("abort",abortListener,{once:!0});try{return await Promise.race([fn(signal),abortPromise.promise])}finally{abortListener&&signal.removeEventListener("abort",abortListener)}}__name(execWithSignal,"execWithSignal");function schemaHasMethod(schema,methodName){return typeof methodName=="string"&&Object.hasOwn(schema,methodName)&&schema[methodName].def.input!==void 0&&schema[methodName].def.output!==void 0}__name(schemaHasMethod,"schemaHasMethod");function getSchemaParameters(schema){return schema.def.input}__name(getSchemaParameters,"getSchemaParameters");function parseWithOptionals(args,schema){let items=schema.def.items,missingCount=items.length-args.length,optionalCount=items.filter(isOptional).length,toParse=missingCount>0&&missingCount<=optionalCount?args.concat(times(missingCount,()=>{})):args;return schema.parseAsync(toParse)}__name(parseWithOptionals,"parseWithOptionals");function isOptional(schema){try{return schema.isOptional()}catch{return schema.def.type==="optional"}}__name(isOptional,"isOptional");function zodFor(){return schema=>schema}__name(zodFor,"zodFor");import{inspect as inspect5}from"util";var _computedKey5;_computedKey5=inspect5.custom;var SecretValue=class _SecretValue{static{__name(this,"SecretValue")}redactedValue;#value;constructor(value,redactedValue="[Redacted]"){this.redactedValue=redactedValue,this.#value=value}getValue(){return this.#value}toString(){return this.redactedValue}toJSON(){return this.redactedValue}[_computedKey5](){return this.toString()}static schema(valueSchema){return valueSchema.transform(value=>new _SecretValue(value))}};var schemas={EpochNumber:EpochNumberSchema,SlotNumber:SlotNumberSchema,EthAddress:EthAddress.schema,Fr:Fr.schema,Fq:Fq.schema,Point:Point.schema,Boolean:external_exports.union([external_exports.boolean(),external_exports.number().refine(arg=>arg===0||arg===1,{message:"Numeric value for a boolean variable must be 0 or 1"}).transform(arg=>arg===1),external_exports.string().transform(arg=>arg.trim().toLowerCase()).refine(arg=>["true","false","1","0"].includes(arg)).transform(arg=>arg==="1"||arg==="true")]),BigInt:external_exports.union([external_exports.bigint(),external_exports.number(),external_exports.string()]).pipe(external_exports.coerce.bigint()),Integer:external_exports.union([external_exports.bigint(),external_exports.number(),external_exports.string()]).pipe(external_exports.coerce.number().int()),UInt32:external_exports.union([external_exports.bigint(),external_exports.number(),external_exports.string()]).pipe(external_exports.coerce.number().int().min(0).max(2**32-1)),UInt64:external_exports.union([external_exports.bigint(),external_exports.number(),external_exports.string()]).pipe(external_exports.coerce.bigint().min(0n).max(2n**64n-1n)),Buffer32:external_exports.string().refine(isHex,"Not a valid hex string").transform(Buffer32.fromString),Buffer:bufferSchema,BufferHex:external_exports.string().refine(isHex,"Not a valid hex string").transform(withoutHexPrefix).transform(data=>Buffer.from(data,"hex")),HexString:hexSchema,HexStringWith0x:external_exports.string().refine(isHex,"Not a valid hex string").transform(withHexPrefix),SecretValue:SecretValue.schema};import{inflate}from"pako";import{Barretenberg,BarretenbergSync as BarretenbergSync3}from"@aztec/bb.js";var IS_BROWSER=typeof self<"u";async function poseidon2HashFields(inputFields){if(IS_BROWSER){await BarretenbergSync3.initSingleton();let response=BarretenbergSync3.getSingleton().poseidon2Hash({inputs:inputFields.map(i=>i.toBuffer())});return Fr.fromBuffer(Buffer.from(response.hash))}else{await Barretenberg.initSingleton();let response=await Barretenberg.getSingleton().poseidon2Hash({inputs:inputFields.map(i=>i.toBuffer())});return Fr.fromBuffer(Buffer.from(response.hash))}}__name(poseidon2HashFields,"poseidon2HashFields");function poseidon2Hash(input){return poseidon2HashFields(serializeToFields(input))}__name(poseidon2Hash,"poseidon2Hash");function poseidon2HashWithSeparator(input,separator){let inputFields=serializeToFields(input);return inputFields.unshift(new Fr(separator)),poseidon2HashFields(inputFields)}__name(poseidon2HashWithSeparator,"poseidon2HashWithSeparator");async function poseidon2Permutation(input){let inputFields=serializeToFields(input);return IS_BROWSER?(await BarretenbergSync3.initSingleton(),BarretenbergSync3.getSingleton().poseidon2Permutation({inputs:inputFields.map(i=>i.toBuffer())}).outputs.map(o=>Fr.fromBuffer(Buffer.from(o)))):(await Barretenberg.initSingleton(),(await Barretenberg.getSingleton().poseidon2Permutation({inputs:inputFields.map(i=>i.toBuffer())})).outputs.map(o=>Fr.fromBuffer(Buffer.from(o))))}__name(poseidon2Permutation,"poseidon2Permutation");function poseidon2HashBytes(input){let inputFields=[];for(let i=0;i<input.length;i+=31){let fieldBytes=Buffer.alloc(32,0);input.slice(i,i+31).copy(fieldBytes),fieldBytes.reverse(),inputFields.push(Fr.fromBuffer(fieldBytes))}return poseidon2HashFields(inputFields)}__name(poseidon2HashBytes,"poseidon2HashBytes");var FunctionSignatureDecoder=class{static{__name(this,"FunctionSignatureDecoder")}name;parameters;includeNames;separator;constructor(name,parameters,includeNames=!1){this.name=name,this.parameters=parameters,this.includeNames=includeNames,this.separator=includeNames?", ":","}getParameterType(param){switch(param.kind){case"field":return"Field";case"integer":return param.sign==="signed"?`i${param.width}`:`u${param.width}`;case"boolean":return"bool";case"array":return`[${this.getParameterType(param.type)};${param.length}]`;case"string":return`str<${param.length}>`;case"struct":return`(${param.fields.map(field=>`${this.decodeParameter(field)}`).join(this.separator)})`;default:throw new Error(`Unsupported type: ${param.kind}`)}}decodeParameter(param){let type=this.getParameterType(param.type);return this.includeNames?`${param.name}: ${type}`:type}decode(){return`${this.name}(${this.parameters.map(param=>this.decodeParameter(param)).join(this.separator)})`}};function decodeFunctionSignature(name,parameters){return new FunctionSignatureDecoder(name,parameters).decode()}__name(decodeFunctionSignature,"decodeFunctionSignature");import{inspect as inspect6}from"util";var _computedKey6;_computedKey6=inspect6.custom;var Selector=class _Selector{static{__name(this,"Selector")}value;static SIZE=4;constructor(value){if(this.value=value,value>2**(_Selector.SIZE*8)-1)throw new Error(`Selector must fit in ${_Selector.SIZE} bytes (got value ${value}).`)}isEmpty(){return this.value===0}toBuffer(bufferSize=_Selector.SIZE){return toBufferBE(BigInt(this.value),bufferSize)}toString(){return bufferToHex(this.toBuffer())}[_computedKey6](){return`Selector<${this.toString()}>`}equals(other){return this.value===other.value}toField(){return new Fr(BigInt(this.value))}};var FunctionSelector=class _FunctionSelector extends Selector{static{__name(this,"FunctionSelector")}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer),value=Number(toBigIntBE(reader.readBytes(Selector.SIZE)));return new _FunctionSelector(value)}static fromField(fr){return new _FunctionSelector(Number(fr.toBigInt()))}static fromFieldOrUndefined(fr){try{return _FunctionSelector.fromField(fr)}catch{return}}static fromFields(fields){let reader=FieldReader.asReader(fields);return _FunctionSelector.fromField(reader.readField())}static async fromSignature(signature){if(/\s/.test(signature))throw new Error("Signature cannot contain whitespace");let bytes=(await poseidon2HashBytes(Buffer.from(signature))).toBuffer().slice(-Selector.SIZE);return _FunctionSelector.fromBuffer(bytes)}static fromString(selector){let buf=fromHex(selector);if(buf.length!==Selector.SIZE)throw new Error(`Invalid FunctionSelector length ${buf.length} (expected ${Selector.SIZE}).`);return _FunctionSelector.fromBuffer(buf)}static empty(){return new _FunctionSelector(0)}static async fromNameAndParameters(nameOrArgs,maybeParameters){let{name,parameters}=typeof nameOrArgs=="string"?{name:nameOrArgs,parameters:maybeParameters}:nameOrArgs,signature=decodeFunctionSignature(name,parameters);return await this.fromSignature(signature)}static random(){return _FunctionSelector.fromBuffer(randomBytes(Selector.SIZE))}toJSON(){return this.toString()}static get schema(){return hexSchemaFor(_FunctionSelector)}};var logger2=createLogger("aztec:foundation:abi"),AbiValueSchema=external_exports.discriminatedUnion("kind",[external_exports.object({kind:external_exports.literal("boolean"),value:external_exports.boolean()}),external_exports.object({kind:external_exports.literal("string"),value:external_exports.string()}),external_exports.object({kind:external_exports.literal("array"),value:external_exports.array(external_exports.lazy(()=>AbiValueSchema))}),external_exports.object({kind:external_exports.literal("tuple"),fields:external_exports.array(external_exports.lazy(()=>AbiValueSchema))}),external_exports.object({kind:external_exports.literal("integer"),value:external_exports.string(),sign:external_exports.boolean()}),external_exports.object({kind:external_exports.literal("struct"),fields:external_exports.array(external_exports.object({name:external_exports.string(),value:external_exports.lazy(()=>AbiValueSchema)}))})]),ABIParameterVisibility=["public","private","databus"],Sign=["unsigned","signed"],AbiTypeSchema=external_exports.discriminatedUnion("kind",[external_exports.object({kind:external_exports.literal("field")}),external_exports.object({kind:external_exports.literal("boolean")}),external_exports.object({kind:external_exports.literal("integer"),sign:external_exports.enum(Sign),width:external_exports.number()}),external_exports.object({kind:external_exports.literal("array"),length:external_exports.number(),type:external_exports.lazy(()=>AbiTypeSchema)}),external_exports.object({kind:external_exports.literal("string"),length:external_exports.number()}),external_exports.object({kind:external_exports.literal("struct"),fields:external_exports.array(external_exports.lazy(()=>ABIVariableSchema)),path:external_exports.string()}),external_exports.object({kind:external_exports.literal("tuple"),fields:external_exports.array(external_exports.lazy(()=>AbiTypeSchema))})]),ABIVariableSchema=external_exports.object({name:external_exports.string(),type:AbiTypeSchema}),ABIParameterSchema=ABIVariableSchema.and(external_exports.object({visibility:external_exports.enum(ABIParameterVisibility)})),AbiErrorTypeSchema=zodFor()(external_exports.union([external_exports.object({error_kind:external_exports.literal("string"),string:external_exports.string()}),external_exports.object({error_kind:external_exports.literal("fmtstring"),length:external_exports.number(),item_types:external_exports.array(AbiTypeSchema)}),external_exports.object({error_kind:external_exports.literal("custom")}).and(AbiTypeSchema)])),FunctionType=(function(FunctionType2){return FunctionType2.PRIVATE="private",FunctionType2.PUBLIC="public",FunctionType2.UTILITY="utility",FunctionType2})({}),FunctionAbiSchema=external_exports.object({name:external_exports.string(),functionType:external_exports.nativeEnum(FunctionType),isOnlySelf:external_exports.boolean(),isStatic:external_exports.boolean(),isInitializer:external_exports.boolean(),parameters:external_exports.array(external_exports.object({name:external_exports.string(),type:AbiTypeSchema,visibility:external_exports.enum(ABIParameterVisibility)})),returnTypes:external_exports.array(AbiTypeSchema),errorTypes:external_exports.record(external_exports.string(),AbiErrorTypeSchema.optional())}),FunctionDebugMetadataSchema=external_exports.object({debugSymbols:external_exports.object({location_tree:external_exports.object({locations:external_exports.array(external_exports.object({parent:external_exports.number().nullable(),value:external_exports.object({span:external_exports.object({start:external_exports.number(),end:external_exports.number()}),file:external_exports.number()})}))}),acir_locations:external_exports.record(external_exports.string(),external_exports.number()),brillig_locations:external_exports.record(external_exports.string(),external_exports.record(external_exports.string(),external_exports.number()))}),files:external_exports.record(external_exports.string(),external_exports.object({source:external_exports.string(),path:external_exports.string(),function_locations:external_exports.array(external_exports.object({start:external_exports.number(),name:external_exports.string()}))}))}),FunctionArtifactSchema=zodFor()(FunctionAbiSchema.and(external_exports.object({bytecode:schemas.Buffer,verificationKey:external_exports.string().optional(),debugSymbols:external_exports.string(),debug:FunctionDebugMetadataSchema.optional()}))),ARTIFACT_VERSION_BEFORE_INJECTION="FROM_RELEASE_BEFORE_VERSION_INJECTION",ContractArtifactSchema=zodFor()(external_exports.object({name:external_exports.string(),aztecVersion:external_exports.string().default(ARTIFACT_VERSION_BEFORE_INJECTION),functions:external_exports.array(FunctionArtifactSchema),nonDispatchPublicFunctions:external_exports.array(FunctionAbiSchema),outputs:external_exports.object({structs:external_exports.record(external_exports.string(),external_exports.array(AbiTypeSchema)).transform(structs=>{for(let[key,value]of Object.entries(structs))(key==="events"||key==="functions")&&(structs[key]=value.sort((a,b)=>a.path>b.path?-1:1));return structs}),globals:external_exports.record(external_exports.string(),external_exports.array(AbiValueSchema))}),storageLayout:external_exports.record(external_exports.string(),external_exports.object({slot:schemas.Fr})),fileMap:external_exports.record(external_exports.coerce.number(),external_exports.object({source:external_exports.string(),path:external_exports.string(),function_locations:external_exports.array(external_exports.object({start:external_exports.number(),name:external_exports.string()}))}))}));async function findFunctionArtifactBySelector(artifact,selector){return(await Promise.all(artifact.functions.map(async fn=>({fn,selector:await FunctionSelector.fromNameAndParameters(fn.name,fn.parameters)})))).find(({selector:s2})=>s2.equals(selector))?.fn}__name(findFunctionArtifactBySelector,"findFunctionArtifactBySelector");async function findFunctionAbiBySelector(artifact,selector){return(await Promise.all(getAllFunctionAbis(artifact).map(async fn=>({fn,selector:await FunctionSelector.fromNameAndParameters(fn.name,fn.parameters)})))).find(({selector:s2})=>s2.equals(selector))?.fn}__name(findFunctionAbiBySelector,"findFunctionAbiBySelector");function getAllFunctionAbis(artifact){return artifact.functions.map(f=>f).concat(artifact.nonDispatchPublicFunctions||[])}__name(getAllFunctionAbis,"getAllFunctionAbis");function parseDebugSymbols(debugSymbols){return JSON.parse(inflate(Buffer.from(debugSymbols,"base64"),{to:"string",raw:!0})).debug_infos}__name(parseDebugSymbols,"parseDebugSymbols");function getFunctionDebugMetadata(contractArtifact,functionArtifact){try{if(functionArtifact.debugSymbols&&contractArtifact.fileMap)return{debugSymbols:parseDebugSymbols(functionArtifact.debugSymbols)[0],files:contractArtifact.fileMap}}catch(err){if(err instanceof RangeError&&err.message.includes("Invalid string length"))logger2.warn(`Caught RangeError: Invalid string length. This suggests the debug_symbols field of the contract ${contractArtifact.name} and function ${functionArtifact.name} is huge; too big to parse. We'll skip returning this info until this issue is resolved. Here's the error:
|
|
88
|
+
`,previous.push(v),i==1e6&&finishUtf8()}return stringBuildCode+=`return fromCharCode(${previous}) + readString(source)}`,stringBuildCode}__name(makeStringBuilder,"makeStringBuilder");var pendingSurrogate;function finishUtf8(byte1,src2){if((byte1&224)===192){let byte2=src2[position++]&63;return(byte1&31)<<6|byte2}else if((byte1&240)===224){let byte2=src2[position++]&63,byte3=src2[position++]&63;return(byte1&31)<<12|byte2<<6|byte3}else if((byte1&248)===240){if(pendingSurrogate)return byte1=pendingSurrogate,pendingSurrogate=null,position+=3,byte1;let byte2=src2[position++]&63,byte3=src2[position++]&63,byte4=src2[position++]&63,unit=(byte1&7)<<18|byte2<<12|byte3<<6|byte4;return unit>65535&&(pendingSurrogate=56320|unit&1023,unit=unit-65536>>>10&1023|55296,position-=4),unit}else return byte1}__name(finishUtf8,"finishUtf8");var readString=typeof process<"u"&&process.isBun?(function(reading){let{setPosition,getPosition,readString:readString3}=reading;return source=>{setPosition(position);let value=readString3(source);return position=getPosition(),value}})(new Function("fromCharCode","let position; let readString = "+makeStringBuilder()+";return {setPosition(p) { position = p },getPosition() { return position },readString }")(fromCharCode)):eval(makeStringBuilder());function readStringSafely(source,end){if(source[end]>0){let previous=source[end];try{return source[end]=0,readString(source)}finally{source[end]=previous}}else return readString(source)}__name(readStringSafely,"readStringSafely");function compareKeys(a,b){if(typeof a=="object"){if(!a)return b==null?0:-1;if(a.compare)return b==null?1:b.compare?a.compare(b):-1;let arrayComparison;if(b instanceof Array){let i=0;for(;(arrayComparison=compareKeys(a[i],b[i]))==0&&i<=a.length;)i++;return arrayComparison}return arrayComparison=compareKeys(a[0],b),arrayComparison==0&&a.length>1?1:arrayComparison}else return typeof a==typeof b?(typeof a=="symbol"&&(a=Symbol.keyFor(a),b=Symbol.keyFor(b)),a<b?-1:a===b?0:1):typeof b=="object"?b instanceof Array?-compareKeys(b,a):1:typeOrder[typeof a]<typeOrder[typeof b]?-1:1}__name(compareKeys,"compareKeys");var typeOrder={symbol:0,undefined:1,boolean:2,number:3,string:4},MINIMUM_KEY=null,MAXIMUM_KEY=new Uint8Array([255]);function keyCmp(a,b){return Buffer.compare(a[0],b[0])}__name(keyCmp,"keyCmp");function singleKeyCmp(a,b){return Buffer.compare(a[0],b)}__name(singleKeyCmp,"singleKeyCmp");function minKey(prefix){return toBufferKey([prefix])}__name(minKey,"minKey");function maxKey(prefix){return toBufferKey([prefix,MAXIMUM_KEY])}__name(maxKey,"maxKey");function serializeKey(prefix,key){return toBufferKey([prefix,key])}__name(serializeKey,"serializeKey");function deserializeKey(prefix,key){let buf=Buffer.from(key),parsed=fromBufferKey(buf);return!Array.isArray(parsed)||parsed[0]!==prefix?!1:parsed[1]}__name(deserializeKey,"deserializeKey");var _computedKey2;_computedKey2=Symbol.asyncIterator;var LMDBArray=class{static{__name(this,"LMDBArray")}store;length;encoder;prefix;constructor(store,name){this.store=store,this.encoder=new Encoder,this.length=store.openSingleton(name+":length"),this.prefix=`array:${name}`}pop(){return execInWriteTx(this.store,async tx=>{let length=await this.lengthAsync();if(length===0)return;let val=await tx.get(serializeKey(this.prefix,length-1));return await tx.remove(serializeKey(this.prefix,length-1)),await this.length.set(length-1),val?this.encoder.unpack(val):void 0})}push(...vals){return execInWriteTx(this.store,async tx=>{let length=await this.lengthAsync();for(let val of vals)await tx.set(serializeKey(this.prefix,length++),this.encoder.pack(val));return await this.length.set(length),length})}setAt(index,val){return execInWriteTx(this.store,async tx=>{let length=await this.lengthAsync();return index<0&&(index+=length),index<0||index>=length?!1:(await tx.set(serializeKey(this.prefix,index),this.encoder.pack(val)),!0)})}atAsync(index){return execInReadTx(this.store,async tx=>{let length=await this.lengthAsync();if(index<0&&(index+=length),index<0||index>=length)return;let val=await tx.get(serializeKey(this.prefix,index));return val?this.encoder.unpack(val):void 0})}async lengthAsync(){return await this.length.getAsync()??0}async*entriesAsync(){let length=await this.lengthAsync();if(length===0)return;let tx=this.store.getCurrentWriteTx(),shouldClose=!tx;tx??=this.store.getReadTx();try{for await(let[key,val]of tx.iterate(serializeKey(this.prefix,0),void 0,!1,length)){let deserializedKey=deserializeKey(this.prefix,key);if(deserializedKey===!1)break;yield[deserializedKey,this.encoder.unpack(val)]}}finally{shouldClose&&tx.close()}}async*valuesAsync(){for await(let[_,value]of this.entriesAsync())yield value}[_computedKey2](){return this.valuesAsync()}};import{Encoder as Encoder2}from"msgpackr";var LMDBMap=class{static{__name(this,"LMDBMap")}store;prefix;encoder;constructor(store,name){this.store=store,this.encoder=new Encoder2,this.prefix=`map:${name}`}set(key,val){return execInWriteTx(this.store,tx=>tx.set(serializeKey(this.prefix,key),this.encoder.pack(val)))}async setMany(entries){await execInWriteTx(this.store,async tx=>{for(let{key,value}of entries)await tx.set(serializeKey(this.prefix,key),this.encoder.pack(value))})}setIfNotExists(key,val){return execInWriteTx(this.store,async tx=>{let strKey=serializeKey(this.prefix,key);return!await tx.get(strKey)?(await tx.set(strKey,this.encoder.pack(val)),!0):!1})}delete(key){return execInWriteTx(this.store,tx=>tx.remove(serializeKey(this.prefix,key)))}getAsync(key){return execInReadTx(this.store,async tx=>{let val=await tx.get(serializeKey(this.prefix,key));return val?this.encoder.unpack(val):void 0})}hasAsync(key){return execInReadTx(this.store,async tx=>!!await tx.get(serializeKey(this.prefix,key)))}sizeAsync(){return execInReadTx(this.store,tx=>tx.countEntries(minKey(this.prefix),maxKey(this.prefix),!1))}async*entriesAsync(range){let reverse=range?.reverse??!1,startKey=range?.start!==void 0?serializeKey(this.prefix,range.start):minKey(this.prefix),endKey=range?.end!==void 0?serializeKey(this.prefix,range.end):reverse?maxKey(this.prefix):void 0,tx=this.store.getCurrentWriteTx(),shouldClose=!tx;tx??=this.store.getReadTx();try{for await(let[key,val]of tx.iterate(reverse?endKey:startKey,reverse?startKey:endKey,reverse,range?.limit)){let deserializedKey=deserializeKey(this.prefix,key);if(deserializedKey===!1)break;yield[deserializedKey,this.encoder.unpack(val)]}}finally{shouldClose&&tx.close()}}async*valuesAsync(range){for await(let[_,value]of this.entriesAsync(range))yield value}async*keysAsync(range){for await(let[key,_]of this.entriesAsync(range))yield key}};var Database=(function(Database2){return Database2.DATA="data",Database2.INDEX="index",Database2})({}),CURSOR_PAGE_SIZE=10,LMDBMessageType=(function(LMDBMessageType2){return LMDBMessageType2[LMDBMessageType2.OPEN_DATABASE=100]="OPEN_DATABASE",LMDBMessageType2[LMDBMessageType2.GET=101]="GET",LMDBMessageType2[LMDBMessageType2.HAS=102]="HAS",LMDBMessageType2[LMDBMessageType2.START_CURSOR=103]="START_CURSOR",LMDBMessageType2[LMDBMessageType2.ADVANCE_CURSOR=104]="ADVANCE_CURSOR",LMDBMessageType2[LMDBMessageType2.ADVANCE_CURSOR_COUNT=105]="ADVANCE_CURSOR_COUNT",LMDBMessageType2[LMDBMessageType2.CLOSE_CURSOR=106]="CLOSE_CURSOR",LMDBMessageType2[LMDBMessageType2.BATCH=107]="BATCH",LMDBMessageType2[LMDBMessageType2.STATS=108]="STATS",LMDBMessageType2[LMDBMessageType2.CLOSE=109]="CLOSE",LMDBMessageType2[LMDBMessageType2.COPY_STORE=110]="COPY_STORE",LMDBMessageType2})({});import{Encoder as Encoder3}from"msgpackr/pack";var LMDBMultiMap=class{static{__name(this,"LMDBMultiMap")}store;prefix;encoder;constructor(store,name){this.store=store,this.encoder=new Encoder3,this.prefix=`multimap:${name}`}set(key,val){return execInWriteTx(this.store,tx=>tx.setIndex(serializeKey(this.prefix,key),this.encoder.pack(val)))}async setMany(entries){await execInWriteTx(this.store,async tx=>{for(let{key,value}of entries)await tx.setIndex(serializeKey(this.prefix,key),this.encoder.pack(value))})}setIfNotExists(key,val){return execInWriteTx(this.store,async tx=>!await this.getAsync(key)?(await tx.setIndex(serializeKey(this.prefix,key),this.encoder.pack(val)),!0):!1)}delete(key){return execInWriteTx(this.store,tx=>tx.removeIndex(serializeKey(this.prefix,key)))}getAsync(key){return execInReadTx(this.store,async tx=>{let val=await tx.getIndex(serializeKey(this.prefix,key));return val.length>0?this.encoder.unpack(val[0]):void 0})}hasAsync(key){return execInReadTx(this.store,async tx=>(await tx.getIndex(serializeKey(this.prefix,key))).length>0)}sizeAsync(){return execInReadTx(this.store,tx=>tx.countEntriesIndex(minKey(this.prefix),maxKey(this.prefix),!1))}async*entriesAsync(range){let reverse=range?.reverse??!1,startKey=range?.start?serializeKey(this.prefix,range.start):minKey(this.prefix),endKey=range?.end?serializeKey(this.prefix,range.end):reverse?maxKey(this.prefix):void 0,tx=this.store.getCurrentWriteTx(),shouldClose=!tx;tx??=this.store.getReadTx();try{for await(let[key,vals]of tx.iterateIndex(reverse?endKey:startKey,reverse?startKey:endKey,reverse,range?.limit)){let deserializedKey=deserializeKey(this.prefix,key);if(!deserializedKey)break;for(let val of vals)yield[deserializedKey,this.encoder.unpack(val)]}}finally{shouldClose&&tx.close()}}async*valuesAsync(range){for await(let[_,value]of this.entriesAsync(range))yield value}async*keysAsync(range){for await(let[key,_]of this.entriesAsync(range))yield key}deleteValue(key,val){return execInWriteTx(this.store,tx=>tx.removeIndex(serializeKey(this.prefix,key),this.encoder.pack(val)))}async*getValuesAsync(key){let values=await execInReadTx(this.store,tx=>tx.getIndex(serializeKey(this.prefix,key)));for(let value of values)yield this.encoder.unpack(value)}getValueCountAsync(key){let startKey=serializeKey(this.prefix,key),endKey=toBufferKey([this.prefix,key,MAXIMUM_KEY]);return execInReadTx(this.store,tx=>tx.countEntriesIndex(startKey,endKey,!1))}};var ReadTransaction=class{static{__name(this,"ReadTransaction")}channel;open;constructor(channel){this.channel=channel,this.open=!0}close(){this.open&&(this.open=!1)}assertIsOpen(){if(!this.open)throw new Error("Transaction is closed")}async get(key){return this.assertIsOpen(),(await this.channel.sendMessage(LMDBMessageType.GET,{keys:[key],db:Database.DATA})).values[0]?.[0]??void 0}async getIndex(key){return this.assertIsOpen(),(await this.channel.sendMessage(LMDBMessageType.GET,{keys:[key],db:Database.INDEX})).values[0]??[]}async*iterate(startKey,endKey,reverse=!1,limit){yield*this.#iterate(Database.DATA,startKey,endKey,reverse,limit,vals=>vals[0])}async*iterateIndex(startKey,endKey,reverse=!1,limit){yield*this.#iterate(Database.INDEX,startKey,endKey,reverse,limit,vals=>vals)}countEntries(startKey,endKey,reverse){return this.#countEntries(Database.DATA,startKey,endKey,reverse)}countEntriesIndex(startKey,endKey,reverse){return this.#countEntries(Database.INDEX,startKey,endKey,reverse)}async*#iterate(db,startKey,endKey,reverse,limit,map2){this.assertIsOpen();let cursor;try{let response=await this.channel.sendMessage(LMDBMessageType.START_CURSOR,{key:startKey,reverse,count:typeof limit=="number"?Math.min(limit,CURSOR_PAGE_SIZE):CURSOR_PAGE_SIZE,onePage:typeof limit=="number"&&limit<CURSOR_PAGE_SIZE,db});cursor=response.cursor??void 0;let entries=response.entries,done=typeof cursor!="number",count2=0;for(;entries.length>0;){for(let[key,values]of entries){if(typeof limit=="number"&&count2>=limit){done=!0;break}if(endKey){let cmp=Buffer.compare(key,endKey);if(!reverse&&cmp>=0||reverse&&cmp<=0){done=!0;break}}count2++,yield[key,map2(values)]}if(typeof cursor!="number"||done)break;let response2=await this.channel.sendMessage(LMDBMessageType.ADVANCE_CURSOR,{cursor,count:CURSOR_PAGE_SIZE});done=response2.done,entries=response2.entries}}finally{typeof cursor=="number"&&await this.channel.sendMessage(LMDBMessageType.CLOSE_CURSOR,{cursor})}}async#countEntries(db,startKey,endKey,reverse){this.assertIsOpen();let cursor;try{return cursor=(await this.channel.sendMessage(LMDBMessageType.START_CURSOR,{key:startKey,reverse,count:0,onePage:!1,db})).cursor??void 0,cursor?(await this.channel.sendMessage(LMDBMessageType.ADVANCE_CURSOR_COUNT,{cursor,endKey})).count:0}finally{typeof cursor=="number"&&await this.channel.sendMessage(LMDBMessageType.CLOSE_CURSOR,{cursor})}}};var LMDBSet=class{static{__name(this,"LMDBSet")}map;constructor(store,mapName){this.map=new LMDBMap(store,mapName)}hasAsync(key){return this.map.hasAsync(key)}add(key){return this.map.set(key,!0)}delete(key){return this.map.delete(key)}async*entriesAsync(range={}){for await(let key of this.map.keysAsync(range))yield key}};import{Encoder as Encoder4}from"msgpackr";var LMDBSingleValue=class{static{__name(this,"LMDBSingleValue")}store;key;encoder;constructor(store,name){this.store=store,this.encoder=new Encoder4,this.key=serializeKey(`singleton:${name}`,"value")}getAsync(){return execInReadTx(this.store,async tx=>{let val=await tx.get(this.key);return val?this.encoder.unpack(val):void 0})}set(val){return execInWriteTx(this.store,async tx=>(await tx.set(this.key,this.encoder.pack(val)),!0))}delete(){return execInWriteTx(this.store,async tx=>(await tx.remove(this.key),!0))}};function makeTuple(length,fn,offset=0){return Array.from({length},(_,i)=>fn(i+offset))}__name(makeTuple,"makeTuple");async function makeTupleAsync(length,fn,offset=0){return await Promise.all(Array(length).fill(0).map(async(_,i)=>await fn(i+offset)))}__name(makeTupleAsync,"makeTupleAsync");function assertMemberLength(obj,member,length){if(obj[member].length!==length)throw new Error(`Expected ${member} to have length ${length} but was ${obj[member].length}`)}__name(assertMemberLength,"assertMemberLength");function dedupeSortedArray(arr,cmp){for(let i=0;i<arr.length;i++){let j=i+1;for(;j<arr.length;j++){let res=cmp(arr[i],arr[j]);if(res!==0){if(res<0)break;throw new Error("Array not sorted")}}j-i>1&&arr.splice(i+1,j-i-1)}}__name(dedupeSortedArray,"dedupeSortedArray");function insertIntoSortedArray(arr,item,cmp,allowDuplicates=!0){let index=findInsertionIndexInSortedArray(arr,item,cmp);return!allowDuplicates&&index>0&&cmp(arr[index-1],item)===0?!1:(arr.splice(index,0,item),!0)}__name(insertIntoSortedArray,"insertIntoSortedArray");function findInsertionIndexInSortedArray(values,needle,cmp){let start=0,end=values.length;for(;start<end;){let mid=start+((end-start)/2|0);cmp(values[mid],needle)<=0?start=mid+1:end=mid}return start}__name(findInsertionIndexInSortedArray,"findInsertionIndexInSortedArray");function findIndexInSortedArray(values,needle,cmp){let start=0,end=values.length-1;for(;start<=end;){let mid=start+((end-start)/2|0),comparison=cmp(values[mid],needle);if(comparison===0)return mid;comparison>0?end=mid-1:start=mid+1}return-1}__name(findIndexInSortedArray,"findIndexInSortedArray");function findInSortedArray(values,needle,cmp){let idx=findIndexInSortedArray(values,needle,cmp);return idx>-1?values[idx]:void 0}__name(findInSortedArray,"findInSortedArray");function removeAnyOf(arr,vals,cmp){let writeIdx=0,readIdx=0,valIdx=0;for(;readIdx<arr.length&&valIdx<vals.length;){let comparison=cmp(arr[readIdx],vals[valIdx]);comparison<0?arr[writeIdx++]=arr[readIdx++]:comparison>0?valIdx++:readIdx++}for(;readIdx<arr.length;)arr[writeIdx++]=arr[readIdx++];arr.length=writeIdx}__name(removeAnyOf,"removeAnyOf");function removeFromSortedArray(arr,val,cmp){let idx=findIndexInSortedArray(arr,val,cmp);idx>-1&&arr.splice(idx,1)}__name(removeFromSortedArray,"removeFromSortedArray");function merge2(arr,toInsert,cmp){let result=new Array(arr.length+toInsert.length),i=0,j=0,k=0;for(;i<arr.length&&j<toInsert.length;)result[k++]=cmp(arr[i],toInsert[j])<=0?arr[i++]:toInsert[j++];for(;i<arr.length;)result[k++]=arr[i++];for(;j<toInsert.length;)result[k++]=toInsert[j++];for(i=0;i<result.length;i++)arr[i]=result[i];arr.length=result.length}__name(merge2,"merge");var WriteTransaction=class extends ReadTransaction{static{__name(this,"WriteTransaction")}dataBatch={addEntries:[],removeEntries:[]};indexBatch={addEntries:[],removeEntries:[]};set(key,value){this.assertIsOpen();let addEntry=findInSortedArray(this.dataBatch.addEntries,key,singleKeyCmp);addEntry?addEntry[1]=[value]:insertIntoSortedArray(this.dataBatch.addEntries,[key,[value]],keyCmp);let removeEntryIndex=findIndexInSortedArray(this.dataBatch.removeEntries,key,singleKeyCmp);return removeEntryIndex>-1&&this.dataBatch.removeEntries.splice(removeEntryIndex,1),Promise.resolve()}remove(key){findIndexInSortedArray(this.dataBatch.removeEntries,key,singleKeyCmp)===-1&&insertIntoSortedArray(this.dataBatch.removeEntries,[key,null],keyCmp);let addEntryIndex=findIndexInSortedArray(this.dataBatch.addEntries,key,singleKeyCmp);return addEntryIndex>-1&&this.dataBatch.addEntries.splice(addEntryIndex,1),Promise.resolve()}async get(key){this.assertIsOpen();let addEntry=findInSortedArray(this.dataBatch.addEntries,key,singleKeyCmp);if(addEntry)return addEntry[1][0];if(!(findIndexInSortedArray(this.dataBatch.removeEntries,key,singleKeyCmp)>-1))return await super.get(key)}setIndex(key,...values){this.assertIsOpen();let addEntries=findInSortedArray(this.indexBatch.addEntries,key,singleKeyCmp),removeEntries=findInSortedArray(this.indexBatch.removeEntries,key,singleKeyCmp);return removeEntries&&(removeEntries[1]&&removeAnyOf(removeEntries[1],values,Buffer.compare),(!removeEntries[1]||removeEntries[1].length===0)&&removeFromSortedArray(this.indexBatch.removeEntries,removeEntries,keyCmp)),addEntries?(merge2(addEntries[1],values,Buffer.compare),dedupeSortedArray(addEntries[1],Buffer.compare)):insertIntoSortedArray(this.indexBatch.addEntries,[key,values],keyCmp),Promise.resolve()}removeIndex(key,...values){this.assertIsOpen();let addEntries=findInSortedArray(this.indexBatch.addEntries,key,singleKeyCmp),removeEntries=findInSortedArray(this.indexBatch.removeEntries,key,singleKeyCmp);return values.length===0?(addEntries&&removeFromSortedArray(this.indexBatch.addEntries,addEntries,keyCmp),removeEntries?removeEntries[1]=null:insertIntoSortedArray(this.indexBatch.removeEntries,[key,null],keyCmp),Promise.resolve()):(addEntries&&(removeAnyOf(addEntries[1],values,Buffer.compare),addEntries[1].length===0&&removeFromSortedArray(this.indexBatch.addEntries,addEntries,keyCmp)),removeEntries?(removeEntries[1]??=[],merge2(removeEntries[1],values,Buffer.compare),dedupeSortedArray(removeEntries[1],Buffer.compare)):insertIntoSortedArray(this.indexBatch.removeEntries,[key,values],keyCmp),Promise.resolve())}async getIndex(key){this.assertIsOpen();let removeEntries=findInSortedArray(this.indexBatch.removeEntries,key,singleKeyCmp);if(removeEntries&&removeEntries[1]===null)return[];let addEntries=findInSortedArray(this.indexBatch.addEntries,key,singleKeyCmp),results=await super.getIndex(key);return addEntries&&(merge2(results,addEntries[1],Buffer.compare),dedupeSortedArray(results,Buffer.compare)),removeEntries&&Array.isArray(removeEntries[1])&&removeAnyOf(results,removeEntries[1],Buffer.compare),results}async*iterate(startKey,endKey,reverse,limit){yield*this.#iterate(super.iterate(startKey,endKey,reverse),this.dataBatch,startKey,endKey,reverse,limit,(committed,toAdd)=>toAdd.length>0?toAdd[0]:committed,vals=>vals[0])}async*iterateIndex(startKey,endKey,reverse,limit){yield*this.#iterate(super.iterateIndex(startKey,endKey,reverse),this.indexBatch,startKey,endKey,reverse,limit,(committed,toAdd,toRemove)=>(toAdd.length>0&&(merge2(committed,toAdd,Buffer.compare),dedupeSortedArray(committed,Buffer.compare)),toRemove.length>0&&removeAnyOf(committed,toRemove,Buffer.compare),committed),vals=>vals)}async*#iterate(iterator,batch,startKey,endKey,reverse=!1,limit,merge3,map2){this.assertIsOpen();let uncommittedEntries=[...batch.addEntries],removeEntries=[...batch.removeEntries],cmpDirection=-1;reverse&&(cmpDirection=1,uncommittedEntries.reverse());let uncommittedEntriesIdx=0;for(;uncommittedEntriesIdx<uncommittedEntries.length;){let entry=uncommittedEntries[uncommittedEntriesIdx];if(Buffer.compare(entry[0],startKey)!==cmpDirection)break;uncommittedEntriesIdx++}let count2=0,checkLimit=typeof limit=="number"?()=>count2<limit:()=>!0;for await(let[key,values]of iterator){for(;uncommittedEntriesIdx<uncommittedEntries.length&&checkLimit();){let entry=uncommittedEntries[uncommittedEntriesIdx];if(endKey&&Buffer.compare(entry[0],endKey)!==cmpDirection)break;if(Buffer.compare(entry[0],key)===cmpDirection)count2++,yield[entry[0],map2(entry[1])];else break;uncommittedEntriesIdx++}if(!checkLimit())break;let toRemove=findInSortedArray(removeEntries,key,singleKeyCmp),toAdd=[];if(uncommittedEntriesIdx<uncommittedEntries.length&&Buffer.compare(uncommittedEntries[uncommittedEntriesIdx][0],key)===0&&(toAdd=uncommittedEntries[uncommittedEntriesIdx][1],uncommittedEntriesIdx++),!(toRemove&&!toRemove[1])){let mergedValues=merge3(values,toAdd,toRemove?.[1]??[]);mergedValues&&(count2++,yield[key,mergedValues])}}for(;uncommittedEntriesIdx<uncommittedEntries.length&&checkLimit();){let entry=uncommittedEntries[uncommittedEntriesIdx];if(endKey&&Buffer.compare(entry[0],endKey)!==cmpDirection)break;count2++,yield[entry[0],map2(entry[1])],uncommittedEntriesIdx++}}async commit(){this.assertIsOpen(),this.close(),await this.channel.sendMessage(LMDBMessageType.BATCH,{batches:new Map([[Database.DATA,this.dataBatch],[Database.INDEX,this.indexBatch]])})}};var AztecLMDBStoreV2=class _AztecLMDBStoreV2{static{__name(this,"AztecLMDBStoreV2")}dataDir;log;cleanup;open;channel;writerCtx;writerQueue;availableCursors;constructor(dataDir,mapSize,maxReaders,log2,cleanup,ephemeral=!1){this.dataDir=dataDir,this.log=log2,this.cleanup=cleanup,this.open=!1,this.writerCtx=new AsyncLocalStorage,this.writerQueue=new SerialQueue,this.log.info(`Starting data store with maxReaders ${maxReaders}`),this.channel=new MsgpackChannel(new NativeLMDBStore(dataDir,mapSize,maxReaders,ephemeral)),this.availableCursors=new Semaphore(maxReaders-1)}get dataDirectory(){return this.dataDir}async start(){this.writerQueue.start(),await this.channel.sendMessage(LMDBMessageType.OPEN_DATABASE,{db:Database.DATA,uniqueKeys:!0}),await this.channel.sendMessage(LMDBMessageType.OPEN_DATABASE,{db:Database.INDEX,uniqueKeys:!1}),this.open=!0}static async new(dataDir,dbMapSizeKb=10*1024*1024,maxReaders=16,cleanup,bindings,ephemeral=!1){let log2=createLogger("kv-store:lmdb-v2",bindings),db=new _AztecLMDBStoreV2(dataDir,dbMapSizeKb,maxReaders,log2,cleanup,ephemeral);return await db.start(),db}async backupTo(dstPath,compact2=!0){await mkdir(dstPath,{recursive:!0}),await this.channel.sendMessage(LMDBMessageType.COPY_STORE,{dstPath,compact:compact2})}getReadTx(){if(!this.open)throw new Error("Store is closed");return new ReadTransaction(this)}getCurrentWriteTx(){if(!this.open)throw new Error("Store is closed");return this.writerCtx.getStore()}openMap(name){return new LMDBMap(this,name)}openMultiMap(name){return new LMDBMultiMap(this,name)}openSingleton(name){return new LMDBSingleValue(this,name)}openArray(name){return new LMDBArray(this,name)}openSet(name){return new LMDBSet(this,name)}openCounter(_name){throw new Error("Not implemented")}async transactionAsync(callback){if(!this.open)throw new Error("Store is closed");let currentTx=this.getCurrentWriteTx();return currentTx?await callback(currentTx):this.writerQueue.put(async()=>{let tx=new WriteTransaction(this);try{let res=await this.writerCtx.run(tx,callback,tx);return await tx.commit(),res}catch(err){throw this.log.error("Failed to commit transaction",err),err}finally{tx.close()}})}clear(){return Promise.resolve()}async delete(){await this.close(),await rm(this.dataDir,{recursive:!0,force:!0,maxRetries:3}),this.log.verbose(`Deleted database files at ${this.dataDir}`),await this.cleanup?.()}async close(){this.open&&(this.open=!1,await this.writerQueue.cancel(),await this.channel.sendMessage(LMDBMessageType.CLOSE,void 0))}async sendMessage(msgType,body){if(!this.open)throw new Error("Store is closed");msgType===LMDBMessageType.START_CURSOR&&await this.availableCursors.acquire();let response;try{return{response}=await this.channel.sendMessage(msgType,body),response}finally{(msgType===LMDBMessageType.START_CURSOR&&response===void 0||msgType===LMDBMessageType.CLOSE_CURSOR||msgType===LMDBMessageType.START_CURSOR&&typeof response.cursor!="number")&&this.availableCursors.release()}}async estimateSize(){let resp=await this.sendMessage(LMDBMessageType.STATS,void 0);return{mappingSize:Number(resp.dbMapSizeBytes),physicalFileSize:Number(resp.dbPhysicalFileSizeBytes),actualSize:resp.stats.reduce((s2,db)=>Number(db.totalUsedSize)+s2,0),numItems:resp.stats.reduce((s2,db)=>Number(db.numDataItems)+s2,0)}}};import{inspect as inspect4}from"util";var import_sha3=__toESM(require_sha3(),1);import{inspect as inspect3}from"util";var _computedKey3;_computedKey3=inspect3.custom;var BaseBuffer32=class _BaseBuffer32{static{__name(this,"BaseBuffer32")}buffer;static SIZE=32;constructor(buffer){if(this.buffer=buffer,buffer.length!==_BaseBuffer32.SIZE)throw new Error(`Expected buffer to have length ${_BaseBuffer32.SIZE} but was ${buffer.length}`)}toBuffer(){return this.buffer}equals(hash5){return this.buffer.equals(hash5.buffer)}isZero(){return this.buffer.equals(Buffer.alloc(32,0))}toString(){return bufferToHex(this.buffer)}[_computedKey3](){return`Buffer32<${this.toString()}>`}toJSON(){return this.toString()}toBigInt(){return deserializeBigInt(this.buffer,0,_BaseBuffer32.SIZE).elem}},Buffer32=class _Buffer32 extends BaseBuffer32{static{__name(this,"Buffer32")}static ZERO=new _Buffer32(Buffer.alloc(_Buffer32.SIZE));static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _Buffer32(reader.readBytes(_Buffer32.SIZE))}static fromBigInt(hash5){return new _Buffer32(serializeBigInt(hash5,_Buffer32.SIZE))}static fromField(hash5){return new _Buffer32(serializeBigInt(hash5.toBigInt()))}static fromBuffer28(buffer){if(buffer.length!=28)throw new Error("Expected Buffer32 input buffer to be 28 bytes");let padded=Buffer.concat([Buffer.alloc(_Buffer32.SIZE-28),buffer]);return new _Buffer32(padded)}static fromString(str){if(str.startsWith("0x")&&(str=str.slice(2)),str.length!==_Buffer32.SIZE*2)throw new Error(`Expected string to be ${_Buffer32.SIZE*2} characters long, but was ${str.length}`);return new _Buffer32(Buffer.from(str,"hex"))}static fromNumber(num){return new _Buffer32(serializeBigInt(BigInt(num),_Buffer32.SIZE))}static random(){return new _Buffer32(Buffer.from(randomBytes(_Buffer32.SIZE)))}};function keccak256(input){return input instanceof Buffer32&&(input=input.buffer),new import_sha3.Keccak(256).update(input).digest()}__name(keccak256,"keccak256");function keccak256String(input){let hash5=new import_sha3.Keccak(256);return hash5.reset(),hash5.update(input),hash5.digest("hex")}__name(keccak256String,"keccak256String");function keccakf1600(state){let Eba,Ebe,Ebi,Ebo,Ebu,Ega,Ege,Egi,Ego,Egu,Eka,Eke,Eki,Eko,Eku,Ema,Eme,Emi,Emo,Emu,Esa,Ese,Esi,Eso,Esu,Ba,Be,Bi,Bo,Bu,Da,De,Di,Do,Du,Aba=state[0],Abe=state[1],Abi=state[2],Abo=state[3],Abu=state[4],Aga=state[5],Age=state[6],Agi=state[7],Ago=state[8],Agu=state[9],Aka=state[10],Ake=state[11],Aki=state[12],Ako=state[13],Aku=state[14],Ama=state[15],Ame=state[16],Ami=state[17],Amo=state[18],Amu=state[19],Asa=state[20],Ase=state[21],Asi=state[22],Aso=state[23],Asu=state[24];for(let round=0;round<24;round+=2)Ba=Aba^Aga^Aka^Ama^Asa,Be=Abe^Age^Ake^Ame^Ase,Bi=Abi^Agi^Aki^Ami^Asi,Bo=Abo^Ago^Ako^Amo^Aso,Bu=Abu^Agu^Aku^Amu^Asu,Da=Bu^rol(Be,1n),De=Ba^rol(Bi,1n),Di=Be^rol(Bo,1n),Do=Bi^rol(Bu,1n),Du=Bo^rol(Ba,1n),Ba=Aba^Da,Be=rol(Age^De,44n),Bi=rol(Aki^Di,43n),Bo=rol(Amo^Do,21n),Bu=rol(Asu^Du,14n),Eba=Ba^~Be&Bi^roundConstants[round],Ebe=Be^~Bi&Bo,Ebi=Bi^~Bo&Bu,Ebo=Bo^~Bu&Ba,Ebu=Bu^~Ba&Be,Ba=rol(Abo^Do,28n),Be=rol(Agu^Du,20n),Bi=rol(Aka^Da,3n),Bo=rol(Ame^De,45n),Bu=rol(Asi^Di,61n),Ega=Ba^~Be&Bi,Ege=Be^~Bi&Bo,Egi=Bi^~Bo&Bu,Ego=Bo^~Bu&Ba,Egu=Bu^~Ba&Be,Ba=rol(Abe^De,1n),Be=rol(Agi^Di,6n),Bi=rol(Ako^Do,25n),Bo=rol(Amu^Du,8n),Bu=rol(Asa^Da,18n),Eka=Ba^~Be&Bi,Eke=Be^~Bi&Bo,Eki=Bi^~Bo&Bu,Eko=Bo^~Bu&Ba,Eku=Bu^~Ba&Be,Ba=rol(Abu^Du,27n),Be=rol(Aga^Da,36n),Bi=rol(Ake^De,10n),Bo=rol(Ami^Di,15n),Bu=rol(Aso^Do,56n),Ema=Ba^~Be&Bi,Eme=Be^~Bi&Bo,Emi=Bi^~Bo&Bu,Emo=Bo^~Bu&Ba,Emu=Bu^~Ba&Be,Ba=rol(Abi^Di,62n),Be=rol(Ago^Do,55n),Bi=rol(Aku^Du,39n),Bo=rol(Ama^Da,41n),Bu=rol(Ase^De,2n),Esa=Ba^~Be&Bi,Ese=Be^~Bi&Bo,Esi=Bi^~Bo&Bu,Eso=Bo^~Bu&Ba,Esu=Bu^~Ba&Be,Ba=Eba^Ega^Eka^Ema^Esa,Be=Ebe^Ege^Eke^Eme^Ese,Bi=Ebi^Egi^Eki^Emi^Esi,Bo=Ebo^Ego^Eko^Emo^Eso,Bu=Ebu^Egu^Eku^Emu^Esu,Da=Bu^rol(Be,1n),De=Ba^rol(Bi,1n),Di=Be^rol(Bo,1n),Do=Bi^rol(Bu,1n),Du=Bo^rol(Ba,1n),Ba=Eba^Da,Be=rol(Ege^De,44n),Bi=rol(Eki^Di,43n),Bo=rol(Emo^Do,21n),Bu=rol(Esu^Du,14n),Aba=Ba^~Be&Bi^roundConstants[round+1],Abe=Be^~Bi&Bo,Abi=Bi^~Bo&Bu,Abo=Bo^~Bu&Ba,Abu=Bu^~Ba&Be,Ba=rol(Ebo^Do,28n),Be=rol(Egu^Du,20n),Bi=rol(Eka^Da,3n),Bo=rol(Eme^De,45n),Bu=rol(Esi^Di,61n),Aga=Ba^~Be&Bi,Age=Be^~Bi&Bo,Agi=Bi^~Bo&Bu,Ago=Bo^~Bu&Ba,Agu=Bu^~Ba&Be,Ba=rol(Ebe^De,1n),Be=rol(Egi^Di,6n),Bi=rol(Eko^Do,25n),Bo=rol(Emu^Du,8n),Bu=rol(Esa^Da,18n),Aka=Ba^~Be&Bi,Ake=Be^~Bi&Bo,Aki=Bi^~Bo&Bu,Ako=Bo^~Bu&Ba,Aku=Bu^~Ba&Be,Ba=rol(Ebu^Du,27n),Be=rol(Ega^Da,36n),Bi=rol(Eke^De,10n),Bo=rol(Emi^Di,15n),Bu=rol(Eso^Do,56n),Ama=Ba^~Be&Bi,Ame=Be^~Bi&Bo,Ami=Bi^~Bo&Bu,Amo=Bo^~Bu&Ba,Amu=Bu^~Ba&Be,Ba=rol(Ebi^Di,62n),Be=rol(Ego^Do,55n),Bi=rol(Eku^Du,39n),Bo=rol(Ema^Da,41n),Bu=rol(Ese^De,2n),Asa=Ba^~Be&Bi,Ase=Be^~Bi&Bo,Asi=Bi^~Bo&Bu,Aso=Bo^~Bu&Ba,Asu=Bu^~Ba&Be;return state[0]=Aba,state[1]=Abe,state[2]=Abi,state[3]=Abo,state[4]=Abu,state[5]=Aga,state[6]=Age,state[7]=Agi,state[8]=Ago,state[9]=Agu,state[10]=Aka,state[11]=Ake,state[12]=Aki,state[13]=Ako,state[14]=Aku,state[15]=Ama,state[16]=Ame,state[17]=Ami,state[18]=Amo,state[19]=Amu,state[20]=Asa,state[21]=Ase,state[22]=Asi,state[23]=Aso,state[24]=Asu,state}__name(keccakf1600,"keccakf1600");function rol(x,s2){return BigInt.asUintN(64,x<<s2)|x>>64n-s2}__name(rol,"rol");var roundConstants=[0x0000000000000001n,0x0000000000008082n,0x800000000000808an,0x8000000080008000n,0x000000000000808bn,0x0000000080000001n,0x8000000080008081n,0x8000000000008009n,0x000000000000008an,0x0000000000000088n,0x0000000080008009n,0x000000008000000an,0x000000008000808bn,0x800000000000008bn,0x8000000000008089n,0x8000000000008003n,0x8000000000008002n,0x8000000000000080n,0x000000000000800an,0x800000008000000an,0x8000000080008081n,0x8000000000008080n,0x0000000080000001n,0x8000000080008008n];var _computedKey4;_computedKey4=inspect4.custom;var EthAddress=class _EthAddress{static{__name(this,"EthAddress")}buffer;static SIZE_IN_BYTES=20;static ZERO=new _EthAddress(Buffer.alloc(_EthAddress.SIZE_IN_BYTES));constructor(buffer){if(this.buffer=buffer,buffer.length!==_EthAddress.SIZE_IN_BYTES)throw new Error(`Expect buffer size to be ${_EthAddress.SIZE_IN_BYTES}. Got ${buffer.length}.`)}static fromString(address){if(!_EthAddress.isAddress(address))throw new Error(`Invalid address string: ${address}`);return new _EthAddress(Buffer.from(address.replace(/^0x/i,""),"hex"))}static fromPlainObject(obj){return obj instanceof _EthAddress?obj:obj instanceof Buffer||Buffer.isBuffer(obj)?obj.length===20?new _EthAddress(obj):_EthAddress.fromField(new Fr(obj)):_EthAddress.fromString(obj)}static random(){return new _EthAddress(randomBytes(20))}static isAddress(address){return/^(0x)?[0-9a-f]{40}$/i.test(address)?/^(0x|0X)?[0-9a-f]{40}$/.test(address)||/^(0x|0X)?[0-9A-F]{40}$/.test(address)?!0:_EthAddress.checkAddressChecksum(address):!1}isZero(){return this.equals(_EthAddress.ZERO)}static checkAddressChecksum(address){address=address.replace(/^0x/i,"");let addressHash=keccak256String(address.toLowerCase());for(let i=0;i<40;i++)if(parseInt(addressHash[i],16)>7&&address[i].toUpperCase()!==address[i]||parseInt(addressHash[i],16)<=7&&address[i].toLowerCase()!==address[i])return!1;return!0}static toChecksumAddress(address){if(!_EthAddress.isAddress(address))throw new Error("Invalid address string.");address=address.toLowerCase().replace(/^0x/i,"");let addressHash=keccak256String(address),checksumAddress="0x";for(let i=0;i<address.length;i++)parseInt(addressHash[i],16)>7?checksumAddress+=address[i].toUpperCase():checksumAddress+=address[i];return checksumAddress}equals(rhs){return this.buffer.equals(rhs.buffer)}toString(){return bufferToHex(this.buffer)}[_computedKey4](){return`EthAddress<${this.toString()}>`}toChecksumString(){return _EthAddress.toChecksumAddress(this.buffer.toString("hex"))}toBuffer(){return this.buffer}toBuffer32(){let buffer=Buffer.alloc(32);return this.buffer.copy(buffer,12),buffer}toField(){return Fr.fromBuffer(this.toBuffer32())}static fromField(fr){return new _EthAddress(fr.toBuffer().slice(-_EthAddress.SIZE_IN_BYTES))}static fromFields(fields){let reader=FieldReader.asReader(fields);return _EthAddress.fromField(reader.readField())}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _EthAddress(reader.readBytes(_EthAddress.SIZE_IN_BYTES))}static fromNumber(num){let buffer=Buffer.alloc(_EthAddress.SIZE_IN_BYTES);return buffer.writeBigUInt64BE(BigInt(num),_EthAddress.SIZE_IN_BYTES-8),new _EthAddress(buffer)}toJSON(){return this.toString()}static get schema(){return hexSchemaFor(_EthAddress,_EthAddress.isAddress)}static areEqual(a,b){let addrA=typeof a=="string"?_EthAddress.fromString(a):a,addrB=typeof b=="string"?_EthAddress.fromString(b):b;return addrA.equals(addrB)}};import fs from"fs/promises";import{join}from"path";import{Buffer as Buffer2}from"buffer";function jsonParseWithSchema(json2,schema){return schema.parse(JSON.parse(json2))}__name(jsonParseWithSchema,"jsonParseWithSchema");function jsonStringify(obj,prettify){return JSON.stringify(obj,(_key,value)=>typeof value=="bigint"?value.toString():typeof value=="object"&&value&&value.type==="Buffer"&&Array.isArray(value.data)?Buffer2.from(value.data).toString("base64"):typeof value=="object"&&value&&Buffer2.isBuffer(value)?value.toString("base64"):typeof value=="object"&&value instanceof Map?Array.from(value.entries()):typeof value=="object"&&value instanceof Set?Array.from(value.values()):value,prettify?2:0)}__name(jsonStringify,"jsonStringify");var BadRequestError=class extends Error{static{__name(this,"BadRequestError")}constructor(message){super(message),this.name="BadRequestError"}};var inspectCustomSymbol=Symbol.for("nodejs.util.inspect.custom"),DatabaseVersion=class _DatabaseVersion{static{__name(this,"DatabaseVersion")}schemaVersion;rollupAddress;constructor(schemaVersion,rollupAddress){this.schemaVersion=schemaVersion,this.rollupAddress=rollupAddress}toBuffer(){return Buffer.from(jsonStringify(this))}static fromBuffer(buf){try{return jsonParseWithSchema(buf.toString("utf-8"),_DatabaseVersion.schema)}catch(err){throw new Error(`Failed to deserialize version information: ${err}`,{cause:err})}}cmp(other){if(this.rollupAddress.equals(other.rollupAddress))return this.schemaVersion<other.schemaVersion?-1:this.schemaVersion>other.schemaVersion?1:0}equals(other){return this.cmp(other)===0}static get schema(){return external_exports.object({schemaVersion:external_exports.number(),rollupAddress:EthAddress.schema}).transform(({schemaVersion,rollupAddress})=>new _DatabaseVersion(schemaVersion,rollupAddress))}[inspectCustomSymbol](){return this.toString()}toString(){return`DatabaseVersion{schemaVersion=${this.schemaVersion},rollupAddress=${this.rollupAddress}"}`}static empty(){return new _DatabaseVersion(0,EthAddress.ZERO)}};var DATABASE_VERSION_FILE_NAME="db_version",DatabaseVersionManager=class _DatabaseVersionManager{static{__name(this,"DatabaseVersionManager")}static VERSION_FILE=DATABASE_VERSION_FILE_NAME;versionFile;currentVersion;dataDirectory;onOpen;onUpgrade;schemaVersionMismatchPolicy;versionFileReadFailurePolicy;fileSystem;log;constructor({schemaVersion,rollupAddress,dataDirectory,onOpen,onUpgrade,schemaVersionMismatchPolicy="reset",versionFileReadFailurePolicy="reset",fileSystem=fs,log:log2=createLogger("foundation:version-manager")}){if(schemaVersion<1)throw new TypeError(`Invalid schema version received: ${schemaVersion}`);this.versionFile=join(dataDirectory,_DatabaseVersionManager.VERSION_FILE),this.currentVersion=new DatabaseVersion(schemaVersion,rollupAddress),this.dataDirectory=dataDirectory,this.onOpen=onOpen,this.onUpgrade=onUpgrade,this.schemaVersionMismatchPolicy=schemaVersionMismatchPolicy,this.versionFileReadFailurePolicy=versionFileReadFailurePolicy,this.fileSystem=fileSystem,this.log=log2}static async writeVersion(version2,dataDir,fileSystem=fs){await fileSystem.mkdir(dataDir,{recursive:!0});let finalPath=join(dataDir,_DatabaseVersionManager.VERSION_FILE),tmpPath=`${finalPath}.tmp`,handle=await fileSystem.open(tmpPath,"w");try{await handle.writeFile(version2.toBuffer()),await handle.sync()}finally{await handle.close()}await fileSystem.rename(tmpPath,finalPath);try{let dirHandle=await fileSystem.open(dataDir,"r");try{await dirHandle.sync()}finally{await dirHandle.close()}}catch{}}async open(){let storedVersion,shouldLogDataReset=!0;try{let versionBuf=await this.fileSystem.readFile(this.versionFile);storedVersion=DatabaseVersion.fromBuffer(versionBuf)}catch(err){if(err&&err.code==="ENOENT")storedVersion=DatabaseVersion.empty(),shouldLogDataReset=!1;else if(this.versionFileReadFailurePolicy==="throw"){let code=err?.code,message=err instanceof Error?err.message:String(err);throw new Error(`Failed to read database version file at ${this.versionFile} (${code??"unknown error"}: ${message}). Refusing to open the database; data was NOT reset. Resolve the underlying filesystem error and retry.`,{cause:err})}else this.log.warn(`Failed to read stored version information: ${err}. Defaulting to empty version`),storedVersion=DatabaseVersion.empty()}let cmp=storedVersion.cmp(this.currentVersion),needsReset=!1;if(typeof cmp=="number"){if(cmp===-1&&this.onUpgrade){this.log.info(`Upgrading from version ${storedVersion.schemaVersion} to ${this.currentVersion.schemaVersion}`);try{await this.onUpgrade(this.dataDirectory,storedVersion.schemaVersion,this.currentVersion.schemaVersion)}catch(error2){if(this.schemaVersionMismatchPolicy==="throw")throw new Error(`Failed to upgrade database at ${this.dataDirectory} from schema version ${storedVersion.schemaVersion} to ${this.currentVersion.schemaVersion}`,{cause:error2});this.log.error(`Failed to upgrade: ${error2}. Falling back to reset.`),needsReset=!0}}else if(cmp!==0){if(this.schemaVersionMismatchPolicy==="throw")throw new Error(`Cannot open database at ${this.dataDirectory}: stored schema version ${storedVersion.schemaVersion} is incompatible with expected schema version ${this.currentVersion.schemaVersion}`);shouldLogDataReset&&this.log.info(`Can't upgrade from version ${storedVersion} to ${this.currentVersion}. Resetting database at ${this.dataDirectory}`),needsReset=!0}}else shouldLogDataReset&&this.log.warn("Rollup address has changed, resetting data directory",{versionFile:this.versionFile,storedVersion,currentVersion:this.currentVersion}),needsReset=!0;needsReset&&await this.resetDataDirectory();let instance=await this.onOpen(this.dataDirectory);if(!storedVersion.equals(this.currentVersion))try{await this.writeVersion()}catch(err){throw await this.closeQuietly(instance),err}return[instance,needsReset]}async closeQuietly(instance){let closable=instance,dispose=closable?.close??closable?.[Symbol.asyncDispose];if(typeof dispose=="function")try{await dispose.call(closable)}catch(err){this.log.warn(`Failed to close database after version-write failure: ${err}`)}}writeVersion(dir){return _DatabaseVersionManager.writeVersion(this.currentVersion,dir??this.dataDirectory,this.fileSystem)}async resetDataDirectory(){try{await this.fileSystem.rm(this.dataDirectory,{recursive:!0,force:!0,maxRetries:3}),await this.fileSystem.mkdir(this.dataDirectory,{recursive:!0})}catch(err){throw this.log.error(`Failed to reset data directory: ${err}`),new Error(`Failed to reset data directory: ${err}`,{cause:err})}}getDataDirectory(){return this.dataDirectory}getSchemaVersion(){return this.currentVersion.schemaVersion}};import{copyFile,mkdir as mkdir2,mkdtemp,rm as rm2}from"fs/promises";import{tmpdir}from"os";import{join as join2}from"path";var MAX_READERS=16;async function openEphemeralStore(name,dbMapSizeKb=10*1024*1024,maxReaders=MAX_READERS,bindings){let log2=createLogger("kv-store:lmdb-v2:"+name,bindings),dataDir=await mkdtemp(join2(tmpdir(),name+"-"));log2.debug(`Created ephemeral data store at: ${dataDir} with size: ${dbMapSizeKb} KB (LMDB v2)`);let cleanup=__name(async()=>{try{await rm2(dataDir,{recursive:!0,force:!0,maxRetries:3}),log2.debug(`Deleted ephemeral data store: ${dataDir}`)}catch(err){log2.warn(`Failed to delete ephemeral data directory (LMDB v2) ${dataDir}: ${err}`)}},"cleanup");return AztecLMDBStoreV2.new(dataDir,dbMapSizeKb,maxReaders,cleanup,bindings,!0)}__name(openEphemeralStore,"openEphemeralStore");async function cloneEphemeralStoreFrom(srcDataMdbPath,name,dbMapSizeKb=10*1024*1024,maxReaders=MAX_READERS,bindings){let log2=createLogger("kv-store:lmdb-v2:"+name,bindings),dataDir=await mkdtemp(join2(tmpdir(),name+"-"));await copyFile(srcDataMdbPath,join2(dataDir,"data.mdb")),log2.debug(`Cloned ephemeral data store at: ${dataDir} from ${srcDataMdbPath} (LMDB v2)`);let cleanup=__name(async()=>{try{await rm2(dataDir,{recursive:!0,force:!0,maxRetries:3}),log2.debug(`Deleted ephemeral data store: ${dataDir}`)}catch(err){log2.warn(`Failed to delete ephemeral data directory (LMDB v2) ${dataDir}: ${err}`)}},"cleanup");return AztecLMDBStoreV2.new(dataDir,dbMapSizeKb,maxReaders,cleanup,bindings,!0)}__name(cloneEphemeralStoreFrom,"cloneEphemeralStoreFrom");var DateProvider=class{static{__name(this,"DateProvider")}now(){return Date.now()}nowInSeconds(){return Math.floor(this.now()/1e3)}nowAsDate(){return new Date(this.now())}},TestDateProvider=class extends DateProvider{static{__name(this,"TestDateProvider")}logger;offset;constructor(logger3=createLogger("foundation:test-date-provider")){super(),this.logger=logger3,this.offset=0}now(){return Date.now()+this.offset}setTime(timeMs){this.offset=timeMs-Date.now(),this.logger.warn(`Time set to ${new Date(timeMs).toISOString()}`,{offset:this.offset,timeMs})}reset(){this.offset=0,this.logger.warn("Time reset to real time")}advanceTime(seconds){this.offset+=seconds*1e3}};var Timer=class{static{__name(this,"Timer")}start;constructor(){this.start=performance?performance.now():Date.now()}us(){return this.ms()*1e3}ms(){return(performance?performance.now():Date.now())-this.start}s(){return this.ms()/1e3}};async function elapsed(fn){let timer=new Timer,result=await(typeof fn=="function"?fn():fn);return[timer.ms(),result]}__name(elapsed,"elapsed");function defaultSignalError(signal){return signal.reason instanceof Error?signal.reason:new Error(signal.reason?String(signal.reason):"Operation aborted")}__name(defaultSignalError,"defaultSignalError");async function execWithSignal(fn,signal,errorFn=defaultSignalError){if(signal.aborted)throw errorFn(signal);let abortPromise=promiseWithResolvers(),abortListener=__name(()=>abortPromise.reject(errorFn(signal)),"abortListener");signal.addEventListener("abort",abortListener,{once:!0});try{return await Promise.race([fn(signal),abortPromise.promise])}finally{abortListener&&signal.removeEventListener("abort",abortListener)}}__name(execWithSignal,"execWithSignal");function schemaHasMethod(schema,methodName){return typeof methodName=="string"&&Object.hasOwn(schema,methodName)&&schema[methodName].def.input!==void 0&&schema[methodName].def.output!==void 0}__name(schemaHasMethod,"schemaHasMethod");function getSchemaParameters(schema){return schema.def.input}__name(getSchemaParameters,"getSchemaParameters");function parseWithOptionals(args,schema){let items=schema.def.items,missingCount=items.length-args.length,optionalCount=items.filter(isOptional).length,toParse=missingCount>0&&missingCount<=optionalCount?args.concat(times(missingCount,()=>{})):args;return schema.parseAsync(toParse)}__name(parseWithOptionals,"parseWithOptionals");function isOptional(schema){try{return schema.isOptional()}catch{return schema.def.type==="optional"}}__name(isOptional,"isOptional");function zodFor(){return schema=>schema}__name(zodFor,"zodFor");import{inspect as inspect5}from"util";var _computedKey5;_computedKey5=inspect5.custom;var SecretValue=class _SecretValue{static{__name(this,"SecretValue")}redactedValue;#value;constructor(value,redactedValue="[Redacted]"){this.redactedValue=redactedValue,this.#value=value}getValue(){return this.#value}toString(){return this.redactedValue}toJSON(){return this.redactedValue}[_computedKey5](){return this.toString()}static schema(valueSchema){return valueSchema.transform(value=>new _SecretValue(value))}};var schemas={EpochNumber:EpochNumberSchema,SlotNumber:SlotNumberSchema,EthAddress:EthAddress.schema,Fr:Fr.schema,Fq:Fq.schema,Point:Point.schema,Boolean:external_exports.union([external_exports.boolean(),external_exports.number().refine(arg=>arg===0||arg===1,{message:"Numeric value for a boolean variable must be 0 or 1"}).transform(arg=>arg===1),external_exports.string().transform(arg=>arg.trim().toLowerCase()).refine(arg=>["true","false","1","0"].includes(arg)).transform(arg=>arg==="1"||arg==="true")]),BigInt:external_exports.union([external_exports.bigint(),external_exports.number(),external_exports.string()]).pipe(external_exports.coerce.bigint()),Integer:external_exports.union([external_exports.bigint(),external_exports.number(),external_exports.string()]).pipe(external_exports.coerce.number().int()),UInt32:external_exports.union([external_exports.bigint(),external_exports.number(),external_exports.string()]).pipe(external_exports.coerce.number().int().min(0).max(2**32-1)),UInt64:external_exports.union([external_exports.bigint(),external_exports.number(),external_exports.string()]).pipe(external_exports.coerce.bigint().min(0n).max(2n**64n-1n)),Buffer32:external_exports.string().refine(isHex,"Not a valid hex string").transform(Buffer32.fromString),Buffer:bufferSchema,BufferHex:external_exports.string().refine(isHex,"Not a valid hex string").transform(withoutHexPrefix).transform(data=>Buffer.from(data,"hex")),HexString:hexSchema,HexStringWith0x:external_exports.string().refine(isHex,"Not a valid hex string").transform(withHexPrefix),SecretValue:SecretValue.schema};import{inflate}from"pako";import{Barretenberg,BarretenbergSync as BarretenbergSync3}from"@aztec/bb.js";var IS_BROWSER=typeof self<"u";async function poseidon2HashFields(inputFields){if(IS_BROWSER){await BarretenbergSync3.initSingleton();let response=BarretenbergSync3.getSingleton().poseidon2Hash({inputs:inputFields.map(i=>i.toBuffer())});return Fr.fromBuffer(Buffer.from(response.hash))}else{await Barretenberg.initSingleton();let response=await Barretenberg.getSingleton().poseidon2Hash({inputs:inputFields.map(i=>i.toBuffer())});return Fr.fromBuffer(Buffer.from(response.hash))}}__name(poseidon2HashFields,"poseidon2HashFields");function poseidon2Hash(input){return poseidon2HashFields(serializeToFields(input))}__name(poseidon2Hash,"poseidon2Hash");function poseidon2HashWithSeparator(input,separator){let inputFields=serializeToFields(input);return inputFields.unshift(new Fr(separator)),poseidon2HashFields(inputFields)}__name(poseidon2HashWithSeparator,"poseidon2HashWithSeparator");async function poseidon2Permutation(input){let inputFields=serializeToFields(input);return IS_BROWSER?(await BarretenbergSync3.initSingleton(),BarretenbergSync3.getSingleton().poseidon2Permutation({inputs:inputFields.map(i=>i.toBuffer())}).outputs.map(o=>Fr.fromBuffer(Buffer.from(o)))):(await Barretenberg.initSingleton(),(await Barretenberg.getSingleton().poseidon2Permutation({inputs:inputFields.map(i=>i.toBuffer())})).outputs.map(o=>Fr.fromBuffer(Buffer.from(o))))}__name(poseidon2Permutation,"poseidon2Permutation");function poseidon2HashBytes(input){let inputFields=[];for(let i=0;i<input.length;i+=31){let fieldBytes=Buffer.alloc(32,0);input.slice(i,i+31).copy(fieldBytes),fieldBytes.reverse(),inputFields.push(Fr.fromBuffer(fieldBytes))}return poseidon2HashFields(inputFields)}__name(poseidon2HashBytes,"poseidon2HashBytes");var FunctionSignatureDecoder=class{static{__name(this,"FunctionSignatureDecoder")}name;parameters;includeNames;separator;constructor(name,parameters,includeNames=!1){this.name=name,this.parameters=parameters,this.includeNames=includeNames,this.separator=includeNames?", ":","}getParameterType(param){switch(param.kind){case"field":return"Field";case"integer":return param.sign==="signed"?`i${param.width}`:`u${param.width}`;case"boolean":return"bool";case"array":return`[${this.getParameterType(param.type)};${param.length}]`;case"string":return`str<${param.length}>`;case"struct":return`(${param.fields.map(field=>`${this.decodeParameter(field)}`).join(this.separator)})`;default:throw new Error(`Unsupported type: ${param.kind}`)}}decodeParameter(param){let type=this.getParameterType(param.type);return this.includeNames?`${param.name}: ${type}`:type}decode(){return`${this.name}(${this.parameters.map(param=>this.decodeParameter(param)).join(this.separator)})`}};function decodeFunctionSignature(name,parameters){return new FunctionSignatureDecoder(name,parameters).decode()}__name(decodeFunctionSignature,"decodeFunctionSignature");import{inspect as inspect6}from"util";var _computedKey6;_computedKey6=inspect6.custom;var Selector=class _Selector{static{__name(this,"Selector")}value;static SIZE=4;constructor(value){if(this.value=value,value>2**(_Selector.SIZE*8)-1)throw new Error(`Selector must fit in ${_Selector.SIZE} bytes (got value ${value}).`)}isEmpty(){return this.value===0}toBuffer(bufferSize=_Selector.SIZE){return toBufferBE(BigInt(this.value),bufferSize)}toString(){return bufferToHex(this.toBuffer())}[_computedKey6](){return`Selector<${this.toString()}>`}equals(other){return this.value===other.value}toField(){return new Fr(BigInt(this.value))}};var FunctionSelector=class _FunctionSelector extends Selector{static{__name(this,"FunctionSelector")}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer),value=Number(toBigIntBE(reader.readBytes(Selector.SIZE)));return new _FunctionSelector(value)}static fromField(fr){return new _FunctionSelector(Number(fr.toBigInt()))}static fromFieldOrUndefined(fr){try{return _FunctionSelector.fromField(fr)}catch{return}}static fromFields(fields){let reader=FieldReader.asReader(fields);return _FunctionSelector.fromField(reader.readField())}static async fromSignature(signature){if(/\s/.test(signature))throw new Error("Signature cannot contain whitespace");let bytes=(await poseidon2HashBytes(Buffer.from(signature))).toBuffer().slice(-Selector.SIZE);return _FunctionSelector.fromBuffer(bytes)}static fromString(selector){let buf=fromHex(selector);if(buf.length!==Selector.SIZE)throw new Error(`Invalid FunctionSelector length ${buf.length} (expected ${Selector.SIZE}).`);return _FunctionSelector.fromBuffer(buf)}static empty(){return new _FunctionSelector(0)}static async fromNameAndParameters(nameOrArgs,maybeParameters){let{name,parameters}=typeof nameOrArgs=="string"?{name:nameOrArgs,parameters:maybeParameters}:nameOrArgs,signature=decodeFunctionSignature(name,parameters);return await this.fromSignature(signature)}static random(){return _FunctionSelector.fromBuffer(randomBytes(Selector.SIZE))}toJSON(){return this.toString()}static get schema(){return hexSchemaFor(_FunctionSelector)}};var logger2=createLogger("aztec:foundation:abi"),AbiValueSchema=external_exports.discriminatedUnion("kind",[external_exports.object({kind:external_exports.literal("boolean"),value:external_exports.boolean()}),external_exports.object({kind:external_exports.literal("string"),value:external_exports.string()}),external_exports.object({kind:external_exports.literal("array"),value:external_exports.array(external_exports.lazy(()=>AbiValueSchema))}),external_exports.object({kind:external_exports.literal("tuple"),fields:external_exports.array(external_exports.lazy(()=>AbiValueSchema))}),external_exports.object({kind:external_exports.literal("integer"),value:external_exports.string(),sign:external_exports.boolean()}),external_exports.object({kind:external_exports.literal("struct"),fields:external_exports.array(external_exports.object({name:external_exports.string(),value:external_exports.lazy(()=>AbiValueSchema)}))})]),ABIParameterVisibility=["public","private","databus"],Sign=["unsigned","signed"],AbiTypeSchema=external_exports.discriminatedUnion("kind",[external_exports.object({kind:external_exports.literal("field")}),external_exports.object({kind:external_exports.literal("boolean")}),external_exports.object({kind:external_exports.literal("integer"),sign:external_exports.enum(Sign),width:external_exports.number()}),external_exports.object({kind:external_exports.literal("array"),length:external_exports.number(),type:external_exports.lazy(()=>AbiTypeSchema)}),external_exports.object({kind:external_exports.literal("string"),length:external_exports.number()}),external_exports.object({kind:external_exports.literal("struct"),fields:external_exports.array(external_exports.lazy(()=>ABIVariableSchema)),path:external_exports.string()}),external_exports.object({kind:external_exports.literal("tuple"),fields:external_exports.array(external_exports.lazy(()=>AbiTypeSchema))})]),ABIVariableSchema=external_exports.object({name:external_exports.string(),type:AbiTypeSchema}),ABIParameterSchema=ABIVariableSchema.and(external_exports.object({visibility:external_exports.enum(ABIParameterVisibility)})),AbiErrorTypeSchema=zodFor()(external_exports.union([external_exports.object({error_kind:external_exports.literal("string"),string:external_exports.string()}),external_exports.object({error_kind:external_exports.literal("fmtstring"),length:external_exports.number(),item_types:external_exports.array(AbiTypeSchema)}),external_exports.object({error_kind:external_exports.literal("custom")}).and(AbiTypeSchema)])),FunctionType=(function(FunctionType2){return FunctionType2.PRIVATE="private",FunctionType2.PUBLIC="public",FunctionType2.UTILITY="utility",FunctionType2})({}),FunctionAbiSchema=external_exports.object({name:external_exports.string(),functionType:external_exports.nativeEnum(FunctionType),isOnlySelf:external_exports.boolean(),isStatic:external_exports.boolean(),isInitializer:external_exports.boolean(),parameters:external_exports.array(external_exports.object({name:external_exports.string(),type:AbiTypeSchema,visibility:external_exports.enum(ABIParameterVisibility)})),returnTypes:external_exports.array(AbiTypeSchema),errorTypes:external_exports.record(external_exports.string(),AbiErrorTypeSchema.optional())}),FunctionDebugMetadataSchema=external_exports.object({debugSymbols:external_exports.object({location_tree:external_exports.object({locations:external_exports.array(external_exports.object({parent:external_exports.number().nullable(),value:external_exports.object({span:external_exports.object({start:external_exports.number(),end:external_exports.number()}),file:external_exports.number()})}))}),acir_locations:external_exports.record(external_exports.string(),external_exports.number()),brillig_locations:external_exports.record(external_exports.string(),external_exports.record(external_exports.string(),external_exports.number()))}),files:external_exports.record(external_exports.string(),external_exports.object({source:external_exports.string(),path:external_exports.string(),function_locations:external_exports.array(external_exports.object({start:external_exports.number(),name:external_exports.string()}))}))}),FunctionArtifactSchema=zodFor()(FunctionAbiSchema.and(external_exports.object({bytecode:schemas.Buffer,verificationKey:external_exports.string().optional(),debugSymbols:external_exports.string(),debug:FunctionDebugMetadataSchema.optional()}))),ARTIFACT_VERSION_BEFORE_INJECTION="FROM_RELEASE_BEFORE_VERSION_INJECTION",ContractArtifactSchema=zodFor()(external_exports.object({name:external_exports.string(),aztecVersion:external_exports.string().default(ARTIFACT_VERSION_BEFORE_INJECTION),functions:external_exports.array(FunctionArtifactSchema),nonDispatchPublicFunctions:external_exports.array(FunctionAbiSchema),outputs:external_exports.object({structs:external_exports.record(external_exports.string(),external_exports.array(AbiTypeSchema)).transform(structs=>{for(let[key,value]of Object.entries(structs))(key==="events"||key==="functions")&&(structs[key]=value.sort((a,b)=>a.path>b.path?-1:1));return structs}),globals:external_exports.record(external_exports.string(),external_exports.array(AbiValueSchema))}),storageLayout:external_exports.record(external_exports.string(),external_exports.object({slot:schemas.Fr})),fileMap:external_exports.record(external_exports.coerce.number(),external_exports.object({source:external_exports.string(),path:external_exports.string(),function_locations:external_exports.array(external_exports.object({start:external_exports.number(),name:external_exports.string()}))}))}));async function findFunctionArtifactBySelector(artifact,selector){return(await Promise.all(artifact.functions.map(async fn=>({fn,selector:await FunctionSelector.fromNameAndParameters(fn.name,fn.parameters)})))).find(({selector:s2})=>s2.equals(selector))?.fn}__name(findFunctionArtifactBySelector,"findFunctionArtifactBySelector");async function findFunctionAbiBySelector(artifact,selector){return(await Promise.all(getAllFunctionAbis(artifact).map(async fn=>({fn,selector:await FunctionSelector.fromNameAndParameters(fn.name,fn.parameters)})))).find(({selector:s2})=>s2.equals(selector))?.fn}__name(findFunctionAbiBySelector,"findFunctionAbiBySelector");function getAllFunctionAbis(artifact){return artifact.functions.map(f=>f).concat(artifact.nonDispatchPublicFunctions||[])}__name(getAllFunctionAbis,"getAllFunctionAbis");function parseDebugSymbols(debugSymbols){return JSON.parse(inflate(Buffer.from(debugSymbols,"base64"),{to:"string",raw:!0})).debug_infos}__name(parseDebugSymbols,"parseDebugSymbols");function getFunctionDebugMetadata(contractArtifact,functionArtifact){try{if(functionArtifact.debugSymbols&&contractArtifact.fileMap)return{debugSymbols:parseDebugSymbols(functionArtifact.debugSymbols)[0],files:contractArtifact.fileMap}}catch(err){if(err instanceof RangeError&&err.message.includes("Invalid string length"))logger2.warn(`Caught RangeError: Invalid string length. This suggests the debug_symbols field of the contract ${contractArtifact.name} and function ${functionArtifact.name} is huge; too big to parse. We'll skip returning this info until this issue is resolved. Here's the error:
|
|
89
89
|
${err.message}`);else throw err}}__name(getFunctionDebugMetadata,"getFunctionDebugMetadata");function getDefaultInitializer(contractArtifact){let initializers=getAllFunctionAbis(contractArtifact).filter(f=>f.isInitializer);return initializers.length>1?initializers.find(f=>f.name==="constructor")??initializers.find(f=>f.name==="initializer")??initializers.find(f=>f.parameters?.length===0)??initializers.find(f=>f.functionType==="private")??initializers[0]:initializers[0]}__name(getDefaultInitializer,"getDefaultInitializer");var import_lodash=__toESM(require_lodash(),1);function bufferAsFields(input,targetLength){let encoded=[new Fr(input.length),...(0,import_lodash.default)(input,Fr.SIZE_IN_BYTES-1).map(c2=>{let fieldBytes=Buffer.alloc(Fr.SIZE_IN_BYTES);return Buffer.from(c2).copy(fieldBytes,1),Fr.fromBuffer(fieldBytes)})];if(encoded.length>targetLength)throw new Error(`Input buffer exceeds maximum size: got ${encoded.length} but max is ${targetLength}`);return[...encoded,...Array(targetLength-encoded.length).fill(Fr.ZERO)]}__name(bufferAsFields,"bufferAsFields");function bufferFromFields(fields,maxByteLength){if(fields.length===0)return Buffer.alloc(0);let[length,...payload]=fields,byteLength=length.toNumber();if(maxByteLength!==void 0&&byteLength>maxByteLength)throw new Error(`Declared byte length ${byteLength} exceeds maximum ${maxByteLength}`);let raw=Buffer.concat(payload.map(f=>f.toBuffer().subarray(1)));if(raw.length>=byteLength)return raw.subarray(0,byteLength);let result=Buffer.alloc(byteLength);return raw.copy(result),result}__name(bufferFromFields,"bufferFromFields");var MAX_ETH_ADDRESS_VALUE=1461501637330902918203684832716283019655932542975n;var GENESIS_BLOCK_HEADER_HASH=6551417544883665873456328017782433997345264442591862482015827744892259451090n,GENESIS_ARCHIVE_ROOT=10619256997260439436842531499967995403253967496480475679746178797053672406517n;var CONTRACT_CLASS_PUBLISHED_MAGIC_VALUE=14907836659448373306373608164128296596488873008270905914742877230397948162628n;var CONTRACT_INSTANCE_UPDATED_MAGIC_VALUE=20721543224513346060908370400407150739273836456436647488068002302723900469047n;var NULL_MSG_SENDER_CONTRACT_ADDRESS=21888242871839275222246405745257275088548364400416034343698204186575808495616n;var DEFAULT_IVPK_M_X=339708709767762472786445938838804872781183545349360029270386718856175781484n,DEFAULT_IVPK_M_Y=12719619215050539905199178334954929730355853796706924300730604757520758976849n;var DEFAULT_NPK_M_HASH=9490941203163884203266873379528043162885952552009707050511473783876867365414n,DEFAULT_OVPK_M_HASH=6503635668323258394266152634006889881423098283582185344306514598322956522059n,DEFAULT_TPK_M_HASH=3696996950890211715833095099359687729113787313245035143274671977290400579312n,DEFAULT_MSPK_M_HASH=9339255027081995322829531434846677508514443987752207871815765570767379563350n,DEFAULT_FBPK_M_HASH=6817041416194035981444514907304573239615033139388669881213007796289638159510n;var TWO_POW_64=18446744073709551616n;var DomainSeparator=(function(DomainSeparator2){return DomainSeparator2[DomainSeparator2.NOTE_HASH=116501019]="NOTE_HASH",DomainSeparator2[DomainSeparator2.PARTIAL_NOTE_COMMITMENT=568912195]="PARTIAL_NOTE_COMMITMENT",DomainSeparator2[DomainSeparator2.SILOED_NOTE_HASH=3361878420]="SILOED_NOTE_HASH",DomainSeparator2[DomainSeparator2.UNIQUE_NOTE_HASH=226850429]="UNIQUE_NOTE_HASH",DomainSeparator2[DomainSeparator2.NOTE_HASH_NONCE=1721808740]="NOTE_HASH_NONCE",DomainSeparator2[DomainSeparator2.SINGLE_USE_CLAIM_NULLIFIER=1465998995]="SINGLE_USE_CLAIM_NULLIFIER",DomainSeparator2[DomainSeparator2.NOTE_NULLIFIER=50789342]="NOTE_NULLIFIER",DomainSeparator2[DomainSeparator2.SILOED_NULLIFIER=57496191]="SILOED_NULLIFIER",DomainSeparator2[DomainSeparator2.MESSAGE_NULLIFIER=3754509616]="MESSAGE_NULLIFIER",DomainSeparator2[DomainSeparator2.EVENT_LOG_TAG=926040838]="EVENT_LOG_TAG",DomainSeparator2[DomainSeparator2.NOTE_COMPLETION_LOG_TAG=3372669888]="NOTE_COMPLETION_LOG_TAG",DomainSeparator2[DomainSeparator2.UNCONSTRAINED_MSG_LOG_TAG=1485357192]="UNCONSTRAINED_MSG_LOG_TAG",DomainSeparator2[DomainSeparator2.CONSTRAINED_MSG_LOG_TAG=3715244738]="CONSTRAINED_MSG_LOG_TAG",DomainSeparator2[DomainSeparator2.CONSTRAINED_MSG_NULLIFIER=3723577546]="CONSTRAINED_MSG_NULLIFIER",DomainSeparator2[DomainSeparator2.CONSTRAINED_MSG_SENDER_SECRET=1182889476]="CONSTRAINED_MSG_SENDER_SECRET",DomainSeparator2[DomainSeparator2.NON_INTERACTIVE_HANDSHAKE_LOG_TAG=4046403018]="NON_INTERACTIVE_HANDSHAKE_LOG_TAG",DomainSeparator2[DomainSeparator2.INTERACTIVE_HANDSHAKE_SIGNATURE=3098455647]="INTERACTIVE_HANDSHAKE_SIGNATURE",DomainSeparator2[DomainSeparator2.PRIVATE_LOG_FIRST_FIELD=2769976252]="PRIVATE_LOG_FIRST_FIELD",DomainSeparator2[DomainSeparator2.PUBLIC_LEAF_SLOT=1247650290]="PUBLIC_LEAF_SLOT",DomainSeparator2[DomainSeparator2.PUBLIC_STORAGE_MAP_SLOT=4015149901]="PUBLIC_STORAGE_MAP_SLOT",DomainSeparator2[DomainSeparator2.MERKLE_HASH=2982624097]="MERKLE_HASH",DomainSeparator2[DomainSeparator2.NULLIFIER_MERKLE=1157584160]="NULLIFIER_MERKLE",DomainSeparator2[DomainSeparator2.PUBLIC_DATA_MERKLE=3756303423]="PUBLIC_DATA_MERKLE",DomainSeparator2[DomainSeparator2.WRITTEN_SLOTS_MERKLE=2292766212]="WRITTEN_SLOTS_MERKLE",DomainSeparator2[DomainSeparator2.RETRIEVED_BYTECODES_MERKLE=2789215184]="RETRIEVED_BYTECODES_MERKLE",DomainSeparator2[DomainSeparator2.PRIVATE_FUNCTION_LEAF=1389398688]="PRIVATE_FUNCTION_LEAF",DomainSeparator2[DomainSeparator2.PUBLIC_BYTECODE=260313585]="PUBLIC_BYTECODE",DomainSeparator2[DomainSeparator2.CONTRACT_CLASS_ID=3923495515]="CONTRACT_CLASS_ID",DomainSeparator2[DomainSeparator2.SALTED_INITIALIZATION_HASH=2763052992]="SALTED_INITIALIZATION_HASH",DomainSeparator2[DomainSeparator2.INITIALIZER=385396519]="INITIALIZER",DomainSeparator2[DomainSeparator2.NHK_M=242137788]="NHK_M",DomainSeparator2[DomainSeparator2.IVSK_M=2747825907]="IVSK_M",DomainSeparator2[DomainSeparator2.OVSK_M=4272201051]="OVSK_M",DomainSeparator2[DomainSeparator2.TSK_M=1546190975]="TSK_M",DomainSeparator2[DomainSeparator2.MSSK_M=617962565]="MSSK_M",DomainSeparator2[DomainSeparator2.FBSK_M=787738027]="FBSK_M",DomainSeparator2[DomainSeparator2.PUBLIC_KEYS_HASH=777457226]="PUBLIC_KEYS_HASH",DomainSeparator2[DomainSeparator2.SINGLE_PUBLIC_KEY_HASH=3452068255]="SINGLE_PUBLIC_KEY_HASH",DomainSeparator2[DomainSeparator2.PARTIAL_ADDRESS=2103633018]="PARTIAL_ADDRESS",DomainSeparator2[DomainSeparator2.CONTRACT_ADDRESS_V2=4099338721]="CONTRACT_ADDRESS_V2",DomainSeparator2[DomainSeparator2.BLOCK_HEADER_HASH=4195546849]="BLOCK_HEADER_HASH",DomainSeparator2[DomainSeparator2.TX_REQUEST=3763737512]="TX_REQUEST",DomainSeparator2[DomainSeparator2.PUBLIC_TX_HASH=1630108851]="PUBLIC_TX_HASH",DomainSeparator2[DomainSeparator2.PRIVATE_TX_HASH=1971680439]="PRIVATE_TX_HASH",DomainSeparator2[DomainSeparator2.PUBLIC_CALLDATA=2760353947]="PUBLIC_CALLDATA",DomainSeparator2[DomainSeparator2.FUNCTION_ARGS=3576554347]="FUNCTION_ARGS",DomainSeparator2[DomainSeparator2.PROTOCOL_CONTRACTS=3904434327]="PROTOCOL_CONTRACTS",DomainSeparator2[DomainSeparator2.EVENT_COMMITMENT=2517418573]="EVENT_COMMITMENT",DomainSeparator2[DomainSeparator2.AUTHWIT_INNER=221354163]="AUTHWIT_INNER",DomainSeparator2[DomainSeparator2.AUTHWIT_OUTER=3283595782]="AUTHWIT_OUTER",DomainSeparator2[DomainSeparator2.AUTHWIT_NULLIFIER=1239150694]="AUTHWIT_NULLIFIER",DomainSeparator2[DomainSeparator2.APP_SILOED_ECDH_SHARED_SECRET=1707851664]="APP_SILOED_ECDH_SHARED_SECRET",DomainSeparator2[DomainSeparator2.ECDH_SUBKEY=4277646631]="ECDH_SUBKEY",DomainSeparator2[DomainSeparator2.ECDH_FIELD_MASK=190532684]="ECDH_FIELD_MASK",DomainSeparator2[DomainSeparator2.PARTIAL_NOTE_VALIDITY_COMMITMENT=623934423]="PARTIAL_NOTE_VALIDITY_COMMITMENT",DomainSeparator2[DomainSeparator2.INITIALIZATION_NULLIFIER=1653084894]="INITIALIZATION_NULLIFIER",DomainSeparator2[DomainSeparator2.PUBLIC_INITIALIZATION_NULLIFIER=3342006647]="PUBLIC_INITIALIZATION_NULLIFIER",DomainSeparator2[DomainSeparator2.PRIVATE_INITIALIZATION_NULLIFIER=3990889078]="PRIVATE_INITIALIZATION_NULLIFIER",DomainSeparator2[DomainSeparator2.SECRET_HASH=4199652938]="SECRET_HASH",DomainSeparator2[DomainSeparator2.TX_NULLIFIER=1025801951]="TX_NULLIFIER",DomainSeparator2[DomainSeparator2.SIGNATURE_PAYLOAD=463525807]="SIGNATURE_PAYLOAD",DomainSeparator2[DomainSeparator2.BLOCK_HEADERS_HASH=515582467]="BLOCK_HEADERS_HASH",DomainSeparator2[DomainSeparator2.BLOB_HASHED_Y_LIMBS=2949331415]="BLOB_HASHED_Y_LIMBS",DomainSeparator2[DomainSeparator2.BLOB_CHALLENGE_Z=60345710]="BLOB_CHALLENGE_Z",DomainSeparator2[DomainSeparator2.BLOB_Z_ACC=1003392952]="BLOB_Z_ACC",DomainSeparator2[DomainSeparator2.BLOB_GAMMA_ACC=855632775]="BLOB_GAMMA_ACC",DomainSeparator2[DomainSeparator2.BLOB_GAMMA_FINAL=1755883835]="BLOB_GAMMA_FINAL",DomainSeparator2})({});var SPONSORED_FPC_SALT=BigInt(0);var MAX_TX_DA_GAS=8475*32,INITIAL_L2_BLOCK_NUM2=BlockNumber(1),INITIAL_CHECKPOINT_NUMBER2=CheckpointNumber(1),GENESIS_BLOCK_HEADER_HASH2=new Fr(GENESIS_BLOCK_HEADER_HASH),MAX_PROCESSABLE_DA_GAS_PER_CHECKPOINT2=786432;import{inspect as inspect7}from"util";var _computedKey7;_computedKey7=inspect7.custom;var AztecAddress=class _AztecAddress{static{__name(this,"AztecAddress")}xCoord;constructor(buffer){if("length"in buffer&&buffer.length!==32)throw new Error(`Invalid AztecAddress length ${buffer.length}.`);this.xCoord=new Fr(buffer)}[_computedKey7](){return`AztecAddress<${this.toString()}>`}static isAddress(str){return/^(0x)?[a-fA-F0-9]{64}$/.test(str)}static SIZE_IN_BYTES=Fr.SIZE_IN_BYTES;static ZERO=new _AztecAddress(Buffer.alloc(32,0));static NULL_MSG_SENDER=_AztecAddress.fromBigIntUnsafe(NULL_MSG_SENDER_CONTRACT_ADDRESS);static zero(){return _AztecAddress.ZERO}static fromFieldUnsafe(fr){return new _AztecAddress(fr)}static fromBuffer(buffer){return new _AztecAddress(fromBuffer(buffer,Fr))}static fromFields(fields){let reader=FieldReader.asReader(fields);return new _AztecAddress(reader.readField())}static fromBigIntUnsafe(value){return new _AztecAddress(new Fr(value))}static fromNumberUnsafe(value){return new _AztecAddress(new Fr(value))}static fromStringUnsafe(buf){return new _AztecAddress(hexToBuffer(buf))}static fromPlainObject(obj){return obj instanceof _AztecAddress?obj:obj instanceof Buffer||Buffer.isBuffer(obj)?new _AztecAddress(obj):_AztecAddress.fromStringUnsafe(obj)}static async random(){for(;;){let candidate=new _AztecAddress(Fr.random());if(await candidate.isValid())return candidate}}get size(){return this.xCoord.size}equals(other){return this.xCoord.equals(other.xCoord)}isZero(){return this.xCoord.isZero()}async isValid(){return await Point.YFromX(this.xCoord)!==null}toAddressPoint(){return Point.fromXAndSign(this.xCoord,!0)}toBuffer(sink){if(!sink)return this.xCoord.toBuffer();this.xCoord.toBuffer(sink)}toBigInt(){return this.xCoord.toBigInt()}toField(){return this.xCoord}toString(){return this.xCoord.toString()}toJSON(){return this.toString()}static get schema(){return external_exports.union([hexSchemaFor(_AztecAddress,_AztecAddress.isAddress),bufferSchemaFor(_AztecAddress,buf=>buf.length===32)])}};function isAddressStruct(abiType){return isEthAddressStruct(abiType)||isAztecAddressStruct(abiType)}__name(isAddressStruct,"isAddressStruct");function isEthAddressStruct(abiType){return abiType.kind==="struct"&&abiType.path.endsWith("address::EthAddress")}__name(isEthAddressStruct,"isEthAddressStruct");function isAztecAddressStruct(abiType){return abiType.kind==="struct"&&abiType.path.endsWith("address::AztecAddress")}__name(isAztecAddressStruct,"isAztecAddressStruct");function isFunctionSelectorStruct(abiType){return abiType.kind==="struct"&&abiType.path.endsWith("types::abis::function_selector::FunctionSelector")}__name(isFunctionSelectorStruct,"isFunctionSelectorStruct");function isWrappedFieldStruct(abiType){return abiType.kind==="struct"&&abiType.fields.length===1&&abiType.fields[0].name==="inner"&&abiType.fields[0].type.kind==="field"}__name(isWrappedFieldStruct,"isWrappedFieldStruct");function isBoundedVecStruct(abiType){return abiType.kind==="struct"&&abiType.path==="std::collections::bounded_vec::BoundedVec"&&abiType.fields.length===2&&abiType.fields[0].name==="storage"&&abiType.fields[1].name==="len"}__name(isBoundedVecStruct,"isBoundedVecStruct");function isOptionStruct(abiType){return abiType.kind==="struct"&&abiType.path==="std::option::Option"&&abiType.fields.length===2&&abiType.fields[0].name==="_is_some"&&abiType.fields[1].name==="_value"}__name(isOptionStruct,"isOptionStruct");var ArgumentEncoder=class _ArgumentEncoder{static{__name(this,"ArgumentEncoder")}abi;args;flattened;constructor(abi,args){this.abi=abi,this.args=args,this.flattened=[]}static typeSize(abiType){switch(abiType.kind){case"field":case"boolean":case"integer":return 1;case"string":return abiType.length;case"array":return abiType.length*_ArgumentEncoder.typeSize(abiType.type);case"struct":return abiType.fields.reduce((acc,field)=>acc+_ArgumentEncoder.typeSize(field.type),0);case"tuple":return abiType.fields.reduce((acc,field)=>acc+_ArgumentEncoder.typeSize(field),0);default:{let exhaustiveCheck=abiType;throw new Error(`Unhandled abi type: ${exhaustiveCheck}`)}}}encodeArgument(abiType,arg,name){if(isOptionStruct(abiType)){let optionType=abiType,[isSomeField,valueField]=optionType.fields;if(arg==null){this.encodeArgument(isSomeField.type,!1,`${name}._is_some`),this.#encodeDefaultValue(valueField.type);return}if(typeof arg=="object"&&"_is_some"in arg){this.encodeArgument(isSomeField.type,arg._is_some,`${name}._is_some`),arg._is_some?this.encodeArgument(valueField.type,arg._value,`${name}._value`):this.#encodeDefaultValue(valueField.type);return}this.encodeArgument(isSomeField.type,!0,`${name}._is_some`),this.encodeArgument(valueField.type,arg,`${name}._value`);return}if(arg===void 0||arg==null)throw new Error(`Undefined argument ${name??"unnamed"} of type ${abiType.kind}`);switch(abiType.kind){case"field":if(typeof arg=="number")this.flattened.push(new Fr(BigInt(arg)));else if(typeof arg=="bigint")this.flattened.push(new Fr(arg));else if(typeof arg=="string")this.flattened.push(Fr.fromString(arg));else if(typeof arg=="boolean")this.flattened.push(new Fr(arg?1n:0n));else if(typeof arg=="object")if(Buffer.isBuffer(arg))this.flattened.push(Fr.fromBuffer(arg));else if(typeof arg.toField=="function")this.flattened.push(arg.toField());else if(typeof arg.value=="string")this.flattened.push(Fr.fromHexString(arg.value));else throw new Error(`Argument for ${name} cannot be serialized to a field`);else throw new Error(`Invalid argument "${arg}" of type ${abiType.kind}`);break;case"boolean":this.flattened.push(new Fr(arg?1n:0n));break;case"array":if(!Array.isArray(arg))throw new Error(`Expected array for '${name??"unnamed"}' but received ${typeof arg}`);if(arg.length!==abiType.length)throw new Error(`Expected array of length ${abiType.length} for '${name??"unnamed"}' but received length ${arg.length}`);for(let i=0;i<abiType.length;i+=1)this.encodeArgument(abiType.type,arg[i],`${name}[${i}]`);break;case"string":if(typeof arg!="string")throw new Error(`Expected string for '${name??"unnamed"}' but received ${typeof arg}`);if(arg.length>abiType.length)throw new Error(`Expected string of max length ${abiType.length} for '${name??"unnamed"}' but received length ${arg.length}`);for(let i=0;i<abiType.length;i+=1){let toInsert=i<arg.length?BigInt(arg.charCodeAt(i)):0n;this.flattened.push(new Fr(toInsert))}break;case"struct":{if(arg.encodeToNoir!==void 0){this.flattened.push(...arg.encodeToNoir());break}let isAddress=isAddressStruct(abiType);if(isAddress&&typeof arg.address>"u"&&typeof arg.inner>"u"){this.encodeArgument({kind:"field"},arg,`${name}.inner`);break}if(isAddress&&typeof arg.address<"u"){this.encodeArgument({kind:"field"},arg.address,`${name}.address`);break}if(isFunctionSelectorStruct(abiType)){this.encodeArgument({kind:"integer",sign:"unsigned",width:32},arg.value??arg,`${name}.inner`);break}if(isWrappedFieldStruct(abiType)){this.encodeArgument({kind:"field"},arg.inner??arg,`${name}.inner`);break}if(isBoundedVecStruct(abiType)){this.#encodeBoundedVec(abiType,arg,name);break}for(let field of abiType.fields)this.encodeArgument(field.type,arg[field.name],`${name}.${field.name}`);break}case"integer":{let value=BigInt(arg);if(abiType.sign==="unsigned"){let maxValue=(1n<<BigInt(abiType.width))-1n;if(value<0n||value>maxValue)throw new Error(`Value ${value} does not fit in u${abiType.width} for '${name??"unnamed"}' (valid range: 0 to ${maxValue})`);this.flattened.push(new Fr(value))}else{let minValue=-(1n<<BigInt(abiType.width-1)),maxValue=(1n<<BigInt(abiType.width-1))-1n;if(value<minValue||value>maxValue)throw new Error(`Value ${value} does not fit in i${abiType.width} for '${name??"unnamed"}' (valid range: ${minValue} to ${maxValue})`);if(value<0n){let twosComplement=value+(1n<<BigInt(abiType.width));this.flattened.push(new Fr(twosComplement))}else this.flattened.push(new Fr(value))}break}default:throw new Error(`Unsupported type: ${abiType.kind}`)}}encode(){if(this.args.length!==this.abi.parameters.length)throw new Error(`Function '${this.abi.name}' expects ${this.abi.parameters.length} argument(s) but received ${this.args.length}`);for(let i=0;i<this.abi.parameters.length;i+=1){let parameterAbi=this.abi.parameters[i];this.encodeArgument(parameterAbi.type,this.args[i],parameterAbi.name)}return this.flattened}#encodeBoundedVec(abiType,arg,name){{let storageField=abiType.fields.find(f=>f.name==="storage"),maxLength=storageField.type.length;if(arg.length>maxLength){let preview=arg.slice(0,3).map(x=>typeof x=="object"&&x!==null?Array.isArray(x)?`[${x.join(", ")}]`:`{${Object.entries(x).map(([k,v])=>`${k}: ${v}`).join(", ")}}`:`${x}`).join(", "),suffix=arg.length>3?", ...":"";throw new Error(`Error encoding param '${name??"unnamed"}': expected an array of maximum length ${maxLength} and got ${arg.length} instead: [ ${preview}${suffix} ]`)}let storageArrayItemType=storageField.type.type;for(let i=0;i<arg.length;i++)this.encodeArgument(storageArrayItemType,arg[i],`storage[${i}]`);let numItemsToPad=maxLength-arg.length;if(numItemsToPad>0){let numFieldsToPad=numItemsToPad*_ArgumentEncoder.typeSize(storageArrayItemType),paddingFields=new Array(numFieldsToPad).fill(Fr.ZERO);this.flattened.push(...paddingFields)}}{let lenField=abiType.fields.find(f=>f.name==="len");this.encodeArgument(lenField.type,arg.length,"len")}}#encodeDefaultValue(abiType){this.flattened.push(...new Array(_ArgumentEncoder.typeSize(abiType)).fill(Fr.ZERO))}};function encodeArguments(abi,args){return new ArgumentEncoder(abi,args).encode()}__name(encodeArguments,"encodeArguments");function countArgumentsSize(abi){return abi.parameters.reduce((acc,parameter)=>acc+ArgumentEncoder.typeSize(parameter.type),0)}__name(countArgumentsSize,"countArgumentsSize");var EventSelector=class _EventSelector extends Selector{static{__name(this,"EventSelector")}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer),value=Number(toBigIntBE(reader.readBytes(Selector.SIZE)));return new _EventSelector(value)}static fromField(fr){return new _EventSelector(Number(fr.toBigInt()))}static async fromSignature(signature){if(/\s/.test(signature))throw new Error("Signature cannot contain whitespace");let bytes=(await poseidon2HashBytes(Buffer.from(signature))).toBuffer().slice(-Selector.SIZE);return _EventSelector.fromBuffer(bytes)}static fromString(selector){let buf=fromHex(selector);if(buf.length!==Selector.SIZE)throw new Error(`Invalid EventSelector length ${buf.length} (expected ${Selector.SIZE}).`);return _EventSelector.fromBuffer(buf)}static empty(){return new _EventSelector(0)}static random(){return _EventSelector.fromBuffer(randomBytes(Selector.SIZE))}toJSON(){return this.toString()}static get schema(){return hexSchemaFor(_EventSelector)}};var NoteSelector=class _NoteSelector extends Selector{static{__name(this,"NoteSelector")}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer),value=Number(toBigIntBE(reader.readBytes(Selector.SIZE)));if(value>=128)throw new Error(`Invalid note selector: ${value}`);return new _NoteSelector(value)}static fromString(buf){let withoutPrefix=buf.replace(/^0x/i,"").slice(-8),buffer=Buffer.from(withoutPrefix,"hex");return _NoteSelector.fromBuffer(buffer)}static fromField(fr){return new _NoteSelector(Number(fr.toBigInt()))}static empty(){return new _NoteSelector(0)}static random(){let value=randomInt(128);return _NoteSelector.fromField(new Fr(value))}toJSON(){return this.toString()}static get schema(){return hexSchemaFor(_NoteSelector)}};var AZTEC_PRIVATE_ATTRIBUTE="abi_private",AZTEC_PUBLIC_ATTRIBUTE="abi_public",AZTEC_UTILITY_ATTRIBUTE="abi_utility",AZTEC_ONLY_SELF_ATTRIBUTE="abi_only_self",AZTEC_INITIALIZER_ATTRIBUTE="abi_initializer",AZTEC_VIEW_ATTRIBUTE="abi_view";function contractArtifactToBuffer(artifact){return Buffer.from(jsonStringify(artifact),"utf-8")}__name(contractArtifactToBuffer,"contractArtifactToBuffer");function contractArtifactFromBuffer(buffer){return jsonParseWithSchema(buffer.toString("utf-8"),ContractArtifactSchema)}__name(contractArtifactFromBuffer,"contractArtifactFromBuffer");function loadContractArtifact(input){return isContractArtifact(input)?input.aztecVersion?input:{...input,aztecVersion:ARTIFACT_VERSION_BEFORE_INJECTION}:generateContractArtifact(input)}__name(loadContractArtifact,"loadContractArtifact");function isContractArtifact(input){if(typeof input!="object")return!1;let maybeContractArtifact=input;if(typeof maybeContractArtifact.name!="string"||!Array.isArray(maybeContractArtifact.functions))return!1;for(let fn of maybeContractArtifact.functions)if(typeof fn.name!="string"||typeof fn.functionType!="string"||!retainBytecode(fn)&&fn.bytecode.length)return!1;if(!Array.isArray(maybeContractArtifact.nonDispatchPublicFunctions))return!1;for(let fn of maybeContractArtifact.nonDispatchPublicFunctions)if(typeof fn.name!="string"||typeof fn.functionType!="string")return!1;return!0}__name(isContractArtifact,"isContractArtifact");function generateFunctionParameter(param){let{visibility}=param;if(visibility==="databus")throw new Error(`Unsupported visibility ${param.visibility} for noir contract function parameter ${param.name}.`);return{...param,visibility}}__name(generateFunctionParameter,"generateFunctionParameter");function retainBytecode(input){return(input.functionType??getFunctionType(input))!==FunctionType.PUBLIC||input.name=="public_dispatch"}__name(retainBytecode,"retainBytecode");function generateFunctionAbi(fn,contract){if(fn.custom_attributes===void 0)throw new Error(`No custom attributes found for contract function ${fn.name}. Try rebuilding the contract with the latest nargo version.`);let functionType=getFunctionType(fn),isOnlySelf=fn.custom_attributes.includes(AZTEC_ONLY_SELF_ATTRIBUTE),isStatic=fn.custom_attributes.includes(AZTEC_VIEW_ATTRIBUTE),parameters=fn.abi.parameters.map(generateFunctionParameter);hasKernelFunctionInputs(parameters)&&(parameters=parameters.slice(1));let returnTypes=[];if(functionType===FunctionType.UTILITY)returnTypes=fn.abi.return_type?[fn.abi.return_type.abi_type]:returnTypes;else{let pathToFind=`${contract.name}::${fn.name}_abi`,returnStruct=contract.outputs.structs.functions.find(a=>a.kind==="struct"&&a.path===pathToFind);if(returnStruct){if(returnStruct.kind!=="struct")throw new Error("Could not generate contract function artifact");let returnTypeField=returnStruct.fields.find(field=>field.name==="return_type");returnTypeField&&(returnTypes=[returnTypeField.type])}}return{name:fn.name,functionType,isOnlySelf,isStatic,isInitializer:fn.custom_attributes.includes(AZTEC_INITIALIZER_ATTRIBUTE),parameters,returnTypes,errorTypes:fn.abi.error_types,...fn.assert_messages?{assertMessages:fn.assert_messages}:void 0}}__name(generateFunctionAbi,"generateFunctionAbi");function generateFunctionArtifact(fn,contract){return{...generateFunctionAbi(fn,contract),bytecode:fn.bytecode,debugSymbols:fn.debug_symbols,...fn.verification_key?{verificationKey:fn.verification_key}:void 0}}__name(generateFunctionArtifact,"generateFunctionArtifact");function getFunctionType(fn){if(fn.custom_attributes.includes(AZTEC_PRIVATE_ATTRIBUTE))return FunctionType.PRIVATE;if(fn.custom_attributes.includes(AZTEC_PUBLIC_ATTRIBUTE))return FunctionType.PUBLIC;if(fn.custom_attributes.includes(AZTEC_UTILITY_ATTRIBUTE))return FunctionType.UTILITY;throw new Error(`Invalid function type for a noir contract function ${fn.name}`)}__name(getFunctionType,"getFunctionType");function hasKernelFunctionInputs(params){let firstParam=params[0];return firstParam?.type.kind==="struct"&&firstParam.type.path.includes("ContextInputs")}__name(hasKernelFunctionInputs,"hasKernelFunctionInputs");function getStorageLayout(input){let storageForContract=(input.outputs.globals.storage?input.outputs.globals.storage:[]).find(storageExport=>(storageExport.fields.find(field=>field.name==="contract_name")?.value).value===input.name),storageFields=storageForContract?storageForContract.fields.find(field=>field.name=="fields").value.fields:[];return storageFields.length===0?{}:storageFields.reduce((acc,field)=>{let name=field.name,slot=field.value.fields[0].value;return acc[name]={slot:`0x${slot.value}`},acc},{})}__name(getStorageLayout,"getStorageLayout");function generateContractArtifact(contract){try{if(!contract.transpiled)throw new Error("Contract's public bytecode has not been transpiled");return ContractArtifactSchema.parse({name:contract.name,aztecVersion:contract.aztec_version,functions:contract.functions.filter(f=>retainBytecode(f)).map(f=>generateFunctionArtifact(f,contract)),nonDispatchPublicFunctions:contract.functions.filter(f=>!retainBytecode(f)).map(f=>generateFunctionAbi(f,contract)),outputs:contract.outputs,storageLayout:getStorageLayout(contract),fileMap:contract.file_map})}catch(err){throw new Error(`Could not generate contract artifact for ${contract.name}: ${err}`)}}__name(generateContractArtifact,"generateContractArtifact");import{inspect as inspect8}from"util";var _computedKey8,GasDimensions=["da","l2"];_computedKey8=inspect8.custom;var Gas=class _Gas{static{__name(this,"Gas")}daGas;l2Gas;constructor(daGas,l2Gas){this.daGas=daGas,this.l2Gas=l2Gas}static get schema(){return external_exports.object({daGas:schemas.UInt32,l2Gas:schemas.UInt32}).transform(_Gas.from)}getSize(){return 8}clone(){return new _Gas(this.daGas,this.l2Gas)}get(dimension){return this[`${dimension}Gas`]}equals(other){return this.daGas===other.daGas&&this.l2Gas===other.l2Gas}static from(fields){return new _Gas(fields.daGas??0,fields.l2Gas??0)}static fromPlainObject(obj){return obj instanceof _Gas?obj:_Gas.from(obj)}static empty(){return new _Gas(0,0)}static random(){return new _Gas(Math.floor(Math.random()*1e9),Math.floor(Math.random()*1e9))}isEmpty(){return this.daGas===0&&this.l2Gas===0}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _Gas(reader.readNumber(),reader.readNumber())}toBuffer(sink){if(!sink)return BufferSink.serialize(this);serializeToSink(sink,this.daGas,this.l2Gas)}[_computedKey8](){return`Gas { daGas=${this.daGas} l2Gas=${this.l2Gas} }`}add(other){return new _Gas(this.daGas+other.daGas,this.l2Gas+other.l2Gas)}sub(other){return new _Gas(this.daGas-other.daGas,this.l2Gas-other.l2Gas)}mul(scalar){return new _Gas(Math.ceil(this.daGas*scalar),Math.ceil(this.l2Gas*scalar))}gtAny(other){return this.daGas>other.daGas||this.l2Gas>other.l2Gas}computeFee(gasFees){return GasDimensions.reduce((acc,dimension)=>acc.add(new Fr(gasFees.get(dimension)).mul(new Fr(this.get(dimension)))),Fr.ZERO)}toFields(){return serializeToFields(this.daGas,this.l2Gas)}static fromFields(fields){let reader=FieldReader.asReader(fields);return new _Gas(reader.readU32(),reader.readU32())}};var schemas2={EthAddress:schemas.EthAddress,Fr:schemas.Fr,Fq:schemas.Fq,Point:schemas.Point,BigInt:schemas.BigInt,Integer:schemas.Integer,UInt32:schemas.UInt32,UInt64:schemas.UInt64,Buffer32:schemas.Buffer32,Buffer:schemas.Buffer,BufferHex:schemas.BufferHex,HexString:schemas.HexString,SecretValue:schemas.SecretValue,AztecAddress:AztecAddress.schema,NoteSelector:NoteSelector.schema,FunctionSelector:FunctionSelector.schema,EventSelector:EventSelector.schema,SlotNumber:schemas.SlotNumber,EpochNumber:schemas.EpochNumber,GasUsed:external_exports.object({totalGas:Gas.schema,teardownGas:Gas.schema,publicGas:Gas.schema,billedGas:Gas.schema})},AbiDecodedSchema=external_exports.union([schemas2.BigInt,external_exports.boolean(),schemas2.AztecAddress,external_exports.array(external_exports.lazy(()=>AbiDecodedSchema)),external_exports.record(external_exports.string(),external_exports.lazy(()=>AbiDecodedSchema))]),NullishToUndefined=__name(schema=>schema.nullish().transform(x=>x??void 0),"NullishToUndefined");var FunctionCall=class _FunctionCall{static{__name(this,"FunctionCall")}name;to;selector;type;hideMsgSender;isStatic;args;returnTypes;constructor(name,to,selector,type,hideMsgSender,isStatic,args,returnTypes){this.name=name,this.to=to,this.selector=selector,this.type=type,this.hideMsgSender=hideMsgSender,this.isStatic=isStatic,this.args=args,this.returnTypes=returnTypes}static getFields(fields){return[fields.name,fields.to,fields.selector,fields.type,fields.hideMsgSender,fields.isStatic,fields.args,fields.returnTypes]}static from(fields){return new _FunctionCall(..._FunctionCall.getFields(fields))}static get schema(){return external_exports.object({name:external_exports.string(),to:schemas2.AztecAddress,selector:schemas2.FunctionSelector,type:external_exports.nativeEnum(FunctionType),isStatic:external_exports.boolean(),hideMsgSender:external_exports.boolean(),args:external_exports.array(schemas2.Fr),returnTypes:external_exports.array(AbiTypeSchema)}).transform(_FunctionCall.from)}isPublicStatic(){return this.type===FunctionType.PUBLIC&&this.isStatic}static empty(){return _FunctionCall.from({name:"",to:AztecAddress.ZERO,selector:FunctionSelector.empty(),type:FunctionType.PUBLIC,hideMsgSender:!1,isStatic:!1,args:[],returnTypes:[]})}};import{inspect as inspect14}from"util";import{inspect as inspect9}from"util";var _computedKey9;_computedKey9=inspect9.custom;var BlockHash=class _BlockHash extends BaseFr{static{__name(this,"BlockHash")}static ZERO=new _BlockHash(Fr.ZERO);constructor(hash5){super(hash5)}[_computedKey9](){return`BlockHash<${this.toString()}>`}toFr(){return new Fr(this.toBigInt())}static isBlockHash(value){return value instanceof _BlockHash}static random(){return new _BlockHash(Fr.random())}static fromBuffer(buffer){return new _BlockHash(Fr.fromBuffer(buffer))}static fromString(str){return new _BlockHash(Fr.fromString(str))}static get schema(){return hexSchemaFor(_BlockHash)}},GENESIS_BLOCK_HEADER_HASH3=new BlockHash(GENESIS_BLOCK_HEADER_HASH2);import{inspect as inspect10}from"util";var _computedKey10;_computedKey10=inspect10.custom;var AppendOnlyTreeSnapshot=class _AppendOnlyTreeSnapshot{static{__name(this,"AppendOnlyTreeSnapshot")}root;nextAvailableLeafIndex;constructor(root,nextAvailableLeafIndex){this.root=root,this.nextAvailableLeafIndex=nextAvailableLeafIndex}static get schema(){return external_exports.object({root:schemas.Fr,nextAvailableLeafIndex:schemas.UInt32}).transform(({root,nextAvailableLeafIndex})=>new _AppendOnlyTreeSnapshot(root,nextAvailableLeafIndex))}getSize(){return this.root.size+4}toBuffer(sink){if(!sink)return BufferSink.serialize(this);serializeToSink(sink,this.root,this.nextAvailableLeafIndex)}toFields(){return[this.root,new Fr(this.nextAvailableLeafIndex)]}toString(){return bufferToHex(this.toBuffer())}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _AppendOnlyTreeSnapshot(Fr.fromBuffer(reader),reader.readNumber())}static fromString(str){return _AppendOnlyTreeSnapshot.fromBuffer(hexToBuffer(str))}static fromFields(fields){let reader=FieldReader.asReader(fields);return new _AppendOnlyTreeSnapshot(reader.readField(),Number(reader.readField().toBigInt()))}toAbi(){return[this.root.toString(),this.nextAvailableLeafIndex]}static empty(){return new _AppendOnlyTreeSnapshot(Fr.ZERO,0)}static fromPlainObject(obj){return new _AppendOnlyTreeSnapshot(Fr.fromPlainObject(obj.root),obj.nextAvailableLeafIndex)}isEmpty(){return this.root.isZero()&&this.nextAvailableLeafIndex===0}[_computedKey10](){return`AppendOnlyTreeSnapshot { root: ${this.root.toString()}, nextAvailableLeafIndex: ${this.nextAvailableLeafIndex} }`}equals(other){return this.root.equals(other.root)&&this.nextAvailableLeafIndex===other.nextAvailableLeafIndex}static random(){return new _AppendOnlyTreeSnapshot(Fr.random(),Math.floor(Math.random()*1e3))}};import{inspect as inspect12}from"util";import{inspect as inspect11}from"util";var _computedKey11;function bigintMulCeil(value,scalar){let SCALE=1000000000000n,scaledScalar=BigInt(Math.round(scalar*1e12));return(value*scaledScalar+SCALE-1n)/SCALE}__name(bigintMulCeil,"bigintMulCeil");_computedKey11=inspect11.custom;var GasFees=class _GasFees{static{__name(this,"GasFees")}feePerDaGas;feePerL2Gas;constructor(feePerDaGas,feePerL2Gas){this.feePerDaGas=BigInt(feePerDaGas),this.feePerL2Gas=BigInt(feePerL2Gas)}static get schema(){return external_exports.object({feePerDaGas:schemas.BigInt,feePerL2Gas:schemas.BigInt}).transform(_GasFees.from)}clone(){return new _GasFees(this.feePerDaGas,this.feePerL2Gas)}equals(other){return this.feePerDaGas===other.feePerDaGas&&this.feePerL2Gas===other.feePerL2Gas}get(dimension){switch(dimension){case"da":return this.feePerDaGas;case"l2":return this.feePerL2Gas}}mul(scalar){if(scalar===1||scalar===1n)return this.clone();if(typeof scalar=="bigint")return new _GasFees(this.feePerDaGas*scalar,this.feePerL2Gas*scalar);if(Number.isInteger(scalar)){let s2=BigInt(scalar);return new _GasFees(this.feePerDaGas*s2,this.feePerL2Gas*s2)}else return new _GasFees(bigintMulCeil(this.feePerDaGas,scalar),bigintMulCeil(this.feePerL2Gas,scalar))}static from(fields){return new _GasFees(fields.feePerDaGas,fields.feePerL2Gas)}static fromPlainObject(obj){return obj instanceof _GasFees?obj:_GasFees.from(obj)}static random(){return new _GasFees(Math.floor(Math.random()*1e9),Math.floor(Math.random()*1e9))}static empty(){return new _GasFees(0,0)}isEmpty(){return this.feePerDaGas===0n&&this.feePerL2Gas===0n}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _GasFees(reader.readUInt128(),reader.readUInt128())}toBuffer(sink){if(!sink)return BufferSink.serialize(this);sink.writeBigInt(this.feePerDaGas,16),sink.writeBigInt(this.feePerL2Gas,16)}static fromFields(fields){let reader=FieldReader.asReader(fields);return new _GasFees(reader.readField().toBigInt(),reader.readField().toBigInt())}toFields(){return serializeToFields(this.feePerDaGas,this.feePerL2Gas)}toInspect(){return{feePerDaGas:this.feePerDaGas,feePerL2Gas:this.feePerL2Gas}}[_computedKey11](){return`GasFees { feePerDaGas=${this.feePerDaGas} feePerL2Gas=${this.feePerL2Gas} }`}};var _computedKey12;_computedKey12=inspect12.custom;var GlobalVariables=class _GlobalVariables{static{__name(this,"GlobalVariables")}chainId;version;blockNumber;slotNumber;timestamp;coinbase;feeRecipient;gasFees;constructor(chainId,version2,blockNumber,slotNumber,timestamp,coinbase,feeRecipient,gasFees){this.chainId=chainId,this.version=version2,this.blockNumber=blockNumber,this.slotNumber=slotNumber,this.timestamp=timestamp,this.coinbase=coinbase,this.feeRecipient=feeRecipient,this.gasFees=gasFees}static get schema(){return external_exports.object({chainId:schemas2.Fr,version:schemas2.Fr,blockNumber:BlockNumberSchema,slotNumber:schemas2.SlotNumber,timestamp:schemas2.BigInt,coinbase:schemas2.EthAddress,feeRecipient:schemas2.AztecAddress,gasFees:GasFees.schema}).transform(_GlobalVariables.from)}getSize(){return this.toBuffer().length}static from(fields){return new _GlobalVariables(..._GlobalVariables.getFields(fields))}static fromPlainObject(obj){return new _GlobalVariables(Fr.fromPlainObject(obj.chainId),Fr.fromPlainObject(obj.version),obj.blockNumber,SlotNumber(Fr.fromPlainObject(obj.slotNumber).toNumber()),typeof obj.timestamp=="bigint"?obj.timestamp:BigInt(obj.timestamp),EthAddress.fromPlainObject(obj.coinbase),AztecAddress.fromPlainObject(obj.feeRecipient),GasFees.fromPlainObject(obj.gasFees))}static empty(fields={}){return _GlobalVariables.from({blockNumber:BlockNumber.ZERO,slotNumber:SlotNumber.ZERO,timestamp:0n,chainId:Fr.ZERO,version:Fr.ZERO,coinbase:EthAddress.ZERO,feeRecipient:AztecAddress.ZERO,gasFees:GasFees.empty(),...fields})}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _GlobalVariables(Fr.fromBuffer(reader),Fr.fromBuffer(reader),BlockNumber(reader.readNumber()),SlotNumber(reader.readNumber()),reader.readUInt64(),reader.readObject(EthAddress),reader.readObject(AztecAddress),reader.readObject(GasFees))}static fromFields(fields){let reader=FieldReader.asReader(fields);return new _GlobalVariables(reader.readField(),reader.readField(),BlockNumber(reader.readU32()),SlotNumber(reader.readU32()),reader.readField().toBigInt(),EthAddress.fromField(reader.readField()),AztecAddress.fromFieldUnsafe(reader.readField()),GasFees.fromFields(reader))}static getFields(fields){return[fields.chainId,fields.version,fields.blockNumber,fields.slotNumber,fields.timestamp,fields.coinbase,fields.feeRecipient,fields.gasFees]}toBuffer(sink){if(!sink)return BufferSink.serialize(this);serializeToSink(sink,this.chainId,this.version,this.blockNumber,this.slotNumber),sink.writeUInt64(this.timestamp),serializeToSink(sink,this.coinbase,this.feeRecipient,this.gasFees)}toFields(){let fields=serializeToFields(..._GlobalVariables.getFields(this));if(fields.length!==9)throw new Error(`Invalid number of fields for GlobalVariables. Expected ${9}, got ${fields.length}`);return fields}toFriendlyJSON(){return{blockNumber:this.blockNumber,slotNumber:this.slotNumber,timestamp:this.timestamp.toString(),coinbase:this.coinbase.toString(),gasFees:jsonStringify(this.gasFees)}}toJSON(){return{chainId:this.chainId,version:this.version,blockNumber:this.blockNumber,slotNumber:new Fr(this.slotNumber),timestamp:this.timestamp,coinbase:this.coinbase,feeRecipient:this.feeRecipient,gasFees:this.gasFees}}clone(){return _GlobalVariables.fromBuffer(this.toBuffer())}isEmpty(){return this.chainId.isZero()&&this.version.isZero()&&this.blockNumber===0&&this.slotNumber===0&&this.timestamp===0n&&this.coinbase.isZero()&&this.feeRecipient.isZero()&&this.gasFees.isEmpty()}static random(overrides={}){return _GlobalVariables.from({chainId:new Fr(randomInt(1e5)),version:new Fr(randomInt(1e5)),blockNumber:BlockNumber(randomInt(1e5)),slotNumber:SlotNumber(randomInt(1e5)),coinbase:EthAddress.random(),feeRecipient:AztecAddress.fromFieldUnsafe(Fr.random()),gasFees:GasFees.random(),timestamp:BigInt(randomInt(1e8)),...overrides})}toInspect(){return{chainId:this.chainId.toNumber(),version:this.version.toNumber(),blockNumber:this.blockNumber,slotNumber:this.slotNumber,timestamp:this.timestamp,coinbase:this.coinbase.toString(),feeRecipient:this.feeRecipient.toString(),feePerDaGas:Number(this.gasFees.feePerDaGas),feePerL2Gas:Number(this.gasFees.feePerL2Gas)}}[_computedKey12](){return`GlobalVariables ${inspect12(this.toInspect())}`}equals(other){return this.chainId.equals(other.chainId)&&this.version.equals(other.version)&&this.blockNumber===other.blockNumber&&this.slotNumber===other.slotNumber&&this.timestamp===other.timestamp&&this.coinbase.equals(other.coinbase)&&this.feeRecipient.equals(other.feeRecipient)&&this.gasFees.equals(other.gasFees)}};import{inspect as inspect13}from"util";var PartialStateReference=class _PartialStateReference{static{__name(this,"PartialStateReference")}noteHashTree;nullifierTree;publicDataTree;constructor(noteHashTree,nullifierTree,publicDataTree){this.noteHashTree=noteHashTree,this.nullifierTree=nullifierTree,this.publicDataTree=publicDataTree}static get schema(){return external_exports.object({noteHashTree:AppendOnlyTreeSnapshot.schema,nullifierTree:AppendOnlyTreeSnapshot.schema,publicDataTree:AppendOnlyTreeSnapshot.schema}).transform(({noteHashTree,nullifierTree,publicDataTree})=>new _PartialStateReference(noteHashTree,nullifierTree,publicDataTree))}getSize(){return this.noteHashTree.getSize()+this.nullifierTree.getSize()+this.publicDataTree.getSize()}static getFields(fields){return[fields.noteHashTree,fields.nullifierTree,fields.publicDataTree]}static from(fields){return new _PartialStateReference(..._PartialStateReference.getFields(fields))}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _PartialStateReference(reader.readObject(AppendOnlyTreeSnapshot),reader.readObject(AppendOnlyTreeSnapshot),reader.readObject(AppendOnlyTreeSnapshot))}static fromFields(fields){let reader=FieldReader.asReader(fields),noteHashTree=AppendOnlyTreeSnapshot.fromFields(reader),nullifierTree=AppendOnlyTreeSnapshot.fromFields(reader),publicDataTree=AppendOnlyTreeSnapshot.fromFields(reader);return new _PartialStateReference(noteHashTree,nullifierTree,publicDataTree)}static random(){return new _PartialStateReference(AppendOnlyTreeSnapshot.random(),AppendOnlyTreeSnapshot.random(),AppendOnlyTreeSnapshot.random())}toAbi(){return[this.noteHashTree.toAbi(),this.nullifierTree.toAbi(),this.publicDataTree.toAbi()]}static empty(){return new _PartialStateReference(AppendOnlyTreeSnapshot.empty(),AppendOnlyTreeSnapshot.empty(),AppendOnlyTreeSnapshot.empty())}toBuffer(sink){if(!sink)return BufferSink.serialize(this);serializeToSink(sink,this.noteHashTree,this.nullifierTree,this.publicDataTree)}toFields(){let fields=[...this.noteHashTree.toFields(),...this.nullifierTree.toFields(),...this.publicDataTree.toFields()];if(fields.length!==6)throw new Error(`Invalid number of fields for PartialStateReference. Expected ${6}, got ${fields.length}`);return fields}isEmpty(){return this.noteHashTree.isEmpty()&&this.nullifierTree.isEmpty()&&this.publicDataTree.isEmpty()}equals(other){return this.noteHashTree.equals(other.noteHashTree)&&this.nullifierTree.equals(other.nullifierTree)&&this.publicDataTree.equals(other.publicDataTree)}};var _computedKey13;_computedKey13=inspect13.custom;var StateReference=class _StateReference{static{__name(this,"StateReference")}l1ToL2MessageTree;partial;constructor(l1ToL2MessageTree,partial2){this.l1ToL2MessageTree=l1ToL2MessageTree,this.partial=partial2}static get schema(){return external_exports.object({l1ToL2MessageTree:AppendOnlyTreeSnapshot.schema,partial:PartialStateReference.schema}).transform(({l1ToL2MessageTree,partial:partial2})=>new _StateReference(l1ToL2MessageTree,partial2))}getSize(){return this.l1ToL2MessageTree.getSize()+this.partial.getSize()}static getFields(fields){return[fields.l1ToL2MessageTree,fields.partial]}static from(fields){return new _StateReference(..._StateReference.getFields(fields))}toBuffer(sink){if(!sink)return BufferSink.serialize(this);serializeToSink(sink,this.l1ToL2MessageTree,this.partial)}toFields(){let fields=[...this.l1ToL2MessageTree.toFields(),...this.partial.toFields()];if(fields.length!==8)throw new Error(`Invalid number of fields for StateReference. Expected ${8}, got ${fields.length}`);return fields}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _StateReference(reader.readObject(AppendOnlyTreeSnapshot),reader.readObject(PartialStateReference))}static fromFields(fields){let reader=FieldReader.asReader(fields),l1ToL2MessageTree=AppendOnlyTreeSnapshot.fromFields(reader),partial2=PartialStateReference.fromFields(reader);return new _StateReference(l1ToL2MessageTree,partial2)}static empty(){return new _StateReference(AppendOnlyTreeSnapshot.empty(),PartialStateReference.empty())}static random(){return new _StateReference(AppendOnlyTreeSnapshot.random(),PartialStateReference.random())}toAbi(){return[this.l1ToL2MessageTree.toAbi(),[...this.partial.toAbi()]]}isEmpty(){return this.l1ToL2MessageTree.isEmpty()&&this.partial.isEmpty()}toInspect(){return{l1ToL2MessageTree:this.l1ToL2MessageTree.root.toString(),noteHashTree:this.partial.noteHashTree.root.toString(),nullifierTree:this.partial.nullifierTree.root.toString(),publicDataTree:this.partial.publicDataTree.root.toString()}}validate(){if(this.l1ToL2MessageTree.nextAvailableLeafIndex%1024!==0)throw new Error(`Invalid L1 to L2 message tree next available leaf index ${this.l1ToL2MessageTree.nextAvailableLeafIndex} (must be a multiple of ${1024})`);if(this.partial.noteHashTree.nextAvailableLeafIndex%64!==0)throw new Error(`Invalid note hash tree next available leaf index ${this.partial.noteHashTree.nextAvailableLeafIndex} (must be a multiple of ${64})`);if(this.partial.nullifierTree.nextAvailableLeafIndex%64!==0)throw new Error(`Invalid nullifier tree next available leaf index ${this.partial.nullifierTree.nextAvailableLeafIndex} (must be a multiple of ${64})`)}[_computedKey13](){return`StateReference {
|
|
90
90
|
l1ToL2MessageTree: ${inspect13(this.l1ToL2MessageTree)},
|
|
91
91
|
noteHashTree: ${inspect13(this.partial.noteHashTree)},
|
|
@@ -139,7 +139,7 @@ ${err.message}`);else throw err}}__name(getFunctionDebugMetadata,"getFunctionDeb
|
|
|
139
139
|
contractAddress: ${this.contractAddress.toString()},
|
|
140
140
|
emittedLength: ${this.emittedLength},
|
|
141
141
|
fields: [${this.fields.fields.map(x=>inspect22(x)).join(", ")}],
|
|
142
|
-
}`}};import{BarretenbergSync as BarretenbergSync4}from"@aztec/bb.js";var Grumpkin=class{static{__name(this,"Grumpkin")}static generator=Point.fromBuffer(Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,2,207,19,94,117,6,164,93,99,45,39,13,69,241,24,18,148,131,63,196,141,130,63,39,44]));static async mul(point,scalar){await BarretenbergSync4.initSingleton();let response=BarretenbergSync4.getSingleton().grumpkinMul({point:{x:point.x.toBuffer(),y:point.y.toBuffer()},scalar:scalar.toBuffer()});return Point.fromBuffer(Buffer.concat([Buffer.from(response.point.x),Buffer.from(response.point.y)]))}static async add(a,b){await BarretenbergSync4.initSingleton();let response=BarretenbergSync4.getSingleton().grumpkinAdd({pointA:{x:a.x.toBuffer(),y:a.y.toBuffer()},pointB:{x:b.x.toBuffer(),y:b.y.toBuffer()}});return Point.fromBuffer(Buffer.concat([Buffer.from(response.point.x),Buffer.from(response.point.y)]))}static async batchMul(points,scalar){return await BarretenbergSync4.initSingleton(),BarretenbergSync4.getSingleton().grumpkinBatchMul({points:points.map(p=>({x:p.x.toBuffer(),y:p.y.toBuffer()})),scalar:scalar.toBuffer()}).points.map(p=>Point.fromBuffer(Buffer.concat([Buffer.from(p.x),Buffer.from(p.y)])))}static async getRandomFr(){await BarretenbergSync4.initSingleton();let response=BarretenbergSync4.getSingleton().grumpkinGetRandomFr({dummy:0});return Fr.fromBuffer(Buffer.from(response.value))}static async reduce512BufferToFr(uint512Buf){await BarretenbergSync4.initSingleton();let response=BarretenbergSync4.getSingleton().grumpkinReduce512({input:uint512Buf});return Fr.fromBuffer(Buffer.from(response.value))}};var import_hash3=__toESM(require_hash(),1);var sha512=__name(data=>Buffer.from(import_hash3.default.sha512().update(data).digest()),"sha512"),sha512ToGrumpkinScalar=__name(data=>{let buffer=serializeToBuffer(data);return GrumpkinScalar.fromBufferReduce(sha512(buffer))},"sha512ToGrumpkinScalar");function hashPublicKey(pk){return poseidon2HashWithSeparator([pk.x,pk.y],DomainSeparator.SINGLE_PUBLIC_KEY_HASH)}__name(hashPublicKey,"hashPublicKey");var PublicKey=Point;var PublicKeys=class _PublicKeys{static{__name(this,"PublicKeys")}npkMHash;ivpkM;ovpkMHash;tpkMHash;mspkMHash;fbpkMHash;constructor(npkMHash,ivpkM,ovpkMHash,tpkMHash,mspkMHash,fbpkMHash){this.npkMHash=npkMHash,this.ivpkM=ivpkM,this.ovpkMHash=ovpkMHash,this.tpkMHash=tpkMHash,this.mspkMHash=mspkMHash,this.fbpkMHash=fbpkMHash}static get schema(){return external_exports.object({npkMHash:schemas.Fr,ivpkM:schemas.Point,ovpkMHash:schemas.Fr,tpkMHash:schemas.Fr,mspkMHash:schemas.Fr,fbpkMHash:schemas.Fr}).transform(_PublicKeys.from)}static from(fields){return new _PublicKeys(fields.npkMHash,fields.ivpkM,fields.ovpkMHash,fields.tpkMHash,fields.mspkMHash,fields.fbpkMHash)}static fromPlainObject(obj){return obj instanceof _PublicKeys?obj:new _PublicKeys(Fr.fromPlainObject(obj.npkMHash),PublicKey.fromPlainObject(obj.ivpkM),Fr.fromPlainObject(obj.ovpkMHash),Fr.fromPlainObject(obj.tpkMHash),Fr.fromPlainObject(obj.mspkMHash),Fr.fromPlainObject(obj.fbpkMHash))}async hash(){if(this.isEmpty())return Fr.ZERO;let ivpkMHash=await hashPublicKey(this.ivpkM);return poseidon2HashWithSeparator([this.npkMHash,ivpkMHash,this.ovpkMHash,this.tpkMHash,this.mspkMHash,this.fbpkMHash],DomainSeparator.PUBLIC_KEYS_HASH)}isEmpty(){return this.npkMHash.isZero()&&this.ivpkM.isZero()&&this.ovpkMHash.isZero()&&this.tpkMHash.isZero()&&this.mspkMHash.isZero()&&this.fbpkMHash.isZero()}static default(){return new _PublicKeys(new Fr(DEFAULT_NPK_M_HASH),new PublicKey(new Fr(DEFAULT_IVPK_M_X),new Fr(DEFAULT_IVPK_M_Y)),new Fr(DEFAULT_OVPK_M_HASH),new Fr(DEFAULT_TPK_M_HASH),new Fr(DEFAULT_MSPK_M_HASH),new Fr(DEFAULT_FBPK_M_HASH))}static async random(){let npkM=await PublicKey.random(),ovpkM=await PublicKey.random(),tpkM=await PublicKey.random(),mspkM=await PublicKey.random(),fbpkM=await PublicKey.random();return new _PublicKeys(await hashPublicKey(npkM),await PublicKey.random(),await hashPublicKey(ovpkM),await hashPublicKey(tpkM),await hashPublicKey(mspkM),await hashPublicKey(fbpkM))}equals(other){return this.npkMHash.equals(other.npkMHash)&&this.ivpkM.equals(other.ivpkM)&&this.ovpkMHash.equals(other.ovpkMHash)&&this.tpkMHash.equals(other.tpkMHash)&&this.mspkMHash.equals(other.mspkMHash)&&this.fbpkMHash.equals(other.fbpkMHash)}toBuffer(){return serializeToBuffer([this.npkMHash,this.ivpkM,this.ovpkMHash,this.tpkMHash,this.mspkMHash,this.fbpkMHash])}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer),npkMHash=Fr.fromBuffer(reader),ivpkM=reader.readObject(PublicKey),ovpkMHash=Fr.fromBuffer(reader),tpkMHash=Fr.fromBuffer(reader),mspkMHash=Fr.fromBuffer(reader),fbpkMHash=Fr.fromBuffer(reader);return new _PublicKeys(npkMHash,ivpkM,ovpkMHash,tpkMHash,mspkMHash,fbpkMHash)}toNoirStruct(){return{npk_m_hash:this.npkMHash,ivpk_m:this.ivpkM.toWrappedNoirStruct(),ovpk_m_hash:this.ovpkMHash,tpk_m_hash:this.tpkMHash,mspk_m_hash:this.mspkMHash,fbpk_m_hash:this.fbpkMHash}}toFields(){return[this.npkMHash,this.ivpkM.x,this.ivpkM.y,this.ovpkMHash,this.tpkMHash,this.mspkMHash,this.fbpkMHash]}encodeToNoir(){return this.toFields()}static fromFields(fields){let reader=FieldReader.asReader(fields),npkMHash=reader.readField(),ivpkM=reader.readObject(PublicKey),ovpkMHash=reader.readField(),tpkMHash=reader.readField(),mspkMHash=reader.readField(),fbpkMHash=reader.readField();return new _PublicKeys(npkMHash,ivpkM,ovpkMHash,tpkMHash,mspkMHash,fbpkMHash)}toString(){return bufferToHex(this.toBuffer())}static fromString(keys){return _PublicKeys.fromBuffer(Buffer.from(withoutHexPrefix(keys),"hex"))}};function getKeyGenerator(prefix){return{n:DomainSeparator.NHK_M,iv:DomainSeparator.IVSK_M,ov:DomainSeparator.OVSK_M,t:DomainSeparator.TSK_M}[prefix]}__name(getKeyGenerator,"getKeyGenerator");function computeAppSecretKey(skM,app,keyPrefix){let generator=getKeyGenerator(keyPrefix);return poseidon2HashWithSeparator([skM.hi,skM.lo,app],generator)}__name(computeAppSecretKey,"computeAppSecretKey");function deriveMasterNullifierHidingSecretKey(secretKey){return sha512ToGrumpkinScalar([secretKey,DomainSeparator.NHK_M])}__name(deriveMasterNullifierHidingSecretKey,"deriveMasterNullifierHidingSecretKey");function deriveMasterIncomingViewingSecretKey(secretKey){return sha512ToGrumpkinScalar([secretKey,DomainSeparator.IVSK_M])}__name(deriveMasterIncomingViewingSecretKey,"deriveMasterIncomingViewingSecretKey");function deriveMasterOutgoingViewingSecretKey(secretKey){return sha512ToGrumpkinScalar([secretKey,DomainSeparator.OVSK_M])}__name(deriveMasterOutgoingViewingSecretKey,"deriveMasterOutgoingViewingSecretKey");function deriveMasterMessageSigningSecretKey(secretKey){return sha512ToGrumpkinScalar([secretKey,DomainSeparator.MSSK_M])}__name(deriveMasterMessageSigningSecretKey,"deriveMasterMessageSigningSecretKey");function deriveMasterFallbackSecretKey(secretKey){return sha512ToGrumpkinScalar([secretKey,DomainSeparator.FBSK_M])}__name(deriveMasterFallbackSecretKey,"deriveMasterFallbackSecretKey");function computePreaddress(publicKeysHash,partialAddress){return poseidon2HashWithSeparator([publicKeysHash,partialAddress],DomainSeparator.CONTRACT_ADDRESS_V2)}__name(computePreaddress,"computePreaddress");async function computeAddress(publicKeys,partialAddress){let preaddress=await computePreaddress(await publicKeys.hash(),partialAddress),address=await Grumpkin.add(await derivePublicKeyFromSecretKey(new Fq(preaddress.toBigInt())),publicKeys.ivpkM);return new AztecAddress(address.x)}__name(computeAddress,"computeAddress");async function computeAddressSecret(preaddress,ivsk){let addressSecretCandidate=ivsk.add(new Fq(preaddress.toBigInt()));return(await derivePublicKeyFromSecretKey(addressSecretCandidate)).y.toBigInt()<=(Fr.MODULUS-1n)/2n?addressSecretCandidate:new Fq(Fq.MODULUS-addressSecretCandidate.toBigInt())}__name(computeAddressSecret,"computeAddressSecret");function derivePublicKeyFromSecretKey(secretKey){return secretKey.isZero()?Promise.resolve(PublicKey.INFINITY):Grumpkin.mul(Grumpkin.generator,secretKey)}__name(derivePublicKeyFromSecretKey,"derivePublicKeyFromSecretKey");function deriveKeys(secretKey){return deriveKeysFromMasterSecretKeys({masterNullifierHidingSecretKey:deriveMasterNullifierHidingSecretKey(secretKey),masterIncomingViewingSecretKey:deriveMasterIncomingViewingSecretKey(secretKey),masterOutgoingViewingSecretKey:deriveMasterOutgoingViewingSecretKey(secretKey),masterTaggingSecretKey:sha512ToGrumpkinScalar([secretKey,DomainSeparator.TSK_M]),masterMessageSigningSecretKey:deriveMasterMessageSigningSecretKey(secretKey),masterFallbackSecretKey:deriveMasterFallbackSecretKey(secretKey)})}__name(deriveKeys,"deriveKeys");async function deriveKeysFromMasterSecretKeys(secretKeys){let{masterNullifierHidingSecretKey,masterIncomingViewingSecretKey,masterOutgoingViewingSecretKey,masterTaggingSecretKey,masterMessageSigningSecretKey,masterFallbackSecretKey}=secretKeys,masterNullifierHidingPublicKey=await derivePublicKeyFromSecretKey(masterNullifierHidingSecretKey),masterIncomingViewingPublicKey=await derivePublicKeyFromSecretKey(masterIncomingViewingSecretKey),masterOutgoingViewingPublicKey=await derivePublicKeyFromSecretKey(masterOutgoingViewingSecretKey),masterTaggingPublicKey=await derivePublicKeyFromSecretKey(masterTaggingSecretKey),masterMessageSigningPublicKey=await derivePublicKeyFromSecretKey(masterMessageSigningSecretKey),masterFallbackPublicKey=await derivePublicKeyFromSecretKey(masterFallbackSecretKey),publicKeys=new PublicKeys(await hashPublicKey(masterNullifierHidingPublicKey),masterIncomingViewingPublicKey,await hashPublicKey(masterOutgoingViewingPublicKey),await hashPublicKey(masterTaggingPublicKey),await hashPublicKey(masterMessageSigningPublicKey),await hashPublicKey(masterFallbackPublicKey));return{masterNullifierHidingSecretKey,masterIncomingViewingSecretKey,masterOutgoingViewingSecretKey,masterTaggingSecretKey,masterMessageSigningSecretKey,masterFallbackSecretKey,masterNullifierHidingPublicKey,masterOutgoingViewingPublicKey,masterTaggingPublicKey,masterMessageSigningPublicKey,masterFallbackPublicKey,publicKeys}}__name(deriveKeysFromMasterSecretKeys,"deriveKeysFromMasterSecretKeys");var AppTaggingSecretKind={UNCONSTRAINED:"unconstrained",CONSTRAINED:"constrained"},ONCHAIN_UNCONSTRAINED_DELIVERY_MODE=2,ONCHAIN_CONSTRAINED_DELIVERY_MODE=3;function appTaggingSecretKindFromDeliveryMode(deliveryMode){switch(deliveryMode){case ONCHAIN_UNCONSTRAINED_DELIVERY_MODE:return AppTaggingSecretKind.UNCONSTRAINED;case ONCHAIN_CONSTRAINED_DELIVERY_MODE:return AppTaggingSecretKind.CONSTRAINED;default:throw new Error(`Unrecognized delivery mode for tagging: ${deliveryMode}`)}}__name(appTaggingSecretKindFromDeliveryMode,"appTaggingSecretKindFromDeliveryMode");async function appSiloEcdhSharedSecret(secretKey,publicKey,contractAddress){if(publicKey.isZero())throw new Error("Attempting to derive a shared secret with a zero public key. You have probably passed a zero public key in your Noir code somewhere thinking that the note won't be broadcast... but it was.");let rawSharedSecret=await Grumpkin.mul(publicKey,secretKey);return appSiloEcdhSharedSecretPoint(rawSharedSecret,contractAddress)}__name(appSiloEcdhSharedSecret,"appSiloEcdhSharedSecret");function appSiloEcdhSharedSecretPoint(point,app){return poseidon2HashWithSeparator([point.x,point.y,app],DomainSeparator.APP_SILOED_ECDH_SHARED_SECRET)}__name(appSiloEcdhSharedSecretPoint,"appSiloEcdhSharedSecretPoint");var AppTaggingSecretKindSchema=external_exports.union([external_exports.literal(AppTaggingSecretKind.UNCONSTRAINED),external_exports.literal(AppTaggingSecretKind.CONSTRAINED)]),AppTaggingSecret=class _AppTaggingSecret{static{__name(this,"AppTaggingSecret")}secret;app;kind;constructor(secret,app,kind=AppTaggingSecretKind.UNCONSTRAINED){this.secret=secret,this.app=app,this.kind=kind}static async computeDirectional(taggingSecretPoint,app,recipient){let appSiloedSecret=await appSiloEcdhSharedSecretPoint(taggingSecretPoint,app),directionalAppTaggingSecret=await poseidon2Hash([appSiloedSecret,recipient]);return new _AppTaggingSecret(directionalAppTaggingSecret,app)}static async computeViaEcdh(localAddress,localIvsk,externalAddress,app,recipient){let taggingSecretPoint=await computeSharedTaggingSecret(localAddress,localIvsk,externalAddress);if(taggingSecretPoint)return _AppTaggingSecret.computeDirectional(taggingSecretPoint,app,recipient)}toString(){return this.kind===AppTaggingSecretKind.UNCONSTRAINED?`${this.secret.toString()}:${this.app.toString()}`:`${this.kind}:${this.secret.toString()}:${this.app.toString()}`}static fromString(str){let parts=str.split(":");if(parts.length===2){let[secretStr,appStr]=parts;return new _AppTaggingSecret(Fr.fromString(secretStr),AztecAddress.fromStringUnsafe(appStr))}if(parts.length===3){let[kindStr,secretStr,appStr]=parts;return new _AppTaggingSecret(Fr.fromString(secretStr),AztecAddress.fromStringUnsafe(appStr),appTaggingSecretKindFromString(kindStr))}throw new Error(`Invalid AppTaggingSecret string: ${str}`)}};var AppTaggingSecretSchema=external_exports.object({kind:AppTaggingSecretKindSchema.default(AppTaggingSecretKind.UNCONSTRAINED),secret:Fr.schema,app:AztecAddress.schema}).transform(({kind,secret,app})=>new AppTaggingSecret(secret,app,kind));function appTaggingSecretKindFromString(kind){switch(kind){case AppTaggingSecretKind.CONSTRAINED:return AppTaggingSecretKind.CONSTRAINED;case AppTaggingSecretKind.UNCONSTRAINED:return AppTaggingSecretKind.UNCONSTRAINED;default:throw new Error(`Invalid AppTaggingSecret kind: ${kind}`)}}__name(appTaggingSecretKindFromString,"appTaggingSecretKindFromString");async function computeSharedTaggingSecret(localAddress,localIvsk,externalAddress){if(!await externalAddress.isValid())return;let externalAddressPoint=await externalAddress.toAddressPoint(),localPreaddress=await computePreaddress(await localAddress.publicKeys.hash(),localAddress.partialAddress),localAddressSecret=await computeAddressSecret(localPreaddress,localIvsk);return Grumpkin.mul(externalAddressPoint,localAddressSecret)}__name(computeSharedTaggingSecret,"computeSharedTaggingSecret");var TaggingIndexRangeSchema=external_exports.object({extendedSecret:AppTaggingSecretSchema,lowestIndex:schemas.Integer,highestIndex:schemas.Integer});var Vector=class{static{__name(this,"Vector")}items;constructor(items){this.items=items}toBuffer(sink){if(!sink)return BufferSink.serialize(this);serializeToSink(sink,this.items.length,this.items)}toFriendlyJSON(){return this.items}};var Note=class _Note extends Vector{static{__name(this,"Note")}toJSON(){return this.toBuffer()}static get schema(){return schemas2.Buffer.transform(_Note.fromBuffer)}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _Note(reader.readVector(Fr))}static random(){let numItems=randomInt(10)+1,items=Array.from({length:numItems},()=>Fr.random());return new _Note(items)}toString(){return bufferToHex(this.toBuffer())}static fromString(str){return _Note.fromBuffer(hexToBuffer(str))}get length(){return this.items.length}equals(other){return this.items.length!==other.items.length?!1:this.items.every((item,index)=>item.equals(other.items[index]))}};var HashedValues=class _HashedValues{static{__name(this,"HashedValues")}values;hash;constructor(values,hash5){this.values=values,this.hash=hash5}getSize(){return this.values.length+1}static get schema(){return external_exports.object({values:external_exports.array(schemas2.Fr),hash:schemas2.Fr}).transform(_HashedValues.from)}static from(fields){return new _HashedValues(..._HashedValues.getFields(fields))}static getFields(fields){return[fields.values,fields.hash]}static random(){return new _HashedValues([Fr.random(),Fr.random()],Fr.random())}toBuffer(sink){if(!sink)return BufferSink.serialize(this);serializeToSink(sink,new Vector(this.values),this.hash)}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _HashedValues(reader.readVector(Fr),Fr.fromBuffer(reader))}static async fromArgs(args){return new _HashedValues(args,await computeVarArgsHash(args))}static async fromCalldata(calldata){return new _HashedValues(calldata,await computeCalldataHash(calldata))}};var NoteAndSlot=class _NoteAndSlot{static{__name(this,"NoteAndSlot")}note;storageSlot;randomness;noteTypeId;constructor(note,storageSlot,randomness,noteTypeId){this.note=note,this.storageSlot=storageSlot,this.randomness=randomness,this.noteTypeId=noteTypeId}static get schema(){return external_exports.object({note:Note.schema,storageSlot:schemas2.Fr,randomness:schemas2.Fr,noteTypeId:schemas2.NoteSelector}).transform(_NoteAndSlot.from)}static from(fields){return new _NoteAndSlot(fields.note,fields.storageSlot,fields.randomness,fields.noteTypeId)}static random(){return new _NoteAndSlot(Note.random(),Fr.random(),Fr.random(),NoteSelector.random())}},CountedContractClassLog=class _CountedContractClassLog{static{__name(this,"CountedContractClassLog")}log;counter;constructor(log2,counter){this.log=log2,this.counter=counter}static get schema(){return external_exports.object({log:ContractClassLog.schema,counter:schemas2.Integer}).transform(_CountedContractClassLog.from)}static from(fields){return new _CountedContractClassLog(fields.log,fields.counter)}isEmpty(){return this.log.isEmpty()&&!this.counter}},PrivateExecutionResult=class _PrivateExecutionResult{static{__name(this,"PrivateExecutionResult")}entrypoint;firstNullifier;publicFunctionCalldata;constructor(entrypoint,firstNullifier,publicFunctionCalldata){this.entrypoint=entrypoint,this.firstNullifier=firstNullifier,this.publicFunctionCalldata=publicFunctionCalldata}static get schema(){return external_exports.object({entrypoint:PrivateCallExecutionResult.schema,firstNullifier:schemas2.Fr,publicFunctionCalldata:external_exports.array(HashedValues.schema)}).transform(_PrivateExecutionResult.from)}static from(fields){return new _PrivateExecutionResult(fields.entrypoint,fields.firstNullifier,fields.publicFunctionCalldata)}static async random(nested=1){return new _PrivateExecutionResult(await PrivateCallExecutionResult.random(nested),Fr.random(),[HashedValues.random(),HashedValues.random()])}getSimulationAnchorBlockNumber(){return this.entrypoint.publicInputs.anchorBlockHeader.globalVariables.blockNumber}},PrivateCallExecutionResult=class _PrivateCallExecutionResult{static{__name(this,"PrivateCallExecutionResult")}acir;vk;partialWitness;publicInputs;newNotes;noteHashNullifierCounterMap;returnValues;offchainEffects;taggingIndexRanges;nestedExecutionResults;contractClassLogs;profileResult;constructor(acir,vk,partialWitness,publicInputs,newNotes,noteHashNullifierCounterMap,returnValues,offchainEffects,taggingIndexRanges,nestedExecutionResults,contractClassLogs,profileResult){this.acir=acir,this.vk=vk,this.partialWitness=partialWitness,this.publicInputs=publicInputs,this.newNotes=newNotes,this.noteHashNullifierCounterMap=noteHashNullifierCounterMap,this.returnValues=returnValues,this.offchainEffects=offchainEffects,this.taggingIndexRanges=taggingIndexRanges,this.nestedExecutionResults=nestedExecutionResults,this.contractClassLogs=contractClassLogs,this.profileResult=profileResult}static get schema(){return external_exports.object({acir:schemas2.Buffer,vk:schemas2.Buffer,partialWitness:mapSchema(external_exports.coerce.number(),external_exports.string()),publicInputs:PrivateCircuitPublicInputs.schema,newNotes:external_exports.array(NoteAndSlot.schema),noteHashNullifierCounterMap:mapSchema(external_exports.coerce.number(),external_exports.number()),returnValues:external_exports.array(schemas2.Fr),offchainEffects:external_exports.array(external_exports.object({data:external_exports.array(schemas2.Fr)})),taggingIndexRanges:external_exports.array(TaggingIndexRangeSchema),nestedExecutionResults:external_exports.array(external_exports.lazy(()=>_PrivateCallExecutionResult.schema)),contractClassLogs:external_exports.array(CountedContractClassLog.schema)}).transform(_PrivateCallExecutionResult.from)}static from(fields){return new _PrivateCallExecutionResult(fields.acir,fields.vk,fields.partialWitness,fields.publicInputs,fields.newNotes,fields.noteHashNullifierCounterMap,fields.returnValues,fields.offchainEffects,fields.taggingIndexRanges,fields.nestedExecutionResults,fields.contractClassLogs)}static async random(nested=1){return new _PrivateCallExecutionResult(randomBytes(4),randomBytes(4),new Map([[1,"one"]]),PrivateCircuitPublicInputs.empty(),[NoteAndSlot.random()],new Map([[0,0]]),[Fr.random()],[{data:[Fr.random()]}],[],await timesParallel(nested,()=>_PrivateCallExecutionResult.random(0)),[new CountedContractClassLog(await ContractClassLog.random(),randomInt(10))])}};function collectNoteHashNullifierCounterMap(execResult){let accum=new Map,collectNoteHashNullifierCounterMapRecursive=__name((callResult,accum2)=>{callResult.noteHashNullifierCounterMap.forEach((value,key)=>accum2.set(key,value)),callResult.nestedExecutionResults.forEach(nested=>collectNoteHashNullifierCounterMapRecursive(nested,accum2))},"collectNoteHashNullifierCounterMapRecursive");return collectNoteHashNullifierCounterMapRecursive(execResult.entrypoint,accum),accum}__name(collectNoteHashNullifierCounterMap,"collectNoteHashNullifierCounterMap");function getFinalMinRevertibleSideEffectCounter(execResult){let collectFinalMinRevertibleSideEffectCounterRecursive=__name(callResult=>callResult.nestedExecutionResults.reduce((counter,exec)=>{let nestedCounter=collectFinalMinRevertibleSideEffectCounterRecursive(exec);return nestedCounter||counter},callResult.publicInputs.minRevertibleSideEffectCounter.toNumber()),"collectFinalMinRevertibleSideEffectCounterRecursive");return collectFinalMinRevertibleSideEffectCounterRecursive(execResult.entrypoint)}__name(getFinalMinRevertibleSideEffectCounter,"getFinalMinRevertibleSideEffectCounter");function collectNested(executionStack,extractExecutionItems){return executionStack.flatMap(extractExecutionItems).concat(executionStack.flatMap(({nestedExecutionResults})=>collectNested(nestedExecutionResults,extractExecutionItems)))}__name(collectNested,"collectNested");import{inspect as inspect23}from"util";var _computedKey23;_computedKey23=inspect23.custom;var PublicCallRequestWithCalldata=class _PublicCallRequestWithCalldata{static{__name(this,"PublicCallRequestWithCalldata")}request;calldata;constructor(request,calldata){this.request=request,this.calldata=calldata}get functionSelector(){return FunctionSelector.fromField(this.calldata[0])}get args(){return this.calldata.slice(1)}static get schema(){return external_exports.object({request:PublicCallRequest.schema,calldata:external_exports.array(schemas2.Fr)}).transform(_PublicCallRequestWithCalldata.from)}static from(fields){return new _PublicCallRequestWithCalldata(fields.request,fields.calldata)}static fromPlainObject(obj){return obj instanceof _PublicCallRequestWithCalldata?obj:new _PublicCallRequestWithCalldata(PublicCallRequest.fromPlainObject(obj.request),obj.calldata.map(f=>Fr.fromPlainObject(f)))}toBuffer(sink){if(!sink)return BufferSink.serialize(this);serializeToSink(sink,this.request,new Vector(this.calldata))}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _PublicCallRequestWithCalldata(PublicCallRequest.fromBuffer(reader),reader.readVector(Fr))}static empty(){return new _PublicCallRequestWithCalldata(PublicCallRequest.empty(),[])}isEmpty(){return this.request.isEmpty()&&this.calldata.length===0}[_computedKey23](){return`PublicCallRequestWithCalldata {
|
|
142
|
+
}`}};import{BarretenbergSync as BarretenbergSync4}from"@aztec/bb.js";var Grumpkin=class{static{__name(this,"Grumpkin")}static generator=Point.fromBuffer(Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,2,207,19,94,117,6,164,93,99,45,39,13,69,241,24,18,148,131,63,196,141,130,63,39,44]));static async mul(point,scalar){await BarretenbergSync4.initSingleton();let response=BarretenbergSync4.getSingleton().grumpkinMul({point:{x:point.x.toBuffer(),y:point.y.toBuffer()},scalar:scalar.toBuffer()});return Point.fromBuffer(Buffer.concat([Buffer.from(response.point.x),Buffer.from(response.point.y)]))}static async add(a,b){await BarretenbergSync4.initSingleton();let response=BarretenbergSync4.getSingleton().grumpkinAdd({pointA:{x:a.x.toBuffer(),y:a.y.toBuffer()},pointB:{x:b.x.toBuffer(),y:b.y.toBuffer()}});return Point.fromBuffer(Buffer.concat([Buffer.from(response.point.x),Buffer.from(response.point.y)]))}static async batchMul(points,scalar){return await BarretenbergSync4.initSingleton(),BarretenbergSync4.getSingleton().grumpkinBatchMul({points:points.map(p=>({x:p.x.toBuffer(),y:p.y.toBuffer()})),scalar:scalar.toBuffer()}).points.map(p=>Point.fromBuffer(Buffer.concat([Buffer.from(p.x),Buffer.from(p.y)])))}static async getRandomFr(){await BarretenbergSync4.initSingleton();let response=BarretenbergSync4.getSingleton().grumpkinGetRandomFr({dummy:0});return Fr.fromBuffer(Buffer.from(response.value))}static async reduce512BufferToFr(uint512Buf){await BarretenbergSync4.initSingleton();let response=BarretenbergSync4.getSingleton().grumpkinReduce512({input:uint512Buf});return Fr.fromBuffer(Buffer.from(response.value))}};var import_hash3=__toESM(require_hash(),1);var sha512=__name(data=>Buffer.from(import_hash3.default.sha512().update(data).digest()),"sha512"),sha512ToGrumpkinScalar=__name(data=>{let buffer=serializeToBuffer(data);return GrumpkinScalar.fromBufferReduce(sha512(buffer))},"sha512ToGrumpkinScalar");function hashPublicKey(pk){return poseidon2HashWithSeparator([pk.x,pk.y],DomainSeparator.SINGLE_PUBLIC_KEY_HASH)}__name(hashPublicKey,"hashPublicKey");var PublicKey=Point;var PublicKeys=class _PublicKeys{static{__name(this,"PublicKeys")}npkMHash;ivpkM;ovpkMHash;tpkMHash;mspkMHash;fbpkMHash;constructor(npkMHash,ivpkM,ovpkMHash,tpkMHash,mspkMHash,fbpkMHash){this.npkMHash=npkMHash,this.ivpkM=ivpkM,this.ovpkMHash=ovpkMHash,this.tpkMHash=tpkMHash,this.mspkMHash=mspkMHash,this.fbpkMHash=fbpkMHash}static get schema(){return external_exports.object({npkMHash:schemas.Fr,ivpkM:schemas.Point,ovpkMHash:schemas.Fr,tpkMHash:schemas.Fr,mspkMHash:schemas.Fr,fbpkMHash:schemas.Fr}).transform(_PublicKeys.from)}static from(fields){return new _PublicKeys(fields.npkMHash,fields.ivpkM,fields.ovpkMHash,fields.tpkMHash,fields.mspkMHash,fields.fbpkMHash)}static fromPlainObject(obj){return obj instanceof _PublicKeys?obj:new _PublicKeys(Fr.fromPlainObject(obj.npkMHash),PublicKey.fromPlainObject(obj.ivpkM),Fr.fromPlainObject(obj.ovpkMHash),Fr.fromPlainObject(obj.tpkMHash),Fr.fromPlainObject(obj.mspkMHash),Fr.fromPlainObject(obj.fbpkMHash))}async hash(){if(this.isEmpty())return Fr.ZERO;let ivpkMHash=await hashPublicKey(this.ivpkM);return poseidon2HashWithSeparator([this.npkMHash,ivpkMHash,this.ovpkMHash,this.tpkMHash,this.mspkMHash,this.fbpkMHash],DomainSeparator.PUBLIC_KEYS_HASH)}isEmpty(){return this.npkMHash.isZero()&&this.ivpkM.isZero()&&this.ovpkMHash.isZero()&&this.tpkMHash.isZero()&&this.mspkMHash.isZero()&&this.fbpkMHash.isZero()}static default(){return new _PublicKeys(new Fr(DEFAULT_NPK_M_HASH),new PublicKey(new Fr(DEFAULT_IVPK_M_X),new Fr(DEFAULT_IVPK_M_Y)),new Fr(DEFAULT_OVPK_M_HASH),new Fr(DEFAULT_TPK_M_HASH),new Fr(DEFAULT_MSPK_M_HASH),new Fr(DEFAULT_FBPK_M_HASH))}static async random(){let npkM=await PublicKey.random(),ovpkM=await PublicKey.random(),tpkM=await PublicKey.random(),mspkM=await PublicKey.random(),fbpkM=await PublicKey.random();return new _PublicKeys(await hashPublicKey(npkM),await PublicKey.random(),await hashPublicKey(ovpkM),await hashPublicKey(tpkM),await hashPublicKey(mspkM),await hashPublicKey(fbpkM))}equals(other){return this.npkMHash.equals(other.npkMHash)&&this.ivpkM.equals(other.ivpkM)&&this.ovpkMHash.equals(other.ovpkMHash)&&this.tpkMHash.equals(other.tpkMHash)&&this.mspkMHash.equals(other.mspkMHash)&&this.fbpkMHash.equals(other.fbpkMHash)}toBuffer(){return serializeToBuffer([this.npkMHash,this.ivpkM,this.ovpkMHash,this.tpkMHash,this.mspkMHash,this.fbpkMHash])}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer),npkMHash=Fr.fromBuffer(reader),ivpkM=reader.readObject(PublicKey),ovpkMHash=Fr.fromBuffer(reader),tpkMHash=Fr.fromBuffer(reader),mspkMHash=Fr.fromBuffer(reader),fbpkMHash=Fr.fromBuffer(reader);return new _PublicKeys(npkMHash,ivpkM,ovpkMHash,tpkMHash,mspkMHash,fbpkMHash)}toNoirStruct(){return{npk_m_hash:this.npkMHash,ivpk_m:this.ivpkM.toWrappedNoirStruct(),ovpk_m_hash:this.ovpkMHash,tpk_m_hash:this.tpkMHash,mspk_m_hash:this.mspkMHash,fbpk_m_hash:this.fbpkMHash}}toFields(){return[this.npkMHash,this.ivpkM.x,this.ivpkM.y,this.ovpkMHash,this.tpkMHash,this.mspkMHash,this.fbpkMHash]}encodeToNoir(){return this.toFields()}static fromFields(fields){let reader=FieldReader.asReader(fields),npkMHash=reader.readField(),ivpkM=reader.readObject(PublicKey),ovpkMHash=reader.readField(),tpkMHash=reader.readField(),mspkMHash=reader.readField(),fbpkMHash=reader.readField();return new _PublicKeys(npkMHash,ivpkM,ovpkMHash,tpkMHash,mspkMHash,fbpkMHash)}toString(){return bufferToHex(this.toBuffer())}static fromString(keys){return _PublicKeys.fromBuffer(Buffer.from(withoutHexPrefix(keys),"hex"))}};function getKeyGenerator(prefix){return{n:DomainSeparator.NHK_M,iv:DomainSeparator.IVSK_M,ov:DomainSeparator.OVSK_M,t:DomainSeparator.TSK_M}[prefix]}__name(getKeyGenerator,"getKeyGenerator");function computeAppSecretKey(skM,app,keyPrefix){let generator=getKeyGenerator(keyPrefix);return poseidon2HashWithSeparator([skM.hi,skM.lo,app],generator)}__name(computeAppSecretKey,"computeAppSecretKey");function deriveMasterNullifierHidingSecretKey(secretKey){return sha512ToGrumpkinScalar([secretKey,DomainSeparator.NHK_M])}__name(deriveMasterNullifierHidingSecretKey,"deriveMasterNullifierHidingSecretKey");function deriveMasterIncomingViewingSecretKey(secretKey){return sha512ToGrumpkinScalar([secretKey,DomainSeparator.IVSK_M])}__name(deriveMasterIncomingViewingSecretKey,"deriveMasterIncomingViewingSecretKey");function deriveMasterOutgoingViewingSecretKey(secretKey){return sha512ToGrumpkinScalar([secretKey,DomainSeparator.OVSK_M])}__name(deriveMasterOutgoingViewingSecretKey,"deriveMasterOutgoingViewingSecretKey");function deriveMasterMessageSigningSecretKey(secretKey){return sha512ToGrumpkinScalar([secretKey,DomainSeparator.MSSK_M])}__name(deriveMasterMessageSigningSecretKey,"deriveMasterMessageSigningSecretKey");function deriveMasterFallbackSecretKey(secretKey){return sha512ToGrumpkinScalar([secretKey,DomainSeparator.FBSK_M])}__name(deriveMasterFallbackSecretKey,"deriveMasterFallbackSecretKey");function computePreaddress(publicKeysHash,partialAddress){return poseidon2HashWithSeparator([publicKeysHash,partialAddress],DomainSeparator.CONTRACT_ADDRESS_V2)}__name(computePreaddress,"computePreaddress");async function computeAddress(publicKeys,partialAddress){let preaddress=await computePreaddress(await publicKeys.hash(),partialAddress),address=await Grumpkin.add(await derivePublicKeyFromSecretKey(new Fq(preaddress.toBigInt())),publicKeys.ivpkM);return new AztecAddress(address.x)}__name(computeAddress,"computeAddress");async function computeAddressSecret(preaddress,ivsk){let addressSecretCandidate=ivsk.add(new Fq(preaddress.toBigInt()));return(await derivePublicKeyFromSecretKey(addressSecretCandidate)).y.toBigInt()<=(Fr.MODULUS-1n)/2n?addressSecretCandidate:new Fq(Fq.MODULUS-addressSecretCandidate.toBigInt())}__name(computeAddressSecret,"computeAddressSecret");function derivePublicKeyFromSecretKey(secretKey){return secretKey.isZero()?Promise.resolve(PublicKey.INFINITY):Grumpkin.mul(Grumpkin.generator,secretKey)}__name(derivePublicKeyFromSecretKey,"derivePublicKeyFromSecretKey");function deriveKeys(secretKey){return deriveKeysFromMasterSecretKeys({masterNullifierHidingSecretKey:deriveMasterNullifierHidingSecretKey(secretKey),masterIncomingViewingSecretKey:deriveMasterIncomingViewingSecretKey(secretKey),masterOutgoingViewingSecretKey:deriveMasterOutgoingViewingSecretKey(secretKey),masterTaggingSecretKey:sha512ToGrumpkinScalar([secretKey,DomainSeparator.TSK_M]),masterMessageSigningSecretKey:deriveMasterMessageSigningSecretKey(secretKey),masterFallbackSecretKey:deriveMasterFallbackSecretKey(secretKey)})}__name(deriveKeys,"deriveKeys");async function deriveKeysFromMasterSecretKeys(secretKeys){let{masterNullifierHidingSecretKey,masterIncomingViewingSecretKey,masterOutgoingViewingSecretKey,masterTaggingSecretKey,masterMessageSigningSecretKey,masterFallbackSecretKey}=secretKeys,masterNullifierHidingPublicKey=await derivePublicKeyFromSecretKey(masterNullifierHidingSecretKey),masterIncomingViewingPublicKey=await derivePublicKeyFromSecretKey(masterIncomingViewingSecretKey),masterOutgoingViewingPublicKey=await derivePublicKeyFromSecretKey(masterOutgoingViewingSecretKey),masterTaggingPublicKey=await derivePublicKeyFromSecretKey(masterTaggingSecretKey),masterMessageSigningPublicKey=await derivePublicKeyFromSecretKey(masterMessageSigningSecretKey),masterFallbackPublicKey=await derivePublicKeyFromSecretKey(masterFallbackSecretKey),publicKeys=new PublicKeys(await hashPublicKey(masterNullifierHidingPublicKey),masterIncomingViewingPublicKey,await hashPublicKey(masterOutgoingViewingPublicKey),await hashPublicKey(masterTaggingPublicKey),await hashPublicKey(masterMessageSigningPublicKey),await hashPublicKey(masterFallbackPublicKey));return{masterNullifierHidingSecretKey,masterIncomingViewingSecretKey,masterOutgoingViewingSecretKey,masterTaggingSecretKey,masterMessageSigningSecretKey,masterFallbackSecretKey,masterNullifierHidingPublicKey,masterOutgoingViewingPublicKey,masterTaggingPublicKey,masterMessageSigningPublicKey,masterFallbackPublicKey,publicKeys}}__name(deriveKeysFromMasterSecretKeys,"deriveKeysFromMasterSecretKeys");var AppTaggingSecretKind={UNCONSTRAINED:"unconstrained",CONSTRAINED:"constrained"},ONCHAIN_UNCONSTRAINED_DELIVERY_MODE=2,ONCHAIN_CONSTRAINED_DELIVERY_MODE=3;function appTaggingSecretKindFromDeliveryMode(deliveryMode){switch(deliveryMode){case ONCHAIN_UNCONSTRAINED_DELIVERY_MODE:return AppTaggingSecretKind.UNCONSTRAINED;case ONCHAIN_CONSTRAINED_DELIVERY_MODE:return AppTaggingSecretKind.CONSTRAINED;default:throw new Error(`Unrecognized delivery mode for tagging: ${deliveryMode}`)}}__name(appTaggingSecretKindFromDeliveryMode,"appTaggingSecretKindFromDeliveryMode");function deriveEcdhSharedSecretPoint(secretKey,publicKey){if(publicKey.isZero())throw new Error("Attempting to derive a shared secret with a zero public key. You have probably passed a zero public key in your Noir code somewhere thinking that the note won't be broadcast... but it was.");return Grumpkin.mul(publicKey,secretKey)}__name(deriveEcdhSharedSecretPoint,"deriveEcdhSharedSecretPoint");async function appSiloEcdhSharedSecret(secretKey,publicKey,contractAddress){let rawSharedSecret=await deriveEcdhSharedSecretPoint(secretKey,publicKey);return appSiloEcdhSharedSecretPoint(rawSharedSecret,contractAddress)}__name(appSiloEcdhSharedSecret,"appSiloEcdhSharedSecret");function appSiloEcdhSharedSecretPoint(point,app){return poseidon2HashWithSeparator([point.x,point.y,app],DomainSeparator.APP_SILOED_ECDH_SHARED_SECRET)}__name(appSiloEcdhSharedSecretPoint,"appSiloEcdhSharedSecretPoint");var AppTaggingSecretKindSchema=external_exports.union([external_exports.literal(AppTaggingSecretKind.UNCONSTRAINED),external_exports.literal(AppTaggingSecretKind.CONSTRAINED)]),AppTaggingSecret=class _AppTaggingSecret{static{__name(this,"AppTaggingSecret")}secret;app;kind;constructor(secret,app,kind=AppTaggingSecretKind.UNCONSTRAINED){this.secret=secret,this.app=app,this.kind=kind}static async computeDirectional(taggingSecretPoint,app,recipient){let appSiloedSecret=await appSiloEcdhSharedSecretPoint(taggingSecretPoint,app),directionalAppTaggingSecret=await poseidon2Hash([appSiloedSecret,recipient]);return new _AppTaggingSecret(directionalAppTaggingSecret,app)}static async computeAppSiloed(taggingSecretPoint,app,kind){return new _AppTaggingSecret(await appSiloEcdhSharedSecretPoint(taggingSecretPoint,app),app,kind)}static async computeViaEcdh(localAddress,localIvsk,externalAddress,app,recipient){let taggingSecretPoint=await computeSharedTaggingSecret(localAddress,localIvsk,externalAddress);if(taggingSecretPoint)return _AppTaggingSecret.computeDirectional(taggingSecretPoint,app,recipient)}toString(){return this.kind===AppTaggingSecretKind.UNCONSTRAINED?`${this.secret.toString()}:${this.app.toString()}`:`${this.kind}:${this.secret.toString()}:${this.app.toString()}`}static fromString(str){let parts=str.split(":");if(parts.length===2){let[secretStr,appStr]=parts;return new _AppTaggingSecret(Fr.fromString(secretStr),AztecAddress.fromStringUnsafe(appStr))}if(parts.length===3){let[kindStr,secretStr,appStr]=parts;return new _AppTaggingSecret(Fr.fromString(secretStr),AztecAddress.fromStringUnsafe(appStr),appTaggingSecretKindFromString(kindStr))}throw new Error(`Invalid AppTaggingSecret string: ${str}`)}};var AppTaggingSecretSchema=external_exports.object({kind:AppTaggingSecretKindSchema.default(AppTaggingSecretKind.UNCONSTRAINED),secret:Fr.schema,app:AztecAddress.schema}).transform(({kind,secret,app})=>new AppTaggingSecret(secret,app,kind));function appTaggingSecretKindFromString(kind){switch(kind){case AppTaggingSecretKind.CONSTRAINED:return AppTaggingSecretKind.CONSTRAINED;case AppTaggingSecretKind.UNCONSTRAINED:return AppTaggingSecretKind.UNCONSTRAINED;default:throw new Error(`Invalid AppTaggingSecret kind: ${kind}`)}}__name(appTaggingSecretKindFromString,"appTaggingSecretKindFromString");async function computeSharedTaggingSecret(localAddress,localIvsk,externalAddress){if(!await externalAddress.isValid())return;let externalAddressPoint=await externalAddress.toAddressPoint(),localPreaddress=await computePreaddress(await localAddress.publicKeys.hash(),localAddress.partialAddress),localAddressSecret=await computeAddressSecret(localPreaddress,localIvsk);return Grumpkin.mul(externalAddressPoint,localAddressSecret)}__name(computeSharedTaggingSecret,"computeSharedTaggingSecret");var TaggingIndexRangeSchema=external_exports.object({extendedSecret:AppTaggingSecretSchema,lowestIndex:schemas.Integer,highestIndex:schemas.Integer});var Vector=class{static{__name(this,"Vector")}items;constructor(items){this.items=items}toBuffer(sink){if(!sink)return BufferSink.serialize(this);serializeToSink(sink,this.items.length,this.items)}toFriendlyJSON(){return this.items}};var Note=class _Note extends Vector{static{__name(this,"Note")}toJSON(){return this.toBuffer()}static get schema(){return schemas2.Buffer.transform(_Note.fromBuffer)}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _Note(reader.readVector(Fr))}static random(){let numItems=randomInt(10)+1,items=Array.from({length:numItems},()=>Fr.random());return new _Note(items)}toString(){return bufferToHex(this.toBuffer())}static fromString(str){return _Note.fromBuffer(hexToBuffer(str))}get length(){return this.items.length}equals(other){return this.items.length!==other.items.length?!1:this.items.every((item,index)=>item.equals(other.items[index]))}};var HashedValues=class _HashedValues{static{__name(this,"HashedValues")}values;hash;constructor(values,hash5){this.values=values,this.hash=hash5}getSize(){return this.values.length+1}static get schema(){return external_exports.object({values:external_exports.array(schemas2.Fr),hash:schemas2.Fr}).transform(_HashedValues.from)}static from(fields){return new _HashedValues(..._HashedValues.getFields(fields))}static getFields(fields){return[fields.values,fields.hash]}static random(){return new _HashedValues([Fr.random(),Fr.random()],Fr.random())}toBuffer(sink){if(!sink)return BufferSink.serialize(this);serializeToSink(sink,new Vector(this.values),this.hash)}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _HashedValues(reader.readVector(Fr),Fr.fromBuffer(reader))}static async fromArgs(args){return new _HashedValues(args,await computeVarArgsHash(args))}static async fromCalldata(calldata){return new _HashedValues(calldata,await computeCalldataHash(calldata))}};var NoteAndSlot=class _NoteAndSlot{static{__name(this,"NoteAndSlot")}note;storageSlot;randomness;noteTypeId;constructor(note,storageSlot,randomness,noteTypeId){this.note=note,this.storageSlot=storageSlot,this.randomness=randomness,this.noteTypeId=noteTypeId}static get schema(){return external_exports.object({note:Note.schema,storageSlot:schemas2.Fr,randomness:schemas2.Fr,noteTypeId:schemas2.NoteSelector}).transform(_NoteAndSlot.from)}static from(fields){return new _NoteAndSlot(fields.note,fields.storageSlot,fields.randomness,fields.noteTypeId)}static random(){return new _NoteAndSlot(Note.random(),Fr.random(),Fr.random(),NoteSelector.random())}},CountedContractClassLog=class _CountedContractClassLog{static{__name(this,"CountedContractClassLog")}log;counter;constructor(log2,counter){this.log=log2,this.counter=counter}static get schema(){return external_exports.object({log:ContractClassLog.schema,counter:schemas2.Integer}).transform(_CountedContractClassLog.from)}static from(fields){return new _CountedContractClassLog(fields.log,fields.counter)}isEmpty(){return this.log.isEmpty()&&!this.counter}},PrivateExecutionResult=class _PrivateExecutionResult{static{__name(this,"PrivateExecutionResult")}entrypoint;firstNullifier;publicFunctionCalldata;constructor(entrypoint,firstNullifier,publicFunctionCalldata){this.entrypoint=entrypoint,this.firstNullifier=firstNullifier,this.publicFunctionCalldata=publicFunctionCalldata}static get schema(){return external_exports.object({entrypoint:PrivateCallExecutionResult.schema,firstNullifier:schemas2.Fr,publicFunctionCalldata:external_exports.array(HashedValues.schema)}).transform(_PrivateExecutionResult.from)}static from(fields){return new _PrivateExecutionResult(fields.entrypoint,fields.firstNullifier,fields.publicFunctionCalldata)}static async random(nested=1){return new _PrivateExecutionResult(await PrivateCallExecutionResult.random(nested),Fr.random(),[HashedValues.random(),HashedValues.random()])}getSimulationAnchorBlockNumber(){return this.entrypoint.publicInputs.anchorBlockHeader.globalVariables.blockNumber}},PrivateCallExecutionResult=class _PrivateCallExecutionResult{static{__name(this,"PrivateCallExecutionResult")}acir;vk;partialWitness;publicInputs;newNotes;noteHashNullifierCounterMap;returnValues;offchainEffects;taggingIndexRanges;nestedExecutionResults;contractClassLogs;profileResult;constructor(acir,vk,partialWitness,publicInputs,newNotes,noteHashNullifierCounterMap,returnValues,offchainEffects,taggingIndexRanges,nestedExecutionResults,contractClassLogs,profileResult){this.acir=acir,this.vk=vk,this.partialWitness=partialWitness,this.publicInputs=publicInputs,this.newNotes=newNotes,this.noteHashNullifierCounterMap=noteHashNullifierCounterMap,this.returnValues=returnValues,this.offchainEffects=offchainEffects,this.taggingIndexRanges=taggingIndexRanges,this.nestedExecutionResults=nestedExecutionResults,this.contractClassLogs=contractClassLogs,this.profileResult=profileResult}static get schema(){return external_exports.object({acir:schemas2.Buffer,vk:schemas2.Buffer,partialWitness:mapSchema(external_exports.coerce.number(),external_exports.string()),publicInputs:PrivateCircuitPublicInputs.schema,newNotes:external_exports.array(NoteAndSlot.schema),noteHashNullifierCounterMap:mapSchema(external_exports.coerce.number(),external_exports.number()),returnValues:external_exports.array(schemas2.Fr),offchainEffects:external_exports.array(external_exports.object({data:external_exports.array(schemas2.Fr)})),taggingIndexRanges:external_exports.array(TaggingIndexRangeSchema),nestedExecutionResults:external_exports.array(external_exports.lazy(()=>_PrivateCallExecutionResult.schema)),contractClassLogs:external_exports.array(CountedContractClassLog.schema)}).transform(_PrivateCallExecutionResult.from)}static from(fields){return new _PrivateCallExecutionResult(fields.acir,fields.vk,fields.partialWitness,fields.publicInputs,fields.newNotes,fields.noteHashNullifierCounterMap,fields.returnValues,fields.offchainEffects,fields.taggingIndexRanges,fields.nestedExecutionResults,fields.contractClassLogs)}static async random(nested=1){return new _PrivateCallExecutionResult(randomBytes(4),randomBytes(4),new Map([[1,"one"]]),PrivateCircuitPublicInputs.empty(),[NoteAndSlot.random()],new Map([[0,0]]),[Fr.random()],[{data:[Fr.random()]}],[],await timesParallel(nested,()=>_PrivateCallExecutionResult.random(0)),[new CountedContractClassLog(await ContractClassLog.random(),randomInt(10))])}};function collectNoteHashNullifierCounterMap(execResult){let accum=new Map,collectNoteHashNullifierCounterMapRecursive=__name((callResult,accum2)=>{callResult.noteHashNullifierCounterMap.forEach((value,key)=>accum2.set(key,value)),callResult.nestedExecutionResults.forEach(nested=>collectNoteHashNullifierCounterMapRecursive(nested,accum2))},"collectNoteHashNullifierCounterMapRecursive");return collectNoteHashNullifierCounterMapRecursive(execResult.entrypoint,accum),accum}__name(collectNoteHashNullifierCounterMap,"collectNoteHashNullifierCounterMap");function getFinalMinRevertibleSideEffectCounter(execResult){let collectFinalMinRevertibleSideEffectCounterRecursive=__name(callResult=>callResult.nestedExecutionResults.reduce((counter,exec)=>{let nestedCounter=collectFinalMinRevertibleSideEffectCounterRecursive(exec);return nestedCounter||counter},callResult.publicInputs.minRevertibleSideEffectCounter.toNumber()),"collectFinalMinRevertibleSideEffectCounterRecursive");return collectFinalMinRevertibleSideEffectCounterRecursive(execResult.entrypoint)}__name(getFinalMinRevertibleSideEffectCounter,"getFinalMinRevertibleSideEffectCounter");function collectNested(executionStack,extractExecutionItems){return executionStack.flatMap(extractExecutionItems).concat(executionStack.flatMap(({nestedExecutionResults})=>collectNested(nestedExecutionResults,extractExecutionItems)))}__name(collectNested,"collectNested");import{inspect as inspect23}from"util";var _computedKey23;_computedKey23=inspect23.custom;var PublicCallRequestWithCalldata=class _PublicCallRequestWithCalldata{static{__name(this,"PublicCallRequestWithCalldata")}request;calldata;constructor(request,calldata){this.request=request,this.calldata=calldata}get functionSelector(){return FunctionSelector.fromField(this.calldata[0])}get args(){return this.calldata.slice(1)}static get schema(){return external_exports.object({request:PublicCallRequest.schema,calldata:external_exports.array(schemas2.Fr)}).transform(_PublicCallRequestWithCalldata.from)}static from(fields){return new _PublicCallRequestWithCalldata(fields.request,fields.calldata)}static fromPlainObject(obj){return obj instanceof _PublicCallRequestWithCalldata?obj:new _PublicCallRequestWithCalldata(PublicCallRequest.fromPlainObject(obj.request),obj.calldata.map(f=>Fr.fromPlainObject(f)))}toBuffer(sink){if(!sink)return BufferSink.serialize(this);serializeToSink(sink,this.request,new Vector(this.calldata))}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _PublicCallRequestWithCalldata(PublicCallRequest.fromBuffer(reader),reader.readVector(Fr))}static empty(){return new _PublicCallRequestWithCalldata(PublicCallRequest.empty(),[])}isEmpty(){return this.request.isEmpty()&&this.calldata.length===0}[_computedKey23](){return`PublicCallRequestWithCalldata {
|
|
143
143
|
request: ${inspect23(this.request)}
|
|
144
144
|
calldata: ${this.calldata}
|
|
145
145
|
}`}};var TxHash=class _TxHash{static{__name(this,"TxHash")}hash;constructor(hash5){this.hash=hash5}static random(){return new _TxHash(Fr.random())}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new this(reader.readObject(Fr))}static fromString(str){return new _TxHash(Fr.fromString(str))}static fromBigInt(value){return new _TxHash(new Fr(value))}static fromField(value){return new _TxHash(value)}toBuffer(sink){if(!sink)return this.hash.toBuffer();this.hash.toBuffer(sink)}toString(){return this.hash.toString()}toBigInt(){return this.hash.toBigInt()}toJSON(){return this.toString()}equals(other){return this.hash.equals(other.hash)}static get schema(){return schemas2.BufferHex.transform(value=>new _TxHash(Fr.fromBuffer(value)))}static zero(){return new _TxHash(Fr.ZERO)}static get SIZE(){return Fr.SIZE_IN_BYTES}};var DebugLog=class _DebugLog{static{__name(this,"DebugLog")}contractAddress;level;message;fields;constructor(contractAddress,level,message,fields){this.contractAddress=contractAddress,this.level=level,this.message=message,this.fields=fields}static get schema(){return external_exports.object({contractAddress:AztecAddress.schema,level:external_exports.enum(LogLevels),message:external_exports.string(),fields:external_exports.array(schemas.Fr)}).transform(({contractAddress,level,message,fields})=>new _DebugLog(contractAddress,level,message,fields))}static fromPlainObject(obj){return obj instanceof _DebugLog?obj:new _DebugLog(AztecAddress.fromPlainObject(obj.contractAddress),obj.level,obj.message,obj.fields.map(f=>Fr.fromPlainObject(f)))}};import{inspect as inspect24}from"util";var _computedKey24;_computedKey24=inspect24.custom;var Buffer16=class _Buffer16{static{__name(this,"Buffer16")}buffer;static SIZE=16;static ZERO=new _Buffer16(Buffer.alloc(_Buffer16.SIZE));constructor(buffer){if(this.buffer=buffer,buffer.length!==_Buffer16.SIZE)throw new Error(`Expected buffer to have length ${_Buffer16.SIZE} but was ${buffer.length}`)}toBuffer(){return this.buffer}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _Buffer16(reader.readBytes(_Buffer16.SIZE))}equals(hash5){return this.buffer.equals(hash5.buffer)}isZero(){return this.buffer.equals(Buffer.alloc(16,0))}toString(){return bufferToHex(this.buffer)}[_computedKey24](){return`Buffer16<${this.toString()}>`}toJSON(){return this.toString()}toBigInt(){return deserializeBigInt(this.buffer,0,_Buffer16.SIZE).elem}static fromBigInt(hash5){return new _Buffer16(serializeBigInt(hash5,_Buffer16.SIZE))}static fromField(hash5){return new _Buffer16(serializeBigInt(hash5.toBigInt()))}static fromString(str){if(str.startsWith("0x")&&(str=str.slice(2)),str.length!==this.SIZE*2)throw new Error(`Expected string to be ${this.SIZE*2} characters long, but was ${str.length}`);return new _Buffer16(Buffer.from(str,"hex"))}static fromNumber(num){return new _Buffer16(serializeBigInt(BigInt(num),_Buffer16.SIZE))}static random(){return new _Buffer16(Buffer.from(randomBytes(_Buffer16.SIZE)))}};import{inspect as inspect25}from"util";var _computedKey25;_computedKey25=inspect25.custom;var PrivateToPublicAccumulatedData=class _PrivateToPublicAccumulatedData{static{__name(this,"PrivateToPublicAccumulatedData")}noteHashes;nullifiers;l2ToL1Msgs;privateLogs;contractClassLogsHashes;publicCallRequests;constructor(noteHashes,nullifiers,l2ToL1Msgs,privateLogs,contractClassLogsHashes,publicCallRequests){this.noteHashes=noteHashes,this.nullifiers=nullifiers,this.l2ToL1Msgs=l2ToL1Msgs,this.privateLogs=privateLogs,this.contractClassLogsHashes=contractClassLogsHashes,this.publicCallRequests=publicCallRequests}getSize(){return arraySerializedSizeOfNonEmpty(this.noteHashes)+arraySerializedSizeOfNonEmpty(this.nullifiers)+arraySerializedSizeOfNonEmpty(this.l2ToL1Msgs)+arraySerializedSizeOfNonEmpty(this.privateLogs)+arraySerializedSizeOfNonEmpty(this.contractClassLogsHashes)+arraySerializedSizeOfNonEmpty(this.publicCallRequests)}static getFields(fields){return[fields.noteHashes,fields.nullifiers,fields.l2ToL1Msgs,fields.privateLogs,fields.contractClassLogsHashes,fields.publicCallRequests]}static fromFields(fields){let reader=FieldReader.asReader(fields);return new this(reader.readFieldArray(64),reader.readFieldArray(64),reader.readArray(8,ScopedL2ToL1Message),reader.readArray(64,PrivateLog),reader.readArray(1,ScopedLogHash),reader.readArray(32,PublicCallRequest))}static from(fields){return new _PrivateToPublicAccumulatedData(..._PrivateToPublicAccumulatedData.getFields(fields))}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _PrivateToPublicAccumulatedData(reader.readArray(64,Fr),reader.readArray(64,Fr),reader.readArray(8,ScopedL2ToL1Message),reader.readArray(64,PrivateLog),reader.readArray(1,ScopedLogHash),reader.readArray(32,PublicCallRequest))}toBuffer(sink){if(!sink)return BufferSink.serialize(this);serializeToSink(sink,..._PrivateToPublicAccumulatedData.getFields(this))}toFields(){let fields=serializeToFields(..._PrivateToPublicAccumulatedData.getFields(this));if(fields.length!==1371)throw new Error(`Invalid number of fields for PrivateToPublicAccumulatedData. Expected ${1371}, got ${fields.length}`);return fields}static empty(){return new _PrivateToPublicAccumulatedData(makeTuple(64,Fr.zero),makeTuple(64,Fr.zero),makeTuple(8,ScopedL2ToL1Message.empty),makeTuple(64,PrivateLog.empty),makeTuple(1,ScopedLogHash.empty),makeTuple(32,PublicCallRequest.empty))}[_computedKey25](){return`PrivateToPublicAccumulatedData {
|
|
@@ -185,7 +185,7 @@ ${err.message}`);else throw err}}__name(getFunctionDebugMetadata,"getFunctionDeb
|
|
|
185
185
|
gasFees: { da:${this.gasFees.feePerDaGas}, l2:${this.gasFees.feePerL2Gas} },
|
|
186
186
|
totalManaUsed: ${this.totalManaUsed.toBigInt()},
|
|
187
187
|
accumulatedFees: ${this.accumulatedFees.toBigInt()},
|
|
188
|
-
}`}};var BlockTag=["latest","proposed","checkpointed","proven","finalized"],BlockTagWithoutLatestSchema=external_exports.union([external_exports.literal("proposed"),external_exports.literal("checkpointed"),external_exports.literal("proven"),external_exports.literal("finalized")]),BlockTagSchema=external_exports.union([external_exports.literal("latest"),BlockTagWithoutLatestSchema]),NormalizedBlockParameterSchema=external_exports.union([external_exports.object({number:BlockNumberSchema}).strict(),external_exports.object({hash:BlockHash.schema}).strict(),external_exports.object({archive:schemas.Fr}).strict(),external_exports.object({tag:BlockTagWithoutLatestSchema}).strict()]),BlockParameterSchema=external_exports.union([NormalizedBlockParameterSchema,BlockHash.schema,BlockTagSchema,BlockNumberSchema]);function inspectBlockParameter(param){return typeof param=="number"?param.toString():typeof param=="string"?param:"number"in param?`number=${param.number.toString()}`:"hash"in param?`hash=${param.hash.toString()}`:"archive"in param?`archive=${param.archive.toString()}`:"tag"in param?`tag=${param.tag}`:jsonStringify(param)}__name(inspectBlockParameter,"inspectBlockParameter");var BlockQuerySchema=external_exports.union([external_exports.object({number:BlockNumberSchema}).strict(),external_exports.object({hash:BlockHash.schema}).strict(),external_exports.object({archive:schemas.Fr}).strict(),external_exports.object({tag:BlockTagWithoutLatestSchema}).strict()]),BlocksQuerySchema=external_exports.union([external_exports.object({from:BlockNumberSchema,limit:external_exports.number().int().min(1),onlyCheckpointed:external_exports.boolean().optional()}).strict(),external_exports.object({epoch:EpochNumberSchema,onlyCheckpointed:external_exports.literal(!0)}).strict()]),CheckpointQuerySchema=external_exports.union([external_exports.object({number:CheckpointNumberSchema}).strict(),external_exports.object({slot:SlotNumberSchema}).strict(),external_exports.object({tag:external_exports.union([external_exports.literal("checkpointed"),external_exports.literal("proven"),external_exports.literal("finalized")])}).strict()]),CheckpointsQuerySchema=external_exports.union([external_exports.object({from:CheckpointNumberSchema,limit:external_exports.number().int().min(1)}).strict(),external_exports.object({epoch:EpochNumberSchema}).strict()]),ProposedCheckpointQuerySchema=external_exports.union([external_exports.object({number:CheckpointNumberSchema}).strict(),external_exports.object({slot:SlotNumberSchema}).strict(),external_exports.object({tag:external_exports.literal("proposed")}).strict()]),GENESIS_CHECKPOINT_HEADER_HASH=CheckpointHeader.empty().hash();var L2BlockIdSchema=external_exports.object({number:BlockNumberSchema,hash:external_exports.string()}),L2CheckpointIdSchema=external_exports.object({number:CheckpointNumberSchema,hash:external_exports.string()}),L2TipIdSchema=external_exports.object({block:L2BlockIdSchema,checkpoint:L2CheckpointIdSchema}),L2TipsSchema=external_exports.object({proposed:L2BlockIdSchema,checkpointed:L2TipIdSchema,proven:L2TipIdSchema,finalized:L2TipIdSchema});var StubInvocationError=class extends Error{static{__name(this,"StubInvocationError")}name="StubInvocationError";constructor(symbol2){super(`${symbol2} is stubbed in this bundle; this code path should never run`)}};function throwStub(symbol2){throw new StubInvocationError(symbol2)}__name(throwStub,"throwStub");var SECP_ORDER=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n,SECP_FIELD_ORDER=0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn,fieldStub=__name((byteSize,order)=>({BYTES:byteSize,ORDER:order,MASK:(1n<<BigInt(byteSize*8))-1n,ZERO:0n,ONE:1n,add:__name(()=>throwStub("secp256k1.add"),"add"),sub:__name(()=>throwStub("secp256k1.sub"),"sub"),mul:__name(()=>throwStub("secp256k1.mul"),"mul"),div:__name(()=>throwStub("secp256k1.div"),"div"),neg:__name(()=>throwStub("secp256k1.neg"),"neg"),sqr:__name(()=>throwStub("secp256k1.sqr"),"sqr"),sqrt:__name(()=>throwStub("secp256k1.sqrt"),"sqrt"),pow:__name(()=>throwStub("secp256k1.pow"),"pow"),inv:__name(()=>throwStub("secp256k1.inv"),"inv"),eql:__name(()=>throwStub("secp256k1.eql"),"eql"),isValid:__name(()=>throwStub("secp256k1.isValid"),"isValid"),is0:__name(()=>throwStub("secp256k1.is0"),"is0"),create:__name(()=>throwStub("secp256k1.create"),"create"),fromBytes:__name(()=>throwStub("secp256k1.fromBytes"),"fromBytes"),toBytes:__name(()=>throwStub("secp256k1.toBytes"),"toBytes")}),"fieldStub"),secp256k1={CURVE:{n:SECP_ORDER,p:SECP_FIELD_ORDER,Gx:0n,Gy:0n},fields:{Fp:fieldStub(32,SECP_FIELD_ORDER),Fr:fieldStub(32,SECP_ORDER)},ProjectivePoint:{ZERO:{x:0n,y:0n,z:0n,equals:__name(()=>throwStub("secp256k1.equals"),"equals")},BASE:{x:0n,y:0n,z:0n},fromHex:__name(()=>throwStub("secp256k1.fromHex"),"fromHex"),fromAffine:__name(()=>throwStub("secp256k1.fromAffine"),"fromAffine"),fromPrivateKey:__name(()=>throwStub("secp256k1.fromPrivateKey"),"fromPrivateKey")},Signature:{fromCompact:__name(()=>throwStub("secp256k1.Signature.fromCompact"),"fromCompact")},utils:{randomPrivateKey:__name(()=>throwStub("secp256k1.randomPrivateKey"),"randomPrivateKey"),isValidPrivateKey:__name(()=>throwStub("secp256k1.isValidPrivateKey"),"isValidPrivateKey"),normPrivateKeyToScalar:__name(()=>throwStub("secp256k1.normPrivateKeyToScalar"),"normPrivateKeyToScalar")},getPublicKey:__name(()=>throwStub("secp256k1.getPublicKey"),"getPublicKey"),sign:__name(()=>throwStub("secp256k1.sign"),"sign"),verify:__name(()=>throwStub("secp256k1.verify"),"verify"),getSharedSecret:__name(()=>throwStub("secp256k1.getSharedSecret"),"getSharedSecret")};var Signature=class _Signature{static{__name(this,"Signature")}r;s;v;size;empty;constructor(r2,s2,v){this.r=r2,this.s=s2,this.v=v,this.empty=r2.isZero()&&s2.isZero()&&v===0}static fromBuffer(buf){let reader=BufferReader.asReader(buf),r2=reader.readObject(Buffer32),s2=reader.readObject(Buffer32),v=reader.readNumber();return new _Signature(r2,s2,v)}static isValidString(sig){return/^0x[0-9a-f]{129,}$/i.test(sig)}static fromString(sig){let buf=hexToBuffer(sig),reader=BufferReader.asReader(buf),r2=reader.readObject(Buffer32),s2=reader.readObject(Buffer32),v=parseInt(sig.slice(130),16);return new _Signature(r2,s2,v)}static fromViemSignature(sig){return new _Signature(Buffer32.fromBuffer(hexToBuffer(sig.r)),Buffer32.fromBuffer(hexToBuffer(sig.s)),sig.v)}static fromViemTransactionSignature(sig){return new _Signature(Buffer32.fromBuffer(hexToBuffer(sig.r)),Buffer32.fromBuffer(hexToBuffer(sig.s)),sig.yParity)}static random(){let privateKey=randomBytes(32),message=randomBytes(32),{r:r2,s:s2,recovery}=secp256k1.sign(message,privateKey);return new _Signature(Buffer32.fromBigInt(r2),Buffer32.fromBigInt(s2),recovery?28:27)}static empty(){return new _Signature(Buffer32.ZERO,Buffer32.ZERO,0)}isEmpty(){return this.empty}equals(other){return this.r.equals(other.r)&&this.s.equals(other.s)&&this.v===other.v&&this.empty===other.empty}toBuffer(){return serializeToBuffer([this.r,this.s,this.v])}getSize(){return this.size?this.size:(this.size=this.toBuffer().length,this.size)}toString(){return`0x${this.r.buffer.toString("hex")}${this.s.buffer.toString("hex")}${this.v.toString(16)}`}toViemSignature(){return{r:this.r.toString(),s:this.s.toString(),v:this.v}}toViemTransactionSignature(){if(this.v!==0&&this.v!==1)throw new Error("Invalid transaction signature");return{r:this.r.toString(),s:this.s.toString(),yParity:this.v}}toJSON(){return this.toString()}static get schema(){return external_exports.string().refine(hasHexPrefix,"No hex prefix").refine(_Signature.isValidString,"Not a valid Ethereum signature").transform(_Signature.fromString)}};var CommitteeAttestation=class _CommitteeAttestation{static{__name(this,"CommitteeAttestation")}address;signature;constructor(address,signature){this.address=address,this.signature=signature}static get schema(){return external_exports.object({address:EthAddress.schema,signature:Signature.schema}).transform(({address,signature})=>new _CommitteeAttestation(address,signature))}static fromAddress(address){return new _CommitteeAttestation(address,Signature.empty())}static fromAddressAndSignature(address,signature){return new _CommitteeAttestation(address,signature)}static fromSignature(signature){return new _CommitteeAttestation(EthAddress.ZERO,signature)}static fromViem(viem){return new _CommitteeAttestation(EthAddress.fromString(viem.addr),Signature.fromViemSignature(viem.signature))}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer),address=reader.readObject(EthAddress),signature=reader.readObject(Signature);return new _CommitteeAttestation(address,signature)}static random(){return new _CommitteeAttestation(EthAddress.random(),Signature.random())}static empty(){return new _CommitteeAttestation(EthAddress.ZERO,Signature.empty())}static fromPacked(packed,committeeSize){let signatureIndicesBuffer=Buffer.from(packed.signatureIndices.slice(2),"hex"),dataBuffer=Buffer.from(packed.signaturesOrAddresses.slice(2),"hex"),attestations=[],dataIndex=0;for(let i=0;i<committeeSize;i++){let byteIndex=Math.floor(i/8),bitIndex=7-i%8;if(byteIndex<signatureIndicesBuffer.length&&(signatureIndicesBuffer[byteIndex]&1<<bitIndex)!==0){if(dataIndex+65>dataBuffer.length)throw new Error(`Insufficient data for signature at position ${i}`);let v=dataBuffer[dataIndex],r2=`0x${dataBuffer.subarray(dataIndex+1,dataIndex+33).toString("hex")}`,s2=`0x${dataBuffer.subarray(dataIndex+33,dataIndex+65).toString("hex")}`,signature=Signature.fromViemSignature({r:r2,s:s2,v});attestations.push(new _CommitteeAttestation(EthAddress.ZERO,signature)),dataIndex+=65}else{if(dataIndex+20>dataBuffer.length)throw new Error(`Insufficient data for address at position ${i}`);let addressBytes=dataBuffer.subarray(dataIndex,dataIndex+20),address=EthAddress.fromString(`0x${addressBytes.toString("hex")}`);attestations.push(new _CommitteeAttestation(address,Signature.empty())),dataIndex+=20}}return attestations}toBuffer(){return serializeToBuffer([this.address,this.signature])}equals(other){return this.address.equals(other.address)&&this.signature.equals(other.signature)}toViem(){return{addr:this.address.toString(),signature:this.signature.toViemSignature()}}};import{encodeAbiParameters,parseAbiParameters}from"viem";var Secp256k1Error=class extends Error{static{__name(this,"Secp256k1Error")}constructor(message,opts){super(message,opts),this.name="Secp256k1Error"}};function publicKeyToAddress(publicKey){let hash5=keccak256(publicKey.subarray(1));return new EthAddress(hash5.subarray(12))}__name(publicKeyToAddress,"publicKeyToAddress");function tryRecoverAddress(hash5,signature,opts){try{let publicKey=recoverPublicKey(hash5,signature,opts);return publicKeyToAddress(publicKey)}catch{return}}__name(tryRecoverAddress,"tryRecoverAddress");function toRecoveryBit(yParityOrV){if(yParityOrV===0||yParityOrV===1)return yParityOrV;if(yParityOrV===27)return 0;if(yParityOrV===28)return 1;throw new Secp256k1Error(`Invalid yParityOrV value ${yParityOrV}`)}__name(toRecoveryBit,"toRecoveryBit");function normalizeSignature(signature){let{r:r2,s:s2,v}=signature,sig=new secp256k1.Signature(r2.toBigInt(),s2.toBigInt());if(sig.hasHighS()){let newV=flipV(v),newS=sig.normalizeS().s;return new Signature(r2,Buffer32.fromBigInt(newS),toVFromYParityOrV(newV))}return new Signature(r2,s2,toVFromYParityOrV(v))}__name(normalizeSignature,"normalizeSignature");function toVFromYParityOrV(yParityOrV){if(yParityOrV===0||yParityOrV===1)return yParityOrV+27;if(yParityOrV===27||yParityOrV===28)return yParityOrV;throw new Secp256k1Error(`Invalid yParityOrV value ${yParityOrV}`)}__name(toVFromYParityOrV,"toVFromYParityOrV");function flipV(v){switch(v){case 27:return 28;case 28:return 27;case 0:return 1;case 1:return 0;default:throw new Secp256k1Error(`Invalid v value ${v}`)}}__name(flipV,"flipV");function recoverPublicKey(hash5,signature,opts={}){let{r:r2,s:s2,v}=signature;if(!opts.allowYParityAsV&&v!==27&&v!==28)throw new Secp256k1Error(`Invalid v value ${v} (expected 27 or 28)`);let recoveryBit=toRecoveryBit(v),sig=new secp256k1.Signature(r2.toBigInt(),s2.toBigInt()).addRecoveryBit(recoveryBit);if(!opts.allowMalleable&&sig.hasHighS())throw new Secp256k1Error("Signature has high s-value (malleable signature)");let publicKey=sig.recoverPublicKey(hash5.buffer).toHex(!1);return Buffer.from(publicKey,"hex")}__name(recoverPublicKey,"recoverPublicKey");var PROBE_HASH=Buffer32.fromBuffer(keccak256(Buffer.from("signature-recoverability-probe")));import{hashTypedData}from"viem";var EMPTY_COORDINATION_SIGNATURE_CONTEXT={chainId:0,rollupAddress:EthAddress.ZERO},coordinationSignatureContextSchema=external_exports.object({chainId:external_exports.number(),rollupAddress:EthAddress.schema});function coordinationSignatureContextEquals(a,b){return a.chainId===b.chainId&&a.rollupAddress.equals(b.rollupAddress)}__name(coordinationSignatureContextEquals,"coordinationSignatureContextEquals");function serializeCoordinationSignatureContext(ctx){return serializeToBuffer([ctx.chainId,ctx.rollupAddress])}__name(serializeCoordinationSignatureContext,"serializeCoordinationSignatureContext");function readCoordinationSignatureContext(reader){let chainId=reader.readNumber(),rollupAddress=reader.readObject(EthAddress);return{chainId,rollupAddress}}__name(readCoordinationSignatureContext,"readCoordinationSignatureContext");var COORDINATION_SIGNATURE_NAME="Aztec Rollup",COORDINATION_SIGNATURE_VERSION="1",EIP712_DOMAIN_FIELDS=[{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"}],COORDINATION_SIGNATURE_TYPES={EIP712Domain:EIP712_DOMAIN_FIELDS,BlockProposal:[{name:"payloadHash",type:"bytes32"}],CheckpointProposal:[{name:"payloadHash",type:"bytes32"}],CheckpointAttestation:[{name:"payloadHash",type:"bytes32"}],AttestationsAndSigners:[{name:"payloadHash",type:"bytes32"}],SignedTxs:[{name:"payloadHash",type:"bytes32"}]};function getCoordinationSignatureTypedDataForPayloadHash(payloadHash,type,context2){return{domain:{name:COORDINATION_SIGNATURE_NAME,version:COORDINATION_SIGNATURE_VERSION,chainId:context2.chainId,verifyingContract:context2.rollupAddress.toString()},types:COORDINATION_SIGNATURE_TYPES,primaryType:type,message:{payloadHash:payloadHash.toString()}}}__name(getCoordinationSignatureTypedDataForPayloadHash,"getCoordinationSignatureTypedDataForPayloadHash");function getCoordinationSignatureTypedData(signable){let payloadHash=getHashedSignaturePayload(signable);return getCoordinationSignatureTypedDataForPayloadHash(payloadHash,signable.primaryType,signable.signatureContext)}__name(getCoordinationSignatureTypedData,"getCoordinationSignatureTypedData");function getHashedSignaturePayloadTypedData(signable){return Buffer32.fromString(hashTypedData(getCoordinationSignatureTypedData(signable)))}__name(getHashedSignaturePayloadTypedData,"getHashedSignaturePayloadTypedData");function recoverCoordinationSigner(signable,signature){let digest2=getHashedSignaturePayloadTypedData(signable);return tryRecoverAddress(digest2,signature,{allowYParityAsV:!0})}__name(recoverCoordinationSigner,"recoverCoordinationSigner");function getHashedSignaturePayload(s2){return Buffer32.fromBuffer(keccak256(s2.getPayloadToSign()))}__name(getHashedSignaturePayload,"getHashedSignaturePayload");var CheckpointInfoSchema=external_exports.object({archive:schemas.Fr,lastArchive:schemas.Fr,slotNumber:SlotNumberSchema,checkpointNumber:CheckpointNumberSchema,timestamp:schemas.BigInt});function serializeCheckpointInfo(info){return serializeToBuffer(info.archive,info.lastArchive,info.slotNumber,info.checkpointNumber,info.timestamp)}__name(serializeCheckpointInfo,"serializeCheckpointInfo");function deserializeCheckpointInfo(buffer){let reader=BufferReader.asReader(buffer);return{archive:reader.readObject(Fr),lastArchive:reader.readObject(Fr),slotNumber:SlotNumber(reader.readNumber()),checkpointNumber:CheckpointNumber(reader.readNumber()),timestamp:reader.readBigInt()}}__name(deserializeCheckpointInfo,"deserializeCheckpointInfo");var ValidateCheckpointResultSchema=external_exports.union([external_exports.object({valid:external_exports.literal(!0)}),external_exports.object({valid:external_exports.literal(!1),checkpoint:CheckpointInfoSchema,committee:external_exports.array(schemas.EthAddress),epoch:EpochNumberSchema,seed:schemas.BigInt,attestors:external_exports.array(schemas.EthAddress),attestations:external_exports.array(CommitteeAttestation.schema),reason:external_exports.literal("insufficient-attestations")}),external_exports.object({valid:external_exports.literal(!1),checkpoint:CheckpointInfoSchema,committee:external_exports.array(schemas.EthAddress),epoch:EpochNumberSchema,seed:schemas.BigInt,attestors:external_exports.array(schemas.EthAddress),attestations:external_exports.array(CommitteeAttestation.schema),reason:external_exports.literal("invalid-attestation"),invalidIndex:external_exports.number()})]);function serializeValidateCheckpointResult(result){if(result.valid)return serializeToBuffer(!0);let checkpointBuffer=serializeCheckpointInfo(result.checkpoint);return serializeToBuffer(result.valid,result.reason,checkpointBuffer.length,checkpointBuffer,result.committee.length,result.committee,result.epoch,result.seed??0n,result.attestors.length,result.attestors,result.attestations.length,result.attestations,result.reason==="invalid-attestation"?result.invalidIndex:0)}__name(serializeValidateCheckpointResult,"serializeValidateCheckpointResult");function deserializeValidateCheckpointResult(bufferOrReader){let reader=BufferReader.asReader(bufferOrReader),valid=reader.readBoolean();if(valid)return{valid};let reason=reader.readString(64),checkpoint=deserializeCheckpointInfo(reader.readBuffer()),committee=reader.readVector(EthAddress,MAX_COMMITTEE_SIZE),epoch=EpochNumber(reader.readNumber()),seed=reader.readBigInt(),attestors=reader.readVector(EthAddress,MAX_COMMITTEE_SIZE),attestations=reader.readVector(CommitteeAttestation,MAX_COMMITTEE_SIZE),invalidIndex=reader.readNumber();if(reason==="insufficient-attestations")return{valid,reason,checkpoint,committee,epoch,seed,attestors,attestations};if(reason==="invalid-attestation")return{valid,reason,checkpoint,committee,epoch,seed,attestors,invalidIndex,attestations};{let _=reason;throw new Error(`Unknown reason: ${reason}`)}}__name(deserializeValidateCheckpointResult,"deserializeValidateCheckpointResult");var BlockInfoSchema=external_exports.object({blockHash:BlockHash.schema.optional(),archive:schemas.Fr,lastArchive:schemas.Fr,blockNumber:BlockNumberSchema,slotNumber:SlotNumberSchema,txCount:external_exports.number(),timestamp:schemas.BigInt});import{encodeAbiParameters as encodeAbiParameters2,parseAbiParameters as parseAbiParameters2}from"viem";var ConsensusPayload=class _ConsensusPayload{static{__name(this,"ConsensusPayload")}header;archive;feeAssetPriceModifier;signatureContext;primaryType;size;constructor(header,archive,feeAssetPriceModifier,signatureContext){this.header=header,this.archive=archive,this.feeAssetPriceModifier=feeAssetPriceModifier,this.signatureContext=signatureContext,this.primaryType="CheckpointAttestation"}static get schema(){return external_exports.object({header:CheckpointHeader.schema,archive:schemas.Fr,feeAssetPriceModifier:schemas.BigInt,signatureContext:coordinationSignatureContextSchema}).transform(obj=>new _ConsensusPayload(obj.header,obj.archive,obj.feeAssetPriceModifier,obj.signatureContext))}static getFields(fields){return[fields.header,fields.archive,fields.feeAssetPriceModifier,fields.signatureContext]}getPayloadToSign(){let abi=parseAbiParameters2("(bytes32, (int256), bytes32)"),archiveRoot=this.archive.toString(),headerHash=this.header.hash().toString(),encodedData=encodeAbiParameters2(abi,[[archiveRoot,[this.feeAssetPriceModifier],headerHash]]);return hexToBuffer(encodedData)}getPayloadHash(){return keccak256(this.getPayloadToSign())}toBuffer(){return serializeToBuffer([this.header,this.archive,serializeSignedBigInt(this.feeAssetPriceModifier),serializeCoordinationSignatureContext(this.signatureContext)])}equals(other){let otherHeader="checkpointHeader"in other?other.checkpointHeader:other.header,otherModifier="feeAssetPriceModifier"in other?other.feeAssetPriceModifier:0n;return this.header.equals(otherHeader)&&this.archive.equals(other.archive)&&this.feeAssetPriceModifier===otherModifier&&coordinationSignatureContextEquals(this.signatureContext,other.signatureContext)}static fromBuffer(buf){let reader=BufferReader.asReader(buf),header=reader.readObject(CheckpointHeader),archive=reader.readObject(Fr),feeAssetPriceModifier=reader.readInt256(),signatureContext=readCoordinationSignatureContext(reader);return new _ConsensusPayload(header,archive,feeAssetPriceModifier,signatureContext)}static fromFields(fields){return new _ConsensusPayload(fields.header,fields.archive,fields.feeAssetPriceModifier,fields.signatureContext)}static fromCheckpoint(checkpoint,signatureContext){return new _ConsensusPayload(checkpoint.header,checkpoint.archive.root,checkpoint.feeAssetPriceModifier,signatureContext)}static empty(){return new _ConsensusPayload(CheckpointHeader.empty(),Fr.ZERO,0n,EMPTY_COORDINATION_SIGNATURE_CONTEXT)}static random(){return new _ConsensusPayload(CheckpointHeader.random(),Fr.random(),0n,EMPTY_COORDINATION_SIGNATURE_CONTEXT)}getSize(){return this.size?this.size:(this.size=this.toBuffer().length,this.size)}toInspect(){return{header:this.header.toInspect(),archive:this.archive.toString(),feeAssetPriceModifier:this.feeAssetPriceModifier.toString(),chainId:this.signatureContext.chainId,rollupAddress:this.signatureContext.rollupAddress.toString()}}toString(){return`header: ${this.header.toString()}, archive: ${this.archive.toString()}, feeAssetPriceModifier: ${this.feeAssetPriceModifier}, chainId: ${this.signatureContext.chainId}, rollupAddress: ${this.signatureContext.rollupAddress.toString()}`}};var shaMerkleHash=__name((left,right)=>sha256Trunc(Buffer.concat([left,right])),"shaMerkleHash");function computeBalancedMerkleTreeRoot(leaves,hasher=shaMerkleHash){let height=getTreeHeight(leaves),nodes=leaves.slice();for(let i=0;i<height;++i){let j=0;for(;j<nodes.length/2;++j){let l=nodes[j*2],r2=nodes[j*2+1];nodes[j]=hasher(l,r2)}nodes=nodes.slice(0,j)}return nodes[0]}__name(computeBalancedMerkleTreeRoot,"computeBalancedMerkleTreeRoot");function getTreeHeight(leaves){if(leaves.length===0)throw new Error("Cannot compute a Merkle root with no leaves");let height=Math.log2(leaves.length);if(!Number.isInteger(height))throw new Error("Cannot compute a Merkle root with a non-power-of-two number of leaves");return height}__name(getTreeHeight,"getTreeHeight");var MerkleTree=class{static{__name(this,"MerkleTree")}height;nodes;constructor(height,nodes){this.height=height,this.nodes=nodes;let expectedNodeCount=2**(height+1)-1;if(nodes.length!==expectedNodeCount)throw new Error(`Invalid node count for Merkle tree: got ${nodes.length} but expected ${expectedNodeCount}`)}get root(){return this.nodes[this.nodes.length-1]}get leaves(){return this.nodes.slice(0,2**this.height)}getSiblingPath(leafIndexOrLeaf){if(Buffer.isBuffer(leafIndexOrLeaf))return this.getSiblingPath(this.getIndex(leafIndexOrLeaf));let leafIndex=leafIndexOrLeaf;if(leafIndex<0||leafIndex>=2**this.height)throw new Error(`Invalid leaf index: got ${leafIndex} but leaves count is ${2**this.height}`);let tree=this.nodes,rowSize=Math.ceil(tree.length/2),rowOffset=0,index=leafIndex,siblingPath=[];for(;rowSize>1;){let isRight=index&1;siblingPath.push(tree[rowOffset+index+(isRight?-1:1)]),rowOffset+=rowSize,rowSize>>=1,index>>=1}return siblingPath}getIndex(element){return this.leaves.findIndex(leaf=>leaf.equals(element))}drawTree(elemSize=8){let levels2=[],tree=this.nodes,maxRowSize=Math.ceil(tree.length/2),paddingSize=1,rowSize=maxRowSize,rowOffset=0;for(;rowSize>0;)levels2.push(tree.slice(rowOffset,rowOffset+rowSize).map(n=>n.toString("hex").slice(0,elemSize)+" ".repeat((paddingSize-1)*(elemSize+1)))),rowOffset+=rowSize,paddingSize<<=1,rowSize>>=1;return levels2.reverse().map(row=>row.join(" ")).join(`
|
|
188
|
+
}`}};var BlockTag=["latest","proposed","checkpointed","proven","finalized"],BlockTagWithoutLatestSchema=external_exports.union([external_exports.literal("proposed"),external_exports.literal("checkpointed"),external_exports.literal("proven"),external_exports.literal("finalized")]),BlockTagSchema=external_exports.union([external_exports.literal("latest"),BlockTagWithoutLatestSchema]),NormalizedBlockParameterSchema=external_exports.union([external_exports.object({number:BlockNumberSchema}).strict(),external_exports.object({hash:BlockHash.schema}).strict(),external_exports.object({archive:schemas.Fr}).strict(),external_exports.object({tag:BlockTagWithoutLatestSchema}).strict()]),BlockParameterSchema=external_exports.union([NormalizedBlockParameterSchema,BlockHash.schema,BlockTagSchema,BlockNumberSchema]);function inspectBlockParameter(param){return typeof param=="number"?param.toString():typeof param=="string"?param:"number"in param?`number=${param.number.toString()}`:"hash"in param?`hash=${param.hash.toString()}`:"archive"in param?`archive=${param.archive.toString()}`:"tag"in param?`tag=${param.tag}`:jsonStringify(param)}__name(inspectBlockParameter,"inspectBlockParameter");var BlockQuerySchema=external_exports.union([external_exports.object({number:BlockNumberSchema}).strict(),external_exports.object({hash:BlockHash.schema}).strict(),external_exports.object({archive:schemas.Fr}).strict(),external_exports.object({tag:BlockTagWithoutLatestSchema}).strict()]),BlocksQuerySchema=external_exports.union([external_exports.object({from:BlockNumberSchema,limit:external_exports.number().int().min(1),onlyCheckpointed:external_exports.boolean().optional()}).strict(),external_exports.object({epoch:EpochNumberSchema,onlyCheckpointed:external_exports.literal(!0)}).strict()]),CheckpointQuerySchema=external_exports.union([external_exports.object({number:CheckpointNumberSchema}).strict(),external_exports.object({slot:SlotNumberSchema}).strict(),external_exports.object({tag:external_exports.union([external_exports.literal("checkpointed"),external_exports.literal("proven"),external_exports.literal("finalized")])}).strict()]),CheckpointsQuerySchema=external_exports.union([external_exports.object({from:CheckpointNumberSchema,limit:external_exports.number().int().min(1)}).strict(),external_exports.object({fromSlot:SlotNumberSchema,limit:external_exports.number().int().min(1),reverse:external_exports.boolean().optional()}).strict(),external_exports.object({epoch:EpochNumberSchema}).strict()]),ProposedCheckpointQuerySchema=external_exports.union([external_exports.object({number:CheckpointNumberSchema}).strict(),external_exports.object({slot:SlotNumberSchema}).strict(),external_exports.object({tag:external_exports.literal("proposed")}).strict()]),GENESIS_CHECKPOINT_HEADER_HASH=CheckpointHeader.empty().hash();var L2BlockIdSchema=external_exports.object({number:BlockNumberSchema,hash:external_exports.string()}),L2CheckpointIdSchema=external_exports.object({number:CheckpointNumberSchema,hash:external_exports.string()}),L2TipIdSchema=external_exports.object({block:L2BlockIdSchema,checkpoint:L2CheckpointIdSchema}),L2TipsSchema=external_exports.object({proposed:L2BlockIdSchema,checkpointed:L2TipIdSchema,proven:L2TipIdSchema,finalized:L2TipIdSchema});var StubInvocationError=class extends Error{static{__name(this,"StubInvocationError")}name="StubInvocationError";constructor(symbol2){super(`${symbol2} is stubbed in this bundle; this code path should never run`)}};function throwStub(symbol2){throw new StubInvocationError(symbol2)}__name(throwStub,"throwStub");var SECP_ORDER=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n,SECP_FIELD_ORDER=0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn,fieldStub=__name((byteSize,order)=>({BYTES:byteSize,ORDER:order,MASK:(1n<<BigInt(byteSize*8))-1n,ZERO:0n,ONE:1n,add:__name(()=>throwStub("secp256k1.add"),"add"),sub:__name(()=>throwStub("secp256k1.sub"),"sub"),mul:__name(()=>throwStub("secp256k1.mul"),"mul"),div:__name(()=>throwStub("secp256k1.div"),"div"),neg:__name(()=>throwStub("secp256k1.neg"),"neg"),sqr:__name(()=>throwStub("secp256k1.sqr"),"sqr"),sqrt:__name(()=>throwStub("secp256k1.sqrt"),"sqrt"),pow:__name(()=>throwStub("secp256k1.pow"),"pow"),inv:__name(()=>throwStub("secp256k1.inv"),"inv"),eql:__name(()=>throwStub("secp256k1.eql"),"eql"),isValid:__name(()=>throwStub("secp256k1.isValid"),"isValid"),is0:__name(()=>throwStub("secp256k1.is0"),"is0"),create:__name(()=>throwStub("secp256k1.create"),"create"),fromBytes:__name(()=>throwStub("secp256k1.fromBytes"),"fromBytes"),toBytes:__name(()=>throwStub("secp256k1.toBytes"),"toBytes")}),"fieldStub"),secp256k1={CURVE:{n:SECP_ORDER,p:SECP_FIELD_ORDER,Gx:0n,Gy:0n},fields:{Fp:fieldStub(32,SECP_FIELD_ORDER),Fr:fieldStub(32,SECP_ORDER)},ProjectivePoint:{ZERO:{x:0n,y:0n,z:0n,equals:__name(()=>throwStub("secp256k1.equals"),"equals")},BASE:{x:0n,y:0n,z:0n},fromHex:__name(()=>throwStub("secp256k1.fromHex"),"fromHex"),fromAffine:__name(()=>throwStub("secp256k1.fromAffine"),"fromAffine"),fromPrivateKey:__name(()=>throwStub("secp256k1.fromPrivateKey"),"fromPrivateKey")},Signature:{fromCompact:__name(()=>throwStub("secp256k1.Signature.fromCompact"),"fromCompact")},utils:{randomPrivateKey:__name(()=>throwStub("secp256k1.randomPrivateKey"),"randomPrivateKey"),isValidPrivateKey:__name(()=>throwStub("secp256k1.isValidPrivateKey"),"isValidPrivateKey"),normPrivateKeyToScalar:__name(()=>throwStub("secp256k1.normPrivateKeyToScalar"),"normPrivateKeyToScalar")},getPublicKey:__name(()=>throwStub("secp256k1.getPublicKey"),"getPublicKey"),sign:__name(()=>throwStub("secp256k1.sign"),"sign"),verify:__name(()=>throwStub("secp256k1.verify"),"verify"),getSharedSecret:__name(()=>throwStub("secp256k1.getSharedSecret"),"getSharedSecret")};var Signature=class _Signature{static{__name(this,"Signature")}r;s;v;size;empty;constructor(r2,s2,v){this.r=r2,this.s=s2,this.v=v,this.empty=r2.isZero()&&s2.isZero()&&v===0}static fromBuffer(buf){let reader=BufferReader.asReader(buf),r2=reader.readObject(Buffer32),s2=reader.readObject(Buffer32),v=reader.readNumber();return new _Signature(r2,s2,v)}static isValidString(sig){return/^0x[0-9a-f]{129,}$/i.test(sig)}static fromString(sig){let buf=hexToBuffer(sig),reader=BufferReader.asReader(buf),r2=reader.readObject(Buffer32),s2=reader.readObject(Buffer32),v=parseInt(sig.slice(130),16);return new _Signature(r2,s2,v)}static fromViemSignature(sig){return new _Signature(Buffer32.fromBuffer(hexToBuffer(sig.r)),Buffer32.fromBuffer(hexToBuffer(sig.s)),sig.v)}static fromViemTransactionSignature(sig){return new _Signature(Buffer32.fromBuffer(hexToBuffer(sig.r)),Buffer32.fromBuffer(hexToBuffer(sig.s)),sig.yParity)}static random(){let privateKey=randomBytes(32),message=randomBytes(32),{r:r2,s:s2,recovery}=secp256k1.sign(message,privateKey);return new _Signature(Buffer32.fromBigInt(r2),Buffer32.fromBigInt(s2),recovery?28:27)}static empty(){return new _Signature(Buffer32.ZERO,Buffer32.ZERO,0)}isEmpty(){return this.empty}equals(other){return this.r.equals(other.r)&&this.s.equals(other.s)&&this.v===other.v&&this.empty===other.empty}toBuffer(){return serializeToBuffer([this.r,this.s,this.v])}getSize(){return this.size?this.size:(this.size=this.toBuffer().length,this.size)}toString(){return`0x${this.r.buffer.toString("hex")}${this.s.buffer.toString("hex")}${this.v.toString(16)}`}toViemSignature(){return{r:this.r.toString(),s:this.s.toString(),v:this.v}}toViemTransactionSignature(){if(this.v!==0&&this.v!==1)throw new Error("Invalid transaction signature");return{r:this.r.toString(),s:this.s.toString(),yParity:this.v}}toJSON(){return this.toString()}static get schema(){return external_exports.string().refine(hasHexPrefix,"No hex prefix").refine(_Signature.isValidString,"Not a valid Ethereum signature").transform(_Signature.fromString)}};var CommitteeAttestation=class _CommitteeAttestation{static{__name(this,"CommitteeAttestation")}address;signature;constructor(address,signature){this.address=address,this.signature=signature}static get schema(){return external_exports.object({address:EthAddress.schema,signature:Signature.schema}).transform(({address,signature})=>new _CommitteeAttestation(address,signature))}static fromAddress(address){return new _CommitteeAttestation(address,Signature.empty())}static fromAddressAndSignature(address,signature){return new _CommitteeAttestation(address,signature)}static fromSignature(signature){return new _CommitteeAttestation(EthAddress.ZERO,signature)}static fromViem(viem){return new _CommitteeAttestation(EthAddress.fromString(viem.addr),Signature.fromViemSignature(viem.signature))}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer),address=reader.readObject(EthAddress),signature=reader.readObject(Signature);return new _CommitteeAttestation(address,signature)}static random(){return new _CommitteeAttestation(EthAddress.random(),Signature.random())}static empty(){return new _CommitteeAttestation(EthAddress.ZERO,Signature.empty())}static fromPacked(packed,committeeSize){let signatureIndicesBuffer=Buffer.from(packed.signatureIndices.slice(2),"hex"),dataBuffer=Buffer.from(packed.signaturesOrAddresses.slice(2),"hex"),attestations=[],dataIndex=0;for(let i=0;i<committeeSize;i++){let byteIndex=Math.floor(i/8),bitIndex=7-i%8;if(byteIndex<signatureIndicesBuffer.length&&(signatureIndicesBuffer[byteIndex]&1<<bitIndex)!==0){if(dataIndex+65>dataBuffer.length)throw new Error(`Insufficient data for signature at position ${i}`);let v=dataBuffer[dataIndex],r2=`0x${dataBuffer.subarray(dataIndex+1,dataIndex+33).toString("hex")}`,s2=`0x${dataBuffer.subarray(dataIndex+33,dataIndex+65).toString("hex")}`,signature=Signature.fromViemSignature({r:r2,s:s2,v});attestations.push(new _CommitteeAttestation(EthAddress.ZERO,signature)),dataIndex+=65}else{if(dataIndex+20>dataBuffer.length)throw new Error(`Insufficient data for address at position ${i}`);let addressBytes=dataBuffer.subarray(dataIndex,dataIndex+20),address=EthAddress.fromString(`0x${addressBytes.toString("hex")}`);attestations.push(new _CommitteeAttestation(address,Signature.empty())),dataIndex+=20}}return attestations}toBuffer(){return serializeToBuffer([this.address,this.signature])}equals(other){return this.address.equals(other.address)&&this.signature.equals(other.signature)}toViem(){return{addr:this.address.toString(),signature:this.signature.toViemSignature()}}};import{encodeAbiParameters,parseAbiParameters}from"viem";var Secp256k1Error=class extends Error{static{__name(this,"Secp256k1Error")}constructor(message,opts){super(message,opts),this.name="Secp256k1Error"}};function publicKeyToAddress(publicKey){let hash5=keccak256(publicKey.subarray(1));return new EthAddress(hash5.subarray(12))}__name(publicKeyToAddress,"publicKeyToAddress");function tryRecoverAddress(hash5,signature,opts){try{let publicKey=recoverPublicKey(hash5,signature,opts);return publicKeyToAddress(publicKey)}catch{return}}__name(tryRecoverAddress,"tryRecoverAddress");function toRecoveryBit(yParityOrV){if(yParityOrV===0||yParityOrV===1)return yParityOrV;if(yParityOrV===27)return 0;if(yParityOrV===28)return 1;throw new Secp256k1Error(`Invalid yParityOrV value ${yParityOrV}`)}__name(toRecoveryBit,"toRecoveryBit");function normalizeSignature(signature){let{r:r2,s:s2,v}=signature,sig=new secp256k1.Signature(r2.toBigInt(),s2.toBigInt());if(sig.hasHighS()){let newV=flipV(v),newS=sig.normalizeS().s;return new Signature(r2,Buffer32.fromBigInt(newS),toVFromYParityOrV(newV))}return new Signature(r2,s2,toVFromYParityOrV(v))}__name(normalizeSignature,"normalizeSignature");function toVFromYParityOrV(yParityOrV){if(yParityOrV===0||yParityOrV===1)return yParityOrV+27;if(yParityOrV===27||yParityOrV===28)return yParityOrV;throw new Secp256k1Error(`Invalid yParityOrV value ${yParityOrV}`)}__name(toVFromYParityOrV,"toVFromYParityOrV");function flipV(v){switch(v){case 27:return 28;case 28:return 27;case 0:return 1;case 1:return 0;default:throw new Secp256k1Error(`Invalid v value ${v}`)}}__name(flipV,"flipV");function recoverPublicKey(hash5,signature,opts={}){let{r:r2,s:s2,v}=signature;if(!opts.allowYParityAsV&&v!==27&&v!==28)throw new Secp256k1Error(`Invalid v value ${v} (expected 27 or 28)`);let recoveryBit=toRecoveryBit(v),sig=new secp256k1.Signature(r2.toBigInt(),s2.toBigInt()).addRecoveryBit(recoveryBit);if(!opts.allowMalleable&&sig.hasHighS())throw new Secp256k1Error("Signature has high s-value (malleable signature)");let publicKey=sig.recoverPublicKey(hash5.buffer).toHex(!1);return Buffer.from(publicKey,"hex")}__name(recoverPublicKey,"recoverPublicKey");var PROBE_HASH=Buffer32.fromBuffer(keccak256(Buffer.from("signature-recoverability-probe")));import{hashTypedData}from"viem";var EMPTY_COORDINATION_SIGNATURE_CONTEXT={chainId:0,rollupAddress:EthAddress.ZERO},coordinationSignatureContextSchema=external_exports.object({chainId:external_exports.number(),rollupAddress:EthAddress.schema});function coordinationSignatureContextEquals(a,b){return a.chainId===b.chainId&&a.rollupAddress.equals(b.rollupAddress)}__name(coordinationSignatureContextEquals,"coordinationSignatureContextEquals");function serializeCoordinationSignatureContext(ctx){return serializeToBuffer([ctx.chainId,ctx.rollupAddress])}__name(serializeCoordinationSignatureContext,"serializeCoordinationSignatureContext");function readCoordinationSignatureContext(reader){let chainId=reader.readNumber(),rollupAddress=reader.readObject(EthAddress);return{chainId,rollupAddress}}__name(readCoordinationSignatureContext,"readCoordinationSignatureContext");var COORDINATION_SIGNATURE_NAME="Aztec Rollup",COORDINATION_SIGNATURE_VERSION="1",EIP712_DOMAIN_FIELDS=[{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"}],COORDINATION_SIGNATURE_TYPES={EIP712Domain:EIP712_DOMAIN_FIELDS,BlockProposal:[{name:"payloadHash",type:"bytes32"}],CheckpointProposal:[{name:"payloadHash",type:"bytes32"}],CheckpointAttestation:[{name:"payloadHash",type:"bytes32"}],AttestationsAndSigners:[{name:"payloadHash",type:"bytes32"}],SignedTxs:[{name:"payloadHash",type:"bytes32"}]};function getCoordinationSignatureTypedDataForPayloadHash(payloadHash,type,context2){return{domain:{name:COORDINATION_SIGNATURE_NAME,version:COORDINATION_SIGNATURE_VERSION,chainId:context2.chainId,verifyingContract:context2.rollupAddress.toString()},types:COORDINATION_SIGNATURE_TYPES,primaryType:type,message:{payloadHash:payloadHash.toString()}}}__name(getCoordinationSignatureTypedDataForPayloadHash,"getCoordinationSignatureTypedDataForPayloadHash");function getCoordinationSignatureTypedData(signable){let payloadHash=getHashedSignaturePayload(signable);return getCoordinationSignatureTypedDataForPayloadHash(payloadHash,signable.primaryType,signable.signatureContext)}__name(getCoordinationSignatureTypedData,"getCoordinationSignatureTypedData");function getHashedSignaturePayloadTypedData(signable){return Buffer32.fromString(hashTypedData(getCoordinationSignatureTypedData(signable)))}__name(getHashedSignaturePayloadTypedData,"getHashedSignaturePayloadTypedData");function recoverCoordinationSigner(signable,signature){let digest2=getHashedSignaturePayloadTypedData(signable);return tryRecoverAddress(digest2,signature,{allowYParityAsV:!0})}__name(recoverCoordinationSigner,"recoverCoordinationSigner");function getHashedSignaturePayload(s2){return Buffer32.fromBuffer(keccak256(s2.getPayloadToSign()))}__name(getHashedSignaturePayload,"getHashedSignaturePayload");var CheckpointInfoSchema=external_exports.object({archive:schemas.Fr,lastArchive:schemas.Fr,slotNumber:SlotNumberSchema,checkpointNumber:CheckpointNumberSchema,timestamp:schemas.BigInt});function serializeCheckpointInfo(info){return serializeToBuffer(info.archive,info.lastArchive,info.slotNumber,info.checkpointNumber,info.timestamp)}__name(serializeCheckpointInfo,"serializeCheckpointInfo");function deserializeCheckpointInfo(buffer){let reader=BufferReader.asReader(buffer);return{archive:reader.readObject(Fr),lastArchive:reader.readObject(Fr),slotNumber:SlotNumber(reader.readNumber()),checkpointNumber:CheckpointNumber(reader.readNumber()),timestamp:reader.readBigInt()}}__name(deserializeCheckpointInfo,"deserializeCheckpointInfo");var ViemCommitteeAttestationsSchema=external_exports.object({signatureIndices:schemas.HexStringWith0x,signaturesOrAddresses:schemas.HexStringWith0x}),ValidateCheckpointResultSchema=external_exports.union([external_exports.object({valid:external_exports.literal(!0)}),external_exports.object({valid:external_exports.literal(!1),checkpoint:CheckpointInfoSchema,committee:external_exports.array(schemas.EthAddress),epoch:EpochNumberSchema,seed:schemas.BigInt,attestors:external_exports.array(schemas.EthAddress),attestations:external_exports.array(CommitteeAttestation.schema),verbatimAttestations:ViemCommitteeAttestationsSchema,reason:external_exports.literal("insufficient-attestations")}),external_exports.object({valid:external_exports.literal(!1),checkpoint:CheckpointInfoSchema,committee:external_exports.array(schemas.EthAddress),epoch:EpochNumberSchema,seed:schemas.BigInt,attestors:external_exports.array(schemas.EthAddress),attestations:external_exports.array(CommitteeAttestation.schema),verbatimAttestations:ViemCommitteeAttestationsSchema,reason:external_exports.literal("invalid-attestation"),invalidIndex:external_exports.number()})]);function serializeValidateCheckpointResult(result){if(result.valid)return serializeToBuffer(!0);let checkpointBuffer=serializeCheckpointInfo(result.checkpoint),signatureIndices=hexToBuffer(result.verbatimAttestations.signatureIndices),signaturesOrAddresses=hexToBuffer(result.verbatimAttestations.signaturesOrAddresses);return serializeToBuffer(result.valid,result.reason,checkpointBuffer.length,checkpointBuffer,result.committee.length,result.committee,result.epoch,result.seed??0n,result.attestors.length,result.attestors,result.attestations.length,result.attestations,result.reason==="invalid-attestation"?result.invalidIndex:0,signatureIndices.length,signatureIndices,signaturesOrAddresses.length,signaturesOrAddresses)}__name(serializeValidateCheckpointResult,"serializeValidateCheckpointResult");function deserializeValidateCheckpointResult(bufferOrReader){let reader=BufferReader.asReader(bufferOrReader),valid=reader.readBoolean();if(valid)return{valid};let reason=reader.readString(64),checkpoint=deserializeCheckpointInfo(reader.readBuffer()),committee=reader.readVector(EthAddress,MAX_COMMITTEE_SIZE),epoch=EpochNumber(reader.readNumber()),seed=reader.readBigInt(),attestors=reader.readVector(EthAddress,MAX_COMMITTEE_SIZE),attestations=reader.readVector(CommitteeAttestation,MAX_COMMITTEE_SIZE),invalidIndex=reader.readNumber(),verbatimAttestations={signatureIndices:bufferToHex(reader.readBuffer()),signaturesOrAddresses:bufferToHex(reader.readBuffer())};if(reason==="insufficient-attestations")return{valid,reason,checkpoint,committee,epoch,seed,attestors,attestations,verbatimAttestations};if(reason==="invalid-attestation")return{valid,reason,checkpoint,committee,epoch,seed,attestors,invalidIndex,attestations,verbatimAttestations};{let _=reason;throw new Error(`Unknown reason: ${reason}`)}}__name(deserializeValidateCheckpointResult,"deserializeValidateCheckpointResult");var BlockInfoSchema=external_exports.object({blockHash:BlockHash.schema.optional(),archive:schemas.Fr,lastArchive:schemas.Fr,blockNumber:BlockNumberSchema,slotNumber:SlotNumberSchema,txCount:external_exports.number(),timestamp:schemas.BigInt});import{encodeAbiParameters as encodeAbiParameters2,parseAbiParameters as parseAbiParameters2}from"viem";var ConsensusPayload=class _ConsensusPayload{static{__name(this,"ConsensusPayload")}header;archive;feeAssetPriceModifier;signatureContext;primaryType;size;constructor(header,archive,feeAssetPriceModifier,signatureContext){this.header=header,this.archive=archive,this.feeAssetPriceModifier=feeAssetPriceModifier,this.signatureContext=signatureContext,this.primaryType="CheckpointAttestation"}static get schema(){return external_exports.object({header:CheckpointHeader.schema,archive:schemas.Fr,feeAssetPriceModifier:schemas.BigInt,signatureContext:coordinationSignatureContextSchema}).transform(obj=>new _ConsensusPayload(obj.header,obj.archive,obj.feeAssetPriceModifier,obj.signatureContext))}static getFields(fields){return[fields.header,fields.archive,fields.feeAssetPriceModifier,fields.signatureContext]}getPayloadToSign(){let abi=parseAbiParameters2("(bytes32, (int256), bytes32)"),archiveRoot=this.archive.toString(),headerHash=this.header.hash().toString(),encodedData=encodeAbiParameters2(abi,[[archiveRoot,[this.feeAssetPriceModifier],headerHash]]);return hexToBuffer(encodedData)}getPayloadHash(){return keccak256(this.getPayloadToSign())}toBuffer(){return serializeToBuffer([this.header,this.archive,serializeSignedBigInt(this.feeAssetPriceModifier),serializeCoordinationSignatureContext(this.signatureContext)])}equals(other){let otherHeader="checkpointHeader"in other?other.checkpointHeader:other.header,otherModifier="feeAssetPriceModifier"in other?other.feeAssetPriceModifier:0n;return this.header.equals(otherHeader)&&this.archive.equals(other.archive)&&this.feeAssetPriceModifier===otherModifier&&coordinationSignatureContextEquals(this.signatureContext,other.signatureContext)}static fromBuffer(buf){let reader=BufferReader.asReader(buf),header=reader.readObject(CheckpointHeader),archive=reader.readObject(Fr),feeAssetPriceModifier=reader.readInt256(),signatureContext=readCoordinationSignatureContext(reader);return new _ConsensusPayload(header,archive,feeAssetPriceModifier,signatureContext)}static fromFields(fields){return new _ConsensusPayload(fields.header,fields.archive,fields.feeAssetPriceModifier,fields.signatureContext)}static fromCheckpoint(checkpoint,signatureContext){return new _ConsensusPayload(checkpoint.header,checkpoint.archive.root,checkpoint.feeAssetPriceModifier,signatureContext)}static empty(){return new _ConsensusPayload(CheckpointHeader.empty(),Fr.ZERO,0n,EMPTY_COORDINATION_SIGNATURE_CONTEXT)}static random(){return new _ConsensusPayload(CheckpointHeader.random(),Fr.random(),0n,EMPTY_COORDINATION_SIGNATURE_CONTEXT)}getSize(){return this.size?this.size:(this.size=this.toBuffer().length,this.size)}toInspect(){return{header:this.header.toInspect(),archive:this.archive.toString(),feeAssetPriceModifier:this.feeAssetPriceModifier.toString(),chainId:this.signatureContext.chainId,rollupAddress:this.signatureContext.rollupAddress.toString()}}toString(){return`header: ${this.header.toString()}, archive: ${this.archive.toString()}, feeAssetPriceModifier: ${this.feeAssetPriceModifier}, chainId: ${this.signatureContext.chainId}, rollupAddress: ${this.signatureContext.rollupAddress.toString()}`}};var shaMerkleHash=__name((left,right)=>sha256Trunc(Buffer.concat([left,right])),"shaMerkleHash");function computeBalancedMerkleTreeRoot(leaves,hasher=shaMerkleHash){let height=getTreeHeight(leaves),nodes=leaves.slice();for(let i=0;i<height;++i){let j=0;for(;j<nodes.length/2;++j){let l=nodes[j*2],r2=nodes[j*2+1];nodes[j]=hasher(l,r2)}nodes=nodes.slice(0,j)}return nodes[0]}__name(computeBalancedMerkleTreeRoot,"computeBalancedMerkleTreeRoot");function getTreeHeight(leaves){if(leaves.length===0)throw new Error("Cannot compute a Merkle root with no leaves");let height=Math.log2(leaves.length);if(!Number.isInteger(height))throw new Error("Cannot compute a Merkle root with a non-power-of-two number of leaves");return height}__name(getTreeHeight,"getTreeHeight");var MerkleTree=class{static{__name(this,"MerkleTree")}height;nodes;constructor(height,nodes){this.height=height,this.nodes=nodes;let expectedNodeCount=2**(height+1)-1;if(nodes.length!==expectedNodeCount)throw new Error(`Invalid node count for Merkle tree: got ${nodes.length} but expected ${expectedNodeCount}`)}get root(){return this.nodes[this.nodes.length-1]}get leaves(){return this.nodes.slice(0,2**this.height)}getSiblingPath(leafIndexOrLeaf){if(Buffer.isBuffer(leafIndexOrLeaf))return this.getSiblingPath(this.getIndex(leafIndexOrLeaf));let leafIndex=leafIndexOrLeaf;if(leafIndex<0||leafIndex>=2**this.height)throw new Error(`Invalid leaf index: got ${leafIndex} but leaves count is ${2**this.height}`);let tree=this.nodes,rowSize=Math.ceil(tree.length/2),rowOffset=0,index=leafIndex,siblingPath=[];for(;rowSize>1;){let isRight=index&1;siblingPath.push(tree[rowOffset+index+(isRight?-1:1)]),rowOffset+=rowSize,rowSize>>=1,index>>=1}return siblingPath}getIndex(element){return this.leaves.findIndex(leaf=>leaf.equals(element))}drawTree(elemSize=8){let levels2=[],tree=this.nodes,maxRowSize=Math.ceil(tree.length/2),paddingSize=1,rowSize=maxRowSize,rowOffset=0;for(;rowSize>0;)levels2.push(tree.slice(rowOffset,rowOffset+rowSize).map(n=>n.toString("hex").slice(0,elemSize)+" ".repeat((paddingSize-1)*(elemSize+1)))),rowOffset+=rowSize,paddingSize<<=1,rowSize>>=1;return levels2.reverse().map(row=>row.join(" ")).join(`
|
|
189
189
|
`)}};var MerkleTreeCalculator=class _MerkleTreeCalculator{static{__name(this,"MerkleTreeCalculator")}height;zeroHashes;hasher;constructor(height,zeroHashes,hasher){this.height=height,this.zeroHashes=zeroHashes,this.hasher=hasher,this.hasher=hasher}static async create(height,zeroLeaf=Buffer.alloc(32),hasher){let zeroHashes=[zeroLeaf];for(let i=0;i<height;i++)zeroHashes.push(await hasher(zeroHashes[i],zeroHashes[i]));return new _MerkleTreeCalculator(height,zeroHashes,hasher)}async computeTree(leaves=[]){leaves.length===0&&(leaves=new Array(2**this.height).fill(this.zeroHashes[0]));let result=leaves.slice();for(let i=0;i<this.height;++i){let numLeaves=2**(this.height-i),newLeaves=[];for(let j=0;j<leaves.length/2;++j){let l=leaves[j*2],r2=leaves[j*2+1]||this.zeroHashes[i];newLeaves[j]=await this.hasher(l,r2)}result=result.concat(new Array(numLeaves-leaves.length).fill(this.zeroHashes[i]),newLeaves),leaves=newLeaves}return new MerkleTree(this.height,result)}async computeTreeRoot(leaves=[]){if(leaves.length===0)return this.zeroHashes[this.zeroHashes.length-1];leaves=leaves.slice();for(let i=0;i<this.height;++i){let j=0;for(;j<leaves.length/2;++j){let l=leaves[j*2],r2=leaves[j*2+1]||this.zeroHashes[i];leaves[j]=await this.hasher(l,r2)}leaves=leaves.slice(0,j)}return leaves[0]}};var MembershipWitness=class _MembershipWitness{static{__name(this,"MembershipWitness")}leafIndex;siblingPath;constructor(pathSize,leafIndex,siblingPath){this.leafIndex=leafIndex,this.siblingPath=siblingPath,assertMemberLength(this,"siblingPath",pathSize)}toBuffer(){return serializeToBuffer(toBufferBE(this.leafIndex,32),...this.siblingPath)}toJSON(){return this.toBuffer()}toFields(){return[new Fr(this.leafIndex),...this.siblingPath]}static schemaFor(size){return schemas.Buffer.transform(b=>_MembershipWitness.fromBuffer(b,size))}static random(pathSize){return new _MembershipWitness(pathSize,0n,Array(pathSize).fill(0).map(()=>Fr.random()))}static empty(pathSize,leafIndex=0n){let arr=Array(pathSize).fill(0).map(()=>Fr.ZERO);return new _MembershipWitness(pathSize,leafIndex,arr)}static fromBufferArray(leafIndex,siblingPath){return new _MembershipWitness(siblingPath.length,leafIndex,siblingPath.map(x=>Fr.fromBuffer(x)))}static fromBuffer(buffer,size){let reader=BufferReader.asReader(buffer),leafIndex=toBigIntBE(reader.readBytes(32)),siblingPath=reader.readArray(size,Fr);return new _MembershipWitness(size,leafIndex,siblingPath)}static deserializer(size){return{fromBuffer:__name(buffer=>{let reader=BufferReader.asReader(buffer),leafIndex=toBigIntBE(reader.readBytes(32)),siblingPath=reader.readArray(size,Fr);return new _MembershipWitness(size,leafIndex,siblingPath)},"fromBuffer")}}static fromSiblingPath(leafIndex,siblingPath){return new _MembershipWitness(siblingPath.pathSize,leafIndex,siblingPath.toFields())}};var SiblingPath=class _SiblingPath{static{__name(this,"SiblingPath")}pathSize;data;constructor(pathSize,path){this.pathSize=pathSize,this.data=assertLength(path,pathSize)}static get schema(){return schemas.Buffer.transform(b=>_SiblingPath.fromBuffer(b))}static schemaFor(size){return schemas.Buffer.transform(b=>_SiblingPath.fromBuffer(b)).superRefine((path,ctx)=>{path.pathSize!==size&&ctx.addIssue({code:external_exports.ZodIssueCode.custom,message:`Expected sibling path size ${size} but got ${path.pathSize}`})})}toJSON(){return this.toBuffer()}static ZERO(size,zeroElement,hasher){let bufs=[],current=zeroElement;for(let i=0;i<size;++i)bufs.push(current),current=hasher.hash(current,current);return new _SiblingPath(size,bufs)}static random(number4){let data=Array.from({length:number4},()=>Fr.random().toBuffer());return new _SiblingPath(number4,data)}toBuffer(){return serializeArrayOfBufferableToVector(this.data)}toBufferArray(){return this.data}toFields(){return this.data.map(buf=>Fr.fromBuffer(buf))}toTuple(){let array2=this.toFields();return makeTuple(array2.length,i=>array2[i],0)}static fromBuffer(buf,offset=0){let{elem}=_SiblingPath.deserialize(buf,offset);return elem}static deserialize(buf,offset=0){let deserializePath=__name((buf2,offset2)=>({elem:buf2.slice(offset2,offset2+32),adv:32}),"deserializePath"),{elem,adv}=deserializeArrayFromVector(deserializePath,buf,offset),size=elem.length;return{elem:new _SiblingPath(size,elem),adv}}toString(){return bufferToHex(this.toBuffer())}static fromString(repr){return _SiblingPath.fromBuffer(hexToBuffer(repr))}getSubtreeSiblingPath(subtreeHeight){let subtreeData=this.data.slice(subtreeHeight),subtreePathSize=this.pathSize-subtreeHeight;return new _SiblingPath(subtreePathSize,subtreeData)}};var UnbalancedTreeStore=class{static{__name(this,"UnbalancedTreeStore")}#nodeMapping=new Map;#numLeaves;constructor(numLeaves){this.#numLeaves=numLeaves}setLeaf(leafIndex,value){if(leafIndex>=this.#numLeaves)throw new Error(`Expected at most ${this.#numLeaves} leaves. Received a leaf at index ${leafIndex}.`);let{level,indexAtLevel}=findLeafLevelAndIndex(this.#numLeaves,leafIndex),location={level,index:indexAtLevel};return this.#nodeMapping.set(this.#getKey(location),{location,value}),location}setNode({level,index},value){let location={level,index};this.#nodeMapping.set(this.#getKey(location),{location,value})}getParentLocation({level,index}){if(level===0)throw new Error("Tree root does not have a parent.");return{level:level-1,index:Math.floor(index/2)}}getSiblingLocation({level,index}){if(level===0)throw new Error("Tree root does not have a sibling.");return{level,index:index%2?index-1:index+1}}getChildLocations({level,index}){let left={level:level+1,index:index*2},right={level:level+1,index:index*2+1};return[left,right]}getLeaf(leafIndex){let{level,indexAtLevel}=findLeafLevelAndIndex(this.#numLeaves,leafIndex),location={level,index:indexAtLevel};return this.getNode(location)}getNode(location){return this.#nodeMapping.get(this.#getKey(location))?.value}getRoot(){return this.getNode({level:0,index:0})}getParent(location){let parentLocation=this.getParentLocation(location);return this.getNode(parentLocation)}getSibling(location){let siblingLocation=this.getSiblingLocation(location);return this.getNode(siblingLocation)}getChildren(location){let[left,right]=this.getChildLocations(location);return[this.getNode(left),this.getNode(right)]}#getKey(location){return`${location.level}-${location.index}`}};function getMaxBalancedSubtreeDepth(numLeaves){return Math.floor(Math.log2(numLeaves))}__name(getMaxBalancedSubtreeDepth,"getMaxBalancedSubtreeDepth");function getMaxUnbalancedTreeDepth(numLeaves){return Math.ceil(Math.log2(numLeaves))}__name(getMaxUnbalancedTreeDepth,"getMaxUnbalancedTreeDepth");function findPosition(rootLevel,leafLevel,numLeaves,indexOffset,targetIndex){if(numLeaves<=1)return{level:rootLevel,indexAtLevel:indexOffset};let maxBalancedTreeDepth=getMaxBalancedSubtreeDepth(numLeaves),numBalancedLeaves=2**maxBalancedTreeDepth,numRemainingLeaves=numLeaves-numBalancedLeaves;if(targetIndex<numBalancedLeaves){let extraLevel=numRemainingLeaves?1:0;return{level:rootLevel+maxBalancedTreeDepth+extraLevel,indexAtLevel:indexOffset+targetIndex}}else{let rightBranchMaxLevel=getMaxUnbalancedTreeDepth(numRemainingLeaves),shiftedUp=leafLevel-rootLevel-rightBranchMaxLevel-1,nextLeafLevel=leafLevel-shiftedUp,newIndexOffset=indexOffset+numBalancedLeaves>>shiftedUp,shiftedTargetIndex=targetIndex-numBalancedLeaves;return findPosition(rootLevel+1,nextLeafLevel,numRemainingLeaves,newIndexOffset,shiftedTargetIndex)}}__name(findPosition,"findPosition");function findLeafLevelAndIndex(numLeaves,leafIndex){let maxLevel=getMaxUnbalancedTreeDepth(numLeaves);return findPosition(0,maxLevel,numLeaves,0,leafIndex)}__name(findLeafLevelAndIndex,"findLeafLevelAndIndex");var UnbalancedMerkleTreeCalculator=class _UnbalancedMerkleTreeCalculator{static{__name(this,"UnbalancedMerkleTreeCalculator")}leaves;valueToCompress;emptyRoot;hasher;store;leafLocations;constructor(leaves,valueToCompress,emptyRoot,hasher){this.leaves=leaves,this.valueToCompress=valueToCompress,this.emptyRoot=emptyRoot,this.hasher=hasher,this.leafLocations=[],this.store=new UnbalancedTreeStore(leaves.length),this.buildTree()}static create(leaves,valueToCompress=Buffer.alloc(0),emptyRoot=Buffer.alloc(32),hasher=shaMerkleHash){return new _UnbalancedMerkleTreeCalculator(leaves,valueToCompress,emptyRoot,hasher)}getRoot(){return this.store.getRoot().value}getSiblingPath(value){let leafIndex=this.leaves.findIndex(leaf=>leaf.equals(value));if(leafIndex===-1)throw Error(`Leaf value ${value.toString("hex")} not found in tree.`);return this.getSiblingPathByLeafIndex(leafIndex)}getSiblingPathByLeafIndex(leafIndex){if(leafIndex>=this.leaves.length)throw Error(`Leaf index ${leafIndex} out of bounds. Tree has ${this.leaves.length} leaves.`);if(this.leaves[leafIndex].equals(this.valueToCompress))throw Error(`Leaf at index ${leafIndex} has been compressed.`);let path=[],location=this.leafLocations[leafIndex];for(;location.level>0;){let sibling=this.store.getSibling(location);path.push(sibling.value),location=this.store.getParentLocation(location)}return new SiblingPath(path.length,path)}getLeafLocation(leafIndex){return this.leafLocations[leafIndex]}buildTree(){this.leafLocations=this.leaves.map((value,i)=>this.store.setLeaf(i,{value,leafIndex:i}));let toProcess=this.leafLocations.filter((_,i)=>!this.leaves[i].equals(this.valueToCompress));if(!toProcess.length){this.store.setNode({level:0,index:0},{value:this.emptyRoot});return}let level=toProcess[0].level;for(let i=level;i>0;i--){let toProcessNext=[];for(let location of toProcess){if(location.level!==i){toProcessNext.push(location);continue}let parentLocation=this.store.getParentLocation(location);if(this.store.getNode(parentLocation))continue;let sibling=this.store.getSibling(location);if(!sibling||sibling.value.equals(this.valueToCompress))this.shiftNodeUp(location,parentLocation);else{let node=this.store.getNode(location),parentValue=this.hasher(node.value,sibling.value);this.store.setNode(parentLocation,{value:parentValue})}toProcessNext.push(parentLocation)}toProcess=toProcessNext}}shiftNodeUp(from,to){let nodesToShift=this.collectNodesToShift(from,to);for(let{node,newLocation}of nodesToShift)this.store.setNode(newLocation,node),node.leafIndex!==void 0&&(this.leafLocations[node.leafIndex]=newLocation)}collectNodesToShift(from,to){let node=this.store.getNode(from);if(!node)return[];let result=[{node,newLocation:to}];if(node.leafIndex===void 0){let[leftChild,rightChild]=this.store.getChildLocations(from),[leftChildNew,rightChildNew]=this.store.getChildLocations(to);result=result.concat(this.collectNodesToShift(leftChild,leftChildNew)).concat(this.collectNodesToShift(rightChild,rightChildNew))}return result}};var computeUnbalancedShaRoot=__name(leaves=>computeUnbalancedMerkleTreeRoot(leaves,shaMerkleHash),"computeUnbalancedShaRoot"),computeWonkyShaRoot=__name(leaves=>computeWonkyMerkleTreeRoot(leaves),"computeWonkyShaRoot");function computeUnbalancedMerkleTreeRoot(leaves,hasher=shaMerkleHash,emptyRoot=Buffer.alloc(32)){if(!leaves.length)return emptyRoot;if(leaves.length===1)return leaves[0];let numRemainingLeaves=leaves.length,subtreeSize=1,root;for(;numRemainingLeaves>1;){if((numRemainingLeaves&subtreeSize)!==0){let subtreeLeaves=leaves.slice(numRemainingLeaves-subtreeSize,numRemainingLeaves),subtreeRoot=computeBalancedMerkleTreeRoot(subtreeLeaves,hasher);root?root=hasher(subtreeRoot,root):root=subtreeRoot,numRemainingLeaves-=subtreeSize}subtreeSize*=2}return root}__name(computeUnbalancedMerkleTreeRoot,"computeUnbalancedMerkleTreeRoot");function computeWonkyMerkleTreeRoot(leaves,valueToCompress=Buffer.alloc(32),emptyRoot=Buffer.alloc(32),hasher=shaMerkleHash){return UnbalancedMerkleTreeCalculator.create(leaves,valueToCompress,emptyRoot,hasher).getRoot()}__name(computeWonkyMerkleTreeRoot,"computeWonkyMerkleTreeRoot");var import_json_stringify_deterministic=__toESM(require_lib(),1);var VERSION2=1,sha256Fr=reduceFn(sha256,Fr);async function computeArtifactHash(artifact){if("privateFunctionRoot"in artifact&&"utilityFunctionRoot"in artifact&&"metadataHash"in artifact){let{privateFunctionRoot,utilityFunctionRoot,metadataHash}=artifact,preimage2=[privateFunctionRoot,utilityFunctionRoot,metadataHash].map(x=>x.toBuffer());return sha256Fr(Buffer.concat([numToUInt8(VERSION2),...preimage2]))}let preimage=await computeArtifactHashPreimage(artifact),artifactHash=computeArtifactHash(preimage);return getLogger().trace("Computed artifact hash",{artifactHash,...preimage}),artifactHash}__name(computeArtifactHash,"computeArtifactHash");async function computeArtifactHashPreimage(artifact){let privateFunctionRoot=await computeArtifactFunctionTreeRoot(artifact,FunctionType.PRIVATE),utilityFunctionRoot=await computeArtifactFunctionTreeRoot(artifact,FunctionType.UTILITY),metadataHash=computeArtifactMetadataHash(artifact);return{privateFunctionRoot,utilityFunctionRoot,metadataHash}}__name(computeArtifactHashPreimage,"computeArtifactHashPreimage");function computeArtifactMetadataHash(artifact){return sha256Fr(Buffer.from((0,import_json_stringify_deterministic.default)({name:artifact.name,outputs:artifact.outputs}),"utf-8"))}__name(computeArtifactMetadataHash,"computeArtifactMetadataHash");async function computeArtifactFunctionTreeRoot(artifact,fnType){let tree=await computeArtifactFunctionTree(artifact,fnType);return tree?.root?Fr.fromBuffer(tree.root):Fr.ZERO}__name(computeArtifactFunctionTreeRoot,"computeArtifactFunctionTreeRoot");async function computeArtifactFunctionTree(artifact,fnType){let leaves=await computeFunctionLeaves(artifact,fnType);if(leaves.length===0)return;let height=Math.ceil(Math.log2(leaves.length));return(await MerkleTreeCalculator.create(height,Buffer.alloc(32),getArtifactMerkleTreeHasher())).computeTree(leaves.map(x=>x.toBuffer()))}__name(computeArtifactFunctionTree,"computeArtifactFunctionTree");async function computeFunctionLeaves(artifact,fnType){let selectors=await Promise.all(artifact.functions.filter(f=>f.functionType===fnType).map(async f=>({...f,selector:await FunctionSelector.fromNameAndParameters(f.name,f.parameters)})));return selectors.sort((a,b)=>a.selector.value-b.selector.value),await Promise.all(selectors.map(computeFunctionArtifactHash))}__name(computeFunctionLeaves,"computeFunctionLeaves");async function computeFunctionArtifactHash(fn){let selector="selector"in fn?fn.selector:await FunctionSelector.fromNameAndParameters(fn),bytecodeHash=sha256Fr(fn.bytecode).toBuffer(),metadataHash="functionMetadataHash"in fn?fn.functionMetadataHash:computeFunctionMetadataHash(fn);return sha256Fr(Buffer.concat([numToUInt8(VERSION2),selector.toBuffer(),metadataHash.toBuffer(),bytecodeHash]))}__name(computeFunctionArtifactHash,"computeFunctionArtifactHash");function computeFunctionMetadataHash(fn){return sha256Fr(Buffer.from((0,import_json_stringify_deterministic.default)(fn.returnTypes),"utf8"))}__name(computeFunctionMetadataHash,"computeFunctionMetadataHash");function getLogger(){return createLogger("circuits:artifact_hash")}__name(getLogger,"getLogger");function getArtifactMerkleTreeHasher(){return(l,r2)=>Promise.resolve(sha256Fr(Buffer.concat([l,r2])).toBuffer())}__name(getArtifactMerkleTreeHasher,"getArtifactMerkleTreeHasher");var KEY_PREFIXES=["n","iv","ov","t"];async function computeContractAddressFromInstance(instance){let partialAddress=await computePartialAddress(instance);return computeAddress(instance.publicKeys,partialAddress)}__name(computeContractAddressFromInstance,"computeContractAddressFromInstance");async function computePartialAddress(instance){let saltedInitializationHash="saltedInitializationHash"in instance?instance.saltedInitializationHash:await computeSaltedInitializationHash(instance);return poseidon2HashWithSeparator([instance.originalContractClassId,saltedInitializationHash],DomainSeparator.PARTIAL_ADDRESS)}__name(computePartialAddress,"computePartialAddress");function computeSaltedInitializationHash(instance){return poseidon2HashWithSeparator([instance.salt,instance.initializationHash,instance.deployer,instance.immutablesHash],DomainSeparator.SALTED_INITIALIZATION_HASH)}__name(computeSaltedInitializationHash,"computeSaltedInitializationHash");async function computeInitializationHash(initFn,args){if(!initFn)return Fr.ZERO;let selector=await FunctionSelector.fromNameAndParameters(initFn.name,initFn.parameters),flatArgs=encodeArguments(initFn,args);return computeInitializationHashFromEncodedArgs(selector,flatArgs)}__name(computeInitializationHash,"computeInitializationHash");async function computeInitializationHashFromEncodedArgs(initFn,encodedArgs){let argsHash=await computeVarArgsHash(encodedArgs);return poseidon2HashWithSeparator([initFn,argsHash],DomainSeparator.INITIALIZER)}__name(computeInitializationHashFromEncodedArgs,"computeInitializationHashFromEncodedArgs");import{BarretenbergSync as BarretenbergSync6}from"@aztec/bb.js";async function vkAsFieldsMegaHonk(input){return await BarretenbergSync6.initSingleton(),BarretenbergSync6.getSingleton().megaVkAsFields({verificationKey:input}).fields.map(field=>Fr.fromBuffer(Buffer.from(field)))}__name(vkAsFieldsMegaHonk,"vkAsFieldsMegaHonk");import{strict as assert2}from"assert";var privateFunctionTreeCalculator,PRIVATE_FUNCTION_SIZE=2;async function computePrivateFunctionsTree(fns){let calculator=await getPrivateFunctionTreeCalculator(),leaves=await computePrivateFunctionLeaves(fns);return calculator.computeTree(leaves)}__name(computePrivateFunctionsTree,"computePrivateFunctionsTree");async function computePrivateFunctionsRoot(fns){let calculator=await getPrivateFunctionTreeCalculator(),leaves=await computePrivateFunctionLeaves(fns);return Fr.fromBuffer(await calculator.computeTreeRoot(leaves))}__name(computePrivateFunctionsRoot,"computePrivateFunctionsRoot");function computePrivateFunctionLeaves(fns){let leaves=[...fns].sort((a,b)=>a.selector.value-b.selector.value);return Promise.all(leaves.map(computePrivateFunctionLeaf))}__name(computePrivateFunctionLeaves,"computePrivateFunctionLeaves");async function computePrivateFunctionLeaf(fn){return(await poseidon2HashWithSeparator([fn.selector,fn.vkHash],DomainSeparator.PRIVATE_FUNCTION_LEAF)).toBuffer()}__name(computePrivateFunctionLeaf,"computePrivateFunctionLeaf");async function getPrivateFunctionTreeCalculator(){if(!privateFunctionTreeCalculator){let functionTreeZeroLeaf=(await poseidon2Hash(new Array(PRIVATE_FUNCTION_SIZE).fill(0))).toBuffer();privateFunctionTreeCalculator=await MerkleTreeCalculator.create(7,functionTreeZeroLeaf,async(left,right)=>(await computeMerkleHash(Fr.fromBuffer(left),Fr.fromBuffer(right))).toBuffer())}return privateFunctionTreeCalculator}__name(getPrivateFunctionTreeCalculator,"getPrivateFunctionTreeCalculator");async function computeContractClassId(contractClass){return(await computeContractClassIdWithPreimage(contractClass)).id}__name(computeContractClassId,"computeContractClassId");async function computeContractClassIdWithPreimage(contractClass){let artifactHash=contractClass.artifactHash,privateFunctionsRoot="privateFunctionsRoot"in contractClass?contractClass.privateFunctionsRoot:await computePrivateFunctionsRoot(contractClass.privateFunctions),publicBytecodeCommitment="publicBytecodeCommitment"in contractClass?contractClass.publicBytecodeCommitment:await computePublicBytecodeCommitment(contractClass.packedBytecode);return{id:await poseidon2HashWithSeparator([artifactHash,privateFunctionsRoot,publicBytecodeCommitment],DomainSeparator.CONTRACT_CLASS_ID),artifactHash,privateFunctionsRoot,publicBytecodeCommitment}}__name(computeContractClassIdWithPreimage,"computeContractClassIdWithPreimage");async function computePublicBytecodeCommitment(packedBytecode){let[bytecodeLengthAsField,...bytecodeAsFields]=bufferAsFields(packedBytecode,3e3),bytecodeLength=Math.ceil(bytecodeLengthAsField.toNumber()/(Fr.SIZE_IN_BYTES-1));assert2(bytecodeLength<3e3,"Bytecode exceeds maximum deployable size");let sep=BigInt(DomainSeparator.PUBLIC_BYTECODE)+(bytecodeLengthAsField.toBigInt()<<32n);return await poseidon2HashWithSeparator(bytecodeAsFields.slice(0,bytecodeLength),new Fr(sep).toNumber())}__name(computePublicBytecodeCommitment,"computePublicBytecodeCommitment");var cmpFunctionArtifacts=__name((a,b)=>a.selector.toField().cmp(b.selector.toField()),"cmpFunctionArtifacts");async function getContractClassFromArtifact(artifact){let artifactHash="artifactHash"in artifact?artifact.artifactHash:await computeArtifactHash(artifact),publicFunctions=artifact.functions.filter(f=>f.functionType===FunctionType.PUBLIC);if(publicFunctions.length>1)throw new Error(`Contract should contain at most one public function artifact. Received ${publicFunctions.length}.`);let packedBytecode=publicFunctions[0]?.bytecode??Buffer.alloc(0),privateFunctions=artifact.functions.filter(f=>f.functionType===FunctionType.PRIVATE),privateArtifactFunctions=await Promise.all(privateFunctions.map(getContractClassPrivateFunctionFromArtifact));privateArtifactFunctions.sort(cmpFunctionArtifacts);let contractClass={version:1,artifactHash,packedBytecode,privateFunctions:privateArtifactFunctions};return{...contractClass,...await computeContractClassIdWithPreimage(contractClass)}}__name(getContractClassFromArtifact,"getContractClassFromArtifact");async function getContractClassPrivateFunctionFromArtifact(f){return{selector:await FunctionSelector.fromNameAndParameters(f.name,f.parameters),vkHash:await computeVerificationKeyHash(f)}}__name(getContractClassPrivateFunctionFromArtifact,"getContractClassPrivateFunctionFromArtifact");async function computeVerificationKeyHash(f){if(!f.verificationKey)throw new Error(`Private function ${f.name} must have a verification key`);return hashVK(await vkAsFieldsMegaHonk(Buffer.from(f.verificationKey,"base64")))}__name(computeVerificationKeyHash,"computeVerificationKeyHash");var PreTagSchema=external_exports.object({extendedSecret:AppTaggingSecretSchema,index:schemas.Integer});var LogIncludeOptionsSchema=external_exports.object({includeEffects:external_exports.boolean().optional()}),LogResultSchema=external_exports.object({logData:external_exports.array(schemas.Fr),blockNumber:BlockNumberSchema,blockHash:BlockHash.schema,blockTimestamp:schemas2.UInt64,txHash:TxHash.schema,txIndexWithinBlock:schemas2.Integer,logIndexWithinTx:schemas2.Integer,noteHashes:external_exports.array(schemas.Fr).optional(),nullifiers:external_exports.array(schemas.Fr).optional()});var LogCursor=class _LogCursor{static{__name(this,"LogCursor")}blockNumber;txIndexWithinBlock;logIndexWithinTx;constructor(blockNumber,txIndexWithinBlock,logIndexWithinTx){this.blockNumber=blockNumber,this.txIndexWithinBlock=txIndexWithinBlock,this.logIndexWithinTx=logIndexWithinTx}static get schema(){return external_exports.object({blockNumber:BlockNumberSchema,txIndexWithinBlock:schemas2.Integer,logIndexWithinTx:schemas2.Integer}).transform(({blockNumber,txIndexWithinBlock,logIndexWithinTx})=>new _LogCursor(blockNumber,txIndexWithinBlock,logIndexWithinTx))}static fromLog(log2){return new _LogCursor(log2.blockNumber,log2.txIndexWithinBlock,log2.logIndexWithinTx)}static random(){return new _LogCursor(BlockNumber(Math.floor(Math.random()*1e5)+1),Math.floor(Math.random()*100),Math.floor(Math.random()*100))}toBuffer(){return Buffer.concat([numToUInt32BE(this.blockNumber),numToUInt32BE(this.txIndexWithinBlock),numToUInt32BE(this.logIndexWithinTx)])}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer),blockNumber=BlockNumber(reader.readNumber()),txIndexWithinBlock=reader.readNumber(),logIndexWithinTx=reader.readNumber();return new _LogCursor(blockNumber,txIndexWithinBlock,logIndexWithinTx)}equals(other){return this.blockNumber===other.blockNumber&&this.txIndexWithinBlock===other.txIndexWithinBlock&&this.logIndexWithinTx===other.logIndexWithinTx}toString(){return`${this.blockNumber}-${this.txIndexWithinBlock}-${this.logIndexWithinTx}`}static parseOptional(value){if(!value)return;let parts=value.split("-");if(parts.length!==3)throw new Error(`Invalid log cursor "${value}". Expected <blockNumber>-<txIndexWithinBlock>-<logIndexWithinTx>.`);let[blockNumberStr,txIndexStr,logIndexStr]=parts,blockNumber=Number(blockNumberStr),txIndexWithinBlock=Number(txIndexStr),logIndexWithinTx=Number(logIndexStr);if(!Number.isInteger(blockNumber)||blockNumber<1)throw new Error(`Invalid log cursor block number: ${blockNumberStr}`);if(!Number.isInteger(txIndexWithinBlock)||txIndexWithinBlock<0)throw new Error(`Invalid log cursor tx index: ${txIndexStr}`);if(!Number.isInteger(logIndexWithinTx)||logIndexWithinTx<0)throw new Error(`Invalid log cursor log index: ${logIndexStr}`);return new _LogCursor(BlockNumber(blockNumber),txIndexWithinBlock,logIndexWithinTx)}};var Tag=class _Tag{static{__name(this,"Tag")}value;constructor(value){this.value=value}static async compute(preTag){let tag=await poseidon2Hash([preTag.extendedSecret.secret,preTag.index]);return new _Tag(tag)}toString(){return this.value.toString()}toJSON(){return this.value.toString()}equals(other){return this.value.equals(other.value)}static random(){return new _Tag(Fr.random())}static get schema(){return schemas2.Fr.transform(fr=>new _Tag(fr))}};var SiloedTag=class _SiloedTag{static{__name(this,"SiloedTag")}value;constructor(value){this.value=value}static async compute(preTag){let tag=await Tag.compute(preTag),domainSeparator=preTag.extendedSecret.kind===AppTaggingSecretKind.CONSTRAINED?DomainSeparator.CONSTRAINED_MSG_LOG_TAG:DomainSeparator.UNCONSTRAINED_MSG_LOG_TAG,logTag=await computeLogTag(tag.value,domainSeparator);return _SiloedTag.computeFromTagAndApp(new Tag(logTag),preTag.extendedSecret.app)}static async computeFromTagAndApp(tag,app){let siloedTag=await computeSiloedPrivateLogFirstField(app,tag.value);return new _SiloedTag(siloedTag)}toString(){return this.value.toString()}toJSON(){return this.value.toString()}equals(other){return this.value.equals(other.value)}static random(){return new _SiloedTag(Fr.random())}static get schema(){return schemas2.Fr.transform(fr=>new _SiloedTag(fr))}};function tagQuerySchema(tagSchema){return external_exports.union([tagSchema,external_exports.object({tag:tagSchema,afterLog:LogCursor.schema.optional()})])}__name(tagQuerySchema,"tagQuerySchema");var logsQueryBaseShape={fromBlock:BlockNumberSchema.optional(),toBlock:BlockNumberSchema.optional(),txHash:TxHash.schema.optional(),referenceBlock:BlockHash.schema.optional(),includeEffects:external_exports.boolean().optional(),limitPerTag:external_exports.number().int().positive().max(20,{message:`limitPerTag must be <= ${20}`}).optional()};function refineTxHashAndRange(schema){return schema.refine(q=>!(q.txHash!==void 0&&(q.fromBlock!==void 0||q.toBlock!==void 0)),{message:"`txHash` is mutually exclusive with `fromBlock`/`toBlock`"})}__name(refineTxHashAndRange,"refineTxHashAndRange");var PrivateLogsQuerySchema=refineTxHashAndRange(zodFor()(external_exports.object({...logsQueryBaseShape,tags:external_exports.array(tagQuerySchema(SiloedTag.schema)).min(1).max(100,{message:`tags must have at most ${100} entries`})}))),PublicLogsQuerySchema=refineTxHashAndRange(zodFor()(external_exports.object({...logsQueryBaseShape,contractAddress:schemas2.AztecAddress,tags:external_exports.array(tagQuerySchema(Tag.schema)).min(1).max(100,{message:`tags must have at most ${100} entries`})})));function queryAllPrivateLogsByTags(node,query){return queryAllByTags(query.tags,tagQueries=>node.getPrivateLogsByTags({...query,tags:tagQueries}),query.limitPerTag)}__name(queryAllPrivateLogsByTags,"queryAllPrivateLogsByTags");function queryAllPublicLogsByTags(node,query){return queryAllByTags(query.tags,tagQueries=>node.getPublicLogsByTags({...query,tags:tagQueries}),query.limitPerTag)}__name(queryAllPublicLogsByTags,"queryAllPublicLogsByTags");async function queryAllByTags(tags,fetchPage,limitPerTag){let effectiveLimit=limitPerTag??20,allResultsPerTag=tags.map(()=>[]),activeIndexes=tags.map((_,i)=>i),nextQueries=tags.slice();for(;activeIndexes.length>0;){let pageResults=await fetchPage(nextQueries),stillActive=[],followups=[];for(let i=0;i<activeIndexes.length;i++){let originalIdx=activeIndexes[i],pageForTag=pageResults[i];if(allResultsPerTag[originalIdx].push(...pageForTag),pageForTag.length===effectiveLimit){let lastLog=pageForTag[pageForTag.length-1];stillActive.push(originalIdx),followups.push({tag:tagOf(tags[originalIdx]),afterLog:LogCursor.fromLog(lastLog)})}}activeIndexes=stillActive,nextQueries=followups}return allResultsPerTag}__name(queryAllByTags,"queryAllByTags");function tagOf(entry){return typeof entry=="object"&&entry!==null&&"tag"in entry?entry.tag:entry}__name(tagOf,"tagOf");var NullDebugLogStore=class{static{__name(this,"NullDebugLogStore")}storeLogs(_txHash,_logs){}decorateReceiptWithLogs(_txHash,_receipt){}get isEnabled(){return!1}};var ContractDeploymentData=class _ContractDeploymentData{static{__name(this,"ContractDeploymentData")}contractClassLogs;privateLogs;constructor(contractClassLogs,privateLogs){this.contractClassLogs=contractClassLogs,this.privateLogs=privateLogs}getContractClassLogs(){return this.contractClassLogs}getPrivateLogs(){return this.privateLogs}static from(args){return new _ContractDeploymentData(args.contractClassLogs,args.privateLogs)}static empty(){return new _ContractDeploymentData([],[])}static get schema(){return external_exports.object({contractClassLogs:external_exports.array(ContractClassLog.schema),privateLogs:external_exports.array(PrivateLog.schema)}).transform(_ContractDeploymentData.from)}static fromPlainObject(obj){return obj instanceof _ContractDeploymentData?obj:new _ContractDeploymentData(obj.contractClassLogs.map(log2=>ContractClassLog.fromPlainObject(log2)),obj.privateLogs.map(log2=>PrivateLog.fromPlainObject(log2)))}},AllContractDeploymentData=class _AllContractDeploymentData{static{__name(this,"AllContractDeploymentData")}nonRevertibleContractDeploymentData;revertibleContractDeploymentData;constructor(nonRevertibleContractDeploymentData,revertibleContractDeploymentData){this.nonRevertibleContractDeploymentData=nonRevertibleContractDeploymentData,this.revertibleContractDeploymentData=revertibleContractDeploymentData}getNonRevertibleContractDeploymentData(){return this.nonRevertibleContractDeploymentData}getRevertibleContractDeploymentData(){return this.revertibleContractDeploymentData}static fromTx(tx){let hasPublicCalls=!!tx.data.forPublic,allClassLogs=tx.getContractClassLogs(),nonRevertibleClassLogs,revertibleClassLogs;hasPublicCalls?(nonRevertibleClassLogs=tx.getSplitContractClassLogs(!1),revertibleClassLogs=tx.getSplitContractClassLogs(!0)):(nonRevertibleClassLogs=allClassLogs,revertibleClassLogs=[]);let nonRevertibleInstanceLogs,revertibleInstanceLogs;return hasPublicCalls?(nonRevertibleInstanceLogs=tx.data.forPublic.nonRevertibleAccumulatedData.privateLogs.filter(l=>!l.isEmpty()),revertibleInstanceLogs=tx.data.forPublic.revertibleAccumulatedData.privateLogs.filter(l=>!l.isEmpty())):(nonRevertibleInstanceLogs=tx.data.forRollup.end.privateLogs.filter(l=>!l.isEmpty()),revertibleInstanceLogs=[]),new _AllContractDeploymentData(new ContractDeploymentData(nonRevertibleClassLogs,nonRevertibleInstanceLogs),new ContractDeploymentData(revertibleClassLogs,revertibleInstanceLogs))}};var VERSION3=2,SerializableContractInstance=class _SerializableContractInstance{static{__name(this,"SerializableContractInstance")}version=VERSION3;salt;deployer;currentContractClassId;originalContractClassId;initializationHash;immutablesHash;publicKeys;constructor(instance){if(instance.version!==VERSION3)throw new Error(`Unexpected contract class version ${instance.version}`);this.salt=instance.salt,this.deployer=instance.deployer,this.currentContractClassId=instance.currentContractClassId,this.originalContractClassId=instance.originalContractClassId,this.initializationHash=instance.initializationHash,this.immutablesHash=instance.immutablesHash,this.publicKeys=instance.publicKeys}toBuffer(){return serializeToBuffer(numToUInt8(this.version),this.salt,this.deployer,this.currentContractClassId,this.originalContractClassId,this.initializationHash,this.immutablesHash,this.publicKeys)}withAddress(address){return{...this,address}}static fromBuffer(bufferOrReader){let reader=BufferReader.asReader(bufferOrReader);return new _SerializableContractInstance({version:reader.readUInt8(),salt:reader.readObject(Fr),deployer:reader.readObject(AztecAddress),currentContractClassId:reader.readObject(Fr),originalContractClassId:reader.readObject(Fr),initializationHash:reader.readObject(Fr),immutablesHash:reader.readObject(Fr),publicKeys:reader.readObject(PublicKeys)})}static async random(opts={}){return new _SerializableContractInstance({version:VERSION3,salt:Fr.random(),deployer:await AztecAddress.random(),currentContractClassId:Fr.random(),originalContractClassId:Fr.random(),initializationHash:Fr.random(),immutablesHash:Fr.random(),publicKeys:await PublicKeys.random(),...opts})}static default(){return new _SerializableContractInstance({version:VERSION3,salt:Fr.zero(),deployer:AztecAddress.zero(),currentContractClassId:Fr.zero(),originalContractClassId:Fr.zero(),initializationHash:Fr.zero(),immutablesHash:Fr.zero(),publicKeys:PublicKeys.default()})}},SerializableContractInstancePreimage=class _SerializableContractInstancePreimage{static{__name(this,"SerializableContractInstancePreimage")}version=VERSION3;salt;deployer;originalContractClassId;initializationHash;immutablesHash;publicKeys;constructor(instance){if(instance.version!==VERSION3)throw new Error(`Unexpected contract class version ${instance.version}`);this.salt=instance.salt,this.deployer=instance.deployer,this.originalContractClassId=instance.originalContractClassId,this.initializationHash=instance.initializationHash,this.immutablesHash=instance.immutablesHash,this.publicKeys=instance.publicKeys}toBuffer(){return serializeToBuffer(numToUInt8(this.version),this.salt,this.deployer,this.originalContractClassId,this.initializationHash,this.immutablesHash,this.publicKeys)}withAddress(address){return{...this,address}}static fromBuffer(bufferOrReader){let reader=BufferReader.asReader(bufferOrReader),version2=reader.readUInt8();if(version2!==VERSION3)throw new Error(`Unexpected contract instance preimage version ${version2}`);return new _SerializableContractInstancePreimage({version:VERSION3,salt:reader.readObject(Fr),deployer:reader.readObject(AztecAddress),originalContractClassId:reader.readObject(Fr),initializationHash:reader.readObject(Fr),immutablesHash:reader.readObject(Fr),publicKeys:reader.readObject(PublicKeys)})}};async function getContractInstanceFromInstantiationParams(artifact,opts){let args=opts.constructorArgs??[],constructorArtifact=getConstructorArtifact(artifact,opts.constructorArtifact),deployer=opts.deployer??AztecAddress.ZERO,contractClass=await getContractClassFromArtifact(artifact),initializationHash=constructorArtifact&&opts?.skipArgsDecoding?await computeInitializationHashFromEncodedArgs(await FunctionSelector.fromNameAndParameters(constructorArtifact?.name,constructorArtifact?.parameters),args):await computeInitializationHash(constructorArtifact,args),publicKeys=opts.publicKeys??PublicKeys.default(),immutablesHash=opts.immutablesHash??Fr.ZERO,instance={currentContractClassId:contractClass.id,originalContractClassId:contractClass.id,initializationHash,immutablesHash,publicKeys,salt:opts.salt,deployer,version:2};return{...instance,address:await computeContractAddressFromInstance(instance)}}__name(getContractInstanceFromInstantiationParams,"getContractInstanceFromInstantiationParams");function getConstructorArtifact(artifact,requestedConstructorArtifact){if(typeof requestedConstructorArtifact=="string"){let found=getAllFunctionAbis(artifact).find(fn=>fn.name===requestedConstructorArtifact);if(!found)throw new Error(`No constructor found with name ${requestedConstructorArtifact}`);return found}return requestedConstructorArtifact??getDefaultInitializer(artifact)}__name(getConstructorArtifact,"getConstructorArtifact");var SerializableContractInstanceUpdate=class _SerializableContractInstanceUpdate{static{__name(this,"SerializableContractInstanceUpdate")}prevContractClassId;newContractClassId;timestampOfChange;constructor(instance){this.prevContractClassId=instance.prevContractClassId,this.newContractClassId=instance.newContractClassId,this.timestampOfChange=instance.timestampOfChange}toBuffer(){return serializeToBuffer(this.prevContractClassId,this.newContractClassId,this.timestampOfChange)}static fromBuffer(bufferOrReader){let reader=BufferReader.asReader(bufferOrReader);return new _SerializableContractInstanceUpdate({prevContractClassId:reader.readObject(Fr),newContractClassId:reader.readObject(Fr),timestampOfChange:reader.readObject(Fr).toBigInt()})}static random(opts={}){return new _SerializableContractInstanceUpdate({prevContractClassId:Fr.random(),newContractClassId:Fr.random(),timestampOfChange:BigInt(Math.floor(Math.random()*1e3)),...opts})}static default(){return new _SerializableContractInstanceUpdate({prevContractClassId:Fr.zero(),newContractClassId:Fr.zero(),timestampOfChange:0n})}};var VERSION4=1,PrivateFunctionSchema=zodFor()(external_exports.object({selector:FunctionSelector.schema,vkHash:schemas.Fr})),ContractClassSchema=zodFor()(external_exports.object({version:external_exports.literal(VERSION4),artifactHash:schemas.Fr,privateFunctions:external_exports.array(PrivateFunctionSchema),packedBytecode:schemas.Buffer})),ContractClassWithIdSchema=zodFor()(ContractClassSchema.extend({id:schemas.Fr})),ContractClassPublicSchema=zodFor()(external_exports.object({id:schemas.Fr,privateFunctionsRoot:schemas.Fr}).and(ContractClassSchema.omit({privateFunctions:!0})));var ContractInstanceUpdateSchema=zodFor()(external_exports.object({prevContractClassId:schemas2.Fr,newContractClassId:schemas2.Fr,timestampOfChange:schemas2.BigInt})),ContractInstanceUpdateWithAddressSchema=zodFor()(ContractInstanceUpdateSchema.and(external_exports.object({address:schemas2.AztecAddress})));import{L1ContractAddressesSchema}from"@aztec/ethereum/l1-contract-addresses";var ProtocolContractAddressesSchema=external_exports.object({classRegistry:schemas2.AztecAddress,feeJuice:schemas2.AztecAddress,instanceRegistry:schemas2.AztecAddress,multiCallEntrypoint:schemas2.AztecAddress});var NodeInfoSchema=external_exports.object({nodeVersion:external_exports.string(),l1ChainId:external_exports.number().int().nonnegative(),rollupVersion:external_exports.number().int().nonnegative(),enr:external_exports.string().optional(),l1ContractAddresses:L1ContractAddressesSchema,protocolContractAddresses:ProtocolContractAddressesSchema,realProofs:external_exports.boolean(),txsLimits:external_exports.object({gas:external_exports.object({daGas:external_exports.number().int().nonnegative(),l2Gas:external_exports.number().int().nonnegative()})})}).transform(obj=>({enr:void 0,...obj}));var CompleteAddress=class _CompleteAddress{static{__name(this,"CompleteAddress")}address;publicKeys;partialAddress;constructor(address,publicKeys,partialAddress){this.address=address,this.publicKeys=publicKeys,this.partialAddress=partialAddress}static async create(address,publicKeys,partialAddress){let completeAddress=new _CompleteAddress(address,publicKeys,partialAddress);return await completeAddress.validate(),completeAddress}static SIZE_IN_BYTES=288;static get schema(){return hexSchemaFor(_CompleteAddress)}toJSON(){return this.toString()}static async random(){return await this.fromSecretKeyAndPartialAddress(Fr.random(),Fr.random())}static async fromSecretKeyAndPartialAddress(secretKey,partialAddress){let{publicKeys}=await deriveKeys(secretKey);return await this.fromPublicKeysAndPartialAddress(publicKeys,partialAddress)}static async fromPublicKeysAndPartialAddress(publicKeys,partialAddress){let address=await computeAddress(publicKeys,partialAddress);return new _CompleteAddress(address,publicKeys,partialAddress)}async getPreaddress(){return computePreaddress(await this.publicKeys.hash(),this.partialAddress)}static async fromSecretKeyAndInstance(secretKey,instance){let partialAddress=await computePartialAddress(instance);return _CompleteAddress.fromSecretKeyAndPartialAddress(secretKey,partialAddress)}async validate(){let expectedAddress=await computeAddress(this.publicKeys,this.partialAddress);if(!expectedAddress.equals(this.address))throw new Error(`Address cannot be derived from public keys and partial address (received ${this.address.toString()}, derived ${expectedAddress.toString()})`)}toReadableString(){return`Address: ${this.address.toString()}
|
|
190
190
|
NpkM hash: ${this.publicKeys.npkMHash.toString()}
|
|
191
191
|
IvpkM: ${this.publicKeys.ivpkM.toString()}
|
|
@@ -194,7 +194,7 @@ TpkM hash: ${this.publicKeys.tpkMHash.toString()}
|
|
|
194
194
|
MspkM hash: ${this.publicKeys.mspkMHash.toString()}
|
|
195
195
|
FbpkM hash: ${this.publicKeys.fbpkMHash.toString()}
|
|
196
196
|
Partial Address: ${this.partialAddress.toString()}
|
|
197
|
-
`}equals(other){return this.address.equals(other.address)&&this.publicKeys.equals(other.publicKeys)&&this.partialAddress.equals(other.partialAddress)}toBuffer(){return serializeToBuffer([this.address,this.publicKeys,this.partialAddress])}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer),address=reader.readObject(AztecAddress),publicKeys=reader.readObject(PublicKeys),partialAddress=reader.readObject(Fr);return _CompleteAddress.create(address,publicKeys,partialAddress)}static fromString(address){return _CompleteAddress.fromBuffer(Buffer.from(address.replace(/^0x/i,""),"hex"))}toString(){return bufferToHex(this.toBuffer())}};var ContractClassService=class{static{__name(this,"ContractClassService")}node;contractStore;#cache;constructor(node,contractStore){this.node=node,this.contractStore=contractStore,this.#cache=new Map}async getCurrentClassId(address,anchorBlockHeader){if(isProtocolContract(address))return(await this.contractStore.getContractInstance(address))?.originalContractClassId;let key=`${address.toString()}:${(await anchorBlockHeader.hash()).toString()}`,promise2=this.#cache.get(key);promise2||(promise2=(async()=>{let nodeInstance=await this.node.getContract(address,await anchorBlockHeader.hash());return nodeInstance?nodeInstance.currentContractClassId:(await this.contractStore.getContractInstance(address))?.originalContractClassId})().catch(err=>{throw this.#cache.delete(key),err}),this.#cache.set(key,promise2));let classId=await promise2;return classId===void 0&&this.#cache.delete(key),classId}wipe(){this.#cache.clear()}};import{L1ContractAddressesSchema as L1ContractAddressesSchema2}from"@aztec/ethereum/l1-contract-addresses";function resolveRetryUntilTimeoutSeconds(timeout){if(typeof timeout=="number")return timeout;if("deadline"in timeout){let now=timeout.dateProvider?.now()??Date.now(),remainingSeconds=(timeout.deadline.getTime()-now)/1e3;return remainingSeconds>0?remainingSeconds:-1}return timeout.timeout}__name(resolveRetryUntilTimeoutSeconds,"resolveRetryUntilTimeoutSeconds");async function retryUntil(fn,name="",timeout=0,interval=1){let timeoutSeconds=resolveRetryUntilTimeoutSeconds(timeout),timer=new Timer;for(;;){let result=await fn();if(result)return result;if(await sleep(interval*1e3),timeoutSeconds&&timer.s()>timeoutSeconds)throw new TimeoutError(name?`Timeout awaiting ${name}`:"Timeout")}}__name(retryUntil,"retryUntil");var log=createLogger("json-rpc:json_rpc_client");var DEFAULT_MAX_REQUESTY_BODY_SIZE=10*1024*1024;function computeTxOutHash(messages){return messages.length?Fr.fromBuffer(computeUnbalancedShaRoot(messages.map(msg=>msg.toBuffer()))):Fr.ZERO}__name(computeTxOutHash,"computeTxOutHash");function computeBlockOutHash(messagesPerTx){let txOutHashes=messagesPerTx.map(messages=>computeTxOutHash(messages));return Fr.fromBuffer(computeWonkyShaRoot(txOutHashes.map(hash5=>hash5.toBuffer())))}__name(computeBlockOutHash,"computeBlockOutHash");function computeCheckpointOutHash(messagesPerBlock){let blockOutHashes=messagesPerBlock.map(block=>computeBlockOutHash(block));return Fr.fromBuffer(computeWonkyShaRoot(blockOutHashes.map(hash5=>hash5.toBuffer())))}__name(computeCheckpointOutHash,"computeCheckpointOutHash");var Checkpoint=class _Checkpoint{static{__name(this,"Checkpoint")}archive;header;blocks;number;feeAssetPriceModifier;constructor(archive,header,blocks,number4,feeAssetPriceModifier=0n){this.archive=archive,this.header=header,this.blocks=blocks,this.number=number4,this.feeAssetPriceModifier=feeAssetPriceModifier}get slot(){return this.header.slotNumber}static get schema(){return external_exports.object({archive:AppendOnlyTreeSnapshot.schema,header:CheckpointHeader.schema,blocks:external_exports.array(L2Block.schema),number:CheckpointNumberSchema,feeAssetPriceModifier:schemas2.BigInt}).transform(({archive,header,blocks,number:number4,feeAssetPriceModifier})=>new _Checkpoint(archive,header,blocks,number4,feeAssetPriceModifier))}static from(fields){return new _Checkpoint(..._Checkpoint.getFields(fields))}static getFields(fields){return[fields.archive,fields.header,fields.blocks,fields.number,fields.feeAssetPriceModifier]}static fromBuffer(buf){let reader=BufferReader.asReader(buf),archive=reader.readObject(AppendOnlyTreeSnapshot),header=reader.readObject(CheckpointHeader),blocks=reader.readVector(L2Block,MAX_CAPACITY_BLOCKS_PER_CHECKPOINT),number4=CheckpointNumber(reader.readNumber()),feeAssetPriceModifier=reader.readInt256();return new _Checkpoint(archive,header,blocks,number4,feeAssetPriceModifier)}toBuffer(){return serializeToBuffer(this.archive,this.header,this.blocks.length,this.blocks,this.number,serializeSignedBigInt(this.feeAssetPriceModifier))}toBlobFields(){let blocks=this.blocks.map(block=>block.toBlockBlobData());return encodeCheckpointBlobDataFromBlocks(blocks)}hash(){return this.header.hash()}getCheckpointOutHash(){return _Checkpoint.getCheckpointOutHash(this.blocks)}static getCheckpointOutHash(blocks){let msgs=blocks.map(block=>block.body.txEffects.map(txEffect=>txEffect.l2ToL1Msgs));return computeCheckpointOutHash(msgs)}getState(){return this.blocks.at(-1).header.state}toCheckpointInfo(){return{archive:this.archive.root,lastArchive:this.header.lastArchiveRoot,slotNumber:this.header.slotNumber,checkpointNumber:this.number,timestamp:this.header.timestamp}}getStats(){let txEffects=this.blocks.flatMap(block=>block.body.txEffects),logsStats={privateLogCount:sum(txEffects.map(tx=>tx.privateLogs.length)),publicLogCount:sum(txEffects.map(tx=>tx.publicLogs.length)),contractClassLogCount:sum(txEffects.map(tx=>tx.contractClassLogs.length)),contractClassLogSize:sum(txEffects.map(tx=>sum(tx.contractClassLogs.map(log2=>log2.emittedLength))))};return{txCount:txEffects.length,blockCount:this.blocks.length,slotNumber:this.header.slotNumber,checkpointNumber:this.number,timestamp:this.header.timestamp,...logsStats}}static async random(checkpointNumber=CheckpointNumber(1),{numBlocks=1,startBlockNumber=1,previousArchive,feeAssetPriceModifier=0n,...options}={}){let headerOptions=previousArchive?{lastArchiveRoot:previousArchive.root,...options}:options,header=CheckpointHeader.random(headerOptions),blocks=[],lastArchive=previousArchive;for(let i=0;i<numBlocks;i++){let block=await L2Block.random(BlockNumber(startBlockNumber+i),{checkpointNumber,indexWithinCheckpoint:IndexWithinCheckpoint(i),...options,...lastArchive?{lastArchive}:{},...pick2(header,"slotNumber","timestamp","coinbase","feeRecipient","gasFees")});lastArchive=block.archive,blocks.push(block)}return new _Checkpoint(options.archive??AppendOnlyTreeSnapshot.random(),header,blocks,checkpointNumber,feeAssetPriceModifier)}};var L1PublishedData=class _L1PublishedData{static{__name(this,"L1PublishedData")}blockNumber;timestamp;blockHash;constructor(blockNumber,timestamp,blockHash){this.blockNumber=blockNumber,this.timestamp=timestamp,this.blockHash=blockHash}static get schema(){return external_exports.object({blockNumber:schemas.BigInt,timestamp:schemas.BigInt,blockHash:external_exports.string()}).transform(obj=>_L1PublishedData.fromFields(obj))}static random(){return new _L1PublishedData(randomBigInt(1000n)+1n,BigInt(Math.floor(Date.now()/1e3)),Buffer32.random().toString())}static fromFields(fields){return new _L1PublishedData(fields.blockNumber,fields.timestamp,fields.blockHash)}static fromBuffer(bufferOrReader){let reader=BufferReader.asReader(bufferOrReader),l1BlockNumber=reader.readBigInt(),l1BlockHash=reader.readString(MAX_BLOCK_HASH_STRING_LENGTH),l1Timestamp=reader.readBigInt();return new _L1PublishedData(l1BlockNumber,l1Timestamp,l1BlockHash)}toBuffer(){return serializeToBuffer(this.blockNumber,this.blockHash,this.timestamp)}},PublishedCheckpoint=class _PublishedCheckpoint{static{__name(this,"PublishedCheckpoint")}checkpoint;l1;attestations;constructor(checkpoint,l1,attestations){this.checkpoint=checkpoint,this.l1=l1,this.attestations=attestations}static get schema(){return external_exports.object({checkpoint:Checkpoint.schema,l1:L1PublishedData.schema,attestations:external_exports.array(CommitteeAttestation.schema)}).transform(obj=>_PublishedCheckpoint.from(obj))}static getFields(fields){return[fields.checkpoint,fields.l1,fields.attestations]}static from(fields){return new _PublishedCheckpoint(..._PublishedCheckpoint.getFields(fields))}static fromBuffer(bufferOrReader){let reader=BufferReader.asReader(bufferOrReader),checkpoint=reader.readObject(Checkpoint),l1BlockNumber=reader.readBigInt(),l1BlockHash=reader.readString(MAX_BLOCK_HASH_STRING_LENGTH),l1Timestamp=reader.readBigInt(),attestations=reader.readVector(CommitteeAttestation,MAX_COMMITTEE_SIZE);return new _PublishedCheckpoint(checkpoint,new L1PublishedData(l1BlockNumber,l1Timestamp,l1BlockHash),attestations)}toBuffer(){return serializeToBuffer(this.checkpoint,this.l1.blockNumber,this.l1.blockHash,this.l1.timestamp,this.attestations.length,this.attestations)}};var ProposedCheckpointDataSchema=external_exports.object({checkpointNumber:CheckpointNumberSchema,header:CheckpointHeader.schema,archive:AppendOnlyTreeSnapshot.schema,checkpointOutHash:schemas.Fr,startBlock:BlockNumberSchema,blockCount:external_exports.number(),totalManaUsed:schemas.BigInt,feeAssetPriceModifier:schemas.BigInt}),CheckpointDataSchema=external_exports.object({checkpointNumber:CheckpointNumberSchema,header:CheckpointHeader.schema,archive:AppendOnlyTreeSnapshot.schema,checkpointOutHash:schemas.Fr,startBlock:BlockNumberSchema,blockCount:schemas.Integer,feeAssetPriceModifier:schemas.BigInt,attestations:external_exports.array(CommitteeAttestation.schema),l1:L1PublishedData.schema}).transform(obj=>({checkpointNumber:obj.checkpointNumber,header:obj.header,archive:obj.archive,checkpointOutHash:obj.checkpointOutHash,startBlock:obj.startBlock,blockCount:obj.blockCount,feeAssetPriceModifier:obj.feeAssetPriceModifier,attestations:obj.attestations,l1:obj.l1}));var L2ToL1MembershipWitnessSchema=external_exports.object({epochNumber:EpochNumberSchema,numCheckpointsInEpoch:schemas2.Integer,root:schemas2.Fr,leafIndex:schemas2.BigInt,siblingPath:SiblingPath.schema});import{pickL1ContractAddressMappings,pickL1ContractAddressesSchema}from"@aztec/ethereum/l1-contract-addresses";var NetworkConfigSchema=external_exports.object({bootnodes:external_exports.array(external_exports.string()),snapshots:external_exports.array(external_exports.string()),blobFileStoreUrls:external_exports.array(external_exports.string()).optional(),txCollectionFileStoreUrls:external_exports.array(external_exports.string()).optional(),registryAddress:external_exports.string(),feeAssetHandlerAddress:external_exports.string().optional(),l1ChainId:external_exports.number(),blockDurationMs:external_exports.number().positive().optional(),txPublicSetupAllowListExtend:external_exports.string().optional(),nodeVersion:external_exports.string().optional()}).passthrough(),NetworkConfigMapSchema=external_exports.record(external_exports.string(),NetworkConfigSchema);function numberConfigHelper(defaultVal){return{parseEnv:__name(val=>safeParseNumber(val,defaultVal),"parseEnv"),defaultValue:defaultVal}}__name(numberConfigHelper,"numberConfigHelper");function floatConfigHelper(defaultVal,validationFn){return{parseEnv:__name(val=>{let parsed=safeParseFloat(val,defaultVal);return validationFn?.(parsed),parsed},"parseEnv"),defaultValue:defaultVal}}__name(floatConfigHelper,"floatConfigHelper");function optionalNumberConfigHelper(){return{parseEnv:__name(val=>{let parsedValue=parseInt(val);if(!Number.isSafeInteger(parsedValue))throw new Error(`Invalid number: ${val}`);return parsedValue},"parseEnv")}}__name(optionalNumberConfigHelper,"optionalNumberConfigHelper");function enumConfigHelper(values,defaultValue){return{parseEnv:__name(val=>{let sanitizedVal=val.trim().toLowerCase();if(values.some(v=>v.toLowerCase()===sanitizedVal))return values.find(v=>v.toLowerCase()===sanitizedVal);throw new Error(`Invalid config value '${val}' (must be one of ${values.join(", ")})`)},"parseEnv"),defaultValue}}__name(enumConfigHelper,"enumConfigHelper");function booleanConfigHelper(defaultVal=!1){let parse4=__name(val=>typeof val=="boolean"?val:parseBooleanEnv(val),"parse");return{parseEnv:parse4,parseVal:parse4,defaultValue:defaultVal,isBoolean:!0}}__name(booleanConfigHelper,"booleanConfigHelper");function secretStringConfigHelper(defaultValue){let parse4=__name(val=>new SecretValue(val),"parse");return{parseEnv:parse4,parseVal:parse4,defaultValue:defaultValue!==void 0?new SecretValue(defaultValue):void 0}}__name(secretStringConfigHelper,"secretStringConfigHelper");function safeParseNumber(value,defaultValue){let parsedValue=parseInt(value,10);return Number.isSafeInteger(parsedValue)?parsedValue:defaultValue}__name(safeParseNumber,"safeParseNumber");function safeParseFloat(value,defaultValue){let parsedValue=parseFloat(value);return Number.isNaN(parsedValue)?defaultValue:parsedValue}__name(safeParseFloat,"safeParseFloat");function pickConfigMappings(configMappings,keys){return Object.fromEntries(keys.map(key=>[key,configMappings[key]]))}__name(pickConfigMappings,"pickConfigMappings");function getDefaultConfig(configMappings){let defaultConfig={};for(let key in configMappings)configMappings[key]&&configMappings[key].defaultValue!==void 0&&(defaultConfig[key]=configMappings[key].defaultValue);return defaultConfig}__name(getDefaultConfig,"getDefaultConfig");var baseSignerConfigMappings={nodeId:{env:"VALIDATOR_HA_NODE_ID",description:"The unique identifier for this node",defaultValue:""},pollingIntervalMs:{env:"VALIDATOR_HA_POLLING_INTERVAL_MS",description:"The number of ms to wait between polls when a duty is being signed",...numberConfigHelper(100)},signingTimeoutMs:{env:"VALIDATOR_HA_SIGNING_TIMEOUT_MS",description:"The maximum time to wait for a duty being signed to complete",...numberConfigHelper(3e3)},maxStuckDutiesAgeMs:{env:"VALIDATOR_HA_MAX_STUCK_DUTIES_AGE_MS",description:"The maximum age of a stuck duty in ms (defaults to 2x Aztec slot duration)",...optionalNumberConfigHelper()},cleanupOldDutiesAfterHours:{env:"VALIDATOR_HA_OLD_DUTIES_MAX_AGE_H",description:"Optional: clean up old duties after this many hours (disabled if not set)",...optionalNumberConfigHelper()},...pickL1ContractAddressMappings("rollupAddress")},BaseSignerConfigSchema=external_exports.object({nodeId:external_exports.string(),pollingIntervalMs:external_exports.number().min(0),signingTimeoutMs:external_exports.number().min(0),maxStuckDutiesAgeMs:external_exports.number().min(0).optional(),cleanupOldDutiesAfterHours:external_exports.number().min(0).optional(),...pickL1ContractAddressesSchema("rollupAddress")}),validatorHASignerConfigMappings={...baseSignerConfigMappings,haSigningEnabled:{env:"VALIDATOR_HA_SIGNING_ENABLED",description:"Whether HA signing / slashing protection is enabled",...booleanConfigHelper(!1)},databaseUrl:{env:"VALIDATOR_HA_DATABASE_URL",description:"PostgreSQL connection string for validator HA signer (format: postgresql://user:password@host:port/database)",...secretStringConfigHelper()},poolMaxCount:{env:"VALIDATOR_HA_POOL_MAX",description:"Maximum number of clients in the pool",...numberConfigHelper(10)},poolMinCount:{env:"VALIDATOR_HA_POOL_MIN",description:"Minimum number of clients in the pool",...numberConfigHelper(0)},poolIdleTimeoutMs:{env:"VALIDATOR_HA_POOL_IDLE_TIMEOUT_MS",description:"Idle timeout in milliseconds",...numberConfigHelper(1e4)},poolConnectionTimeoutMs:{env:"VALIDATOR_HA_POOL_CONNECTION_TIMEOUT_MS",description:"Connection timeout in milliseconds (0 means no timeout)",...numberConfigHelper(0)}},defaultValidatorHASignerConfig=getDefaultConfig(validatorHASignerConfigMappings);var ValidatorHASignerConfigSchema=BaseSignerConfigSchema.extend({haSigningEnabled:external_exports.boolean(),databaseUrl:SecretValue.schema(external_exports.string()).optional(),poolMaxCount:external_exports.number().min(0).optional(),poolMinCount:external_exports.number().min(0).optional(),poolIdleTimeoutMs:external_exports.number().min(0).optional(),poolConnectionTimeoutMs:external_exports.number().min(0).optional()});import{pickL1ContractAddressMappings as pickL1ContractAddressMappings2}from"@aztec/ethereum/l1-contract-addresses";var dataConfigMappings={dataDirectory:{env:"DATA_DIRECTORY",description:"Optional dir to store data. If omitted will store in memory."},dataStoreMapSizeKb:{env:"DATA_STORE_MAP_SIZE_KB",description:"The maximum possible size of a data store DB in KB. Can be overridden by component-specific options.",...numberConfigHelper(128*1024*1024)},...pickL1ContractAddressMappings2("rollupAddress")};var localSignerConfigMappings={...baseSignerConfigMappings,...dataConfigMappings,signingProtectionMapSizeKb:{env:"SIGNING_PROTECTION_MAP_SIZE_KB",description:"Maximum size of the local signing-protection LMDB store in KB. Overwrites the general dataStoreMapSizeKb.",...optionalNumberConfigHelper()}},LocalSignerConfigSchema=zodFor()(BaseSignerConfigSchema.extend({dataDirectory:external_exports.string().optional(),dataStoreMapSizeKb:external_exports.number(),signingProtectionMapSizeKb:external_exports.number().optional()}));var DutyType=(function(DutyType2){return DutyType2.BLOCK_PROPOSAL="BLOCK_PROPOSAL",DutyType2.CHECKPOINT_PROPOSAL="CHECKPOINT_PROPOSAL",DutyType2.ATTESTATION="ATTESTATION",DutyType2.ATTESTATIONS_AND_SIGNERS="ATTESTATIONS_AND_SIGNERS",DutyType2.GOVERNANCE_VOTE="GOVERNANCE_VOTE",DutyType2.SLASHING_VOTE="SLASHING_VOTE",DutyType2.AUTH_REQUEST="AUTH_REQUEST",DutyType2.TXS="TXS",DutyType2})({});var SignedTxs=class _SignedTxs{static{__name(this,"SignedTxs")}txs;signature;signatureContext;primaryType;cachedSender;constructor(txs,signature,signatureContext){this.txs=txs,this.signature=signature,this.signatureContext=signatureContext,this.primaryType="SignedTxs",this.cachedSender=void 0}getPayloadToSign(){return serializeToBuffer([this.txs.length,this.txs])}getSender(){return this.cachedSender===void 0&&(this.cachedSender=recoverCoordinationSigner(this,this.signature)??null),this.cachedSender??void 0}static async createFromSigner(txs,signatureContext,typedDataSigner){let tempSignedTxs=new _SignedTxs(txs,Signature.empty(),signatureContext),typedData=getCoordinationSignatureTypedData(tempSignedTxs),signature=await typedDataSigner(typedData);return new _SignedTxs(txs,signature,signatureContext)}toBuffer(){return serializeToBuffer([this.txs.length,this.txs,this.signature,serializeCoordinationSignatureContext(this.signatureContext)])}static fromBuffer(buf){let reader=BufferReader.asReader(buf),txCount=reader.readNumber();if(txCount>MAX_TXS_PER_BLOCK)throw new Error(`txs count ${txCount} exceeds maximum ${MAX_TXS_PER_BLOCK}`);let txs=reader.readArray(txCount,Tx),signature=reader.readObject(Signature),signatureContext=readCoordinationSignatureContext(reader);return new _SignedTxs(txs,signature,signatureContext)}getSize(){return 4+this.txs.reduce((acc,tx)=>acc+tx.getSize(),0)+this.signature.getSize()+4+20}static empty(){return new _SignedTxs([],Signature.empty(),EMPTY_COORDINATION_SIGNATURE_CONTEXT)}static random(){return new _SignedTxs([Tx.random(),Tx.random()],Signature.random(),EMPTY_COORDINATION_SIGNATURE_CONTEXT)}};var BlockProposal=class _BlockProposal extends Gossipable{static{__name(this,"BlockProposal")}blockHeader;indexWithinCheckpoint;inHash;archiveRoot;txHashes;signature;signatureContext;signedTxs;static p2pTopic=TopicType.block_proposal;primaryType;cachedSender;constructor(blockHeader,indexWithinCheckpoint,inHash,archiveRoot,txHashes,signature,signatureContext,signedTxs){super(),this.blockHeader=blockHeader,this.indexWithinCheckpoint=indexWithinCheckpoint,this.inHash=inHash,this.archiveRoot=archiveRoot,this.txHashes=txHashes,this.signature=signature,this.signatureContext=signatureContext,this.signedTxs=signedTxs,this.primaryType="BlockProposal",this.cachedSender=void 0}generateP2PMessageIdentifier(){return Promise.resolve(new Buffer32(this.getPayloadHashBuffer()))}get archive(){return this.archiveRoot}get slotNumber(){return this.blockHeader.getSlot()}get blockNumber(){return this.blockHeader.getBlockNumber()}get txs(){return this.signedTxs?.txs}toBlockInfo(){return{slotNumber:this.slotNumber,lastArchive:this.blockHeader.lastArchive.root,timestamp:this.blockHeader.globalVariables.timestamp,archive:this.archiveRoot,txCount:this.txHashes.length}}getPayloadToSign(){return serializeToBuffer([this.blockHeader,this.indexWithinCheckpoint,this.inHash,this.archiveRoot,this.txHashes.length,this.txHashes])}getPayloadHashBuffer(){return keccak256(this.getPayloadToSign())}getPayloadHash(){return BlockProposalHash.fromBuffer(this.getPayloadHashBuffer())}static async createProposalFromSigner(blockHeader,checkpointNumber,indexWithinCheckpoint,inHash,archiveRoot,txHashes,txs,signatureContext,proposalSigner,txsSigner){let tempProposal=new _BlockProposal(blockHeader,indexWithinCheckpoint,inHash,archiveRoot,txHashes,Signature.empty(),signatureContext),blockContext={slot:blockHeader.globalVariables.slotNumber,blockNumber:blockHeader.globalVariables.blockNumber,checkpointNumber,blockIndexWithinCheckpoint:indexWithinCheckpoint,dutyType:DutyType.BLOCK_PROPOSAL},typedData=getCoordinationSignatureTypedData(tempProposal),sig=await proposalSigner(typedData,blockContext),signedTxs;if(txs){let txsSigningContext={dutyType:DutyType.TXS};if(!txsSigner)throw new Error("signed_txs requires a typed-data signer");signedTxs=await SignedTxs.createFromSigner(txs,signatureContext,typedData2=>txsSigner(typedData2,txsSigningContext))}return new _BlockProposal(blockHeader,indexWithinCheckpoint,inHash,archiveRoot,txHashes,sig,signatureContext,signedTxs)}getSender(){if(this.cachedSender===void 0){let blockSender=recoverCoordinationSigner(this,this.signature);if(blockSender&&this.signedTxs){if(!coordinationSignatureContextEquals(this.signedTxs.signatureContext,this.signatureContext)){this.cachedSender=null;return}let txsSender=this.signedTxs.getSender();if(!txsSender||!txsSender.equals(blockSender)){this.cachedSender=null;return}}this.cachedSender=blockSender??null}return this.cachedSender??void 0}getPayload(){return this.getPayloadToSign()}toBuffer(){let buffer=[this.blockHeader,this.indexWithinCheckpoint,this.inHash,this.archiveRoot,this.signature,serializeCoordinationSignatureContext(this.signatureContext),this.txHashes.length,this.txHashes];return this.signedTxs?(buffer.push(1),buffer.push(this.signedTxs.toBuffer())):buffer.push(0),serializeToBuffer(buffer)}static fromBuffer(buf){let reader=BufferReader.asReader(buf),blockHeader=reader.readObject(BlockHeader),indexWithinCheckpoint=IndexWithinCheckpoint(reader.readNumber()),inHash=reader.readObject(Fr),archiveRoot=reader.readObject(Fr),signature=reader.readObject(Signature),signatureContext=readCoordinationSignatureContext(reader),txHashCount=reader.readNumber();if(txHashCount>MAX_TXS_PER_BLOCK)throw new Error(`txHashes count ${txHashCount} exceeds maximum ${MAX_TXS_PER_BLOCK}`);let txHashes=reader.readArray(txHashCount,TxHash);if(!reader.isEmpty()&&reader.readNumber()){let signedTxs=SignedTxs.fromBuffer(reader);return new _BlockProposal(blockHeader,indexWithinCheckpoint,inHash,archiveRoot,txHashes,signature,signatureContext,signedTxs)}return new _BlockProposal(blockHeader,indexWithinCheckpoint,inHash,archiveRoot,txHashes,signature,signatureContext)}getSize(){return this.blockHeader.getSize()+4+this.inHash.size+this.archiveRoot.size+this.signature.getSize()+4+20+4+this.txHashes.length*TxHash.SIZE+4+(this.signedTxs?this.signedTxs.getSize():0)}static empty(){return new _BlockProposal(BlockHeader.empty(),IndexWithinCheckpoint(0),Fr.ZERO,Fr.ZERO,[],Signature.empty(),EMPTY_COORDINATION_SIGNATURE_CONTEXT)}static random(){return new _BlockProposal(BlockHeader.random(),IndexWithinCheckpoint(Math.floor(Math.random()*5)),Fr.random(),Fr.random(),[TxHash.random(),TxHash.random()],Signature.random(),EMPTY_COORDINATION_SIGNATURE_CONTEXT)}toInspect(){return{blockHeader:this.blockHeader.toInspect(),indexWithinCheckpoint:this.indexWithinCheckpoint,inHash:this.inHash.toString(),archiveRoot:this.archiveRoot.toString(),signature:this.signature.toString(),txHashes:this.txHashes.map(h=>h.toString()),chainId:this.signatureContext.chainId,rollupAddress:this.signatureContext.rollupAddress.toString()}}matchesBlock(block){return this.archiveRoot.equals(block.archive.root)&&this.blockHeader.equals(block.header)}withoutSignedTxs(){return new _BlockProposal(this.blockHeader,this.indexWithinCheckpoint,this.inHash,this.archiveRoot,this.txHashes,this.signature,this.signatureContext)}};var CheckpointProposal=class _CheckpointProposal extends Gossipable{static{__name(this,"CheckpointProposal")}checkpointHeader;archive;feeAssetPriceModifier;signature;signatureContext;lastBlock;static p2pTopic=TopicType.checkpoint_proposal;primaryType;cachedSender;constructor(checkpointHeader,archive,feeAssetPriceModifier,signature,signatureContext,lastBlock){if(super(),this.checkpointHeader=checkpointHeader,this.archive=archive,this.feeAssetPriceModifier=feeAssetPriceModifier,this.signature=signature,this.signatureContext=signatureContext,this.lastBlock=lastBlock,this.primaryType="CheckpointProposal",this.cachedSender=void 0,lastBlock&&"inHash"in lastBlock&&!lastBlock.inHash.equals(checkpointHeader.inHash))throw new Error(`CheckpointProposal lastBlock inHash ${lastBlock.inHash} does not match checkpoint inHash ${checkpointHeader.inHash}`);if(lastBlock&&"archiveRoot"in lastBlock&&!lastBlock.archiveRoot.equals(archive))throw new Error(`CheckpointProposal lastBlock archive ${lastBlock.archiveRoot} does not match checkpoint archive ${archive}`);if(lastBlock&&"signatureContext"in lastBlock&&!coordinationSignatureContextEquals(lastBlock.signatureContext,signatureContext))throw new Error("CheckpointProposal lastBlock signatureContext does not match checkpoint signatureContext")}generateP2PMessageIdentifier(){return Promise.resolve(new Buffer32(this.toConsensusPayload().getPayloadHash()))}get slotNumber(){return this.checkpointHeader.slotNumber}getBlockProposal(){if(this.lastBlock)return new BlockProposal(this.lastBlock.blockHeader,this.lastBlock.indexWithinCheckpoint,this.checkpointHeader.inHash,this.archive,this.lastBlock.txHashes,this.lastBlock.signature,this.signatureContext,this.lastBlock.signedTxs)}toBlockInfo(){if(!this.lastBlock)throw new Error("Cannot get blockInfo without lastBlock");return{slotNumber:this.slotNumber,lastArchive:this.lastBlock.blockHeader.lastArchive.root,timestamp:this.lastBlock.blockHeader.globalVariables.timestamp,archive:this.archive,txCount:this.lastBlock.txHashes.length}}toCheckpointInfo(){return{slotNumber:this.slotNumber,archive:this.archive,lastBlockNumber:this.lastBlock?.blockHeader.getBlockNumber(),lastBlockIndex:this.lastBlock?.indexWithinCheckpoint,blockHeadersHash:this.checkpointHeader.blockHeadersHash}}getPayloadToSign(){return serializeToBuffer([this.checkpointHeader,this.archive,serializeSignedBigInt(this.feeAssetPriceModifier)])}getPayloadHash(){return CheckpointProposalHash.fromBuffer(this.toConsensusPayload().getPayloadHash())}toConsensusPayload(){return new ConsensusPayload(this.checkpointHeader,this.archive,this.feeAssetPriceModifier,this.signatureContext)}static async createProposalFromSigner(checkpointHeader,archiveRoot,checkpointNumber,feeAssetPriceModifier,lastBlockProposal,signatureContext,payloadSigner){let tempProposal=new _CheckpointProposal(checkpointHeader,archiveRoot,feeAssetPriceModifier,Signature.empty(),signatureContext),checkpointContext={slot:checkpointHeader.slotNumber,checkpointNumber,dutyType:DutyType.CHECKPOINT_PROPOSAL},typedData=getCoordinationSignatureTypedData(tempProposal),checkpointSignature=await payloadSigner(typedData,checkpointContext);return new _CheckpointProposal(checkpointHeader,archiveRoot,feeAssetPriceModifier,checkpointSignature,signatureContext,lastBlockProposal)}getSender(){if(this.cachedSender===void 0){let checkpointSender=recoverCoordinationSigner(this,this.signature);if(checkpointSender&&this.lastBlock){let blockSender=this.getBlockProposal()?.getSender();if(!blockSender||!blockSender.equals(checkpointSender)){this.cachedSender=null;return}}this.cachedSender=checkpointSender??null}return this.cachedSender??void 0}getPayload(){return this.getPayloadToSign()}toBuffer(){let buffer=[this.checkpointHeader,this.archive,serializeSignedBigInt(this.feeAssetPriceModifier),this.signature,serializeCoordinationSignatureContext(this.signatureContext)];return this.lastBlock?(buffer.push(1),buffer.push(this.lastBlock.blockHeader),buffer.push(this.lastBlock.indexWithinCheckpoint),buffer.push(this.lastBlock.signature),buffer.push(this.lastBlock.txHashes.length),buffer.push(this.lastBlock.txHashes),this.lastBlock.signedTxs?(buffer.push(1),buffer.push(this.lastBlock.signedTxs.toBuffer())):buffer.push(0)):buffer.push(0),serializeToBuffer(buffer)}static fromBuffer(buf){let reader=BufferReader.asReader(buf),checkpointHeader=reader.readObject(CheckpointHeader),archive=reader.readObject(Fr),feeAssetPriceModifier=reader.readInt256(),signature=reader.readObject(Signature),signatureContext=readCoordinationSignatureContext(reader);if(reader.readNumber()){let blockHeader=reader.readObject(BlockHeader),indexWithinCheckpoint=IndexWithinCheckpoint(reader.readNumber()),blockSignature=reader.readObject(Signature),txHashCount=reader.readNumber();if(txHashCount>MAX_TXS_PER_BLOCK)throw new Error(`txHashes count ${txHashCount} exceeds maximum ${MAX_TXS_PER_BLOCK}`);let txHashes=reader.readArray(txHashCount,TxHash),signedTxs;return reader.isEmpty()||reader.readNumber()&&(signedTxs=SignedTxs.fromBuffer(reader)),new _CheckpointProposal(checkpointHeader,archive,feeAssetPriceModifier,signature,signatureContext,{blockHeader,indexWithinCheckpoint,txHashes,signature:blockSignature,signedTxs})}return new _CheckpointProposal(checkpointHeader,archive,feeAssetPriceModifier,signature,signatureContext)}getSize(){let size=this.checkpointHeader.toBuffer().length+this.archive.size+this.signature.getSize()+8+4+20+4;return this.lastBlock&&(size+=this.lastBlock.blockHeader.getSize()+4+this.lastBlock.signature.getSize()+4+this.lastBlock.txHashes.length*TxHash.SIZE+4+(this.lastBlock.signedTxs?this.lastBlock.signedTxs.getSize():0)),size}static empty(){return new _CheckpointProposal(CheckpointHeader.empty(),Fr.ZERO,0n,Signature.empty(),EMPTY_COORDINATION_SIGNATURE_CONTEXT)}static random(){return new _CheckpointProposal(CheckpointHeader.random(),Fr.random(),0n,Signature.random(),EMPTY_COORDINATION_SIGNATURE_CONTEXT,{blockHeader:BlockHeader.random(),indexWithinCheckpoint:IndexWithinCheckpoint(Math.floor(Math.random()*5)),txHashes:[TxHash.random(),TxHash.random()],signature:Signature.random()})}toInspect(){return{checkpointHeader:this.checkpointHeader.toInspect(),archive:this.archive.toString(),signature:this.signature.toString(),feeAssetPriceModifier:this.feeAssetPriceModifier.toString(),chainId:this.signatureContext.chainId,rollupAddress:this.signatureContext.rollupAddress.toString(),lastBlock:this.lastBlock?{blockHeader:this.lastBlock.blockHeader.toInspect(),indexWithinCheckpoint:this.lastBlock.indexWithinCheckpoint,txHashes:this.lastBlock.txHashes.map(h=>h.toString()),signature:this.lastBlock.signature.toString()}:void 0}}toCore(){return new _CheckpointProposal(this.checkpointHeader,this.archive,this.feeAssetPriceModifier,this.signature,this.signatureContext)}};var CheckpointAttestation=class _CheckpointAttestation extends Gossipable{static{__name(this,"CheckpointAttestation")}payload;signature;proposerSignature;static p2pTopic=TopicType.checkpoint_attestation;cachedSender;cachedProposer;constructor(payload,signature,proposerSignature){super(),this.payload=payload,this.signature=signature,this.proposerSignature=proposerSignature,this.cachedSender=void 0,this.cachedProposer=void 0}static get schema(){return external_exports.object({payload:ConsensusPayload.schema,signature:Signature.schema,proposerSignature:Signature.schema}).transform(obj=>new _CheckpointAttestation(obj.payload,obj.signature,obj.proposerSignature))}generateP2PMessageIdentifier(){return Promise.resolve(new Buffer32(this.payload.getPayloadHash()))}get archive(){return this.payload.archive}get slotNumber(){return this.payload.header.slotNumber}get signatureContext(){return this.payload.signatureContext}getSender(){return this.cachedSender===void 0&&(this.cachedSender=recoverCoordinationSigner(this.payload,this.signature)??null),this.cachedSender??void 0}getProposer(){if(this.cachedProposer===void 0){let proposal=new CheckpointProposal(this.payload.header,this.payload.archive,this.payload.feeAssetPriceModifier,this.proposerSignature,this.payload.signatureContext);this.cachedProposer=proposal.getSender()??null}return this.cachedProposer??void 0}withNormalizedSignature(){return new _CheckpointAttestation(this.payload,normalizeSignature(this.signature),this.proposerSignature)}getPayload(){return this.payload.getPayloadToSign()}getPayloadHash(){return CheckpointProposalHash.fromBuffer(this.payload.getPayloadHash())}toBuffer(){return serializeToBuffer([this.payload,this.signature,this.proposerSignature])}static fromBuffer(buf){let reader=BufferReader.asReader(buf);return new _CheckpointAttestation(reader.readObject(ConsensusPayload),reader.readObject(Signature),reader.readObject(Signature))}static empty(){return new _CheckpointAttestation(ConsensusPayload.empty(),Signature.empty(),Signature.empty())}static random(){return new _CheckpointAttestation(ConsensusPayload.random(),Signature.random(),Signature.random())}getSize(){return this.payload.getSize()+this.signature.getSize()+this.proposerSignature.getSize()}toInspect(){return{payload:this.payload.toInspect(),signature:this.signature.toString(),proposerSignature:this.proposerSignature.toString()}}};var MerkleTreeId=(function(MerkleTreeId2){return MerkleTreeId2[MerkleTreeId2.NULLIFIER_TREE=0]="NULLIFIER_TREE",MerkleTreeId2[MerkleTreeId2.NOTE_HASH_TREE=1]="NOTE_HASH_TREE",MerkleTreeId2[MerkleTreeId2.PUBLIC_DATA_TREE=2]="PUBLIC_DATA_TREE",MerkleTreeId2[MerkleTreeId2.L1_TO_L2_MESSAGE_TREE=3]="L1_TO_L2_MESSAGE_TREE",MerkleTreeId2[MerkleTreeId2.ARCHIVE=4]="ARCHIVE",MerkleTreeId2})({}),merkleTreeIds=__name(()=>Object.values(MerkleTreeId).filter(v=>!isNaN(Number(v))),"merkleTreeIds"),TREE_HEIGHTS={[MerkleTreeId.NOTE_HASH_TREE]:42,[MerkleTreeId.ARCHIVE]:30,[MerkleTreeId.L1_TO_L2_MESSAGE_TREE]:36,[MerkleTreeId.NULLIFIER_TREE]:42,[MerkleTreeId.PUBLIC_DATA_TREE]:40};var TREE_NAMES={[MerkleTreeId.NULLIFIER_TREE]:"NULLIFIER_TREE",[MerkleTreeId.NOTE_HASH_TREE]:"NOTE_HASH_TREE",[MerkleTreeId.PUBLIC_DATA_TREE]:"PUBLIC_DATA_TREE",[MerkleTreeId.L1_TO_L2_MESSAGE_TREE]:"L1_TO_L2_MESSAGE_TREE",[MerkleTreeId.ARCHIVE]:"ARCHIVE"};function getTreeName(treeId){return TREE_NAMES[treeId]}__name(getTreeName,"getTreeName");var NullifierLeafPreimage=class _NullifierLeafPreimage{static{__name(this,"NullifierLeafPreimage")}leaf;nextKey;nextIndex;constructor(leaf,nextKey,nextIndex){this.leaf=leaf,this.nextKey=nextKey,this.nextIndex=nextIndex}static get schema(){return external_exports.object({leaf:NullifierLeaf.schema,nextKey:schemas.Fr,nextIndex:schemas.BigInt}).transform(({leaf,nextKey,nextIndex})=>new _NullifierLeafPreimage(leaf,nextKey,nextIndex))}static fromPlainObject(obj){return obj instanceof _NullifierLeafPreimage?obj:new _NullifierLeafPreimage(NullifierLeaf.fromPlainObject(obj.leaf),Fr.fromPlainObject(obj.nextKey),typeof obj.nextIndex=="bigint"?obj.nextIndex:BigInt(obj.nextIndex))}static get leafSchema(){return NullifierLeaf.schema}getKey(){return this.leaf.getKey()}getNextKey(){return this.nextKey.toBigInt()}getNextIndex(){return this.nextIndex}asLeaf(){return this.leaf}toBuffer(){return Buffer.concat(this.toHashInputs())}toHashInputs(){return[...this.leaf.toHashInputs(),Buffer.from(this.nextKey.toBuffer()),Buffer.from(toBufferBE(this.nextIndex,32))]}isEmpty(){return this.leaf.isEmpty()&&this.nextKey.isZero()&&this.nextIndex===0n}toFields(){return this.toHashInputs().map(buf=>Fr.fromBuffer(buf))}clone(){return new _NullifierLeafPreimage(this.leaf.clone(),this.nextKey,this.nextIndex)}static random(){return new _NullifierLeafPreimage(NullifierLeaf.random(),Fr.random(),BigInt(Math.floor(Math.random()*1e3)))}static empty(){return new _NullifierLeafPreimage(NullifierLeaf.empty(),Fr.zero(),0n)}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _NullifierLeafPreimage(NullifierLeaf.fromBuffer(reader),reader.readObject(Fr),toBigIntBE(reader.readBytes(32)))}static fromLeaf(leaf,nextKey,nextIndex){return new _NullifierLeafPreimage(leaf,new Fr(nextKey),nextIndex)}static clone(preimage){return preimage.clone()}},NullifierLeaf=class _NullifierLeaf{static{__name(this,"NullifierLeaf")}nullifier;constructor(nullifier){this.nullifier=nullifier}getKey(){return this.nullifier.toBigInt()}toBuffer(){return this.nullifier.toBuffer()}clone(){return new _NullifierLeaf(new Fr(this.nullifier))}toHashInputs(){return[Buffer.from(this.nullifier.toBuffer())]}static empty(){return new _NullifierLeaf(Fr.ZERO)}static random(){return new _NullifierLeaf(Fr.random())}isEmpty(){return this.nullifier.isZero()}updateTo(_another){throw new Error("Nullifiers are create only")}static buildDummy(key){return new _NullifierLeaf(new Fr(key))}static fromBuffer(buf){let reader=BufferReader.asReader(buf);return new _NullifierLeaf(reader.readObject(Fr))}static get schema(){return external_exports.object({nullifier:schemas.Fr}).transform(({nullifier})=>new _NullifierLeaf(nullifier))}static fromPlainObject(obj){return obj instanceof _NullifierLeaf?obj:new _NullifierLeaf(Fr.fromPlainObject(obj.nullifier))}};var NullifierMembershipWitness=class _NullifierMembershipWitness{static{__name(this,"NullifierMembershipWitness")}index;leafPreimage;siblingPath;constructor(index,leafPreimage,siblingPath){this.index=index,this.leafPreimage=leafPreimage,this.siblingPath=siblingPath}static get schema(){return external_exports.object({index:schemas2.BigInt,leafPreimage:NullifierLeafPreimage.schema,siblingPath:SiblingPath.schemaFor(42)}).transform(({index,leafPreimage,siblingPath})=>new _NullifierMembershipWitness(index,leafPreimage,siblingPath))}static random(){return new _NullifierMembershipWitness(BigInt(Math.floor(Math.random()*1e3)),NullifierLeafPreimage.random(),SiblingPath.random(42))}withoutPreimage(){return new MembershipWitness(42,this.index,this.siblingPath.toTuple())}};var PublicDataTreeLeafPreimage=class _PublicDataTreeLeafPreimage{static{__name(this,"PublicDataTreeLeafPreimage")}leaf;nextKey;nextIndex;constructor(leaf,nextKey,nextIndex){this.leaf=leaf,this.nextKey=nextKey,this.nextIndex=nextIndex}static get schema(){return external_exports.object({leaf:PublicDataTreeLeaf.schema,nextKey:schemas.Fr,nextIndex:schemas.BigInt}).transform(({leaf,nextKey,nextIndex})=>new _PublicDataTreeLeafPreimage(leaf,nextKey,nextIndex))}static fromPlainObject(obj){return obj instanceof _PublicDataTreeLeafPreimage?obj:new _PublicDataTreeLeafPreimage(PublicDataTreeLeaf.fromPlainObject(obj.leaf),Fr.fromPlainObject(obj.nextKey),typeof obj.nextIndex=="bigint"?obj.nextIndex:BigInt(obj.nextIndex))}static get leafSchema(){return PublicDataTreeLeaf.schema}getKey(){return this.leaf.getKey()}getNextKey(){return this.nextKey.toBigInt()}getNextIndex(){return this.nextIndex}asLeaf(){return this.leaf}toBuffer(){return Buffer.concat(this.toHashInputs())}toHashInputs(){return[...this.leaf.toHashInputs(),Buffer.from(this.nextKey.toBuffer()),Buffer.from(toBufferBE(this.nextIndex,32))]}hash(){return poseidon2Hash(this.toHashInputs())}clone(){return new _PublicDataTreeLeafPreimage(this.leaf.clone(),this.nextKey,this.nextIndex)}static random(){return new _PublicDataTreeLeafPreimage(PublicDataTreeLeaf.buildDummy(BigInt(Math.floor(Math.random()*1e3))),Fr.random(),BigInt(Math.floor(Math.random()*1e3)))}static empty(){return new _PublicDataTreeLeafPreimage(PublicDataTreeLeaf.empty(),Fr.ZERO,0n)}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _PublicDataTreeLeafPreimage(PublicDataTreeLeaf.fromBuffer(reader),Fr.fromBuffer(reader),toBigIntBE(reader.readBytes(32)))}static fromLeaf(leaf,nextKey,nextIndex){return new _PublicDataTreeLeafPreimage(leaf,new Fr(nextKey),nextIndex)}static clone(preimage){return preimage.clone()}},PublicDataTreeLeaf=class _PublicDataTreeLeaf{static{__name(this,"PublicDataTreeLeaf")}slot;value;constructor(slot,value){this.slot=slot,this.value=value}getKey(){return this.slot.toBigInt()}toBuffer(){return serializeToBuffer([this.slot,this.value])}clone(){return new _PublicDataTreeLeaf(this.slot,this.value)}toHashInputs(){return[this.slot.toBuffer(),this.value.toBuffer()]}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _PublicDataTreeLeaf(Fr.fromBuffer(reader),Fr.fromBuffer(reader))}equals(another){return this.slot.equals(another.slot)&&this.value.equals(another.value)}toString(){return`PublicDataTreeLeaf(${this.slot.toString()}, ${this.value.toString()})`}isEmpty(){return this.slot.isZero()&&this.value.isZero()}updateTo(another){if(!this.slot.equals(another.slot))throw new Error("Invalid update: slots do not match");return new _PublicDataTreeLeaf(this.slot,another.value)}static buildDummy(key){return new _PublicDataTreeLeaf(new Fr(key),new Fr(0))}static empty(){return new _PublicDataTreeLeaf(Fr.ZERO,Fr.ZERO)}static get schema(){return external_exports.object({slot:schemas.Fr,value:schemas.Fr}).transform(({slot,value})=>new _PublicDataTreeLeaf(slot,value))}static fromPlainObject(obj){return obj instanceof _PublicDataTreeLeaf?obj:new _PublicDataTreeLeaf(Fr.fromPlainObject(obj.slot),Fr.fromPlainObject(obj.value))}};var PublicDataWitness=class _PublicDataWitness{static{__name(this,"PublicDataWitness")}index;leafPreimage;siblingPath;constructor(index,leafPreimage,siblingPath){this.index=index,this.leafPreimage=leafPreimage,this.siblingPath=siblingPath}static get schema(){return external_exports.object({index:schemas2.BigInt,leafPreimage:PublicDataTreeLeafPreimage.schema,siblingPath:SiblingPath.schemaFor(40)}).transform(({index,leafPreimage,siblingPath})=>new _PublicDataWitness(index,leafPreimage,siblingPath))}toBuffer(){return serializeToBuffer([this.index,this.leafPreimage,this.siblingPath])}toString(){return bufferToHex(this.toBuffer())}static random(){return new _PublicDataWitness(BigInt(Math.floor(Math.random()*1e3)),PublicDataTreeLeafPreimage.random(),SiblingPath.random(40))}withoutPreimage(){return new MembershipWitness(40,this.index,this.siblingPath.toTuple())}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _PublicDataWitness(toBigIntBE(reader.readBytes(32)),reader.readObject(PublicDataTreeLeafPreimage),SiblingPath.fromBuffer(reader.readBytes(1284)))}static fromString(str){return _PublicDataWitness.fromBuffer(hexToBuffer(str))}};var ValidatorStatusInSlotSchema=zodFor()(external_exports.enum(["checkpoint-mined","checkpoint-valid","checkpoint-invalid","checkpoint-unvalidated","checkpoint-missed","blocks-missed","attestation-sent","attestation-missed"])),ValidatorStatusHistorySchema=zodFor()(external_exports.array(external_exports.object({slot:schemas.SlotNumber,status:ValidatorStatusInSlotSchema}))),ValidatorStatusHistorySchemaArray=external_exports.array(ValidatorStatusHistorySchema),ValidatorStatusHistorySchemaMap=external_exports.record(external_exports.string(),ValidatorStatusHistorySchemaArray),ValidatorTimeStatSchema=external_exports.object({timestamp:schemas.BigInt,slot:schemas.SlotNumber,date:external_exports.string()}),ValidatorMissedStatsSchema=zodFor()(external_exports.object({currentStreak:schemas.Integer,rate:external_exports.number().optional(),count:schemas.Integer,total:schemas.Integer})),ValidatorStatsSchema=zodFor()(external_exports.object({address:schemas.EthAddress,lastProposal:ValidatorTimeStatSchema.optional(),lastAttestation:ValidatorTimeStatSchema.optional(),totalSlots:schemas.Integer,missedProposals:ValidatorMissedStatsSchema,missedAttestations:ValidatorMissedStatsSchema,history:ValidatorStatusHistorySchema})),ValidatorsStatsSchema=zodFor()(external_exports.object({stats:external_exports.record(external_exports.string(),ValidatorStatsSchema),lastProcessedSlot:schemas.SlotNumber.optional(),initialSlot:schemas.SlotNumber.optional(),slotWindow:schemas.Integer})),SingleValidatorStatsSchema=zodFor()(external_exports.object({validator:ValidatorStatsSchema,allTimeEpochPerformance:external_exports.array(external_exports.object({missed:schemas.Integer,total:schemas.Integer,epoch:schemas.EpochNumber})),lastProcessedSlot:schemas.SlotNumber.optional(),initialSlot:schemas.SlotNumber.optional(),slotWindow:schemas.Integer}));var AllowedElementSchema=zodFor()(external_exports.union([external_exports.object({address:schemas2.AztecAddress,selector:schemas2.FunctionSelector,onlySelf:external_exports.boolean().optional(),rejectNullMsgSender:external_exports.boolean().optional(),calldataLength:external_exports.number().optional()}),external_exports.object({classId:schemas2.Fr,selector:schemas2.FunctionSelector,onlySelf:external_exports.boolean().optional(),rejectNullMsgSender:external_exports.boolean().optional(),calldataLength:external_exports.number().optional()})]));var L1PublishInfoSchema=external_exports.union([external_exports.object({published:external_exports.literal(!1)}),external_exports.object({published:external_exports.literal(!0),blockNumber:schemas.BigInt,timestamp:schemas.BigInt,blockHash:external_exports.string()})]);function l1PublishInfoFromL1PublishedData(data){return data?{published:!0,blockNumber:data.blockNumber,timestamp:data.timestamp,blockHash:data.blockHash}:{published:!1}}__name(l1PublishInfoFromL1PublishedData,"l1PublishInfoFromL1PublishedData");var BlockIncludeOptionsSchema=external_exports.object({includeTransactions:external_exports.boolean().optional(),includeL1PublishInfo:external_exports.boolean().optional(),includeAttestations:external_exports.boolean().optional()}),BlocksIncludeOptionsSchema=external_exports.object({includeTransactions:external_exports.boolean().optional(),includeL1PublishInfo:external_exports.boolean().optional(),includeAttestations:external_exports.boolean().optional(),onlyCheckpointed:external_exports.boolean().optional()}),BlockResponseSchema=external_exports.object({header:BlockHeader.schema,archive:AppendOnlyTreeSnapshot.schema,hash:BlockHash.schema,checkpointNumber:CheckpointNumberSchema,indexWithinCheckpoint:IndexWithinCheckpointSchema,number:BlockNumberSchema,body:Body.schema.optional(),l1:L1PublishInfoSchema.optional(),attestations:external_exports.array(CommitteeAttestation.schema).optional()});var CheckpointTagSchema=external_exports.union([external_exports.literal("checkpointed"),external_exports.literal("proven"),external_exports.literal("finalized")]);var CheckpointParameterSchema=external_exports.union([external_exports.object({number:CheckpointNumberSchema}).strict(),external_exports.object({slot:SlotNumberSchema}).strict(),CheckpointTagSchema,CheckpointNumberSchema]);var CheckpointIncludeOptionsSchema=external_exports.object({includeBlocks:external_exports.boolean().optional(),includeTransactions:external_exports.boolean().optional(),includeL1PublishInfo:external_exports.boolean().optional(),includeAttestations:external_exports.boolean().optional()}),CheckpointResponseSchema=external_exports.object({number:CheckpointNumberSchema,header:CheckpointHeader.schema,archive:AppendOnlyTreeSnapshot.schema,checkpointOutHash:schemas.Fr,startBlock:BlockNumberSchema,blockCount:external_exports.number(),feeAssetPriceModifier:schemas.BigInt,blocks:external_exports.array(BlockResponseSchema).optional(),l1:L1PublishInfoSchema.optional(),attestations:external_exports.array(CommitteeAttestation.schema).optional()});var GetTxByHashOptionsSchema=external_exports.object({includeProof:external_exports.boolean().optional()});var PeerInfoSchema=external_exports.discriminatedUnion("status",[external_exports.object({status:external_exports.literal("connected"),score:external_exports.number(),id:external_exports.string()}),external_exports.object({status:external_exports.literal("dialing"),dialStatus:external_exports.string(),id:external_exports.string(),addresses:external_exports.array(external_exports.string())}),external_exports.object({status:external_exports.literal("cached"),id:external_exports.string(),addresses:external_exports.array(external_exports.string()),enr:external_exports.string(),dialAttempts:external_exports.number()})]),MAX_PROPOSALS_FOR_SLOT_RPC_LEN=256,BlockProposalSchema=bufferSchemaFor(BlockProposal),CheckpointProposalSchema=bufferSchemaFor(CheckpointProposal),ProposalsForSlotSchema=external_exports.object({blockProposals:external_exports.array(BlockProposalSchema).max(MAX_PROPOSALS_FOR_SLOT_RPC_LEN),checkpointProposals:external_exports.array(CheckpointProposalSchema).max(MAX_PROPOSALS_FOR_SLOT_RPC_LEN)}),P2PApiSchema={getCheckpointAttestationsForSlot:external_exports.function({input:external_exports.tuple([schemas2.SlotNumber,optional2(external_exports.string().regex(/^0x[0-9a-fA-F]+$/))]),output:external_exports.array(CheckpointAttestation.schema)}),getPendingTxs:external_exports.function({input:external_exports.tuple([optional2(external_exports.number().gte(1).lte(50).default(50)),optional2(TxHash.schema),optional2(GetTxByHashOptionsSchema)]),output:external_exports.array(Tx.schema)}),getPendingTxCount:external_exports.function({input:external_exports.tuple([]),output:schemas2.Integer}),getEncodedEnr:external_exports.function({input:external_exports.tuple([]),output:external_exports.string().optional()}),getPeers:external_exports.function({input:external_exports.tuple([optional2(external_exports.boolean())]),output:external_exports.array(PeerInfoSchema)})};var WorldStateSyncStatusSchema=external_exports.object({finalizedBlockNumber:BlockNumberSchema,latestBlockNumber:BlockNumberSchema,latestBlockHash:external_exports.string(),oldestHistoricBlockNumber:BlockNumberSchema,treesAreSynched:external_exports.boolean()});var AztecNodeApiSchema={getWorldStateSyncStatus:external_exports.function({input:external_exports.tuple([]),output:WorldStateSyncStatusSchema}),findLeavesIndexes:external_exports.function({input:external_exports.tuple([BlockParameterSchema,external_exports.nativeEnum(MerkleTreeId),external_exports.array(schemas2.Fr).max(100)]),output:external_exports.array(optional2(dataInBlockSchemaFor(schemas2.BigInt)))}),getNullifierMembershipWitness:external_exports.function({input:external_exports.tuple([BlockParameterSchema,schemas2.Fr]),output:NullifierMembershipWitness.schema.optional()}),getLowNullifierMembershipWitness:external_exports.function({input:external_exports.tuple([BlockParameterSchema,schemas2.Fr]),output:NullifierMembershipWitness.schema.optional()}),getPublicDataWitness:external_exports.function({input:external_exports.tuple([BlockParameterSchema,schemas2.Fr]),output:PublicDataWitness.schema.optional()}),getBlockHashMembershipWitness:external_exports.function({input:external_exports.tuple([BlockParameterSchema,BlockHash.schema]),output:MembershipWitness.schemaFor(30).optional()}),getNoteHashMembershipWitness:external_exports.function({input:external_exports.tuple([BlockParameterSchema,schemas2.Fr]),output:MembershipWitness.schemaFor(42).optional()}),getL1ToL2MessageMembershipWitness:external_exports.function({input:external_exports.tuple([BlockParameterSchema,schemas2.Fr]),output:external_exports.tuple([schemas2.BigInt,SiblingPath.schemaFor(36)]).optional()}),getL1ToL2MessageCheckpoint:external_exports.function({input:external_exports.tuple([schemas2.Fr]),output:CheckpointNumberSchema.optional()}),getL2ToL1Messages:external_exports.function({input:external_exports.tuple([EpochNumberSchema]),output:external_exports.array(external_exports.array(external_exports.array(external_exports.array(schemas2.Fr))))}),getL2ToL1MembershipWitness:external_exports.function({input:external_exports.tuple([TxHash.schema,schemas2.Fr,optional2(schemas2.Integer)]),output:L2ToL1MembershipWitnessSchema.optional()}),getBlockNumber:external_exports.function({input:external_exports.tuple([optional2(BlockTagWithoutLatestSchema)]),output:BlockNumberSchema}),getCheckpointNumber:external_exports.function({input:external_exports.tuple([optional2(CheckpointTagSchema)]),output:CheckpointNumberSchema}),getChainTips:external_exports.function({input:external_exports.tuple([]),output:L2TipsSchema}),getL1Constants:external_exports.function({input:external_exports.tuple([]),output:L1RollupConstantsSchema}),getSyncedL2SlotNumber:external_exports.function({input:external_exports.tuple([]),output:SlotNumberSchema.optional()}),getSyncedL2EpochNumber:external_exports.function({input:external_exports.tuple([]),output:EpochNumberSchema.optional()}),getSyncedL1Timestamp:external_exports.function({input:external_exports.tuple([]),output:schemas2.BigInt.optional()}),getCheckpointsData:external_exports.function({input:external_exports.tuple([CheckpointsQuerySchema]),output:external_exports.array(CheckpointDataSchema)}),getBlock:external_exports.function({input:external_exports.tuple([BlockParameterSchema,optional2(BlockIncludeOptionsSchema)]),output:BlockResponseSchema.optional()}),getBlockData:external_exports.function({input:external_exports.tuple([BlockParameterSchema]),output:BlockDataSchema.optional()}),getBlocks:external_exports.function({input:external_exports.tuple([BlockNumberPositiveSchema,external_exports.number().gt(0).lte(50),optional2(BlocksIncludeOptionsSchema)]),output:external_exports.array(BlockResponseSchema)}),getCheckpoint:external_exports.function({input:external_exports.tuple([CheckpointParameterSchema,optional2(CheckpointIncludeOptionsSchema)]),output:CheckpointResponseSchema.optional()}),getCheckpoints:external_exports.function({input:external_exports.tuple([CheckpointNumberPositiveSchema,external_exports.number().gt(0).lte(50),optional2(CheckpointIncludeOptionsSchema)]),output:external_exports.array(CheckpointResponseSchema)}),isReady:external_exports.function({input:external_exports.tuple([]),output:external_exports.boolean()}),getNodeInfo:external_exports.function({input:external_exports.tuple([]),output:NodeInfoSchema}),getCurrentMinFees:external_exports.function({input:external_exports.tuple([]),output:GasFees.schema}),getPredictedMinFees:external_exports.function({input:external_exports.tuple([optional2(external_exports.nativeEnum(ManaUsageEstimate))]),output:external_exports.array(GasFees.schema)}),getMaxPriorityFees:external_exports.function({input:external_exports.tuple([]),output:GasFees.schema}),getNodeVersion:external_exports.function({input:external_exports.tuple([]),output:external_exports.string()}),getVersion:external_exports.function({input:external_exports.tuple([]),output:external_exports.number()}),getChainId:external_exports.function({input:external_exports.tuple([]),output:external_exports.number()}),getL1ContractAddresses:external_exports.function({input:external_exports.tuple([]),output:L1ContractAddressesSchema2}),getProtocolContractAddresses:external_exports.function({input:external_exports.tuple([]),output:ProtocolContractAddressesSchema}),getPrivateLogsByTags:external_exports.function({input:external_exports.tuple([PrivateLogsQuerySchema]),output:external_exports.array(external_exports.array(LogResultSchema))}),getPublicLogsByTags:external_exports.function({input:external_exports.tuple([PublicLogsQuerySchema]),output:external_exports.array(external_exports.array(LogResultSchema))}),sendTx:external_exports.function({input:external_exports.tuple([Tx.schema]),output:external_exports.void()}),getTxReceipt:external_exports.function({input:external_exports.tuple([TxHash.schema,optional2(GetTxReceiptOptionsSchema)]),output:TxReceiptSchema}),getTxEffect:external_exports.function({input:external_exports.tuple([TxHash.schema]),output:indexedTxSchema().optional()}),getPendingTxs:external_exports.function({input:external_exports.tuple([optional2(external_exports.number().gte(1).lte(50).default(50)),optional2(TxHash.schema),optional2(GetTxByHashOptionsSchema)]),output:external_exports.array(Tx.schema)}),getPendingTxCount:external_exports.function({input:external_exports.tuple([]),output:external_exports.number()}),getTxByHash:external_exports.function({input:external_exports.tuple([TxHash.schema,optional2(GetTxByHashOptionsSchema)]),output:Tx.schema.optional()}),getTxsByHash:external_exports.function({input:external_exports.tuple([external_exports.array(TxHash.schema).max(50),optional2(GetTxByHashOptionsSchema)]),output:external_exports.array(Tx.schema)}),getPublicStorageAt:external_exports.function({input:external_exports.tuple([BlockParameterSchema,schemas2.AztecAddress,schemas2.Fr]),output:schemas2.Fr}),getValidatorsStats:external_exports.function({input:external_exports.tuple([]),output:ValidatorsStatsSchema}),getValidatorStats:external_exports.function({input:external_exports.tuple([schemas2.EthAddress,optional2(schemas2.SlotNumber),optional2(schemas2.SlotNumber)]),output:SingleValidatorStatsSchema.optional()}),simulatePublicCalls:external_exports.function({input:external_exports.tuple([Tx.schema,optional2(external_exports.boolean()),optional2(SimulationOverrides.schema)]),output:PublicSimulationOutput.schema}),isValidTx:external_exports.function({input:external_exports.tuple([Tx.schema,optional2(external_exports.object({isSimulation:optional2(external_exports.boolean()).optional(),skipFeeEnforcement:optional2(external_exports.boolean()).optional()}))]),output:TxValidationResultSchema}),getContractClass:external_exports.function({input:external_exports.tuple([schemas2.Fr]),output:ContractClassPublicSchema.optional()}),getContract:external_exports.function({input:external_exports.tuple([schemas2.AztecAddress,optional2(BlockParameterSchema)]),output:ContractInstanceWithAddressSchema.optional()}),getEncodedEnr:external_exports.function({input:external_exports.tuple([]),output:external_exports.string().optional()}),getAllowedPublicSetup:external_exports.function({input:external_exports.tuple([]),output:external_exports.array(AllowedElementSchema)}),getPeers:external_exports.function({input:external_exports.tuple([optional2(external_exports.boolean())]),output:external_exports.array(PeerInfoSchema)}),getCheckpointAttestationsForSlot:external_exports.function({input:external_exports.tuple([schemas2.SlotNumber,optional2(external_exports.string().regex(/^0x[0-9a-fA-F]+$/))]),output:external_exports.array(CheckpointAttestation.schema)}),getProposalsForSlot:external_exports.function({input:external_exports.tuple([schemas2.SlotNumber]),output:ProposalsForSlotSchema})};var OffenseType=(function(OffenseType3){return OffenseType3[OffenseType3.UNKNOWN=0]="UNKNOWN",OffenseType3[OffenseType3.DATA_WITHHOLDING=1]="DATA_WITHHOLDING",OffenseType3[OffenseType3.INACTIVITY=3]="INACTIVITY",OffenseType3[OffenseType3.BROADCASTED_INVALID_BLOCK_PROPOSAL=4]="BROADCASTED_INVALID_BLOCK_PROPOSAL",OffenseType3[OffenseType3.PROPOSED_INSUFFICIENT_ATTESTATIONS=5]="PROPOSED_INSUFFICIENT_ATTESTATIONS",OffenseType3[OffenseType3.PROPOSED_INCORRECT_ATTESTATIONS=6]="PROPOSED_INCORRECT_ATTESTATIONS",OffenseType3[OffenseType3.PROPOSED_DESCENDANT_OF_CHECKPOINT_WITH_INVALID_ATTESTATIONS=7]="PROPOSED_DESCENDANT_OF_CHECKPOINT_WITH_INVALID_ATTESTATIONS",OffenseType3[OffenseType3.DUPLICATE_PROPOSAL=8]="DUPLICATE_PROPOSAL",OffenseType3[OffenseType3.DUPLICATE_ATTESTATION=9]="DUPLICATE_ATTESTATION",OffenseType3[OffenseType3.ATTESTED_TO_INVALID_CHECKPOINT_PROPOSAL=10]="ATTESTED_TO_INVALID_CHECKPOINT_PROPOSAL",OffenseType3[OffenseType3.BROADCASTED_INVALID_CHECKPOINT_PROPOSAL=11]="BROADCASTED_INVALID_CHECKPOINT_PROPOSAL",OffenseType3})({});var OffenseTypeSchema=external_exports.nativeEnum(OffenseType);var OffenseSchema=zodFor()(external_exports.object({validator:schemas2.EthAddress,amount:schemas2.BigInt,offenseType:OffenseTypeSchema,epochOrSlot:schemas2.BigInt}));var ArchiverSpecificConfigSchema=external_exports.object({archiverPollingIntervalMS:schemas2.Integer.optional(),archiverBatchSize:schemas2.Integer.optional(),viemPollingIntervalMS:schemas2.Integer.optional(),archiverStoreMapSizeKb:schemas2.Integer.optional(),maxAllowedEthClientDriftSeconds:schemas2.Integer.optional(),ethereumAllowNoDebugHosts:external_exports.boolean().optional(),archiverSkipHistoricalLogsCheck:external_exports.boolean().optional(),skipValidateCheckpointAttestations:external_exports.boolean().optional(),skipPromoteProposedCheckpointDuringL1Sync:external_exports.boolean().optional(),orphanPruneNoProposalTolerance:schemas2.Integer.optional(),skipOrphanProposedBlockPruning:external_exports.boolean().optional()}),ArchiverApiSchema={getRollupAddress:external_exports.function({input:external_exports.tuple([]),output:schemas2.EthAddress}),getRegistryAddress:external_exports.function({input:external_exports.tuple([]),output:schemas2.EthAddress}),getBlockNumber:external_exports.function({input:external_exports.tuple([optional2(BlockQuerySchema)]),output:BlockNumberSchema.optional()}),getCheckpointNumber:external_exports.function({input:external_exports.tuple([]),output:CheckpointNumberSchema}),getCheckpoint:external_exports.function({input:external_exports.tuple([CheckpointQuerySchema]),output:PublishedCheckpoint.schema.optional()}),getCheckpoints:external_exports.function({input:external_exports.tuple([CheckpointsQuerySchema]),output:external_exports.array(PublishedCheckpoint.schema)}),getCheckpointData:external_exports.function({input:external_exports.tuple([CheckpointQuerySchema]),output:CheckpointDataSchema.optional()}),getCheckpointsData:external_exports.function({input:external_exports.tuple([CheckpointsQuerySchema]),output:external_exports.array(CheckpointDataSchema)}),getTxEffect:external_exports.function({input:external_exports.tuple([TxHash.schema]),output:indexedTxSchema().optional()}),getL2ToL1MembershipWitness:external_exports.function({input:external_exports.tuple([TxHash.schema,schemas2.Fr,optional2(schemas2.Integer)]),output:L2ToL1MembershipWitnessSchema.optional()}),getSyncedL2SlotNumber:external_exports.function({input:external_exports.tuple([]),output:schemas2.SlotNumber.optional()}),getSyncedL2EpochNumber:external_exports.function({input:external_exports.tuple([]),output:EpochNumberSchema.optional()}),getBlocksForSlot:external_exports.function({input:external_exports.tuple([schemas2.SlotNumber]),output:external_exports.array(L2Block.schema)}),isEpochComplete:external_exports.function({input:external_exports.tuple([EpochNumberSchema]),output:external_exports.boolean()}),getL2Tips:external_exports.function({input:external_exports.tuple([]),output:L2TipsSchema}),getPrivateLogsByTags:external_exports.function({input:external_exports.tuple([PrivateLogsQuerySchema]),output:external_exports.array(external_exports.array(LogResultSchema))}),getPublicLogsByTags:external_exports.function({input:external_exports.tuple([PublicLogsQuerySchema]),output:external_exports.array(external_exports.array(LogResultSchema))}),getContractClass:external_exports.function({input:external_exports.tuple([schemas2.Fr]),output:ContractClassPublicSchema.optional()}),getBytecodeCommitment:external_exports.function({input:external_exports.tuple([schemas2.Fr]),output:schemas2.Fr}),getContract:external_exports.function({input:external_exports.tuple([schemas2.AztecAddress,schemas2.BigInt]),output:ContractInstanceWithAddressSchema.optional()}),getContractClassIds:external_exports.function({input:external_exports.tuple([]),output:external_exports.array(schemas2.Fr)}),registerContractFunctionSignatures:external_exports.function({input:external_exports.tuple([external_exports.array(external_exports.string())]),output:external_exports.void()}),getL1ToL2Messages:external_exports.function({input:external_exports.tuple([CheckpointNumberSchema]),output:external_exports.array(schemas2.Fr)}),getL1ToL2MessageIndex:external_exports.function({input:external_exports.tuple([schemas2.Fr]),output:schemas2.BigInt.optional()}),getDebugFunctionName:external_exports.function({input:external_exports.tuple([schemas2.AztecAddress,schemas2.FunctionSelector]),output:optional2(external_exports.string())}),getL1Constants:external_exports.function({input:external_exports.tuple([]),output:L1RollupConstantsSchema}),isPruneDueAtSlot:external_exports.function({input:external_exports.tuple([schemas2.SlotNumber]),output:external_exports.boolean()}),getGenesisValues:external_exports.function({input:external_exports.tuple([]),output:external_exports.object({genesisArchiveRoot:schemas2.Fr})}),getL1Timestamp:external_exports.function({input:external_exports.tuple([]),output:schemas2.BigInt.optional()}),getProposedCheckpointData:external_exports.function({input:external_exports.tuple([optional2(ProposedCheckpointQuerySchema)]),output:ProposedCheckpointDataSchema.optional()}),syncImmediate:external_exports.function({input:external_exports.tuple([]),output:external_exports.void()}),isPendingChainInvalid:external_exports.function({input:external_exports.tuple([]),output:external_exports.boolean()}),getPendingChainValidationStatus:external_exports.function({input:external_exports.tuple([]),output:ValidateCheckpointResultSchema}),getBlock:external_exports.function({input:external_exports.tuple([BlockQuerySchema]),output:L2Block.schema.optional()}),getBlocks:external_exports.function({input:external_exports.tuple([BlocksQuerySchema]),output:external_exports.array(L2Block.schema)}),getBlockData:external_exports.function({input:external_exports.tuple([BlockQuerySchema]),output:BlockDataSchema.optional()}),getBlocksData:external_exports.function({input:external_exports.tuple([BlocksQuerySchema]),output:external_exports.array(BlockDataSchema)})};var SequencerConfigSchema=zodFor()(external_exports.object({sequencerPollingIntervalMS:external_exports.number().optional(),maxTxsPerBlock:external_exports.number().optional(),maxTxsPerCheckpoint:external_exports.number().optional(),maxBlocksPerCheckpoint:external_exports.number().positive().optional(),minValidTxsPerBlock:external_exports.number().optional(),minTxsPerBlock:external_exports.number().optional(),maxL2BlockGas:external_exports.number().optional(),publishTxsWithProposals:external_exports.boolean().optional(),maxDABlockGas:external_exports.number().optional(),perBlockAllocationMultiplier:external_exports.number().optional(),perBlockDAAllocationMultiplier:external_exports.number().optional(),redistributeCheckpointBudget:external_exports.boolean().optional(),coinbase:schemas2.EthAddress.optional(),feeRecipient:schemas2.AztecAddress.optional(),acvmWorkingDirectory:external_exports.string().optional(),acvmBinaryPath:external_exports.string().optional(),txPublicSetupAllowListExtend:external_exports.array(AllowedElementSchema).optional(),governanceProposerPayload:schemas2.EthAddress.optional(),minBlockDuration:external_exports.number().positive().optional(),checkpointProposalPrepareTime:external_exports.number().nonnegative().optional(),l1PublishingTime:external_exports.number().optional(),fakeProcessingDelayPerTxMs:external_exports.number().optional(),fakeThrowAfterProcessingTxCount:external_exports.number().optional(),attestationPropagationTime:external_exports.number().optional(),skipCollectingAttestations:external_exports.boolean().optional(),skipInvalidateBlockAsProposer:external_exports.boolean().optional(),skipWaitForValidParentCheckpointOnL1:external_exports.boolean().optional(),secondsBeforeInvalidatingBlockAsCommitteeMember:external_exports.number(),secondsBeforeInvalidatingBlockAsNonCommitteeMember:external_exports.number(),broadcastInvalidBlockProposal:external_exports.boolean().optional(),invalidBlockProposalIndexWithinCheckpoint:external_exports.number().int().nonnegative().optional(),broadcastInvalidCheckpointProposalOnly:external_exports.boolean().optional(),injectFakeAttestation:external_exports.boolean().optional(),injectHighSValueAttestation:external_exports.boolean().optional(),injectUnrecoverableSignatureAttestation:external_exports.boolean().optional(),fishermanMode:external_exports.boolean().optional(),shuffleAttestationOrdering:external_exports.boolean().optional(),blockDurationMs:external_exports.number().positive().optional(),checkpointProposalSyncGraceSeconds:external_exports.number().nonnegative().optional(),expectedBlockProposalsPerSlot:external_exports.number().nonnegative().optional(),buildCheckpointIfEmpty:external_exports.boolean().optional(),skipPushProposedBlocksToArchiver:external_exports.boolean().optional(),minBlocksForCheckpoint:external_exports.number().positive().optional(),skipPublishingCheckpointsPercent:external_exports.number().gte(0).lte(100).optional(),skipBroadcastProposals:external_exports.boolean().optional(),skipBroadcastCheckpointProposal:external_exports.boolean().optional(),pauseProposingForSlots:external_exports.array(SlotNumberSchema).optional()}));var ProverConfigSchema=zodFor()(external_exports.object({nodeUrl:external_exports.string().optional(),realProofs:external_exports.boolean(),proverId:schemas2.EthAddress.optional(),proverTestDelayType:external_exports.enum(["fixed","realistic"]),proverTestDelayMs:external_exports.number(),proverTestDelayFactor:external_exports.number(),proverAgentCount:external_exports.number(),proofStore:external_exports.string().optional(),failedProofStore:external_exports.string().optional(),cancelJobsOnStop:external_exports.boolean(),enqueueConcurrency:external_exports.number()})),proverConfigMappings={nodeUrl:{env:"AZTEC_NODE_URL",description:"The URL to the Aztec node to take proving jobs from"},realProofs:{env:"PROVER_REAL_PROOFS",description:"Whether to construct real proofs",...booleanConfigHelper(!0)},proverId:{env:"PROVER_ID",parseEnv:__name(val=>parseProverId(val),"parseEnv"),description:"Hex value that identifies the prover. Defaults to the address used for submitting proofs if not set."},proverTestDelayType:{env:"PROVER_TEST_DELAY_TYPE",description:"The type of artificial delay to introduce"},proverTestDelayMs:{env:"PROVER_TEST_DELAY_MS",description:"Artificial delay to introduce to all operations to the test prover.",...numberConfigHelper(0)},proverTestDelayFactor:{env:"PROVER_TEST_DELAY_FACTOR",description:"If using realistic delays, what percentage of realistic times to apply.",...numberConfigHelper(1)},proverAgentCount:{env:"PROVER_AGENT_COUNT",description:"The number of prover agents to start",...numberConfigHelper(1)},proofStore:{env:"PROVER_PROOF_STORE",description:"Optional proof input store for the prover"},failedProofStore:{env:"PROVER_FAILED_PROOF_STORE",description:"Store for failed proof inputs. Google cloud storage is only supported at the moment. Set this value as gs://bucket-name/path/to/store."},cancelJobsOnStop:{env:"PROVER_CANCEL_JOBS_ON_STOP",description:"Whether to abort pending proving jobs when the orchestrator is cancelled. When false (default), jobs remain in the broker queue and can be reused on restart/reorg. When true, jobs are explicitly cancelled with the broker, which prevents reuse.",...booleanConfigHelper(!1)},enqueueConcurrency:{env:"PROVER_ENQUEUE_CONCURRENCY",description:"Max concurrent jobs the orchestrator serializes and enqueues to the broker.",...numberConfigHelper(50)}};function parseProverId(str){return EthAddress.fromString(str)}__name(parseProverId,"parseProverId");var SlasherConfigSchema=zodFor()(external_exports.object({slashOverridePayload:schemas.EthAddress.optional(),slashValidatorsAlways:external_exports.array(schemas.EthAddress),slashValidatorsNever:external_exports.array(schemas.EthAddress),slashDataWithholdingPenalty:schemas.BigInt,slashDataWithholdingToleranceSlots:external_exports.number().default(3),slashInactivityTargetPercentage:external_exports.number(),slashInactivityConsecutiveEpochThreshold:external_exports.number(),slashInactivityPenalty:schemas.BigInt,slashProposeInvalidAttestationsPenalty:schemas.BigInt,slashBroadcastedInvalidCheckpointProposalPenalty:schemas.BigInt.default(0n),slashDuplicateProposalPenalty:schemas.BigInt,slashDuplicateAttestationPenalty:schemas.BigInt,slashProposeDescendantOfCheckpointWithInvalidAttestationsPenalty:schemas.BigInt,slashAttestInvalidCheckpointProposalPenalty:schemas.BigInt,slashUnknownPenalty:schemas.BigInt,slashOffenseExpirationRounds:external_exports.number(),slashMaxPayloadSize:external_exports.number(),slashGracePeriodL2Slots:external_exports.number(),slashBroadcastedInvalidBlockPenalty:schemas.BigInt,slashExecuteRoundsLookBack:external_exports.number(),slashSelfAllowed:external_exports.boolean().optional()}));var ValidatorClientConfigSchema=zodFor()(ValidatorHASignerConfigSchema.merge(LocalSignerConfigSchema).extend({l1ChainId:external_exports.number().int().nonnegative(),validatorAddresses:external_exports.array(schemas.EthAddress).optional(),disableValidator:external_exports.boolean(),disabledValidators:external_exports.array(schemas.EthAddress),attestationPollingIntervalMs:external_exports.number().min(0),alwaysReexecuteBlockProposals:external_exports.boolean().optional(),fishermanMode:external_exports.boolean().optional(),skipCheckpointProposalValidation:external_exports.boolean().optional(),skipPushProposedBlocksToArchiver:external_exports.boolean().optional(),attestToEquivocatedProposals:external_exports.boolean().optional(),skipProposalSlotValidation:external_exports.boolean().optional(),validateMaxL2BlockGas:external_exports.number().optional(),validateMaxDABlockGas:external_exports.number().optional(),validateMaxTxsPerBlock:external_exports.number().optional(),validateMaxTxsPerCheckpoint:external_exports.number().optional()})),ValidatorClientFullConfigSchema=zodFor()(ValidatorClientConfigSchema.extend({txPublicSetupAllowListExtend:external_exports.array(AllowedElementSchema).optional(),broadcastInvalidBlockProposal:external_exports.boolean().optional(),blockDurationMs:external_exports.number().positive(),maxBlocksPerCheckpoint:external_exports.number().positive().optional(),slashBroadcastedInvalidBlockPenalty:schemas.BigInt,slashBroadcastedInvalidCheckpointProposalPenalty:schemas.BigInt,slashDuplicateProposalPenalty:schemas.BigInt,slashDuplicateAttestationPenalty:schemas.BigInt,slashAttestInvalidCheckpointProposalPenalty:schemas.BigInt,disableTransactions:external_exports.boolean().optional(),maxGossipClockDisparityMs:external_exports.number().optional()}));var AztecNodeAdminConfigSchema=SequencerConfigSchema.merge(ProverConfigSchema).merge(SlasherConfigSchema).merge(ValidatorClientFullConfigSchema.omit({rollupAddress:!0})).merge(ArchiverSpecificConfigSchema.pick({archiverPollingIntervalMS:!0,archiverBatchSize:!0,skipValidateCheckpointAttestations:!0})).merge(external_exports.object({maxPendingTxCount:external_exports.number(),skipIncomingProposals:external_exports.boolean().optional()})),AztecNodeAdminApiSchema={getConfig:external_exports.function({input:external_exports.tuple([]),output:AztecNodeAdminConfigSchema}),setConfig:external_exports.function({input:external_exports.tuple([AztecNodeAdminConfigSchema.partial()]),output:external_exports.void()}),startSnapshotUpload:external_exports.function({input:external_exports.tuple([external_exports.string()]),output:external_exports.void()}),rollbackTo:external_exports.function({input:external_exports.tuple([external_exports.number(),optional2(external_exports.boolean()),optional2(external_exports.boolean())]),output:external_exports.void()}),pauseSync:external_exports.function({input:external_exports.tuple([]),output:external_exports.void()}),resumeSync:external_exports.function({input:external_exports.tuple([]),output:external_exports.void()}),pauseSequencer:external_exports.function({input:external_exports.tuple([]),output:external_exports.void()}),resumeSequencer:external_exports.function({input:external_exports.tuple([]),output:external_exports.void()}),getSlashOffenses:external_exports.function({input:external_exports.tuple([external_exports.union([external_exports.bigint(),external_exports.literal("all"),external_exports.literal("current")])]),output:external_exports.array(OffenseSchema)}),reloadKeystore:external_exports.function({input:external_exports.tuple([]),output:external_exports.void()})};var MAX_SIGNATURES_PER_REGISTER_CALL=100,MAX_SIGNATURE_LEN=1e4,AztecNodeDebugApiSchema={mineBlock:external_exports.function({input:external_exports.tuple([]),output:external_exports.void()}),prove:external_exports.function({input:external_exports.tuple([optional2(CheckpointNumberSchema)]),output:CheckpointNumberSchema}),warpL2TimeAtLeastTo:external_exports.function({input:external_exports.tuple([external_exports.number()]),output:external_exports.void()}),warpL2TimeAtLeastBy:external_exports.function({input:external_exports.tuple([external_exports.number()]),output:external_exports.void()}),registerContractFunctionSignatures:external_exports.function({input:external_exports.tuple([external_exports.array(external_exports.string().max(MAX_SIGNATURE_LEN)).max(MAX_SIGNATURES_PER_REGISTER_CALL)]),output:external_exports.void()})};var Comparator=(function(Comparator2){return Comparator2[Comparator2.EQ=1]="EQ",Comparator2[Comparator2.NEQ=2]="NEQ",Comparator2[Comparator2.LT=3]="LT",Comparator2[Comparator2.LTE=4]="LTE",Comparator2[Comparator2.GT=5]="GT",Comparator2[Comparator2.GTE=6]="GTE",Comparator2})({});var NoteDao=class _NoteDao{static{__name(this,"NoteDao")}note;contractAddress;owner;storageSlot;randomness;noteNonce;noteHash;siloedNullifier;txHash;l2BlockNumber;l2BlockHash;txIndexInBlock;noteIndexInTx;constructor(note,contractAddress,owner,storageSlot,randomness,noteNonce,noteHash,siloedNullifier,txHash,l2BlockNumber,l2BlockHash,txIndexInBlock,noteIndexInTx){this.note=note,this.contractAddress=contractAddress,this.owner=owner,this.storageSlot=storageSlot,this.randomness=randomness,this.noteNonce=noteNonce,this.noteHash=noteHash,this.siloedNullifier=siloedNullifier,this.txHash=txHash,this.l2BlockNumber=l2BlockNumber,this.l2BlockHash=l2BlockHash,this.txIndexInBlock=txIndexInBlock,this.noteIndexInTx=noteIndexInTx}toBuffer(){return serializeToBuffer([this.note,this.contractAddress,this.owner,this.storageSlot,this.randomness,this.noteNonce,this.noteHash,this.siloedNullifier,this.txHash,this.l2BlockNumber,Fr.fromHexString(this.l2BlockHash),this.txIndexInBlock,this.noteIndexInTx])}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer),note=Note.fromBuffer(reader),contractAddress=AztecAddress.fromBuffer(reader),owner=AztecAddress.fromBuffer(reader),storageSlot=Fr.fromBuffer(reader),randomness=Fr.fromBuffer(reader),noteNonce=Fr.fromBuffer(reader),noteHash=Fr.fromBuffer(reader),siloedNullifier=Fr.fromBuffer(reader),txHash=reader.readObject(TxHash),l2BlockNumber=BlockNumber(reader.readNumber()),l2BlockHash=Fr.fromBuffer(reader).toString(),txIndexInBlock=reader.readNumber(),noteIndexInTx=reader.readNumber();return new _NoteDao(note,contractAddress,owner,storageSlot,randomness,noteNonce,noteHash,siloedNullifier,txHash,l2BlockNumber,l2BlockHash,txIndexInBlock,noteIndexInTx)}toString(){return"0x"+this.toBuffer().toString("hex")}static fromString(str){let hex3=str.replace(/^0x/,"");return _NoteDao.fromBuffer(Buffer.from(hex3,"hex"))}equals(other){return this.note.equals(other.note)&&this.contractAddress.equals(other.contractAddress)&&this.owner.equals(other.owner)&&this.storageSlot.equals(other.storageSlot)&&this.randomness.equals(other.randomness)&&this.noteNonce.equals(other.noteNonce)&&this.noteHash.equals(other.noteHash)&&this.siloedNullifier.equals(other.siloedNullifier)&&this.txHash.equals(other.txHash)&&this.l2BlockNumber===other.l2BlockNumber&&this.l2BlockHash===other.l2BlockHash&&this.txIndexInBlock===other.txIndexInBlock&&this.noteIndexInTx===other.noteIndexInTx}getSize(){return this.toBuffer().length}static async random({note=Note.random(),contractAddress=void 0,owner=void 0,storageSlot=Fr.random(),randomness=Fr.random(),noteNonce=Fr.random(),noteHash=Fr.random(),siloedNullifier=Fr.random(),txHash=TxHash.random(),l2BlockNumber=BlockNumber(Math.floor(Math.random()*1e3)),l2BlockHash=Fr.random().toString(),txIndexInBlock=Math.floor(Math.random()*100),noteIndexInTx=Math.floor(Math.random()*100)}={}){return new _NoteDao(note,contractAddress??await AztecAddress.random(),owner??await AztecAddress.random(),storageSlot,randomness,noteNonce,noteHash,siloedNullifier,txHash,l2BlockNumber,l2BlockHash,txIndexInBlock,noteIndexInTx)}};var NoteStatus=(function(NoteStatus2){return NoteStatus2[NoteStatus2.ACTIVE=1]="ACTIVE",NoteStatus2[NoteStatus2.ACTIVE_OR_NULLIFIED=2]="ACTIVE_OR_NULLIFIED",NoteStatus2})({});var NoteService=class{static{__name(this,"NoteService")}noteStore;aztecNode;anchorBlockHeader;jobId;constructor(noteStore,aztecNode,anchorBlockHeader,jobId){this.noteStore=noteStore,this.aztecNode=aztecNode,this.anchorBlockHeader=anchorBlockHeader,this.jobId=jobId}async getNotes(contractAddress,owner,storageSlot,status,scopes){return(await this.noteStore.getNotes({contractAddress,owner,storageSlot,status,scopes},this.jobId)).map(({contractAddress:contractAddress2,owner:owner2,storageSlot:storageSlot2,randomness,noteNonce,note,noteHash,siloedNullifier})=>({contractAddress:contractAddress2,owner:owner2,storageSlot:storageSlot2,randomness,noteNonce,note,noteHash,isPending:!1,siloedNullifier}))}async syncNoteNullifiers(contractAddress,scopes){let anchorBlockHash=await this.anchorBlockHeader.hash(),contractNotes=await this.noteStore.getNotes({contractAddress,scopes},this.jobId);if(contractNotes.length===0)return;let nullifiersToCheck=contractNotes.map(note=>note.siloedNullifier),nullifierIndexes=await this.#findNullifierIndexes(anchorBlockHash,nullifiersToCheck),foundNullifiers=nullifiersToCheck.map((nullifier,i)=>{if(nullifierIndexes[i]!==void 0)return{...nullifierIndexes[i],data:nullifier}}).filter(nullifier=>nullifier!==void 0);await this.noteStore.applyNullifiers(foundNullifiers,this.jobId)}async validateAndStoreNotes(requests,scope,txEffects){if(requests.length===0)return;let anchorBlockNumber=this.anchorBlockHeader.getBlockNumber(),anchorBlockHash=await this.anchorBlockHeader.hash(),computed=await Promise.all(requests.map(async({contractAddress,noteHash,nullifier,noteNonce})=>{let[siloedNoteHash,siloedNullifier]=await Promise.all([siloNoteHash(contractAddress,noteHash),siloNullifier(contractAddress,nullifier)]);return{uniqueNoteHash:await computeUniqueNoteHash(noteNonce,siloedNoteHash),siloedNullifier}})),nullifierIndexes=await this.#findNullifierIndexes(anchorBlockHash,computed.map(c2=>c2.siloedNullifier)),noteDaos=[],foundNullifiers=[];for(let i=0;i<requests.length;i++){let{contractAddress,owner,storageSlot,randomness,noteNonce,content,noteHash,txHash}=requests[i],{uniqueNoteHash,siloedNullifier}=computed[i],nullifierIndex=nullifierIndexes[i],txEffect=txEffects.get(txHash.toString());if(!txEffect)throw new Error(`Could not find tx effect for tx hash ${txHash} when processing a note.`);if(txEffect.l2BlockNumber>anchorBlockNumber)throw new Error(`Obtained a newer tx effect for ${txHash} for a note validation request than the anchor block ${anchorBlockNumber}. This is a bug as we should not ever be processing a note from a newer block than the anchor block.`);let noteIndexInTx=txEffect.data.noteHashes.findIndex(nh=>nh.equals(uniqueNoteHash));if(noteIndexInTx===-1)throw new Error(`Note hash ${noteHash} (uniqued as ${uniqueNoteHash}) is not present in tx ${txHash}`);if(noteDaos.push(new NoteDao(new Note(content),contractAddress,owner,storageSlot,randomness,noteNonce,noteHash,siloedNullifier,txHash,txEffect.l2BlockNumber,txEffect.l2BlockHash.toString(),txEffect.txIndexInBlock,noteIndexInTx)),nullifierIndex!==void 0){let{data:_,...blockHashAndNum}=nullifierIndex;foundNullifiers.push({data:siloedNullifier,...blockHashAndNum})}}await this.noteStore.addNotes(noteDaos,scope,this.jobId),foundNullifiers.length>0&&await this.noteStore.applyNullifiers(foundNullifiers,this.jobId)}async#findNullifierIndexes(anchorBlockHash,siloedNullifiers){let batches=chunk(siloedNullifiers,100);return(await Promise.all(batches.map(batch=>this.aztecNode.findLeavesIndexes(anchorBlockHash,MerkleTreeId.NULLIFIER_TREE,batch)))).flat()}};async function syncScope(contractAddress,contractStore,contractClassService,anchorBlockHeader,functionToInvokeAfterSync,utilityExecutor,scope){if(isProtocolContract(contractAddress))return;let classId=await contractClassService.getCurrentClassId(contractAddress,anchorBlockHeader);if(!classId)throw new Error(`Cannot sync contract ${contractAddress}: its instance is not registered nor published.`);let syncStateFunctionCall=await contractStore.getFunctionCall("sync_state",[scope],contractAddress,classId);if(functionToInvokeAfterSync&&functionToInvokeAfterSync.equals(syncStateFunctionCall.selector))throw new Error("Forbidden `sync_state` invocation. `sync_state` can only be invoked by PXE, manual execution can lead to inconsistencies.");await utilityExecutor(syncStateFunctionCall,[scope])}__name(syncScope,"syncScope");var MAX_CONCURRENT_SCOPE_SYNCS=5,ContractSyncService=class{static{__name(this,"ContractSyncService")}aztecNode;contractStore;contractClassService;noteStore;log;storeName;syncedContracts;constructor(aztecNode,contractStore,contractClassService,noteStore,log2){this.aztecNode=aztecNode,this.contractStore=contractStore,this.contractClassService=contractClassService,this.noteStore=noteStore,this.log=log2,this.storeName="contract_sync",this.syncedContracts=new Map}async ensureContractSynced(contractAddress,functionToInvokeAfterSync,utilityExecutor,anchorBlockHeader,jobId,scopes){this.#startSyncIfNeeded(contractAddress,scopes,anchorBlockHeader,jobId,scope=>syncScope(contractAddress,this.contractStore,this.contractClassService,anchorBlockHeader,functionToInvokeAfterSync,utilityExecutor,scope)),await this.#awaitSync(contractAddress,scopes)}invalidateContractForScopes(contractAddress,scopes){scopes.length!==0&&scopes.forEach(scope=>this.syncedContracts.delete(toKey(contractAddress,scope)))}wipe(){this.log.debug(`Wiping contract sync cache (${this.syncedContracts.size} entries)`),this.syncedContracts.clear()}commit(_jobId){return Promise.resolve()}discardStaged(_jobId){return this.syncedContracts.clear(),Promise.resolve()}#startSyncIfNeeded(contractAddress,scopes,anchorBlockHeader,jobId,syncScopeFn){let scopesToSync=scopes.filter(scope=>!this.syncedContracts.has(toKey(contractAddress,scope)));if(scopesToSync.length===0)return;this.log.debug(`Syncing contract ${contractAddress} for ${scopesToSync.length} scope(s)`);let syncNullifiersPromise=this.#syncNoteNullifiers(contractAddress,anchorBlockHeader,jobId,scopesToSync),syncSlot=new Semaphore(MAX_CONCURRENT_SCOPE_SYNCS);for(let scope of scopesToSync){let key=toKey(contractAddress,scope),promise2=Promise.all([syncNullifiersPromise,runBounded(syncSlot,()=>syncScopeFn(scope))]).then(()=>{}).catch(err=>{throw this.syncedContracts.delete(key),err});this.syncedContracts.set(key,promise2)}}async#syncNoteNullifiers(contractAddress,anchorBlockHeader,jobId,scopes){if(isProtocolContract(contractAddress))return;await new NoteService(this.noteStore,this.aztecNode,anchorBlockHeader,jobId).syncNoteNullifiers(contractAddress,scopes)}async#awaitSync(contractAddress,scopes){let promises=scopes.map(scope=>this.syncedContracts.get(toKey(contractAddress,scope))).filter(p=>p!==void 0);await Promise.all(promises)}};function toKey(contract,scope){return`${contract.toString()}:${scope.toString()}`}__name(toKey,"toKey");async function runBounded(syncSlot,fn){await syncSlot.acquire();try{return await fn()}finally{syncSlot.release()}}__name(runBounded,"runBounded");import{getVKTreeRoot}from"@aztec/noir-protocol-circuits-types/vk-tree";import{executeCircuitWithReturnWitness}from"@aztec/noir-acvm_js";import{abiDecodeError}from"@aztec/noir-noirc_abi";var ExecutionError=class extends Error{static{__name(this,"ExecutionError")}failingFunction;noirCallStack;constructor(message,failingFunction,noirCallStack,options){super(message,options),this.failingFunction=failingFunction,this.noirCallStack=noirCallStack}};function traverseCauseChain(error2,callback){let currentError=error2;for(;currentError;)callback(currentError),currentError.cause&¤tError.cause instanceof Error?currentError=currentError.cause:currentError=void 0}__name(traverseCauseChain,"traverseCauseChain");function createSimulationError(error2,revertData){let rootCause=error2,noirCallStack,aztecCallStack=[];return traverseCauseChain(error2,cause=>{rootCause=cause,cause instanceof ExecutionError&&(aztecCallStack.push(cause.failingFunction),cause.noirCallStack&&(noirCallStack=cause.noirCallStack))}),new SimulationError(rootCause.message,aztecCallStack,revertData,noirCallStack,{cause:rootCause})}__name(createSimulationError,"createSimulationError");function resolveOpcodeLocations(opcodeLocations,debug,files,brilligFunctionId){let locations=opcodeLocations.flatMap(opcodeLocation=>getSourceCodeLocationsFromOpcodeLocation(opcodeLocation,debug,files,brilligFunctionId));if(locations.length>0){let decomposedOpcodeLocation=opcodeLocations[opcodeLocations.length-1].split(".");if(decomposedOpcodeLocation.length===2){let acirCallstackId=debug.acir_locations[decomposedOpcodeLocation[0]];if(acirCallstackId!==void 0){let callStack=debug.location_tree.locations[acirCallstackId];locations=getCallStackFromLocationNode(callStack,debug.location_tree.locations,files).concat(locations)}}}return locations}__name(resolveOpcodeLocations,"resolveOpcodeLocations");function getCallStackFromLocationNode(callStack,locationTree,files){let result=[];for(;callStack.parent!==null;){let{file:fileId,span}=callStack.value,{path,source}=files[fileId],locationText=source.substring(span.start,span.end),previousLines=source.substring(0,span.start).split(`
|
|
197
|
+
`}equals(other){return this.address.equals(other.address)&&this.publicKeys.equals(other.publicKeys)&&this.partialAddress.equals(other.partialAddress)}toBuffer(){return serializeToBuffer([this.address,this.publicKeys,this.partialAddress])}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer),address=reader.readObject(AztecAddress),publicKeys=reader.readObject(PublicKeys),partialAddress=reader.readObject(Fr);return _CompleteAddress.create(address,publicKeys,partialAddress)}static fromString(address){return _CompleteAddress.fromBuffer(Buffer.from(address.replace(/^0x/i,""),"hex"))}toString(){return bufferToHex(this.toBuffer())}};var ContractClassService=class{static{__name(this,"ContractClassService")}node;contractStore;#cache;constructor(node,contractStore){this.node=node,this.contractStore=contractStore,this.#cache=new Map}async getCurrentClassId(address,anchorBlockHeader){if(isProtocolContract(address))return(await this.contractStore.getContractInstance(address))?.originalContractClassId;let key=`${address.toString()}:${(await anchorBlockHeader.hash()).toString()}`,promise2=this.#cache.get(key);promise2||(promise2=(async()=>{let nodeInstance=await this.node.getContract(address,await anchorBlockHeader.hash());return nodeInstance?nodeInstance.currentContractClassId:(await this.contractStore.getContractInstance(address))?.originalContractClassId})().catch(err=>{throw this.#cache.delete(key),err}),this.#cache.set(key,promise2));let classId=await promise2;return classId===void 0&&this.#cache.delete(key),classId}wipe(){this.#cache.clear()}};import{L1ContractAddressesSchema as L1ContractAddressesSchema2}from"@aztec/ethereum/l1-contract-addresses";function resolveRetryUntilTimeoutSeconds(timeout){if(typeof timeout=="number")return timeout;if("deadline"in timeout){let now=timeout.dateProvider?.now()??Date.now(),remainingSeconds=(timeout.deadline.getTime()-now)/1e3;return remainingSeconds>0?remainingSeconds:-1}return timeout.timeout}__name(resolveRetryUntilTimeoutSeconds,"resolveRetryUntilTimeoutSeconds");async function retryUntil(fn,name="",timeout=0,interval=1){let timeoutSeconds=resolveRetryUntilTimeoutSeconds(timeout),timer=new Timer;for(;;){let result=await fn();if(result)return result;if(await sleep(interval*1e3),timeoutSeconds&&timer.s()>timeoutSeconds)throw new TimeoutError(name?`Timeout awaiting ${name}`:"Timeout")}}__name(retryUntil,"retryUntil");var log=createLogger("json-rpc:json_rpc_client");var DEFAULT_MAX_REQUESTY_BODY_SIZE=10*1024*1024;function computeTxOutHash(messages){return messages.length?Fr.fromBuffer(computeUnbalancedShaRoot(messages.map(msg=>msg.toBuffer()))):Fr.ZERO}__name(computeTxOutHash,"computeTxOutHash");function computeBlockOutHash(messagesPerTx){let txOutHashes=messagesPerTx.map(messages=>computeTxOutHash(messages));return Fr.fromBuffer(computeWonkyShaRoot(txOutHashes.map(hash5=>hash5.toBuffer())))}__name(computeBlockOutHash,"computeBlockOutHash");function computeCheckpointOutHash(messagesPerBlock){let blockOutHashes=messagesPerBlock.map(block=>computeBlockOutHash(block));return Fr.fromBuffer(computeWonkyShaRoot(blockOutHashes.map(hash5=>hash5.toBuffer())))}__name(computeCheckpointOutHash,"computeCheckpointOutHash");var Checkpoint=class _Checkpoint{static{__name(this,"Checkpoint")}archive;header;blocks;number;feeAssetPriceModifier;constructor(archive,header,blocks,number4,feeAssetPriceModifier=0n){this.archive=archive,this.header=header,this.blocks=blocks,this.number=number4,this.feeAssetPriceModifier=feeAssetPriceModifier}get slot(){return this.header.slotNumber}static get schema(){return external_exports.object({archive:AppendOnlyTreeSnapshot.schema,header:CheckpointHeader.schema,blocks:external_exports.array(L2Block.schema),number:CheckpointNumberSchema,feeAssetPriceModifier:schemas2.BigInt}).transform(({archive,header,blocks,number:number4,feeAssetPriceModifier})=>new _Checkpoint(archive,header,blocks,number4,feeAssetPriceModifier))}static from(fields){return new _Checkpoint(..._Checkpoint.getFields(fields))}static getFields(fields){return[fields.archive,fields.header,fields.blocks,fields.number,fields.feeAssetPriceModifier]}static fromBuffer(buf){let reader=BufferReader.asReader(buf),archive=reader.readObject(AppendOnlyTreeSnapshot),header=reader.readObject(CheckpointHeader),blocks=reader.readVector(L2Block,MAX_CAPACITY_BLOCKS_PER_CHECKPOINT),number4=CheckpointNumber(reader.readNumber()),feeAssetPriceModifier=reader.readInt256();return new _Checkpoint(archive,header,blocks,number4,feeAssetPriceModifier)}toBuffer(){return serializeToBuffer(this.archive,this.header,this.blocks.length,this.blocks,this.number,serializeSignedBigInt(this.feeAssetPriceModifier))}toBlobFields(){let blocks=this.blocks.map(block=>block.toBlockBlobData());return encodeCheckpointBlobDataFromBlocks(blocks)}hash(){return this.header.hash()}getCheckpointOutHash(){return _Checkpoint.getCheckpointOutHash(this.blocks)}static getCheckpointOutHash(blocks){let msgs=blocks.map(block=>block.body.txEffects.map(txEffect=>txEffect.l2ToL1Msgs));return computeCheckpointOutHash(msgs)}getState(){return this.blocks.at(-1).header.state}toCheckpointInfo(){return{archive:this.archive.root,lastArchive:this.header.lastArchiveRoot,slotNumber:this.header.slotNumber,checkpointNumber:this.number,timestamp:this.header.timestamp}}getStats(){let txEffects=this.blocks.flatMap(block=>block.body.txEffects),logsStats={privateLogCount:sum(txEffects.map(tx=>tx.privateLogs.length)),publicLogCount:sum(txEffects.map(tx=>tx.publicLogs.length)),contractClassLogCount:sum(txEffects.map(tx=>tx.contractClassLogs.length)),contractClassLogSize:sum(txEffects.map(tx=>sum(tx.contractClassLogs.map(log2=>log2.emittedLength))))};return{txCount:txEffects.length,blockCount:this.blocks.length,slotNumber:this.header.slotNumber,checkpointNumber:this.number,timestamp:this.header.timestamp,...logsStats}}static async random(checkpointNumber=CheckpointNumber(1),{numBlocks=1,startBlockNumber=1,previousArchive,feeAssetPriceModifier=0n,...options}={}){let headerOptions=previousArchive?{lastArchiveRoot:previousArchive.root,...options}:options,header=CheckpointHeader.random(headerOptions),blocks=[],lastArchive=previousArchive;for(let i=0;i<numBlocks;i++){let block=await L2Block.random(BlockNumber(startBlockNumber+i),{checkpointNumber,indexWithinCheckpoint:IndexWithinCheckpoint(i),...options,...lastArchive?{lastArchive}:{},...pick2(header,"slotNumber","timestamp","coinbase","feeRecipient","gasFees")});lastArchive=block.archive,blocks.push(block)}return new _Checkpoint(options.archive??AppendOnlyTreeSnapshot.random(),header,blocks,checkpointNumber,feeAssetPriceModifier)}};var L1PublishedData=class _L1PublishedData{static{__name(this,"L1PublishedData")}blockNumber;timestamp;blockHash;constructor(blockNumber,timestamp,blockHash){this.blockNumber=blockNumber,this.timestamp=timestamp,this.blockHash=blockHash}static get schema(){return external_exports.object({blockNumber:schemas.BigInt,timestamp:schemas.BigInt,blockHash:external_exports.string()}).transform(obj=>_L1PublishedData.fromFields(obj))}static random(){return new _L1PublishedData(randomBigInt(1000n)+1n,BigInt(Math.floor(Date.now()/1e3)),Buffer32.random().toString())}static fromFields(fields){return new _L1PublishedData(fields.blockNumber,fields.timestamp,fields.blockHash)}static fromBuffer(bufferOrReader){let reader=BufferReader.asReader(bufferOrReader),l1BlockNumber=reader.readBigInt(),l1BlockHash=reader.readString(MAX_BLOCK_HASH_STRING_LENGTH),l1Timestamp=reader.readBigInt();return new _L1PublishedData(l1BlockNumber,l1Timestamp,l1BlockHash)}toBuffer(){return serializeToBuffer(this.blockNumber,this.blockHash,this.timestamp)}},PublishedCheckpoint=class _PublishedCheckpoint{static{__name(this,"PublishedCheckpoint")}checkpoint;l1;attestations;constructor(checkpoint,l1,attestations){this.checkpoint=checkpoint,this.l1=l1,this.attestations=attestations}static get schema(){return external_exports.object({checkpoint:Checkpoint.schema,l1:L1PublishedData.schema,attestations:external_exports.array(CommitteeAttestation.schema)}).transform(obj=>_PublishedCheckpoint.from(obj))}static getFields(fields){return[fields.checkpoint,fields.l1,fields.attestations]}static from(fields){return new _PublishedCheckpoint(..._PublishedCheckpoint.getFields(fields))}static fromBuffer(bufferOrReader){let reader=BufferReader.asReader(bufferOrReader),checkpoint=reader.readObject(Checkpoint),l1BlockNumber=reader.readBigInt(),l1BlockHash=reader.readString(MAX_BLOCK_HASH_STRING_LENGTH),l1Timestamp=reader.readBigInt(),attestations=reader.readVector(CommitteeAttestation,MAX_COMMITTEE_SIZE);return new _PublishedCheckpoint(checkpoint,new L1PublishedData(l1BlockNumber,l1Timestamp,l1BlockHash),attestations)}toBuffer(){return serializeToBuffer(this.checkpoint,this.l1.blockNumber,this.l1.blockHash,this.l1.timestamp,this.attestations.length,this.attestations)}};var ProposedCheckpointDataSchema=external_exports.object({checkpointNumber:CheckpointNumberSchema,header:CheckpointHeader.schema,archive:AppendOnlyTreeSnapshot.schema,checkpointOutHash:schemas.Fr,startBlock:BlockNumberSchema,blockCount:external_exports.number(),totalManaUsed:schemas.BigInt,feeAssetPriceModifier:schemas.BigInt}),CheckpointDataSchema=external_exports.object({checkpointNumber:CheckpointNumberSchema,header:CheckpointHeader.schema,archive:AppendOnlyTreeSnapshot.schema,checkpointOutHash:schemas.Fr,startBlock:BlockNumberSchema,blockCount:schemas.Integer,feeAssetPriceModifier:schemas.BigInt,attestations:external_exports.array(CommitteeAttestation.schema),l1:L1PublishedData.schema}).transform(obj=>({checkpointNumber:obj.checkpointNumber,header:obj.header,archive:obj.archive,checkpointOutHash:obj.checkpointOutHash,startBlock:obj.startBlock,blockCount:obj.blockCount,feeAssetPriceModifier:obj.feeAssetPriceModifier,attestations:obj.attestations,l1:obj.l1}));var L2ToL1MembershipWitnessSchema=external_exports.object({epochNumber:EpochNumberSchema,numCheckpointsInEpoch:schemas2.Integer,root:schemas2.Fr,leafIndex:schemas2.BigInt,siblingPath:SiblingPath.schema});import{pickL1ContractAddressMappings,pickL1ContractAddressesSchema}from"@aztec/ethereum/l1-contract-addresses";var NetworkConfigSchema=external_exports.object({bootnodes:external_exports.array(external_exports.string()),snapshots:external_exports.array(external_exports.string()),blobFileStoreUrls:external_exports.array(external_exports.string()).optional(),txCollectionFileStoreUrls:external_exports.array(external_exports.string()).optional(),registryAddress:external_exports.string(),feeAssetHandlerAddress:external_exports.string().optional(),l1ChainId:external_exports.number(),blockDurationMs:external_exports.number().positive().optional(),txPublicSetupAllowListExtend:external_exports.string().optional(),nodeVersion:external_exports.string().optional()}).passthrough(),NetworkConfigMapSchema=external_exports.record(external_exports.string(),NetworkConfigSchema);function numberConfigHelper(defaultVal){return{parseEnv:__name(val=>parseSafeInteger(val),"parseEnv"),defaultValue:defaultVal}}__name(numberConfigHelper,"numberConfigHelper");function floatConfigHelper(defaultVal,validationFn){return{parseEnv:__name(val=>{let parsed=parseFiniteNumber(val);return validationFn?.(parsed),parsed},"parseEnv"),defaultValue:defaultVal}}__name(floatConfigHelper,"floatConfigHelper");function optionalNumberConfigHelper(){return{parseEnv:__name(val=>parseSafeInteger(val),"parseEnv")}}__name(optionalNumberConfigHelper,"optionalNumberConfigHelper");function enumConfigHelper(values,defaultValue){return{parseEnv:__name(val=>{let sanitizedVal=val.trim().toLowerCase();if(values.some(v=>v.toLowerCase()===sanitizedVal))return values.find(v=>v.toLowerCase()===sanitizedVal);throw new Error(`Invalid config value '${val}' (must be one of ${values.join(", ")})`)},"parseEnv"),defaultValue}}__name(enumConfigHelper,"enumConfigHelper");function booleanConfigHelper(defaultVal=!1){let parse4=__name(val=>typeof val=="boolean"?val:parseBooleanEnv(val),"parse");return{parseEnv:parse4,parseVal:parse4,defaultValue:defaultVal,isBoolean:!0}}__name(booleanConfigHelper,"booleanConfigHelper");function secretStringConfigHelper(defaultValue){let parse4=__name(val=>new SecretValue(val),"parse");return{parseEnv:parse4,parseVal:parse4,defaultValue:defaultValue!==void 0?new SecretValue(defaultValue):void 0}}__name(secretStringConfigHelper,"secretStringConfigHelper");function parseSafeInteger(value){let parsedValue=parseFloat(value);if(!Number.isSafeInteger(parsedValue))throw new Error(`Invalid integer config value '${value}'; expected a whole number`);return parsedValue}__name(parseSafeInteger,"parseSafeInteger");function parseFiniteNumber(value){let parsedValue=parseFloat(value);if(!Number.isFinite(parsedValue))throw new Error(`Invalid number config value '${value}'`);return parsedValue}__name(parseFiniteNumber,"parseFiniteNumber");function pickConfigMappings(configMappings,keys){return Object.fromEntries(keys.map(key=>[key,configMappings[key]]))}__name(pickConfigMappings,"pickConfigMappings");function getDefaultConfig(configMappings){let defaultConfig={};for(let key in configMappings)configMappings[key]&&configMappings[key].defaultValue!==void 0&&(defaultConfig[key]=configMappings[key].defaultValue);return defaultConfig}__name(getDefaultConfig,"getDefaultConfig");var baseSignerConfigMappings={nodeId:{env:"VALIDATOR_HA_NODE_ID",description:"The unique identifier for this node",defaultValue:""},pollingIntervalMs:{env:"VALIDATOR_HA_POLLING_INTERVAL_MS",description:"The number of ms to wait between polls when a duty is being signed",...numberConfigHelper(100)},peerSigningTimeoutMs:{env:"VALIDATOR_HA_SIGNING_TIMEOUT_MS",description:"How long to wait for a peer node's in-progress signing before giving up",...numberConfigHelper(3e3)},signerCallTimeoutMs:{env:"VALIDATOR_SIGNER_CALL_TIMEOUT_MS",description:"Hard upper bound in ms on a single signer call before it is aborted (default 30000)",...numberConfigHelper(3e4)},maxStuckDutiesAgeMs:{env:"VALIDATOR_HA_MAX_STUCK_DUTIES_AGE_MS",description:"The maximum age of a stuck duty in ms (defaults to 2x Aztec slot duration)",...optionalNumberConfigHelper()},cleanupOldDutiesAfterHours:{env:"VALIDATOR_HA_OLD_DUTIES_MAX_AGE_H",description:"Optional: clean up old duties after this many hours (disabled if not set)",...optionalNumberConfigHelper()},...pickL1ContractAddressMappings("rollupAddress")},BaseSignerConfigSchema=external_exports.object({nodeId:external_exports.string(),pollingIntervalMs:external_exports.number().min(0),peerSigningTimeoutMs:external_exports.number().min(0),signerCallTimeoutMs:external_exports.number().min(0).optional(),maxStuckDutiesAgeMs:external_exports.number().min(0).optional(),cleanupOldDutiesAfterHours:external_exports.number().min(0).optional(),...pickL1ContractAddressesSchema("rollupAddress")}),validatorHASignerConfigMappings={...baseSignerConfigMappings,haSigningEnabled:{env:"VALIDATOR_HA_SIGNING_ENABLED",description:"Whether HA signing / slashing protection is enabled",...booleanConfigHelper(!1)},databaseUrl:{env:"VALIDATOR_HA_DATABASE_URL",description:"PostgreSQL connection string for validator HA signer (format: postgresql://user:password@host:port/database)",...secretStringConfigHelper()},poolMaxCount:{env:"VALIDATOR_HA_POOL_MAX",description:"Maximum number of clients in the pool",...numberConfigHelper(10)},poolMinCount:{env:"VALIDATOR_HA_POOL_MIN",description:"Minimum number of clients in the pool",...numberConfigHelper(0)},poolIdleTimeoutMs:{env:"VALIDATOR_HA_POOL_IDLE_TIMEOUT_MS",description:"Idle timeout in milliseconds",...numberConfigHelper(1e4)},poolConnectionTimeoutMs:{env:"VALIDATOR_HA_POOL_CONNECTION_TIMEOUT_MS",description:"Connection timeout in milliseconds (0 means no timeout)",...numberConfigHelper(0)}},defaultValidatorHASignerConfig=getDefaultConfig(validatorHASignerConfigMappings);var ValidatorHASignerConfigSchema=BaseSignerConfigSchema.extend({haSigningEnabled:external_exports.boolean(),databaseUrl:SecretValue.schema(external_exports.string()).optional(),poolMaxCount:external_exports.number().min(0).optional(),poolMinCount:external_exports.number().min(0).optional(),poolIdleTimeoutMs:external_exports.number().min(0).optional(),poolConnectionTimeoutMs:external_exports.number().min(0).optional()});import{pickL1ContractAddressMappings as pickL1ContractAddressMappings2}from"@aztec/ethereum/l1-contract-addresses";var dataConfigMappings={dataDirectory:{env:"DATA_DIRECTORY",description:"Optional dir to store data. If omitted will store in memory."},dataStoreMapSizeKb:{env:"DATA_STORE_MAP_SIZE_KB",description:"The maximum possible size of a data store DB in KB. Can be overridden by component-specific options.",...numberConfigHelper(128*1024*1024)},...pickL1ContractAddressMappings2("rollupAddress")};var localSignerConfigMappings={...baseSignerConfigMappings,...dataConfigMappings,signingProtectionMapSizeKb:{env:"SIGNING_PROTECTION_MAP_SIZE_KB",description:"Maximum size of the local signing-protection LMDB store in KB. Overwrites the general dataStoreMapSizeKb.",...optionalNumberConfigHelper()},allowEphemeralSigningProtection:{env:"VALIDATOR_ALLOW_EPHEMERAL_SIGNING_PROTECTION",description:"Allow local signing protection to run against an ephemeral store when no data directory is set (dev/test only). Ephemeral protection does not survive restarts, so this is unsafe for production validators.",...booleanConfigHelper(!1)}},LocalSignerConfigSchema=zodFor()(BaseSignerConfigSchema.extend({dataDirectory:external_exports.string().optional(),dataStoreMapSizeKb:external_exports.number(),signingProtectionMapSizeKb:external_exports.number().optional(),allowEphemeralSigningProtection:external_exports.boolean().optional()}));var DutyType=(function(DutyType2){return DutyType2.BLOCK_PROPOSAL="BLOCK_PROPOSAL",DutyType2.CHECKPOINT_PROPOSAL="CHECKPOINT_PROPOSAL",DutyType2.ATTESTATION="ATTESTATION",DutyType2.ATTESTATIONS_AND_SIGNERS="ATTESTATIONS_AND_SIGNERS",DutyType2.GOVERNANCE_VOTE="GOVERNANCE_VOTE",DutyType2.SLASHING_VOTE="SLASHING_VOTE",DutyType2.AUTH_REQUEST="AUTH_REQUEST",DutyType2.TXS="TXS",DutyType2})({});var SignedTxs=class _SignedTxs{static{__name(this,"SignedTxs")}txs;signature;signatureContext;primaryType;cachedSender;constructor(txs,signature,signatureContext){this.txs=txs,this.signature=signature,this.signatureContext=signatureContext,this.primaryType="SignedTxs",this.cachedSender=void 0}getPayloadToSign(){return serializeToBuffer([this.txs.length,this.txs])}getSender(){return this.cachedSender===void 0&&(this.cachedSender=recoverCoordinationSigner(this,this.signature)??null),this.cachedSender??void 0}static async createFromSigner(txs,signatureContext,typedDataSigner){let tempSignedTxs=new _SignedTxs(txs,Signature.empty(),signatureContext),typedData=getCoordinationSignatureTypedData(tempSignedTxs),signature=await typedDataSigner(typedData);return new _SignedTxs(txs,signature,signatureContext)}toBuffer(){return serializeToBuffer([this.txs.length,this.txs,this.signature,serializeCoordinationSignatureContext(this.signatureContext)])}static fromBuffer(buf){let reader=BufferReader.asReader(buf),txCount=reader.readNumber();if(txCount>MAX_TXS_PER_BLOCK)throw new Error(`txs count ${txCount} exceeds maximum ${MAX_TXS_PER_BLOCK}`);let txs=reader.readArray(txCount,Tx),signature=reader.readObject(Signature),signatureContext=readCoordinationSignatureContext(reader);return new _SignedTxs(txs,signature,signatureContext)}getSize(){return 4+this.txs.reduce((acc,tx)=>acc+tx.getSize(),0)+this.signature.getSize()+4+20}static empty(){return new _SignedTxs([],Signature.empty(),EMPTY_COORDINATION_SIGNATURE_CONTEXT)}static random(){return new _SignedTxs([Tx.random(),Tx.random()],Signature.random(),EMPTY_COORDINATION_SIGNATURE_CONTEXT)}};var BlockProposal=class _BlockProposal extends Gossipable{static{__name(this,"BlockProposal")}blockHeader;indexWithinCheckpoint;inHash;archiveRoot;txHashes;signature;signatureContext;signedTxs;static p2pTopic=TopicType.block_proposal;primaryType;cachedSender;constructor(blockHeader,indexWithinCheckpoint,inHash,archiveRoot,txHashes,signature,signatureContext,signedTxs){super(),this.blockHeader=blockHeader,this.indexWithinCheckpoint=indexWithinCheckpoint,this.inHash=inHash,this.archiveRoot=archiveRoot,this.txHashes=txHashes,this.signature=signature,this.signatureContext=signatureContext,this.signedTxs=signedTxs,this.primaryType="BlockProposal",this.cachedSender=void 0}generateP2PMessageIdentifier(){return Promise.resolve(new Buffer32(this.getPayloadHashBuffer()))}get archive(){return this.archiveRoot}get slotNumber(){return this.blockHeader.getSlot()}get blockNumber(){return this.blockHeader.getBlockNumber()}get txs(){return this.signedTxs?.txs}toBlockInfo(){return{slotNumber:this.slotNumber,lastArchive:this.blockHeader.lastArchive.root,timestamp:this.blockHeader.globalVariables.timestamp,archive:this.archiveRoot,txCount:this.txHashes.length}}getPayloadToSign(){return serializeToBuffer([this.blockHeader,this.indexWithinCheckpoint,this.inHash,this.archiveRoot,this.txHashes.length,this.txHashes])}getPayloadHashBuffer(){return keccak256(this.getPayloadToSign())}getPayloadHash(){return BlockProposalHash.fromBuffer(this.getPayloadHashBuffer())}static async createProposalFromSigner(blockHeader,checkpointNumber,indexWithinCheckpoint,inHash,archiveRoot,txHashes,txs,signatureContext,proposalSigner,txsSigner){let tempProposal=new _BlockProposal(blockHeader,indexWithinCheckpoint,inHash,archiveRoot,txHashes,Signature.empty(),signatureContext),blockContext={slot:blockHeader.globalVariables.slotNumber,blockNumber:blockHeader.globalVariables.blockNumber,checkpointNumber,blockIndexWithinCheckpoint:indexWithinCheckpoint,dutyType:DutyType.BLOCK_PROPOSAL},typedData=getCoordinationSignatureTypedData(tempProposal),sig=await proposalSigner(typedData,blockContext),signedTxs;if(txs){let txsSigningContext={dutyType:DutyType.TXS};if(!txsSigner)throw new Error("signed_txs requires a typed-data signer");signedTxs=await SignedTxs.createFromSigner(txs,signatureContext,typedData2=>txsSigner(typedData2,txsSigningContext))}return new _BlockProposal(blockHeader,indexWithinCheckpoint,inHash,archiveRoot,txHashes,sig,signatureContext,signedTxs)}getSender(){if(this.cachedSender===void 0){let blockSender=recoverCoordinationSigner(this,this.signature);if(blockSender&&this.signedTxs){if(!coordinationSignatureContextEquals(this.signedTxs.signatureContext,this.signatureContext)){this.cachedSender=null;return}let txsSender=this.signedTxs.getSender();if(!txsSender||!txsSender.equals(blockSender)){this.cachedSender=null;return}}this.cachedSender=blockSender??null}return this.cachedSender??void 0}getPayload(){return this.getPayloadToSign()}toBuffer(){let buffer=[this.blockHeader,this.indexWithinCheckpoint,this.inHash,this.archiveRoot,this.signature,serializeCoordinationSignatureContext(this.signatureContext),this.txHashes.length,this.txHashes];return this.signedTxs?(buffer.push(1),buffer.push(this.signedTxs.toBuffer())):buffer.push(0),serializeToBuffer(buffer)}static fromBuffer(buf){let reader=BufferReader.asReader(buf),blockHeader=reader.readObject(BlockHeader),indexWithinCheckpoint=IndexWithinCheckpoint(reader.readNumber()),inHash=reader.readObject(Fr),archiveRoot=reader.readObject(Fr),signature=reader.readObject(Signature),signatureContext=readCoordinationSignatureContext(reader),txHashCount=reader.readNumber();if(txHashCount>MAX_TXS_PER_BLOCK)throw new Error(`txHashes count ${txHashCount} exceeds maximum ${MAX_TXS_PER_BLOCK}`);let txHashes=reader.readArray(txHashCount,TxHash);if(!reader.isEmpty()&&reader.readNumber()){let signedTxs=SignedTxs.fromBuffer(reader);return new _BlockProposal(blockHeader,indexWithinCheckpoint,inHash,archiveRoot,txHashes,signature,signatureContext,signedTxs)}return new _BlockProposal(blockHeader,indexWithinCheckpoint,inHash,archiveRoot,txHashes,signature,signatureContext)}getSize(){return this.blockHeader.getSize()+4+this.inHash.size+this.archiveRoot.size+this.signature.getSize()+4+20+4+this.txHashes.length*TxHash.SIZE+4+(this.signedTxs?this.signedTxs.getSize():0)}static empty(){return new _BlockProposal(BlockHeader.empty(),IndexWithinCheckpoint(0),Fr.ZERO,Fr.ZERO,[],Signature.empty(),EMPTY_COORDINATION_SIGNATURE_CONTEXT)}static random(){return new _BlockProposal(BlockHeader.random(),IndexWithinCheckpoint(Math.floor(Math.random()*5)),Fr.random(),Fr.random(),[TxHash.random(),TxHash.random()],Signature.random(),EMPTY_COORDINATION_SIGNATURE_CONTEXT)}toInspect(){return{blockHeader:this.blockHeader.toInspect(),indexWithinCheckpoint:this.indexWithinCheckpoint,inHash:this.inHash.toString(),archiveRoot:this.archiveRoot.toString(),signature:this.signature.toString(),txHashes:this.txHashes.map(h=>h.toString()),chainId:this.signatureContext.chainId,rollupAddress:this.signatureContext.rollupAddress.toString()}}matchesBlock(block){return this.archiveRoot.equals(block.archive.root)&&this.blockHeader.equals(block.header)}withoutSignedTxs(){return new _BlockProposal(this.blockHeader,this.indexWithinCheckpoint,this.inHash,this.archiveRoot,this.txHashes,this.signature,this.signatureContext)}};var CheckpointProposal=class _CheckpointProposal extends Gossipable{static{__name(this,"CheckpointProposal")}checkpointHeader;archive;feeAssetPriceModifier;signature;signatureContext;lastBlock;static p2pTopic=TopicType.checkpoint_proposal;primaryType;cachedSender;constructor(checkpointHeader,archive,feeAssetPriceModifier,signature,signatureContext,lastBlock){if(super(),this.checkpointHeader=checkpointHeader,this.archive=archive,this.feeAssetPriceModifier=feeAssetPriceModifier,this.signature=signature,this.signatureContext=signatureContext,this.lastBlock=lastBlock,this.primaryType="CheckpointProposal",this.cachedSender=void 0,lastBlock&&"inHash"in lastBlock&&!lastBlock.inHash.equals(checkpointHeader.inHash))throw new Error(`CheckpointProposal lastBlock inHash ${lastBlock.inHash} does not match checkpoint inHash ${checkpointHeader.inHash}`);if(lastBlock&&"archiveRoot"in lastBlock&&!lastBlock.archiveRoot.equals(archive))throw new Error(`CheckpointProposal lastBlock archive ${lastBlock.archiveRoot} does not match checkpoint archive ${archive}`);if(lastBlock&&"signatureContext"in lastBlock&&!coordinationSignatureContextEquals(lastBlock.signatureContext,signatureContext))throw new Error("CheckpointProposal lastBlock signatureContext does not match checkpoint signatureContext")}generateP2PMessageIdentifier(){return Promise.resolve(new Buffer32(this.toConsensusPayload().getPayloadHash()))}get slotNumber(){return this.checkpointHeader.slotNumber}getBlockProposal(){if(this.lastBlock)return new BlockProposal(this.lastBlock.blockHeader,this.lastBlock.indexWithinCheckpoint,this.checkpointHeader.inHash,this.archive,this.lastBlock.txHashes,this.lastBlock.signature,this.signatureContext,this.lastBlock.signedTxs)}toBlockInfo(){if(!this.lastBlock)throw new Error("Cannot get blockInfo without lastBlock");return{slotNumber:this.slotNumber,lastArchive:this.lastBlock.blockHeader.lastArchive.root,timestamp:this.lastBlock.blockHeader.globalVariables.timestamp,archive:this.archive,txCount:this.lastBlock.txHashes.length}}toCheckpointInfo(){return{slotNumber:this.slotNumber,archive:this.archive,lastBlockNumber:this.lastBlock?.blockHeader.getBlockNumber(),lastBlockIndex:this.lastBlock?.indexWithinCheckpoint,blockHeadersHash:this.checkpointHeader.blockHeadersHash}}getPayloadToSign(){return serializeToBuffer([this.checkpointHeader,this.archive,serializeSignedBigInt(this.feeAssetPriceModifier)])}getPayloadHash(){return CheckpointProposalHash.fromBuffer(this.toConsensusPayload().getPayloadHash())}toConsensusPayload(){return new ConsensusPayload(this.checkpointHeader,this.archive,this.feeAssetPriceModifier,this.signatureContext)}static async createProposalFromSigner(checkpointHeader,archiveRoot,checkpointNumber,feeAssetPriceModifier,lastBlockProposal,signatureContext,payloadSigner){let tempProposal=new _CheckpointProposal(checkpointHeader,archiveRoot,feeAssetPriceModifier,Signature.empty(),signatureContext),checkpointContext={slot:checkpointHeader.slotNumber,checkpointNumber,dutyType:DutyType.CHECKPOINT_PROPOSAL},typedData=getCoordinationSignatureTypedData(tempProposal),checkpointSignature=await payloadSigner(typedData,checkpointContext);return new _CheckpointProposal(checkpointHeader,archiveRoot,feeAssetPriceModifier,checkpointSignature,signatureContext,lastBlockProposal)}getSender(){if(this.cachedSender===void 0){let checkpointSender=recoverCoordinationSigner(this,this.signature);if(checkpointSender&&this.lastBlock){let blockSender=this.getBlockProposal()?.getSender();if(!blockSender||!blockSender.equals(checkpointSender)){this.cachedSender=null;return}}this.cachedSender=checkpointSender??null}return this.cachedSender??void 0}getPayload(){return this.getPayloadToSign()}toBuffer(){let buffer=[this.checkpointHeader,this.archive,serializeSignedBigInt(this.feeAssetPriceModifier),this.signature,serializeCoordinationSignatureContext(this.signatureContext)];return this.lastBlock?(buffer.push(1),buffer.push(this.lastBlock.blockHeader),buffer.push(this.lastBlock.indexWithinCheckpoint),buffer.push(this.lastBlock.signature),buffer.push(this.lastBlock.txHashes.length),buffer.push(this.lastBlock.txHashes),this.lastBlock.signedTxs?(buffer.push(1),buffer.push(this.lastBlock.signedTxs.toBuffer())):buffer.push(0)):buffer.push(0),serializeToBuffer(buffer)}static fromBuffer(buf){let reader=BufferReader.asReader(buf),checkpointHeader=reader.readObject(CheckpointHeader),archive=reader.readObject(Fr),feeAssetPriceModifier=reader.readInt256(),signature=reader.readObject(Signature),signatureContext=readCoordinationSignatureContext(reader);if(reader.readNumber()){let blockHeader=reader.readObject(BlockHeader),indexWithinCheckpoint=IndexWithinCheckpoint(reader.readNumber()),blockSignature=reader.readObject(Signature),txHashCount=reader.readNumber();if(txHashCount>MAX_TXS_PER_BLOCK)throw new Error(`txHashes count ${txHashCount} exceeds maximum ${MAX_TXS_PER_BLOCK}`);let txHashes=reader.readArray(txHashCount,TxHash),signedTxs;return reader.isEmpty()||reader.readNumber()&&(signedTxs=SignedTxs.fromBuffer(reader)),new _CheckpointProposal(checkpointHeader,archive,feeAssetPriceModifier,signature,signatureContext,{blockHeader,indexWithinCheckpoint,txHashes,signature:blockSignature,signedTxs})}return new _CheckpointProposal(checkpointHeader,archive,feeAssetPriceModifier,signature,signatureContext)}getSize(){let size=this.checkpointHeader.toBuffer().length+this.archive.size+this.signature.getSize()+8+4+20+4;return this.lastBlock&&(size+=this.lastBlock.blockHeader.getSize()+4+this.lastBlock.signature.getSize()+4+this.lastBlock.txHashes.length*TxHash.SIZE+4+(this.lastBlock.signedTxs?this.lastBlock.signedTxs.getSize():0)),size}static empty(){return new _CheckpointProposal(CheckpointHeader.empty(),Fr.ZERO,0n,Signature.empty(),EMPTY_COORDINATION_SIGNATURE_CONTEXT)}static random(){return new _CheckpointProposal(CheckpointHeader.random(),Fr.random(),0n,Signature.random(),EMPTY_COORDINATION_SIGNATURE_CONTEXT,{blockHeader:BlockHeader.random(),indexWithinCheckpoint:IndexWithinCheckpoint(Math.floor(Math.random()*5)),txHashes:[TxHash.random(),TxHash.random()],signature:Signature.random()})}toInspect(){return{checkpointHeader:this.checkpointHeader.toInspect(),archive:this.archive.toString(),signature:this.signature.toString(),feeAssetPriceModifier:this.feeAssetPriceModifier.toString(),chainId:this.signatureContext.chainId,rollupAddress:this.signatureContext.rollupAddress.toString(),lastBlock:this.lastBlock?{blockHeader:this.lastBlock.blockHeader.toInspect(),indexWithinCheckpoint:this.lastBlock.indexWithinCheckpoint,txHashes:this.lastBlock.txHashes.map(h=>h.toString()),signature:this.lastBlock.signature.toString()}:void 0}}toCore(){return new _CheckpointProposal(this.checkpointHeader,this.archive,this.feeAssetPriceModifier,this.signature,this.signatureContext)}};var CheckpointAttestation=class _CheckpointAttestation extends Gossipable{static{__name(this,"CheckpointAttestation")}payload;signature;proposerSignature;static p2pTopic=TopicType.checkpoint_attestation;cachedSender;cachedProposer;constructor(payload,signature,proposerSignature){super(),this.payload=payload,this.signature=signature,this.proposerSignature=proposerSignature,this.cachedSender=void 0,this.cachedProposer=void 0}static get schema(){return external_exports.object({payload:ConsensusPayload.schema,signature:Signature.schema,proposerSignature:Signature.schema}).transform(obj=>new _CheckpointAttestation(obj.payload,obj.signature,obj.proposerSignature))}generateP2PMessageIdentifier(){return Promise.resolve(new Buffer32(this.payload.getPayloadHash()))}get archive(){return this.payload.archive}get slotNumber(){return this.payload.header.slotNumber}get signatureContext(){return this.payload.signatureContext}getSender(){return this.cachedSender===void 0&&(this.cachedSender=recoverCoordinationSigner(this.payload,this.signature)??null),this.cachedSender??void 0}getProposer(){if(this.cachedProposer===void 0){let proposal=new CheckpointProposal(this.payload.header,this.payload.archive,this.payload.feeAssetPriceModifier,this.proposerSignature,this.payload.signatureContext);this.cachedProposer=proposal.getSender()??null}return this.cachedProposer??void 0}withNormalizedSignature(){return new _CheckpointAttestation(this.payload,normalizeSignature(this.signature),this.proposerSignature)}getPayload(){return this.payload.getPayloadToSign()}getPayloadHash(){return CheckpointProposalHash.fromBuffer(this.payload.getPayloadHash())}toBuffer(){return serializeToBuffer([this.payload,this.signature,this.proposerSignature])}static fromBuffer(buf){let reader=BufferReader.asReader(buf);return new _CheckpointAttestation(reader.readObject(ConsensusPayload),reader.readObject(Signature),reader.readObject(Signature))}static empty(){return new _CheckpointAttestation(ConsensusPayload.empty(),Signature.empty(),Signature.empty())}static random(){return new _CheckpointAttestation(ConsensusPayload.random(),Signature.random(),Signature.random())}getSize(){return this.payload.getSize()+this.signature.getSize()+this.proposerSignature.getSize()}toInspect(){return{payload:this.payload.toInspect(),signature:this.signature.toString(),proposerSignature:this.proposerSignature.toString()}}};var MerkleTreeId=(function(MerkleTreeId2){return MerkleTreeId2[MerkleTreeId2.NULLIFIER_TREE=0]="NULLIFIER_TREE",MerkleTreeId2[MerkleTreeId2.NOTE_HASH_TREE=1]="NOTE_HASH_TREE",MerkleTreeId2[MerkleTreeId2.PUBLIC_DATA_TREE=2]="PUBLIC_DATA_TREE",MerkleTreeId2[MerkleTreeId2.L1_TO_L2_MESSAGE_TREE=3]="L1_TO_L2_MESSAGE_TREE",MerkleTreeId2[MerkleTreeId2.ARCHIVE=4]="ARCHIVE",MerkleTreeId2})({}),merkleTreeIds=__name(()=>Object.values(MerkleTreeId).filter(v=>!isNaN(Number(v))),"merkleTreeIds"),TREE_HEIGHTS={[MerkleTreeId.NOTE_HASH_TREE]:42,[MerkleTreeId.ARCHIVE]:30,[MerkleTreeId.L1_TO_L2_MESSAGE_TREE]:36,[MerkleTreeId.NULLIFIER_TREE]:42,[MerkleTreeId.PUBLIC_DATA_TREE]:40};var TREE_NAMES={[MerkleTreeId.NULLIFIER_TREE]:"NULLIFIER_TREE",[MerkleTreeId.NOTE_HASH_TREE]:"NOTE_HASH_TREE",[MerkleTreeId.PUBLIC_DATA_TREE]:"PUBLIC_DATA_TREE",[MerkleTreeId.L1_TO_L2_MESSAGE_TREE]:"L1_TO_L2_MESSAGE_TREE",[MerkleTreeId.ARCHIVE]:"ARCHIVE"};function getTreeName(treeId){return TREE_NAMES[treeId]}__name(getTreeName,"getTreeName");var NullifierLeafPreimage=class _NullifierLeafPreimage{static{__name(this,"NullifierLeafPreimage")}leaf;nextKey;nextIndex;constructor(leaf,nextKey,nextIndex){this.leaf=leaf,this.nextKey=nextKey,this.nextIndex=nextIndex}static get schema(){return external_exports.object({leaf:NullifierLeaf.schema,nextKey:schemas.Fr,nextIndex:schemas.BigInt}).transform(({leaf,nextKey,nextIndex})=>new _NullifierLeafPreimage(leaf,nextKey,nextIndex))}static fromPlainObject(obj){return obj instanceof _NullifierLeafPreimage?obj:new _NullifierLeafPreimage(NullifierLeaf.fromPlainObject(obj.leaf),Fr.fromPlainObject(obj.nextKey),typeof obj.nextIndex=="bigint"?obj.nextIndex:BigInt(obj.nextIndex))}static get leafSchema(){return NullifierLeaf.schema}getKey(){return this.leaf.getKey()}getNextKey(){return this.nextKey.toBigInt()}getNextIndex(){return this.nextIndex}asLeaf(){return this.leaf}toBuffer(){return Buffer.concat(this.toHashInputs())}toHashInputs(){return[...this.leaf.toHashInputs(),Buffer.from(this.nextKey.toBuffer()),Buffer.from(toBufferBE(this.nextIndex,32))]}isEmpty(){return this.leaf.isEmpty()&&this.nextKey.isZero()&&this.nextIndex===0n}toFields(){return this.toHashInputs().map(buf=>Fr.fromBuffer(buf))}clone(){return new _NullifierLeafPreimage(this.leaf.clone(),this.nextKey,this.nextIndex)}static random(){return new _NullifierLeafPreimage(NullifierLeaf.random(),Fr.random(),BigInt(Math.floor(Math.random()*1e3)))}static empty(){return new _NullifierLeafPreimage(NullifierLeaf.empty(),Fr.zero(),0n)}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _NullifierLeafPreimage(NullifierLeaf.fromBuffer(reader),reader.readObject(Fr),toBigIntBE(reader.readBytes(32)))}static fromLeaf(leaf,nextKey,nextIndex){return new _NullifierLeafPreimage(leaf,new Fr(nextKey),nextIndex)}static clone(preimage){return preimage.clone()}},NullifierLeaf=class _NullifierLeaf{static{__name(this,"NullifierLeaf")}nullifier;constructor(nullifier){this.nullifier=nullifier}getKey(){return this.nullifier.toBigInt()}toBuffer(){return this.nullifier.toBuffer()}clone(){return new _NullifierLeaf(new Fr(this.nullifier))}toHashInputs(){return[Buffer.from(this.nullifier.toBuffer())]}static empty(){return new _NullifierLeaf(Fr.ZERO)}static random(){return new _NullifierLeaf(Fr.random())}isEmpty(){return this.nullifier.isZero()}updateTo(_another){throw new Error("Nullifiers are create only")}static buildDummy(key){return new _NullifierLeaf(new Fr(key))}static fromBuffer(buf){let reader=BufferReader.asReader(buf);return new _NullifierLeaf(reader.readObject(Fr))}static get schema(){return external_exports.object({nullifier:schemas.Fr}).transform(({nullifier})=>new _NullifierLeaf(nullifier))}static fromPlainObject(obj){return obj instanceof _NullifierLeaf?obj:new _NullifierLeaf(Fr.fromPlainObject(obj.nullifier))}};var NullifierMembershipWitness=class _NullifierMembershipWitness{static{__name(this,"NullifierMembershipWitness")}index;leafPreimage;siblingPath;constructor(index,leafPreimage,siblingPath){this.index=index,this.leafPreimage=leafPreimage,this.siblingPath=siblingPath}static get schema(){return external_exports.object({index:schemas2.BigInt,leafPreimage:NullifierLeafPreimage.schema,siblingPath:SiblingPath.schemaFor(42)}).transform(({index,leafPreimage,siblingPath})=>new _NullifierMembershipWitness(index,leafPreimage,siblingPath))}static random(){return new _NullifierMembershipWitness(BigInt(Math.floor(Math.random()*1e3)),NullifierLeafPreimage.random(),SiblingPath.random(42))}withoutPreimage(){return new MembershipWitness(42,this.index,this.siblingPath.toTuple())}};var PublicDataTreeLeafPreimage=class _PublicDataTreeLeafPreimage{static{__name(this,"PublicDataTreeLeafPreimage")}leaf;nextKey;nextIndex;constructor(leaf,nextKey,nextIndex){this.leaf=leaf,this.nextKey=nextKey,this.nextIndex=nextIndex}static get schema(){return external_exports.object({leaf:PublicDataTreeLeaf.schema,nextKey:schemas.Fr,nextIndex:schemas.BigInt}).transform(({leaf,nextKey,nextIndex})=>new _PublicDataTreeLeafPreimage(leaf,nextKey,nextIndex))}static fromPlainObject(obj){return obj instanceof _PublicDataTreeLeafPreimage?obj:new _PublicDataTreeLeafPreimage(PublicDataTreeLeaf.fromPlainObject(obj.leaf),Fr.fromPlainObject(obj.nextKey),typeof obj.nextIndex=="bigint"?obj.nextIndex:BigInt(obj.nextIndex))}static get leafSchema(){return PublicDataTreeLeaf.schema}getKey(){return this.leaf.getKey()}getNextKey(){return this.nextKey.toBigInt()}getNextIndex(){return this.nextIndex}asLeaf(){return this.leaf}toBuffer(){return Buffer.concat(this.toHashInputs())}toHashInputs(){return[...this.leaf.toHashInputs(),Buffer.from(this.nextKey.toBuffer()),Buffer.from(toBufferBE(this.nextIndex,32))]}hash(){return poseidon2Hash(this.toHashInputs())}clone(){return new _PublicDataTreeLeafPreimage(this.leaf.clone(),this.nextKey,this.nextIndex)}static random(){return new _PublicDataTreeLeafPreimage(PublicDataTreeLeaf.buildDummy(BigInt(Math.floor(Math.random()*1e3))),Fr.random(),BigInt(Math.floor(Math.random()*1e3)))}static empty(){return new _PublicDataTreeLeafPreimage(PublicDataTreeLeaf.empty(),Fr.ZERO,0n)}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _PublicDataTreeLeafPreimage(PublicDataTreeLeaf.fromBuffer(reader),Fr.fromBuffer(reader),toBigIntBE(reader.readBytes(32)))}static fromLeaf(leaf,nextKey,nextIndex){return new _PublicDataTreeLeafPreimage(leaf,new Fr(nextKey),nextIndex)}static clone(preimage){return preimage.clone()}},PublicDataTreeLeaf=class _PublicDataTreeLeaf{static{__name(this,"PublicDataTreeLeaf")}slot;value;constructor(slot,value){this.slot=slot,this.value=value}getKey(){return this.slot.toBigInt()}toBuffer(){return serializeToBuffer([this.slot,this.value])}clone(){return new _PublicDataTreeLeaf(this.slot,this.value)}toHashInputs(){return[this.slot.toBuffer(),this.value.toBuffer()]}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _PublicDataTreeLeaf(Fr.fromBuffer(reader),Fr.fromBuffer(reader))}equals(another){return this.slot.equals(another.slot)&&this.value.equals(another.value)}toString(){return`PublicDataTreeLeaf(${this.slot.toString()}, ${this.value.toString()})`}isEmpty(){return this.slot.isZero()&&this.value.isZero()}updateTo(another){if(!this.slot.equals(another.slot))throw new Error("Invalid update: slots do not match");return new _PublicDataTreeLeaf(this.slot,another.value)}static buildDummy(key){return new _PublicDataTreeLeaf(new Fr(key),new Fr(0))}static empty(){return new _PublicDataTreeLeaf(Fr.ZERO,Fr.ZERO)}static get schema(){return external_exports.object({slot:schemas.Fr,value:schemas.Fr}).transform(({slot,value})=>new _PublicDataTreeLeaf(slot,value))}static fromPlainObject(obj){return obj instanceof _PublicDataTreeLeaf?obj:new _PublicDataTreeLeaf(Fr.fromPlainObject(obj.slot),Fr.fromPlainObject(obj.value))}};var PublicDataWitness=class _PublicDataWitness{static{__name(this,"PublicDataWitness")}index;leafPreimage;siblingPath;constructor(index,leafPreimage,siblingPath){this.index=index,this.leafPreimage=leafPreimage,this.siblingPath=siblingPath}static get schema(){return external_exports.object({index:schemas2.BigInt,leafPreimage:PublicDataTreeLeafPreimage.schema,siblingPath:SiblingPath.schemaFor(40)}).transform(({index,leafPreimage,siblingPath})=>new _PublicDataWitness(index,leafPreimage,siblingPath))}toBuffer(){return serializeToBuffer([this.index,this.leafPreimage,this.siblingPath])}toString(){return bufferToHex(this.toBuffer())}static random(){return new _PublicDataWitness(BigInt(Math.floor(Math.random()*1e3)),PublicDataTreeLeafPreimage.random(),SiblingPath.random(40))}withoutPreimage(){return new MembershipWitness(40,this.index,this.siblingPath.toTuple())}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _PublicDataWitness(toBigIntBE(reader.readBytes(32)),reader.readObject(PublicDataTreeLeafPreimage),SiblingPath.fromBuffer(reader.readBytes(1284)))}static fromString(str){return _PublicDataWitness.fromBuffer(hexToBuffer(str))}};var ValidatorStatusInSlotSchema=zodFor()(external_exports.enum(["checkpoint-mined","checkpoint-valid","checkpoint-invalid","checkpoint-unvalidated","checkpoint-missed","blocks-missed","attestation-sent","attestation-missed"])),ValidatorStatusHistorySchema=zodFor()(external_exports.array(external_exports.object({slot:schemas.SlotNumber,status:ValidatorStatusInSlotSchema}))),ValidatorStatusHistorySchemaArray=external_exports.array(ValidatorStatusHistorySchema),ValidatorStatusHistorySchemaMap=external_exports.record(external_exports.string(),ValidatorStatusHistorySchemaArray),ValidatorTimeStatSchema=external_exports.object({timestamp:schemas.BigInt,slot:schemas.SlotNumber,date:external_exports.string()}),ValidatorMissedStatsSchema=zodFor()(external_exports.object({currentStreak:schemas.Integer,rate:external_exports.number().optional(),count:schemas.Integer,total:schemas.Integer})),ValidatorStatsSchema=zodFor()(external_exports.object({address:schemas.EthAddress,lastProposal:ValidatorTimeStatSchema.optional(),lastAttestation:ValidatorTimeStatSchema.optional(),totalSlots:schemas.Integer,missedProposals:ValidatorMissedStatsSchema,missedAttestations:ValidatorMissedStatsSchema,history:ValidatorStatusHistorySchema})),ValidatorsStatsSchema=zodFor()(external_exports.object({stats:external_exports.record(external_exports.string(),ValidatorStatsSchema),lastProcessedSlot:schemas.SlotNumber.optional(),initialSlot:schemas.SlotNumber.optional(),slotWindow:schemas.Integer})),SingleValidatorStatsSchema=zodFor()(external_exports.object({validator:ValidatorStatsSchema,allTimeEpochPerformance:external_exports.array(external_exports.object({missed:schemas.Integer,total:schemas.Integer,epoch:schemas.EpochNumber})),lastProcessedSlot:schemas.SlotNumber.optional(),initialSlot:schemas.SlotNumber.optional(),slotWindow:schemas.Integer}));var AllowedElementSchema=zodFor()(external_exports.union([external_exports.object({address:schemas2.AztecAddress,selector:schemas2.FunctionSelector,onlySelf:external_exports.boolean().optional(),rejectNullMsgSender:external_exports.boolean().optional(),calldataLength:external_exports.number().optional()}),external_exports.object({classId:schemas2.Fr,selector:schemas2.FunctionSelector,onlySelf:external_exports.boolean().optional(),rejectNullMsgSender:external_exports.boolean().optional(),calldataLength:external_exports.number().optional()})]));var L1PublishInfoSchema=external_exports.union([external_exports.object({published:external_exports.literal(!1)}),external_exports.object({published:external_exports.literal(!0),blockNumber:schemas.BigInt,timestamp:schemas.BigInt,blockHash:external_exports.string()})]);function l1PublishInfoFromL1PublishedData(data){return data?{published:!0,blockNumber:data.blockNumber,timestamp:data.timestamp,blockHash:data.blockHash}:{published:!1}}__name(l1PublishInfoFromL1PublishedData,"l1PublishInfoFromL1PublishedData");var BlockIncludeOptionsSchema=external_exports.object({includeTransactions:external_exports.boolean().optional(),includeL1PublishInfo:external_exports.boolean().optional(),includeAttestations:external_exports.boolean().optional()}),BlocksIncludeOptionsSchema=external_exports.object({includeTransactions:external_exports.boolean().optional(),includeL1PublishInfo:external_exports.boolean().optional(),includeAttestations:external_exports.boolean().optional(),onlyCheckpointed:external_exports.boolean().optional()}),BlockResponseSchema=external_exports.object({header:BlockHeader.schema,archive:AppendOnlyTreeSnapshot.schema,hash:BlockHash.schema,checkpointNumber:CheckpointNumberSchema,indexWithinCheckpoint:IndexWithinCheckpointSchema,number:BlockNumberSchema,body:Body.schema.optional(),l1:L1PublishInfoSchema.optional(),attestations:external_exports.array(CommitteeAttestation.schema).optional()});var CheckpointTagSchema=external_exports.union([external_exports.literal("checkpointed"),external_exports.literal("proven"),external_exports.literal("finalized")]);var CheckpointParameterSchema=external_exports.union([external_exports.object({number:CheckpointNumberSchema}).strict(),external_exports.object({slot:SlotNumberSchema}).strict(),CheckpointTagSchema,CheckpointNumberSchema]);var CheckpointIncludeOptionsSchema=external_exports.object({includeBlocks:external_exports.boolean().optional(),includeTransactions:external_exports.boolean().optional(),includeL1PublishInfo:external_exports.boolean().optional(),includeAttestations:external_exports.boolean().optional()}),CheckpointResponseSchema=external_exports.object({number:CheckpointNumberSchema,header:CheckpointHeader.schema,archive:AppendOnlyTreeSnapshot.schema,checkpointOutHash:schemas.Fr,startBlock:BlockNumberSchema,blockCount:external_exports.number(),feeAssetPriceModifier:schemas.BigInt,blocks:external_exports.array(BlockResponseSchema).optional(),l1:L1PublishInfoSchema.optional(),attestations:external_exports.array(CommitteeAttestation.schema).optional()});var GetTxByHashOptionsSchema=external_exports.object({includeProof:external_exports.boolean().optional()});var PeerInfoSchema=external_exports.discriminatedUnion("status",[external_exports.object({status:external_exports.literal("connected"),score:external_exports.number(),id:external_exports.string()}),external_exports.object({status:external_exports.literal("dialing"),dialStatus:external_exports.string(),id:external_exports.string(),addresses:external_exports.array(external_exports.string())}),external_exports.object({status:external_exports.literal("cached"),id:external_exports.string(),addresses:external_exports.array(external_exports.string()),enr:external_exports.string(),dialAttempts:external_exports.number()})]),MAX_PROPOSALS_FOR_SLOT_RPC_LEN=256,BlockProposalSchema=bufferSchemaFor(BlockProposal),CheckpointProposalSchema=bufferSchemaFor(CheckpointProposal),ProposalsForSlotSchema=external_exports.object({blockProposals:external_exports.array(BlockProposalSchema).max(MAX_PROPOSALS_FOR_SLOT_RPC_LEN),checkpointProposals:external_exports.array(CheckpointProposalSchema).max(MAX_PROPOSALS_FOR_SLOT_RPC_LEN)}),P2PApiSchema={getCheckpointAttestationsForSlot:external_exports.function({input:external_exports.tuple([schemas2.SlotNumber,optional2(external_exports.string().regex(/^0x[0-9a-fA-F]+$/))]),output:external_exports.array(CheckpointAttestation.schema)}),getPendingTxs:external_exports.function({input:external_exports.tuple([optional2(external_exports.number().gte(1).lte(50).default(50)),optional2(TxHash.schema),optional2(GetTxByHashOptionsSchema)]),output:external_exports.array(Tx.schema)}),getPendingTxCount:external_exports.function({input:external_exports.tuple([]),output:schemas2.Integer}),getEncodedEnr:external_exports.function({input:external_exports.tuple([]),output:external_exports.string().optional()}),getPeers:external_exports.function({input:external_exports.tuple([optional2(external_exports.boolean())]),output:external_exports.array(PeerInfoSchema)})};var WorldStateSyncStatusSchema=external_exports.object({finalizedBlockNumber:BlockNumberSchema,latestBlockNumber:BlockNumberSchema,latestBlockHash:external_exports.string(),oldestHistoricBlockNumber:BlockNumberSchema,treesAreSynched:external_exports.boolean()});var AztecNodeApiSchema={getWorldStateSyncStatus:external_exports.function({input:external_exports.tuple([]),output:WorldStateSyncStatusSchema}),findLeavesIndexes:external_exports.function({input:external_exports.tuple([BlockParameterSchema,external_exports.nativeEnum(MerkleTreeId),external_exports.array(schemas2.Fr).max(100)]),output:external_exports.array(optional2(dataInBlockSchemaFor(schemas2.BigInt)))}),getNullifierMembershipWitness:external_exports.function({input:external_exports.tuple([BlockParameterSchema,schemas2.Fr]),output:NullifierMembershipWitness.schema.optional()}),getLowNullifierMembershipWitness:external_exports.function({input:external_exports.tuple([BlockParameterSchema,schemas2.Fr]),output:NullifierMembershipWitness.schema.optional()}),getPublicDataWitness:external_exports.function({input:external_exports.tuple([BlockParameterSchema,schemas2.Fr]),output:PublicDataWitness.schema.optional()}),getBlockHashMembershipWitness:external_exports.function({input:external_exports.tuple([BlockParameterSchema,BlockHash.schema]),output:MembershipWitness.schemaFor(30).optional()}),getNoteHashMembershipWitness:external_exports.function({input:external_exports.tuple([BlockParameterSchema,schemas2.Fr]),output:MembershipWitness.schemaFor(42).optional()}),getL1ToL2MessageMembershipWitness:external_exports.function({input:external_exports.tuple([BlockParameterSchema,schemas2.Fr]),output:external_exports.tuple([schemas2.BigInt,SiblingPath.schemaFor(36)]).optional()}),getL1ToL2MessageCheckpoint:external_exports.function({input:external_exports.tuple([schemas2.Fr]),output:CheckpointNumberSchema.optional()}),getL2ToL1Messages:external_exports.function({input:external_exports.tuple([EpochNumberSchema]),output:external_exports.array(external_exports.array(external_exports.array(external_exports.array(schemas2.Fr))))}),getL2ToL1MembershipWitness:external_exports.function({input:external_exports.tuple([TxHash.schema,schemas2.Fr,optional2(schemas2.Integer)]),output:L2ToL1MembershipWitnessSchema.optional()}),getBlockNumber:external_exports.function({input:external_exports.tuple([optional2(BlockTagWithoutLatestSchema)]),output:BlockNumberSchema}),getCheckpointNumber:external_exports.function({input:external_exports.tuple([optional2(CheckpointTagSchema)]),output:CheckpointNumberSchema}),getChainTips:external_exports.function({input:external_exports.tuple([]),output:L2TipsSchema}),getL1Constants:external_exports.function({input:external_exports.tuple([]),output:L1RollupConstantsSchema}),getSyncedL2SlotNumber:external_exports.function({input:external_exports.tuple([]),output:SlotNumberSchema.optional()}),getSyncedL2EpochNumber:external_exports.function({input:external_exports.tuple([]),output:EpochNumberSchema.optional()}),getSyncedL1Timestamp:external_exports.function({input:external_exports.tuple([]),output:schemas2.BigInt.optional()}),getCheckpointsData:external_exports.function({input:external_exports.tuple([CheckpointsQuerySchema]),output:external_exports.array(CheckpointDataSchema)}),getBlock:external_exports.function({input:external_exports.tuple([BlockParameterSchema,optional2(BlockIncludeOptionsSchema)]),output:BlockResponseSchema.optional()}),getBlockData:external_exports.function({input:external_exports.tuple([BlockParameterSchema]),output:BlockDataSchema.optional()}),getBlocks:external_exports.function({input:external_exports.tuple([BlockNumberPositiveSchema,external_exports.number().gt(0).lte(50),optional2(BlocksIncludeOptionsSchema)]),output:external_exports.array(BlockResponseSchema)}),getCheckpoint:external_exports.function({input:external_exports.tuple([CheckpointParameterSchema,optional2(CheckpointIncludeOptionsSchema)]),output:CheckpointResponseSchema.optional()}),getCheckpoints:external_exports.function({input:external_exports.tuple([CheckpointNumberPositiveSchema,external_exports.number().gt(0).lte(50),optional2(CheckpointIncludeOptionsSchema)]),output:external_exports.array(CheckpointResponseSchema)}),isReady:external_exports.function({input:external_exports.tuple([]),output:external_exports.boolean()}),getNodeInfo:external_exports.function({input:external_exports.tuple([]),output:NodeInfoSchema}),getCurrentMinFees:external_exports.function({input:external_exports.tuple([]),output:GasFees.schema}),getPredictedMinFees:external_exports.function({input:external_exports.tuple([optional2(external_exports.nativeEnum(ManaUsageEstimate))]),output:external_exports.array(GasFees.schema)}),getMaxPriorityFees:external_exports.function({input:external_exports.tuple([]),output:GasFees.schema}),getNodeVersion:external_exports.function({input:external_exports.tuple([]),output:external_exports.string()}),getVersion:external_exports.function({input:external_exports.tuple([]),output:external_exports.number()}),getChainId:external_exports.function({input:external_exports.tuple([]),output:external_exports.number()}),getL1ContractAddresses:external_exports.function({input:external_exports.tuple([]),output:L1ContractAddressesSchema2}),getProtocolContractAddresses:external_exports.function({input:external_exports.tuple([]),output:ProtocolContractAddressesSchema}),getPrivateLogsByTags:external_exports.function({input:external_exports.tuple([PrivateLogsQuerySchema]),output:external_exports.array(external_exports.array(LogResultSchema))}),getPublicLogsByTags:external_exports.function({input:external_exports.tuple([PublicLogsQuerySchema]),output:external_exports.array(external_exports.array(LogResultSchema))}),sendTx:external_exports.function({input:external_exports.tuple([Tx.schema]),output:external_exports.void()}),getTxReceipt:external_exports.function({input:external_exports.tuple([TxHash.schema,optional2(GetTxReceiptOptionsSchema)]),output:TxReceiptSchema}),getTxEffect:external_exports.function({input:external_exports.tuple([TxHash.schema]),output:indexedTxSchema().optional()}),getPendingTxs:external_exports.function({input:external_exports.tuple([optional2(external_exports.number().gte(1).lte(50).default(50)),optional2(TxHash.schema),optional2(GetTxByHashOptionsSchema)]),output:external_exports.array(Tx.schema)}),getPendingTxCount:external_exports.function({input:external_exports.tuple([]),output:external_exports.number()}),getTxByHash:external_exports.function({input:external_exports.tuple([TxHash.schema,optional2(GetTxByHashOptionsSchema)]),output:Tx.schema.optional()}),getTxsByHash:external_exports.function({input:external_exports.tuple([external_exports.array(TxHash.schema).max(50),optional2(GetTxByHashOptionsSchema)]),output:external_exports.array(Tx.schema)}),getPublicStorageAt:external_exports.function({input:external_exports.tuple([BlockParameterSchema,schemas2.AztecAddress,schemas2.Fr]),output:schemas2.Fr}),getValidatorsStats:external_exports.function({input:external_exports.tuple([]),output:ValidatorsStatsSchema}),getValidatorStats:external_exports.function({input:external_exports.tuple([schemas2.EthAddress,optional2(schemas2.SlotNumber),optional2(schemas2.SlotNumber)]),output:SingleValidatorStatsSchema.optional()}),simulatePublicCalls:external_exports.function({input:external_exports.tuple([Tx.schema,optional2(external_exports.boolean()),optional2(SimulationOverrides.schema)]),output:PublicSimulationOutput.schema}),isValidTx:external_exports.function({input:external_exports.tuple([Tx.schema,optional2(external_exports.object({isSimulation:optional2(external_exports.boolean()).optional(),skipFeeEnforcement:optional2(external_exports.boolean()).optional()}))]),output:TxValidationResultSchema}),getContractClass:external_exports.function({input:external_exports.tuple([schemas2.Fr]),output:ContractClassPublicSchema.optional()}),getContract:external_exports.function({input:external_exports.tuple([schemas2.AztecAddress,optional2(BlockParameterSchema)]),output:ContractInstanceWithAddressSchema.optional()}),getEncodedEnr:external_exports.function({input:external_exports.tuple([]),output:external_exports.string().optional()}),getAllowedPublicSetup:external_exports.function({input:external_exports.tuple([]),output:external_exports.array(AllowedElementSchema)}),getPeers:external_exports.function({input:external_exports.tuple([optional2(external_exports.boolean())]),output:external_exports.array(PeerInfoSchema)}),getCheckpointAttestationsForSlot:external_exports.function({input:external_exports.tuple([schemas2.SlotNumber,optional2(external_exports.string().regex(/^0x[0-9a-fA-F]+$/))]),output:external_exports.array(CheckpointAttestation.schema)}),getProposalsForSlot:external_exports.function({input:external_exports.tuple([schemas2.SlotNumber]),output:ProposalsForSlotSchema})};var OffenseType=(function(OffenseType3){return OffenseType3[OffenseType3.UNKNOWN=0]="UNKNOWN",OffenseType3[OffenseType3.DATA_WITHHOLDING=1]="DATA_WITHHOLDING",OffenseType3[OffenseType3.INACTIVITY=3]="INACTIVITY",OffenseType3[OffenseType3.BROADCASTED_INVALID_BLOCK_PROPOSAL=4]="BROADCASTED_INVALID_BLOCK_PROPOSAL",OffenseType3[OffenseType3.PROPOSED_INSUFFICIENT_ATTESTATIONS=5]="PROPOSED_INSUFFICIENT_ATTESTATIONS",OffenseType3[OffenseType3.PROPOSED_INCORRECT_ATTESTATIONS=6]="PROPOSED_INCORRECT_ATTESTATIONS",OffenseType3[OffenseType3.PROPOSED_DESCENDANT_OF_CHECKPOINT_WITH_INVALID_ATTESTATIONS=7]="PROPOSED_DESCENDANT_OF_CHECKPOINT_WITH_INVALID_ATTESTATIONS",OffenseType3[OffenseType3.DUPLICATE_PROPOSAL=8]="DUPLICATE_PROPOSAL",OffenseType3[OffenseType3.DUPLICATE_ATTESTATION=9]="DUPLICATE_ATTESTATION",OffenseType3[OffenseType3.ATTESTED_TO_INVALID_CHECKPOINT_PROPOSAL=10]="ATTESTED_TO_INVALID_CHECKPOINT_PROPOSAL",OffenseType3[OffenseType3.BROADCASTED_INVALID_CHECKPOINT_PROPOSAL=11]="BROADCASTED_INVALID_CHECKPOINT_PROPOSAL",OffenseType3})({});var OffenseTypeSchema=external_exports.nativeEnum(OffenseType);var OffenseSchema=zodFor()(external_exports.object({validator:schemas2.EthAddress,amount:schemas2.BigInt,offenseType:OffenseTypeSchema,epochOrSlot:schemas2.BigInt}));var ArchiverSpecificConfigSchema=external_exports.object({archiverPollingIntervalMS:schemas2.Integer.optional(),archiverBatchSize:schemas2.Integer.optional(),viemPollingIntervalMS:schemas2.Integer.optional(),archiverStoreMapSizeKb:schemas2.Integer.optional(),maxAllowedEthClientDriftSeconds:schemas2.Integer.optional(),ethereumAllowNoDebugHosts:external_exports.boolean().optional(),archiverSkipHistoricalLogsCheck:external_exports.boolean().optional(),skipValidateCheckpointAttestations:external_exports.boolean().optional(),skipPromoteProposedCheckpointDuringL1Sync:external_exports.boolean().optional(),orphanPruneNoProposalTolerance:schemas2.Integer.optional(),skipOrphanProposedBlockPruning:external_exports.boolean().optional()}),ArchiverApiSchema={getRollupAddress:external_exports.function({input:external_exports.tuple([]),output:schemas2.EthAddress}),getRegistryAddress:external_exports.function({input:external_exports.tuple([]),output:schemas2.EthAddress}),getBlockNumber:external_exports.function({input:external_exports.tuple([optional2(BlockQuerySchema)]),output:BlockNumberSchema.optional()}),getCheckpointNumber:external_exports.function({input:external_exports.tuple([]),output:CheckpointNumberSchema}),getCheckpoint:external_exports.function({input:external_exports.tuple([CheckpointQuerySchema]),output:PublishedCheckpoint.schema.optional()}),getCheckpoints:external_exports.function({input:external_exports.tuple([CheckpointsQuerySchema]),output:external_exports.array(PublishedCheckpoint.schema)}),getCheckpointData:external_exports.function({input:external_exports.tuple([CheckpointQuerySchema]),output:CheckpointDataSchema.optional()}),getCheckpointsData:external_exports.function({input:external_exports.tuple([CheckpointsQuerySchema]),output:external_exports.array(CheckpointDataSchema)}),getTxEffect:external_exports.function({input:external_exports.tuple([TxHash.schema]),output:indexedTxSchema().optional()}),getL2ToL1MembershipWitness:external_exports.function({input:external_exports.tuple([TxHash.schema,schemas2.Fr,optional2(schemas2.Integer)]),output:L2ToL1MembershipWitnessSchema.optional()}),getSyncedL2SlotNumber:external_exports.function({input:external_exports.tuple([]),output:schemas2.SlotNumber.optional()}),getSyncedL2EpochNumber:external_exports.function({input:external_exports.tuple([]),output:EpochNumberSchema.optional()}),getBlocksForSlot:external_exports.function({input:external_exports.tuple([schemas2.SlotNumber]),output:external_exports.array(L2Block.schema)}),isEpochComplete:external_exports.function({input:external_exports.tuple([EpochNumberSchema]),output:external_exports.boolean()}),getL2Tips:external_exports.function({input:external_exports.tuple([]),output:L2TipsSchema}),getPrivateLogsByTags:external_exports.function({input:external_exports.tuple([PrivateLogsQuerySchema]),output:external_exports.array(external_exports.array(LogResultSchema))}),getPublicLogsByTags:external_exports.function({input:external_exports.tuple([PublicLogsQuerySchema]),output:external_exports.array(external_exports.array(LogResultSchema))}),getContractClass:external_exports.function({input:external_exports.tuple([schemas2.Fr]),output:ContractClassPublicSchema.optional()}),getBytecodeCommitment:external_exports.function({input:external_exports.tuple([schemas2.Fr]),output:schemas2.Fr}),getContract:external_exports.function({input:external_exports.tuple([schemas2.AztecAddress,schemas2.BigInt]),output:ContractInstanceWithAddressSchema.optional()}),getContractClassIds:external_exports.function({input:external_exports.tuple([]),output:external_exports.array(schemas2.Fr)}),registerContractFunctionSignatures:external_exports.function({input:external_exports.tuple([external_exports.array(external_exports.string())]),output:external_exports.void()}),getL1ToL2Messages:external_exports.function({input:external_exports.tuple([CheckpointNumberSchema]),output:external_exports.array(schemas2.Fr)}),getL1ToL2MessageIndex:external_exports.function({input:external_exports.tuple([schemas2.Fr]),output:schemas2.BigInt.optional()}),getDebugFunctionName:external_exports.function({input:external_exports.tuple([schemas2.AztecAddress,schemas2.FunctionSelector]),output:optional2(external_exports.string())}),getL1Constants:external_exports.function({input:external_exports.tuple([]),output:L1RollupConstantsSchema}),isPruneDueAtSlot:external_exports.function({input:external_exports.tuple([schemas2.SlotNumber]),output:external_exports.boolean()}),getGenesisValues:external_exports.function({input:external_exports.tuple([]),output:external_exports.object({genesisArchiveRoot:schemas2.Fr})}),getL1Timestamp:external_exports.function({input:external_exports.tuple([]),output:schemas2.BigInt.optional()}),getProposedCheckpointData:external_exports.function({input:external_exports.tuple([optional2(ProposedCheckpointQuerySchema)]),output:ProposedCheckpointDataSchema.optional()}),syncImmediate:external_exports.function({input:external_exports.tuple([]),output:external_exports.void()}),isPendingChainInvalid:external_exports.function({input:external_exports.tuple([]),output:external_exports.boolean()}),getPendingChainValidationStatus:external_exports.function({input:external_exports.tuple([]),output:ValidateCheckpointResultSchema}),getBlock:external_exports.function({input:external_exports.tuple([BlockQuerySchema]),output:L2Block.schema.optional()}),getBlocks:external_exports.function({input:external_exports.tuple([BlocksQuerySchema]),output:external_exports.array(L2Block.schema)}),getBlockData:external_exports.function({input:external_exports.tuple([BlockQuerySchema]),output:BlockDataSchema.optional()}),getBlocksData:external_exports.function({input:external_exports.tuple([BlocksQuerySchema]),output:external_exports.array(BlockDataSchema)})};var SequencerConfigSchema=zodFor()(external_exports.object({sequencerPollingIntervalMS:external_exports.number().optional(),maxTxsPerBlock:external_exports.number().optional(),maxTxsPerCheckpoint:external_exports.number().optional(),maxBlocksPerCheckpoint:external_exports.number().positive().optional(),minValidTxsPerBlock:external_exports.number().optional(),minTxsPerBlock:external_exports.number().optional(),maxL2BlockGas:external_exports.number().optional(),publishTxsWithProposals:external_exports.boolean().optional(),maxDABlockGas:external_exports.number().optional(),perBlockAllocationMultiplier:external_exports.number().optional(),perBlockDAAllocationMultiplier:external_exports.number().optional(),redistributeCheckpointBudget:external_exports.boolean().optional(),coinbase:schemas2.EthAddress.optional(),feeRecipient:schemas2.AztecAddress.optional(),acvmWorkingDirectory:external_exports.string().optional(),acvmBinaryPath:external_exports.string().optional(),txPublicSetupAllowListExtend:external_exports.array(AllowedElementSchema).optional(),governanceProposerPayload:schemas2.EthAddress.optional(),minBlockDuration:external_exports.number().positive().optional(),checkpointProposalPrepareTime:external_exports.number().nonnegative().optional(),l1PublishingTime:external_exports.number().optional(),fakeProcessingDelayPerTxMs:external_exports.number().optional(),fakeThrowAfterProcessingTxCount:external_exports.number().optional(),attestationPropagationTime:external_exports.number().optional(),skipCollectingAttestations:external_exports.boolean().optional(),skipInvalidateBlockAsProposer:external_exports.boolean().optional(),skipWaitForValidParentCheckpointOnL1:external_exports.boolean().optional(),secondsBeforeInvalidatingBlockAsCommitteeMember:external_exports.number(),secondsBeforeInvalidatingBlockAsNonCommitteeMember:external_exports.number(),broadcastInvalidBlockProposal:external_exports.boolean().optional(),invalidBlockProposalIndexWithinCheckpoint:external_exports.number().int().nonnegative().optional(),broadcastInvalidCheckpointProposalOnly:external_exports.boolean().optional(),injectFakeAttestation:external_exports.boolean().optional(),injectHighSValueAttestation:external_exports.boolean().optional(),injectUnrecoverableSignatureAttestation:external_exports.boolean().optional(),injectYParityAttestation:external_exports.boolean().optional(),fishermanMode:external_exports.boolean().optional(),shuffleAttestationOrdering:external_exports.boolean().optional(),blockDurationMs:external_exports.number().positive().optional(),checkpointProposalSyncGraceSeconds:external_exports.number().nonnegative().optional(),expectedBlockProposalsPerSlot:external_exports.number().nonnegative().optional(),buildCheckpointIfEmpty:external_exports.boolean().optional(),skipPushProposedBlocksToArchiver:external_exports.boolean().optional(),minBlocksForCheckpoint:external_exports.number().positive().optional(),skipPublishingCheckpointsPercent:external_exports.number().gte(0).lte(100).optional(),skipBroadcastProposals:external_exports.boolean().optional(),skipBroadcastCheckpointProposal:external_exports.boolean().optional(),pauseProposingForSlots:external_exports.array(SlotNumberSchema).optional()}));var ProverConfigSchema=zodFor()(external_exports.object({nodeUrl:external_exports.string().optional(),realProofs:external_exports.boolean(),proverId:schemas2.EthAddress.optional(),proverTestDelayType:external_exports.enum(["fixed","realistic"]),proverTestDelayMs:external_exports.number(),proverTestDelayFactor:external_exports.number(),proverAgentCount:external_exports.number(),proofStore:external_exports.string().optional(),failedProofStore:external_exports.string().optional(),cancelJobsOnStop:external_exports.boolean(),enqueueConcurrency:external_exports.number()})),proverConfigMappings={nodeUrl:{env:"AZTEC_NODE_URL",description:"The URL to the Aztec node to take proving jobs from"},realProofs:{env:"PROVER_REAL_PROOFS",description:"Whether to construct real proofs",...booleanConfigHelper(!0)},proverId:{env:"PROVER_ID",parseEnv:__name(val=>parseProverId(val),"parseEnv"),description:"Hex value that identifies the prover. Defaults to the address used for submitting proofs if not set."},proverTestDelayType:{env:"PROVER_TEST_DELAY_TYPE",description:"The type of artificial delay to introduce"},proverTestDelayMs:{env:"PROVER_TEST_DELAY_MS",description:"Artificial delay to introduce to all operations to the test prover.",...numberConfigHelper(0)},proverTestDelayFactor:{env:"PROVER_TEST_DELAY_FACTOR",description:"If using realistic delays, what percentage of realistic times to apply.",...numberConfigHelper(1)},proverAgentCount:{env:"PROVER_AGENT_COUNT",description:"The number of prover agents to start",...numberConfigHelper(1)},proofStore:{env:"PROVER_PROOF_STORE",description:"Optional proof input store for the prover"},failedProofStore:{env:"PROVER_FAILED_PROOF_STORE",description:"Store for failed proof inputs. Google cloud storage is only supported at the moment. Set this value as gs://bucket-name/path/to/store."},cancelJobsOnStop:{env:"PROVER_CANCEL_JOBS_ON_STOP",description:"Whether to abort pending proving jobs when the orchestrator is cancelled. When false (default), jobs remain in the broker queue and can be reused on restart/reorg. When true, jobs are explicitly cancelled with the broker, which prevents reuse.",...booleanConfigHelper(!1)},enqueueConcurrency:{env:"PROVER_ENQUEUE_CONCURRENCY",description:"Max concurrent jobs the orchestrator serializes and enqueues to the broker.",...numberConfigHelper(50)}};function parseProverId(str){return EthAddress.fromString(str)}__name(parseProverId,"parseProverId");var SlasherConfigSchema=zodFor()(external_exports.object({slashOverridePayload:schemas.EthAddress.optional(),slashValidatorsAlways:external_exports.array(schemas.EthAddress),slashValidatorsNever:external_exports.array(schemas.EthAddress),slashDataWithholdingPenalty:schemas.BigInt,slashDataWithholdingToleranceSlots:external_exports.number().default(3),slashInactivityTargetPercentage:external_exports.number(),slashInactivityConsecutiveEpochThreshold:external_exports.number(),slashInactivityPenalty:schemas.BigInt,slashProposeInvalidAttestationsPenalty:schemas.BigInt,slashBroadcastedInvalidCheckpointProposalPenalty:schemas.BigInt.default(0n),slashDuplicateProposalPenalty:schemas.BigInt,slashDuplicateAttestationPenalty:schemas.BigInt,slashProposeDescendantOfCheckpointWithInvalidAttestationsPenalty:schemas.BigInt,slashAttestInvalidCheckpointProposalPenalty:schemas.BigInt,slashUnknownPenalty:schemas.BigInt,slashOffenseExpirationRounds:external_exports.number(),slashMaxPayloadSize:external_exports.number(),slashGracePeriodL2Slots:external_exports.number(),slashBroadcastedInvalidBlockPenalty:schemas.BigInt,slashExecuteRoundsLookBack:external_exports.number(),slashSelfAllowed:external_exports.boolean().optional()}));var ValidatorClientConfigSchema=zodFor()(ValidatorHASignerConfigSchema.merge(LocalSignerConfigSchema).extend({l1ChainId:external_exports.number().int().nonnegative(),validatorAddresses:external_exports.array(schemas.EthAddress).optional(),disableValidator:external_exports.boolean(),disabledValidators:external_exports.array(schemas.EthAddress),attestationPollingIntervalMs:external_exports.number().min(0),alwaysReexecuteBlockProposals:external_exports.boolean().optional(),fishermanMode:external_exports.boolean().optional(),skipCheckpointProposalValidation:external_exports.boolean().optional(),skipPushProposedBlocksToArchiver:external_exports.boolean().optional(),attestToEquivocatedProposals:external_exports.boolean().optional(),skipProposalSlotValidation:external_exports.boolean().optional(),validateMaxL2BlockGas:external_exports.number().optional(),validateMaxDABlockGas:external_exports.number().optional(),validateMaxTxsPerBlock:external_exports.number().optional(),validateMaxTxsPerCheckpoint:external_exports.number().optional()})),ValidatorClientFullConfigSchema=zodFor()(ValidatorClientConfigSchema.extend({txPublicSetupAllowListExtend:external_exports.array(AllowedElementSchema).optional(),broadcastInvalidBlockProposal:external_exports.boolean().optional(),blockDurationMs:external_exports.number().positive(),maxBlocksPerCheckpoint:external_exports.number().positive().optional(),slashBroadcastedInvalidBlockPenalty:schemas.BigInt,slashBroadcastedInvalidCheckpointProposalPenalty:schemas.BigInt,slashDuplicateProposalPenalty:schemas.BigInt,slashDuplicateAttestationPenalty:schemas.BigInt,slashAttestInvalidCheckpointProposalPenalty:schemas.BigInt,disableTransactions:external_exports.boolean().optional(),maxGossipClockDisparityMs:external_exports.number().optional()}));var AztecNodeAdminConfigSchema=SequencerConfigSchema.merge(ProverConfigSchema).merge(SlasherConfigSchema).merge(ValidatorClientFullConfigSchema.omit({rollupAddress:!0})).merge(ArchiverSpecificConfigSchema.pick({archiverPollingIntervalMS:!0,archiverBatchSize:!0,skipValidateCheckpointAttestations:!0})).merge(external_exports.object({maxPendingTxCount:external_exports.number(),skipIncomingProposals:external_exports.boolean().optional()})),AztecNodeAdminApiSchema={getConfig:external_exports.function({input:external_exports.tuple([]),output:AztecNodeAdminConfigSchema}),setConfig:external_exports.function({input:external_exports.tuple([AztecNodeAdminConfigSchema.partial()]),output:external_exports.void()}),startSnapshotUpload:external_exports.function({input:external_exports.tuple([external_exports.string()]),output:external_exports.void()}),rollbackTo:external_exports.function({input:external_exports.tuple([external_exports.number(),optional2(external_exports.boolean()),optional2(external_exports.boolean())]),output:external_exports.void()}),pauseSync:external_exports.function({input:external_exports.tuple([]),output:external_exports.void()}),resumeSync:external_exports.function({input:external_exports.tuple([]),output:external_exports.void()}),pauseSequencer:external_exports.function({input:external_exports.tuple([]),output:external_exports.void()}),resumeSequencer:external_exports.function({input:external_exports.tuple([]),output:external_exports.void()}),getSlashOffenses:external_exports.function({input:external_exports.tuple([external_exports.union([external_exports.bigint(),external_exports.literal("all"),external_exports.literal("current")])]),output:external_exports.array(OffenseSchema)}),reloadKeystore:external_exports.function({input:external_exports.tuple([]),output:external_exports.void()})};var MAX_SIGNATURES_PER_REGISTER_CALL=100,MAX_SIGNATURE_LEN=1e4,AztecNodeDebugApiSchema={mineBlock:external_exports.function({input:external_exports.tuple([]),output:external_exports.void()}),prove:external_exports.function({input:external_exports.tuple([optional2(CheckpointNumberSchema)]),output:CheckpointNumberSchema}),warpL2TimeAtLeastTo:external_exports.function({input:external_exports.tuple([external_exports.number()]),output:external_exports.void()}),warpL2TimeAtLeastBy:external_exports.function({input:external_exports.tuple([external_exports.number()]),output:external_exports.void()}),registerContractFunctionSignatures:external_exports.function({input:external_exports.tuple([external_exports.array(external_exports.string().max(MAX_SIGNATURE_LEN)).max(MAX_SIGNATURES_PER_REGISTER_CALL)]),output:external_exports.void()})};var Comparator=(function(Comparator2){return Comparator2[Comparator2.EQ=1]="EQ",Comparator2[Comparator2.NEQ=2]="NEQ",Comparator2[Comparator2.LT=3]="LT",Comparator2[Comparator2.LTE=4]="LTE",Comparator2[Comparator2.GT=5]="GT",Comparator2[Comparator2.GTE=6]="GTE",Comparator2})({});var NoteDao=class _NoteDao{static{__name(this,"NoteDao")}note;contractAddress;owner;storageSlot;randomness;noteNonce;noteHash;siloedNullifier;txHash;l2BlockNumber;l2BlockHash;txIndexInBlock;noteIndexInTx;constructor(note,contractAddress,owner,storageSlot,randomness,noteNonce,noteHash,siloedNullifier,txHash,l2BlockNumber,l2BlockHash,txIndexInBlock,noteIndexInTx){this.note=note,this.contractAddress=contractAddress,this.owner=owner,this.storageSlot=storageSlot,this.randomness=randomness,this.noteNonce=noteNonce,this.noteHash=noteHash,this.siloedNullifier=siloedNullifier,this.txHash=txHash,this.l2BlockNumber=l2BlockNumber,this.l2BlockHash=l2BlockHash,this.txIndexInBlock=txIndexInBlock,this.noteIndexInTx=noteIndexInTx}toBuffer(){return serializeToBuffer([this.note,this.contractAddress,this.owner,this.storageSlot,this.randomness,this.noteNonce,this.noteHash,this.siloedNullifier,this.txHash,this.l2BlockNumber,Fr.fromHexString(this.l2BlockHash),this.txIndexInBlock,this.noteIndexInTx])}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer),note=Note.fromBuffer(reader),contractAddress=AztecAddress.fromBuffer(reader),owner=AztecAddress.fromBuffer(reader),storageSlot=Fr.fromBuffer(reader),randomness=Fr.fromBuffer(reader),noteNonce=Fr.fromBuffer(reader),noteHash=Fr.fromBuffer(reader),siloedNullifier=Fr.fromBuffer(reader),txHash=reader.readObject(TxHash),l2BlockNumber=BlockNumber(reader.readNumber()),l2BlockHash=Fr.fromBuffer(reader).toString(),txIndexInBlock=reader.readNumber(),noteIndexInTx=reader.readNumber();return new _NoteDao(note,contractAddress,owner,storageSlot,randomness,noteNonce,noteHash,siloedNullifier,txHash,l2BlockNumber,l2BlockHash,txIndexInBlock,noteIndexInTx)}toString(){return"0x"+this.toBuffer().toString("hex")}static fromString(str){let hex3=str.replace(/^0x/,"");return _NoteDao.fromBuffer(Buffer.from(hex3,"hex"))}equals(other){return this.note.equals(other.note)&&this.contractAddress.equals(other.contractAddress)&&this.owner.equals(other.owner)&&this.storageSlot.equals(other.storageSlot)&&this.randomness.equals(other.randomness)&&this.noteNonce.equals(other.noteNonce)&&this.noteHash.equals(other.noteHash)&&this.siloedNullifier.equals(other.siloedNullifier)&&this.txHash.equals(other.txHash)&&this.l2BlockNumber===other.l2BlockNumber&&this.l2BlockHash===other.l2BlockHash&&this.txIndexInBlock===other.txIndexInBlock&&this.noteIndexInTx===other.noteIndexInTx}getSize(){return this.toBuffer().length}static async random({note=Note.random(),contractAddress=void 0,owner=void 0,storageSlot=Fr.random(),randomness=Fr.random(),noteNonce=Fr.random(),noteHash=Fr.random(),siloedNullifier=Fr.random(),txHash=TxHash.random(),l2BlockNumber=BlockNumber(Math.floor(Math.random()*1e3)),l2BlockHash=Fr.random().toString(),txIndexInBlock=Math.floor(Math.random()*100),noteIndexInTx=Math.floor(Math.random()*100)}={}){return new _NoteDao(note,contractAddress??await AztecAddress.random(),owner??await AztecAddress.random(),storageSlot,randomness,noteNonce,noteHash,siloedNullifier,txHash,l2BlockNumber,l2BlockHash,txIndexInBlock,noteIndexInTx)}};var NoteStatus=(function(NoteStatus2){return NoteStatus2[NoteStatus2.ACTIVE=1]="ACTIVE",NoteStatus2[NoteStatus2.ACTIVE_OR_NULLIFIED=2]="ACTIVE_OR_NULLIFIED",NoteStatus2})({});var NoteService=class{static{__name(this,"NoteService")}noteStore;aztecNode;anchorBlockHeader;jobId;constructor(noteStore,aztecNode,anchorBlockHeader,jobId){this.noteStore=noteStore,this.aztecNode=aztecNode,this.anchorBlockHeader=anchorBlockHeader,this.jobId=jobId}async getNotes(contractAddress,owner,storageSlot,status,scopes){return(await this.noteStore.getNotes({contractAddress,owner,storageSlot,status,scopes},this.jobId)).map(({contractAddress:contractAddress2,owner:owner2,storageSlot:storageSlot2,randomness,noteNonce,note,noteHash,siloedNullifier})=>({contractAddress:contractAddress2,owner:owner2,storageSlot:storageSlot2,randomness,noteNonce,note,noteHash,isPending:!1,siloedNullifier}))}async syncNoteNullifiers(contractAddress,scopes){let anchorBlockHash=await this.anchorBlockHeader.hash(),contractNotes=await this.noteStore.getNotes({contractAddress,scopes},this.jobId);if(contractNotes.length===0)return;let nullifiersToCheck=contractNotes.map(note=>note.siloedNullifier),nullifierIndexes=await this.#findNullifierIndexes(anchorBlockHash,nullifiersToCheck),foundNullifiers=nullifiersToCheck.map((nullifier,i)=>{if(nullifierIndexes[i]!==void 0)return{...nullifierIndexes[i],data:nullifier}}).filter(nullifier=>nullifier!==void 0);await this.noteStore.applyNullifiers(foundNullifiers,this.jobId)}async validateAndStoreNotes(requests,scope,txEffects){if(requests.length===0)return;let anchorBlockNumber=this.anchorBlockHeader.getBlockNumber(),anchorBlockHash=await this.anchorBlockHeader.hash(),computed=await Promise.all(requests.map(async({contractAddress,noteHash,nullifier,noteNonce})=>{let[siloedNoteHash,siloedNullifier]=await Promise.all([siloNoteHash(contractAddress,noteHash),siloNullifier(contractAddress,nullifier)]);return{uniqueNoteHash:await computeUniqueNoteHash(noteNonce,siloedNoteHash),siloedNullifier}})),nullifierIndexes=await this.#findNullifierIndexes(anchorBlockHash,computed.map(c2=>c2.siloedNullifier)),noteDaos=[],foundNullifiers=[];for(let i=0;i<requests.length;i++){let{contractAddress,owner,storageSlot,randomness,noteNonce,content,noteHash,txHash}=requests[i],{uniqueNoteHash,siloedNullifier}=computed[i],nullifierIndex=nullifierIndexes[i],txEffect=txEffects.get(txHash.toString());if(!txEffect)throw new Error(`Could not find tx effect for tx hash ${txHash} when processing a note.`);if(txEffect.l2BlockNumber>anchorBlockNumber)throw new Error(`Obtained a newer tx effect for ${txHash} for a note validation request than the anchor block ${anchorBlockNumber}. This is a bug as we should not ever be processing a note from a newer block than the anchor block.`);let noteIndexInTx=txEffect.data.noteHashes.findIndex(nh=>nh.equals(uniqueNoteHash));if(noteIndexInTx===-1)throw new Error(`Note hash ${noteHash} (uniqued as ${uniqueNoteHash}) is not present in tx ${txHash}`);if(noteDaos.push(new NoteDao(new Note(content),contractAddress,owner,storageSlot,randomness,noteNonce,noteHash,siloedNullifier,txHash,txEffect.l2BlockNumber,txEffect.l2BlockHash.toString(),txEffect.txIndexInBlock,noteIndexInTx)),nullifierIndex!==void 0){let{data:_,...blockHashAndNum}=nullifierIndex;foundNullifiers.push({data:siloedNullifier,...blockHashAndNum})}}await this.noteStore.addNotes(noteDaos,scope,this.jobId),foundNullifiers.length>0&&await this.noteStore.applyNullifiers(foundNullifiers,this.jobId)}async#findNullifierIndexes(anchorBlockHash,siloedNullifiers){let batches=chunk(siloedNullifiers,100);return(await Promise.all(batches.map(batch=>this.aztecNode.findLeavesIndexes(anchorBlockHash,MerkleTreeId.NULLIFIER_TREE,batch)))).flat()}};async function syncScope(contractAddress,contractStore,contractClassService,anchorBlockHeader,functionToInvokeAfterSync,utilityExecutor,scope){if(isProtocolContract(contractAddress))return;let classId=await contractClassService.getCurrentClassId(contractAddress,anchorBlockHeader);if(!classId)throw new Error(`Cannot sync contract ${contractAddress}: its instance is not registered nor published.`);let syncStateFunctionCall=await contractStore.getFunctionCall("sync_state",[scope],contractAddress,classId);if(functionToInvokeAfterSync&&functionToInvokeAfterSync.equals(syncStateFunctionCall.selector))throw new Error("Forbidden `sync_state` invocation. `sync_state` can only be invoked by PXE, manual execution can lead to inconsistencies.");await utilityExecutor(syncStateFunctionCall,[scope])}__name(syncScope,"syncScope");var MAX_CONCURRENT_SCOPE_SYNCS=5,ContractSyncService=class{static{__name(this,"ContractSyncService")}aztecNode;contractStore;contractClassService;noteStore;log;storeName;syncedContracts;constructor(aztecNode,contractStore,contractClassService,noteStore,log2){this.aztecNode=aztecNode,this.contractStore=contractStore,this.contractClassService=contractClassService,this.noteStore=noteStore,this.log=log2,this.storeName="contract_sync",this.syncedContracts=new Map}async ensureContractSynced(contractAddress,functionToInvokeAfterSync,utilityExecutor,anchorBlockHeader,jobId,scopes){this.#startSyncIfNeeded(contractAddress,scopes,anchorBlockHeader,jobId,scope=>syncScope(contractAddress,this.contractStore,this.contractClassService,anchorBlockHeader,functionToInvokeAfterSync,utilityExecutor,scope)),await this.#awaitSync(contractAddress,scopes)}invalidateContractForScopes(contractAddress,scopes){scopes.length!==0&&scopes.forEach(scope=>this.syncedContracts.delete(toKey(contractAddress,scope)))}wipe(){this.log.debug(`Wiping contract sync cache (${this.syncedContracts.size} entries)`),this.syncedContracts.clear()}commit(_jobId){return Promise.resolve()}discardStaged(_jobId){return this.syncedContracts.clear(),Promise.resolve()}#startSyncIfNeeded(contractAddress,scopes,anchorBlockHeader,jobId,syncScopeFn){let scopesToSync=scopes.filter(scope=>!this.syncedContracts.has(toKey(contractAddress,scope)));if(scopesToSync.length===0)return;this.log.debug(`Syncing contract ${contractAddress} for ${scopesToSync.length} scope(s)`);let syncNullifiersPromise=this.#syncNoteNullifiers(contractAddress,anchorBlockHeader,jobId,scopesToSync),syncSlot=new Semaphore(MAX_CONCURRENT_SCOPE_SYNCS);for(let scope of scopesToSync){let key=toKey(contractAddress,scope),promise2=Promise.all([syncNullifiersPromise,runBounded(syncSlot,()=>syncScopeFn(scope))]).then(()=>{}).catch(err=>{throw this.syncedContracts.delete(key),err});this.syncedContracts.set(key,promise2)}}async#syncNoteNullifiers(contractAddress,anchorBlockHeader,jobId,scopes){if(isProtocolContract(contractAddress))return;await new NoteService(this.noteStore,this.aztecNode,anchorBlockHeader,jobId).syncNoteNullifiers(contractAddress,scopes)}async#awaitSync(contractAddress,scopes){let promises=scopes.map(scope=>this.syncedContracts.get(toKey(contractAddress,scope))).filter(p=>p!==void 0);await Promise.all(promises)}};function toKey(contract,scope){return`${contract.toString()}:${scope.toString()}`}__name(toKey,"toKey");async function runBounded(syncSlot,fn){await syncSlot.acquire();try{return await fn()}finally{syncSlot.release()}}__name(runBounded,"runBounded");import{getVKTreeRoot}from"@aztec/noir-protocol-circuits-types/vk-tree";import{executeCircuitWithReturnWitness}from"@aztec/noir-acvm_js";import{abiDecodeError}from"@aztec/noir-noirc_abi";var ExecutionError=class extends Error{static{__name(this,"ExecutionError")}failingFunction;noirCallStack;constructor(message,failingFunction,noirCallStack,options){super(message,options),this.failingFunction=failingFunction,this.noirCallStack=noirCallStack}};function traverseCauseChain(error2,callback){let currentError=error2;for(;currentError;)callback(currentError),currentError.cause&¤tError.cause instanceof Error?currentError=currentError.cause:currentError=void 0}__name(traverseCauseChain,"traverseCauseChain");function createSimulationError(error2,revertData){let rootCause=error2,noirCallStack,aztecCallStack=[];return traverseCauseChain(error2,cause=>{rootCause=cause,cause instanceof ExecutionError&&(aztecCallStack.push(cause.failingFunction),cause.noirCallStack&&(noirCallStack=cause.noirCallStack))}),new SimulationError(rootCause.message,aztecCallStack,revertData,noirCallStack,{cause:rootCause})}__name(createSimulationError,"createSimulationError");function resolveOpcodeLocations(opcodeLocations,debug,files,brilligFunctionId){let locations=opcodeLocations.flatMap(opcodeLocation=>getSourceCodeLocationsFromOpcodeLocation(opcodeLocation,debug,files,brilligFunctionId));if(locations.length>0){let decomposedOpcodeLocation=opcodeLocations[opcodeLocations.length-1].split(".");if(decomposedOpcodeLocation.length===2){let acirCallstackId=debug.acir_locations[decomposedOpcodeLocation[0]];if(acirCallstackId!==void 0){let callStack=debug.location_tree.locations[acirCallstackId];locations=getCallStackFromLocationNode(callStack,debug.location_tree.locations,files).concat(locations)}}}return locations}__name(resolveOpcodeLocations,"resolveOpcodeLocations");function getCallStackFromLocationNode(callStack,locationTree,files){let result=[];for(;callStack.parent!==null;){let{file:fileId,span}=callStack.value,{path,source}=files[fileId],locationText=source.substring(span.start,span.end),previousLines=source.substring(0,span.start).split(`
|
|
198
198
|
`),line=previousLines.length,column=previousLines[previousLines.length-1].length+1;result.unshift({filePath:path,line,column,fileSource:source,locationText}),callStack=locationTree[callStack.parent]}return result}__name(getCallStackFromLocationNode,"getCallStackFromLocationNode");function getSourceCodeLocationsFromOpcodeLocation(opcodeLocation,debug,files,brilligFunctionId){let callStackID=debug.acir_locations[opcodeLocation],brilligLocation=extractBrilligLocation(opcodeLocation);if(brilligFunctionId!==void 0&&brilligLocation!==void 0&&(callStackID=debug.brillig_locations[brilligFunctionId][brilligLocation],callStackID===void 0))return[];if(callStackID===void 0)return[];let callStack=debug.location_tree.locations[callStackID];return getCallStackFromLocationNode(callStack,debug.location_tree.locations,files)}__name(getSourceCodeLocationsFromOpcodeLocation,"getSourceCodeLocationsFromOpcodeLocation");function extractBrilligLocation(opcodeLocation){let splitted=opcodeLocation.split(".");if(splitted.length===2)return splitted[1]}__name(extractBrilligLocation,"extractBrilligLocation");function resolveAssertionMessage(errorPayload,abi){let decoded=abiDecodeError({parameters:[],error_types:abi.errorTypes,return_type:null},errorPayload);return typeof decoded=="string"?decoded:jsonStringify(decoded)}__name(resolveAssertionMessage,"resolveAssertionMessage");function resolveAssertionMessageFromRevertData(revertData,abi){if(revertData.length==0)return;let[errorSelector,...errorData]=revertData;return resolveAssertionMessage({selector:errorSelector.toBigInt().toString(),data:errorData.map(f=>f.toString())},abi)}__name(resolveAssertionMessageFromRevertData,"resolveAssertionMessageFromRevertData");function resolveAssertionMessageFromError(err,abi){return typeof err=="object"&&err!==null&&"rawAssertionPayload"in err&&err.rawAssertionPayload?`Assertion failed: ${resolveAssertionMessage(err.rawAssertionPayload,abi)}`:err.message}__name(resolveAssertionMessageFromError,"resolveAssertionMessageFromError");async function acvm(acir,initialWitness,callback,loggerOrBindings){let logger3=resolveLogger("simulator:acvm",loggerOrBindings),solvedAndReturnWitness=await executeCircuitWithReturnWitness(acir,initialWitness,(name,args)=>{try{logger3.debug(`Oracle callback ${name}`);let oracleFunction=callback[name];if(!oracleFunction)throw new Error(`Oracle callback ${name} not found`);return oracleFunction.call(callback,...args)}catch(err){let typedError;throw err instanceof Error?typedError=err:typedError=new Error(`Error in oracle callback ${err}`),logger3.error(`Error in oracle callback ${name}: ${typedError.message}`),typedError}}).catch(err=>{let stack=new Error().stack;throw traverseCauseChain(err,cause=>{cause.stack&&(cause.stack+=stack)}),err});return{partialWitness:solvedAndReturnWitness.solvedWitness,returnWitness:solvedAndReturnWitness.returnWitness}}__name(acvm,"acvm");function extractCallStack(error2,debug){if(!("callStack"in error2)||!error2.callStack)return;let{callStack,brilligFunctionId}=error2;if(!debug)return callStack;try{return resolveOpcodeLocations(callStack,debug.debugSymbols,debug.files,brilligFunctionId)}catch{return callStack}}__name(extractCallStack,"extractCallStack");function witnessMapToFields(witness){return[...witness.keys()].sort((a,b)=>a-b).map(key=>witness.get(key)).map(Fr.fromString)}__name(witnessMapToFields,"witnessMapToFields");function fromUintArray(obj,uintBitSize){if(uintBitSize%8!==0)throw new Error(`u${uintBitSize} is not a supported type in Noir`);let uintByteSize=uintBitSize/8;return Buffer.concat(obj.map(str=>hexToBuffer(str).slice(-uintByteSize)))}__name(fromUintArray,"fromUintArray");function adaptBufferSize(originalBuf){let buffer=Buffer.alloc(Fr.SIZE_IN_BYTES);if(originalBuf.length>buffer.length)throw new Error("Buffer does not fit in field");return originalBuf.copy(buffer,buffer.length-originalBuf.length),buffer}__name(adaptBufferSize,"adaptBufferSize");function toACVMField(value){let buffer;return Buffer.isBuffer(value)?buffer=value:typeof value=="boolean"||typeof value=="number"||typeof value=="bigint"?buffer=new Fr(value).toBuffer():typeof value=="string"?buffer=Fr.fromHexString(value).toBuffer():buffer=value.toBuffer(),`0x${adaptBufferSize(buffer).toString("hex")}`}__name(toACVMField,"toACVMField");function toACVMWitness(witnessStartIndex,fields){return fields.reduce((witness,field,index)=>(witness.set(index+witnessStartIndex,toACVMField(field)),witness),new Map)}__name(toACVMWitness,"toACVMWitness");import initACVM,{executeCircuit}from"@aztec/noir-acvm_js";import initAbi from"@aztec/noir-noirc_abi";import{abiDecodeError as abiDecodeError2}from"@aztec/noir-noirc_abi";function enrichNoirError(artifact,originalError){let enrichedError=originalError;if(originalError.rawAssertionPayload)try{let decodedPayload=abiDecodeError2(artifact.abi,originalError.rawAssertionPayload);typeof decodedPayload=="string"?enrichedError.message=`Circuit execution failed: ${decodedPayload}`:enrichedError.decodedAssertionPayload=decodedPayload}catch{}try{let callStack=extractCallStack(originalError,{debugSymbols:parseDebugSymbols(artifact.debug_symbols)[0],files:artifact.file_map});enrichedError.noirCallStack=callStack?.map(errorLocation=>typeof errorLocation=="string"?`at opcode ${errorLocation}`:`at ${errorLocation.locationText} (${errorLocation.filePath}:${errorLocation.line}:${errorLocation.column})`)}catch{}return enrichedError}__name(enrichNoirError,"enrichNoirError");var wasmInitPromise,WASMSimulator=class{static{__name(this,"WASMSimulator")}log;constructor(loggerOrBindings){this.log=resolveLogger("wasm-simulator",loggerOrBindings)}async init(){typeof initAbi=="function"&&(wasmInitPromise??=Promise.all([initAbi(),initACVM()]),await wasmInitPromise)}async executeProtocolCircuit(input,artifact,callback){this.log.debug("init",{hash:artifact.hash}),await this.init();let decodedBytecode=Buffer.from(artifact.bytecode,"base64");try{let timer=new Timer,result=await executeCircuit(decodedBytecode,input,callback);return this.log.debug("execution successful",{hash:artifact.hash}),{witness:result,duration:timer.ms()}}catch(err){if(typeof err=="object"&&err!==null&&"rawAssertionPayload"in err){let parsed=enrichNoirError(artifact,err);throw this.log.debug("execution failed",{hash:artifact.hash,error:parsed,message:parsed.message}),parsed}throw this.log.debug("execution failed",{hash:artifact.hash,error:err}),new Error(`Circuit execution failed: ${err}`)}}async executeUserCircuit(input,artifact,callback){return await this.init(),acvm(artifact.bytecode,input,callback,this.log.createChild("acvm"))}};var CIRCUIT_SIZE_INDEX=0,CIRCUIT_PUBLIC_INPUTS_INDEX=1,VerificationKeyAsFields=class _VerificationKeyAsFields{static{__name(this,"VerificationKeyAsFields")}key;hash;constructor(key,hash5){this.key=key,this.hash=hash5}static async fromKey(key){let hash5=await hashVK(key);return new _VerificationKeyAsFields(key,hash5)}get numPublicInputs(){return Number(this.key[CIRCUIT_PUBLIC_INPUTS_INDEX])}get circuitSize(){return Number(this.key[CIRCUIT_SIZE_INDEX])}static get schema(){return bufferSchemaFor(_VerificationKeyAsFields)}toJSON(){return this.toBuffer()}toBuffer(){return serializeToBuffer(...this.toFields())}toFields(){return[this.key.length,...this.key,this.hash]}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _VerificationKeyAsFields(reader.readVector(Fr),reader.readObject(Fr))}static fromFrBuffer(vkBytes){let numFields=vkBytes.length/Fr.SIZE_IN_BYTES,fields=BufferReader.asReader(vkBytes).readArray(numFields,Fr);return _VerificationKeyAsFields.fromKey(fields)}static makeFake(size,seed=1){return new _VerificationKeyAsFields(makeTuple(size,Fr.random,seed),Fr.random())}static makeFakeHonk(seed=1){return new _VerificationKeyAsFields(makeTuple(115,Fr.random,seed),Fr.random())}static makeFakeRollupHonk(seed=1){return new _VerificationKeyAsFields(makeTuple(115,i=>new Fr(i),seed),new Fr(seed+1))}static makeEmpty(size){return new _VerificationKeyAsFields(makeTuple(size,Fr.zero),Fr.zero())}},VerificationKeyData=class _VerificationKeyData{static{__name(this,"VerificationKeyData")}keyAsFields;keyAsBytes;constructor(keyAsFields,keyAsBytes){this.keyAsFields=keyAsFields,this.keyAsBytes=keyAsBytes}get numPublicInputs(){return this.keyAsFields.numPublicInputs}get circuitSize(){return this.keyAsFields.circuitSize}static empty(){return new _VerificationKeyData(VerificationKeyAsFields.makeEmpty(0),Buffer.alloc(0))}static makeFakeHonk(){let keyAsFields=VerificationKeyAsFields.makeFakeHonk();return new _VerificationKeyData(keyAsFields,keyAsFields.toBuffer())}static makeFakeRollupHonk(){let keyAsFields=VerificationKeyAsFields.makeFakeRollupHonk();return new _VerificationKeyData(keyAsFields,keyAsFields.toBuffer())}toBuffer(){return serializeToBuffer(this.keyAsFields,this.keyAsBytes.length,this.keyAsBytes)}toString(){return bufferToHex(this.toBuffer())}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer),verificationKeyAsFields=reader.readObject(VerificationKeyAsFields),length=reader.readNumber(),bytes=reader.readBytes(length);return new _VerificationKeyData(verificationKeyAsFields,bytes)}static async fromFrBuffer(vkBytes){return new _VerificationKeyData(await VerificationKeyAsFields.fromFrBuffer(vkBytes),vkBytes)}static fromString(str){return _VerificationKeyData.fromBuffer(hexToBuffer(str))}clone(){return _VerificationKeyData.fromBuffer(this.toBuffer())}toJSON(){return this.toBuffer()}static get schema(){return bufferSchemaFor(_VerificationKeyData)}};var VkData=class _VkData{static{__name(this,"VkData")}vk;leafIndex;siblingPath;constructor(vk,leafIndex,siblingPath){this.vk=vk,this.leafIndex=leafIndex,this.siblingPath=siblingPath}static empty(){return new _VkData(VerificationKeyData.empty(),0,makeTuple(7,Fr.zero))}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _VkData(reader.readObject(VerificationKeyData),reader.readNumber(),reader.readArray(7,Fr))}toBuffer(){return serializeToBuffer(this.vk,this.leafIndex,this.siblingPath)}toString(){return bufferToHex(this.toBuffer())}};var PrivateAccumulatedData=class _PrivateAccumulatedData{static{__name(this,"PrivateAccumulatedData")}noteHashes;nullifiers;l2ToL1Msgs;privateLogs;contractClassLogsHashes;publicCallRequests;privateCallStack;constructor(noteHashes,nullifiers,l2ToL1Msgs,privateLogs,contractClassLogsHashes,publicCallRequests,privateCallStack){this.noteHashes=noteHashes,this.nullifiers=nullifiers,this.l2ToL1Msgs=l2ToL1Msgs,this.privateLogs=privateLogs,this.contractClassLogsHashes=contractClassLogsHashes,this.publicCallRequests=publicCallRequests,this.privateCallStack=privateCallStack}toBuffer(){return serializeToBuffer(this.noteHashes,this.nullifiers,this.l2ToL1Msgs,this.privateLogs,this.contractClassLogsHashes,this.publicCallRequests,this.privateCallStack)}toString(){return bufferToHex(this.toBuffer())}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _PrivateAccumulatedData(reader.readObject(ClaimedLengthArrayFromBuffer(ScopedNoteHash,64)),reader.readObject(ClaimedLengthArrayFromBuffer(ScopedNullifier,64)),reader.readObject(ClaimedLengthArrayFromBuffer(ScopedCountedL2ToL1Message,8)),reader.readObject(ClaimedLengthArrayFromBuffer(ScopedPrivateLogData,64)),reader.readObject(ClaimedLengthArrayFromBuffer(ScopedCountedLogHash,1)),reader.readObject(ClaimedLengthArrayFromBuffer(CountedPublicCallRequest,32)),reader.readObject(ClaimedLengthArrayFromBuffer(PrivateCallRequest,16)))}static fromString(str){return _PrivateAccumulatedData.fromBuffer(hexToBuffer(str))}static empty(){return new _PrivateAccumulatedData(ClaimedLengthArray.empty(ScopedNoteHash,64),ClaimedLengthArray.empty(ScopedNullifier,64),ClaimedLengthArray.empty(ScopedCountedL2ToL1Message,8),ClaimedLengthArray.empty(ScopedPrivateLogData,64),ClaimedLengthArray.empty(ScopedCountedLogHash,1),ClaimedLengthArray.empty(CountedPublicCallRequest,32),ClaimedLengthArray.empty(PrivateCallRequest,16))}};var ScheduledDelayChange=class{static{__name(this,"ScheduledDelayChange")}pre;post;timestampOfChange;constructor(pre,post,timestampOfChange){this.pre=pre,this.post=post,this.timestampOfChange=timestampOfChange}static empty(){return new this(void 0,void 0,0n)}isEmpty(){return this.pre===void 0&&this.post===void 0&&this.timestampOfChange===0n}};var ScheduledValueChange=class{static{__name(this,"ScheduledValueChange")}previous;post;timestampOfChange;constructor(previous,post,timestampOfChange){if(this.previous=previous,this.post=post,this.timestampOfChange=timestampOfChange,this.previous.length!==this.post.length)throw new Error("Previous and post must have the same length")}static empty(valueSize){return new this(Array(valueSize).fill(new Fr(0)),Array(valueSize).fill(new Fr(0)),0n)}isEmpty(){return this.previous.every(v=>v.isZero())&&this.post.every(v=>v.isZero())&&this.timestampOfChange===0n}getCurrentAt(timestamp){return timestamp<this.timestampOfChange?this.previous:this.post}};var DELAYED_PUBLIC_MUTABLE_VALUES_LEN=3,DelayedPublicMutableValues=class _DelayedPublicMutableValues{static{__name(this,"DelayedPublicMutableValues")}svc;sdc;constructor(svc,sdc){this.svc=svc,this.sdc=sdc}static fromFields(fields){let reader=FieldReader.asReader(fields),firstField=reader.readField().toBigInt(),svcPre=reader.readFieldArray(1),svcPost=reader.readFieldArray(1),svcTimestampOfChange=firstField&0xffffffffn,svc=new ScheduledValueChange(svcPre,svcPost,svcTimestampOfChange),sdcTimestampOfChange=firstField>>32n&0xffffffffn,sdcIsPostSome=firstField>>64n&1n,sdcPost=firstField>>72n&0xffffffffn,sdcIsPreSome=firstField>>104n&1n,sdcPre=firstField>>112n&0xffffffffn,sdc=new ScheduledDelayChange(sdcIsPreSome?sdcPre:void 0,sdcIsPostSome?sdcPost:void 0,sdcTimestampOfChange);return new this(svc,sdc)}toFields(){let firstField=this.svc.timestampOfChange;return firstField|=this.sdc.timestampOfChange<<32n,firstField|=(this.sdc.post===void 0?0n:1n)<<64n,firstField|=BigInt(this.sdc.post||0)<<72n,firstField|=(this.sdc.pre===void 0?0n:1n)<<104n,firstField|=BigInt(this.sdc.pre||0)<<112n,[new Fr(firstField),...this.svc.previous,...this.svc.post]}toBuffer(){return serializeToBuffer(this.toFields())}static fromBuffer(buffer,valueSize){let reader=BufferReader.asReader(buffer);return _DelayedPublicMutableValues.fromFields(reader.readArray(2*valueSize+1,Fr))}static empty(valueSize){return new this(ScheduledValueChange.empty(valueSize),ScheduledDelayChange.empty())}static async readFromTree(delayedPublicMutableSlot,readStorage){let fieldPromises=Array.from({length:DELAYED_PUBLIC_MUTABLE_VALUES_LEN}).map((_,i)=>readStorage(delayedPublicMutableSlot.add(new Fr(i))));return _DelayedPublicMutableValues.fromFields(await Promise.all(fieldPromises))}isEmpty(){return this.svc.isEmpty()&&this.sdc.isEmpty()}writeToTree(delayedPublicMutableSlot,storageWrite){let fieldPromises=this.toFields().map((field,i)=>storageWrite(delayedPublicMutableSlot.add(new Fr(i)),field));return Promise.all(fieldPromises)}async hash(){let fields=this.toFields();return await poseidon2Hash(fields)}};import{inspect as inspect33}from"util";var ScopedKeyValidationRequestAndSeparator=class _ScopedKeyValidationRequestAndSeparator{static{__name(this,"ScopedKeyValidationRequestAndSeparator")}request;contractAddress;constructor(request,contractAddress){this.request=request,this.contractAddress=contractAddress}toBuffer(){return serializeToBuffer(this.request,this.contractAddress)}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _ScopedKeyValidationRequestAndSeparator(KeyValidationRequestAndSeparator.fromBuffer(reader),AztecAddress.fromBuffer(reader))}toFields(){let fields=[...this.request.toFields(),this.contractAddress.toField()];if(fields.length!==4)throw new Error(`Invalid number of fields for ScopedKeyValidationRequestAndSeparator. Expected ${4}, got ${fields.length}`);return fields}static fromFields(fields){let reader=FieldReader.asReader(fields);return new _ScopedKeyValidationRequestAndSeparator(KeyValidationRequestAndSeparator.fromFields(reader),AztecAddress.fromFields(reader))}isEmpty(){return this.request.isEmpty()&&this.contractAddress.isZero()}static empty(){return new _ScopedKeyValidationRequestAndSeparator(KeyValidationRequestAndSeparator.empty(),AztecAddress.ZERO)}};var _computedKey33;_computedKey33=inspect33.custom;var PrivateValidationRequests=class _PrivateValidationRequests{static{__name(this,"PrivateValidationRequests")}noteHashReadRequests;nullifierReadRequests;scopedKeyValidationRequestsAndSeparators;constructor(noteHashReadRequests,nullifierReadRequests,scopedKeyValidationRequestsAndSeparators){this.noteHashReadRequests=noteHashReadRequests,this.nullifierReadRequests=nullifierReadRequests,this.scopedKeyValidationRequestsAndSeparators=scopedKeyValidationRequestsAndSeparators}getSize(){return this.noteHashReadRequests.getSize()+this.nullifierReadRequests.getSize()+this.scopedKeyValidationRequestsAndSeparators.getSize()}toBuffer(){return serializeToBuffer(this.noteHashReadRequests,this.nullifierReadRequests,this.scopedKeyValidationRequestsAndSeparators)}toString(){return bufferToHex(this.toBuffer())}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _PrivateValidationRequests(reader.readObject(ClaimedLengthArrayFromBuffer(ScopedReadRequest,64)),reader.readObject(ClaimedLengthArrayFromBuffer(ScopedReadRequest,64)),reader.readObject(ClaimedLengthArrayFromBuffer(ScopedKeyValidationRequestAndSeparator,64)))}static fromString(str){return _PrivateValidationRequests.fromBuffer(hexToBuffer(str))}static empty(){return new _PrivateValidationRequests(ClaimedLengthArray.empty(ScopedReadRequest,64),ClaimedLengthArray.empty(ScopedReadRequest,64),ClaimedLengthArray.empty(ScopedKeyValidationRequestAndSeparator,64))}[_computedKey33](){return`PrivateValidationRequests {
|
|
199
199
|
noteHashReadRequests: ${inspect33(this.noteHashReadRequests)},
|
|
200
200
|
nullifierReadRequests: ${inspect33(this.nullifierReadRequests)},
|
|
@@ -207,14 +207,14 @@ Partial Address: ${this.partialAddress.toString()}
|
|
|
207
207
|
noteHashes: ${this.noteHashes},
|
|
208
208
|
nullifiers: ${this.nullifiers},
|
|
209
209
|
l2ToL1Msgs: ${this.l2ToL1Msgs},
|
|
210
|
-
}`}};var ReadRequestActionEnum=(function(ReadRequestActionEnum2){return ReadRequestActionEnum2[ReadRequestActionEnum2.SKIP=0]="SKIP",ReadRequestActionEnum2[ReadRequestActionEnum2.READ_AS_PENDING=1]="READ_AS_PENDING",ReadRequestActionEnum2[ReadRequestActionEnum2.READ_AS_SETTLED=2]="READ_AS_SETTLED",ReadRequestActionEnum2})({});var PendingReadHint=class _PendingReadHint{static{__name(this,"PendingReadHint")}readRequestIndex;pendingValueIndex;constructor(readRequestIndex,pendingValueIndex){this.readRequestIndex=readRequestIndex,this.pendingValueIndex=pendingValueIndex}static nada(readRequestLen){return new _PendingReadHint(readRequestLen,0)}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _PendingReadHint(reader.readNumber(),reader.readNumber())}toBuffer(){return serializeToBuffer(this.readRequestIndex,this.pendingValueIndex)}};var ReadRequestResetActions=class _ReadRequestResetActions{static{__name(this,"ReadRequestResetActions")}actions;pendingReadHints;constructor(actions,pendingReadHints){this.actions=actions,this.pendingReadHints=pendingReadHints}static empty(numReads){return new _ReadRequestResetActions(makeTuple(numReads,()=>0),[])}};function isValidNoteHashReadRequest(readRequest,noteHash){return noteHash.value.equals(readRequest.value)&¬eHash.contractAddress.equals(readRequest.contractAddress)&&readRequest.counter>noteHash.counter}__name(isValidNoteHashReadRequest,"isValidNoteHashReadRequest");function getNoteHashReadRequestResetActions(noteHashReadRequests,noteHashes){let resetActions=ReadRequestResetActions.empty(64),noteHashMap=new Map;noteHashes.getActiveItems().forEach((noteHash,index)=>{let value=noteHash.value.toBigInt(),arr=noteHashMap.get(value)??[];arr.push({noteHash,index}),noteHashMap.set(value,arr)});for(let i=0;i<noteHashReadRequests.claimedLength;++i){let readRequest=noteHashReadRequests.array[i];if(readRequest.contractAddress.isZero())resetActions.actions[i]=ReadRequestActionEnum.READ_AS_SETTLED;else{let pendingNoteHash=noteHashMap.get(readRequest.value.toBigInt())?.find(n=>isValidNoteHashReadRequest(readRequest,n.noteHash));pendingNoteHash&&(resetActions.actions[i]=ReadRequestActionEnum.READ_AS_PENDING,resetActions.pendingReadHints.push(new PendingReadHint(i,pendingNoteHash.index)))}}return resetActions}__name(getNoteHashReadRequestResetActions,"getNoteHashReadRequestResetActions");function isValidNullifierReadRequest(readRequest,nullifier){return readRequest.value.equals(nullifier.value)&&nullifier.contractAddress.equals(readRequest.contractAddress)&&readRequest.counter>nullifier.counter}__name(isValidNullifierReadRequest,"isValidNullifierReadRequest");function getNullifierReadRequestResetActions(nullifierReadRequests,nullifiers){let resetActions=ReadRequestResetActions.empty(64),nullifierMap=new Map;nullifiers.getActiveItems().forEach((nullifier,index)=>{let value=nullifier.value.toBigInt(),arr=nullifierMap.get(value)??[];arr.push({nullifier,index}),nullifierMap.set(value,arr)});for(let i=0;i<nullifierReadRequests.claimedLength;++i){let readRequest=nullifierReadRequests.array[i];if(readRequest.contractAddress.isZero())resetActions.actions[i]=ReadRequestActionEnum.READ_AS_SETTLED;else{let pendingNullifier=nullifierMap.get(readRequest.value.toBigInt())?.find(({nullifier})=>isValidNullifierReadRequest(readRequest,nullifier));pendingNullifier&&(resetActions.actions[i]=ReadRequestActionEnum.READ_AS_PENDING,resetActions.pendingReadHints.push(new PendingReadHint(i,pendingNullifier.index)))}}return resetActions}__name(getNullifierReadRequestResetActions,"getNullifierReadRequestResetActions");var ScopedValueCache=class{static{__name(this,"ScopedValueCache")}cache=new Map;constructor(items){items.forEach(item=>{let value=item.value.toBigInt(),arr=this.cache.get(value)??[];arr.push(item),this.cache.set(value,arr)})}get(matcher){return this.cache.get(matcher.value.toBigInt())??[]}};import{inspect as inspect35}from"util";var _computedKey35;_computedKey35=inspect35.custom;var TransientDataSquashingHint=class _TransientDataSquashingHint{static{__name(this,"TransientDataSquashingHint")}nullifierIndex;noteHashIndex;constructor(nullifierIndex,noteHashIndex){this.nullifierIndex=nullifierIndex,this.noteHashIndex=noteHashIndex}toFields(){return[new Fr(this.nullifierIndex),new Fr(this.noteHashIndex)]}static fromFields(fields){let reader=FieldReader.asReader(fields);return new _TransientDataSquashingHint(reader.readU32(),reader.readU32())}isEmpty(){return!this.nullifierIndex&&!this.noteHashIndex}static empty(){return new _TransientDataSquashingHint(0,0)}toBuffer(){return serializeToBuffer(this.nullifierIndex,this.noteHashIndex)}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _TransientDataSquashingHint(reader.readNumber(),reader.readNumber())}toString(){return`nullifierIndex=${this.nullifierIndex} noteHashIndex=${this.noteHashIndex}`}[_computedKey35](){return`TransientDataSquashingHint { ${this.toString()} }`}};function buildTransientDataHints(noteHashes,nullifiers,futureNoteHashReads,futureNullifierReads,futureLogs,noteHashNullifierCounterMap,splitCounter){let futureNoteHashReadsMap=new ScopedValueCache(futureNoteHashReads),futureNullifierReadsMap=new ScopedValueCache(futureNullifierReads),futureLogNoteHashCounters=new Set(futureLogs.filter(l=>l.noteHashCounter>0).map(l=>l.noteHashCounter)),nullifierIndexMap=new Map;nullifiers.getActiveItems().forEach((n,i)=>nullifierIndexMap.set(n.counter,i));let hints=[];for(let noteHashIndex=0;noteHashIndex<noteHashes.claimedLength;noteHashIndex++){let noteHash=noteHashes.array[noteHashIndex],noteHashNullifierCounter=noteHashNullifierCounterMap.get(noteHash.counter);if(!noteHashNullifierCounter||futureNoteHashReadsMap.get(noteHash).find(read2=>isValidNoteHashReadRequest(read2,noteHash))||futureLogNoteHashCounters.has(noteHash.counter))continue;let nullifierIndex=nullifierIndexMap.get(noteHashNullifierCounter);if(nullifierIndex===void 0)continue;let nullifier=nullifiers.array[nullifierIndex];if(!(noteHash.counter<splitCounter&&nullifier.counter>=splitCounter)){if(nullifier.counter<noteHash.counter)throw new Error("Hinted nullifier has smaller counter than note hash.");if(!nullifier.contractAddress.equals(noteHash.contractAddress))throw new Error("Contract address of hinted note hash does not match.");nullifier.nullifiedNoteHash.equals(noteHash.value)&&(futureNullifierReadsMap.get(nullifier).find(read2=>isValidNullifierReadRequest(read2,nullifier))||hints.push(new TransientDataSquashingHint(nullifierIndex,noteHashIndex)))}}let noActionHint=new TransientDataSquashingHint(nullifiers.array.length,noteHashes.array.length);return{numTransientData:hints.length,hints:padArrayEnd(hints,noActionHint,nullifiers.array.length)}}__name(buildTransientDataHints,"buildTransientDataHints");var PrivateContextInputs=class _PrivateContextInputs{static{__name(this,"PrivateContextInputs")}callContext;anchorBlockHeader;txContext;startSideEffectCounter;constructor(callContext,anchorBlockHeader,txContext,startSideEffectCounter){this.callContext=callContext,this.anchorBlockHeader=anchorBlockHeader,this.txContext=txContext,this.startSideEffectCounter=startSideEffectCounter}static empty(){return new _PrivateContextInputs(CallContext.empty(),BlockHeader.empty(),TxContext.empty(),0)}toFields(){return serializeToFields([this.callContext,this.anchorBlockHeader,this.txContext,this.startSideEffectCounter])}};async function appendL1ToL2MessagesToTree(db,l1ToL2Messages){let padded=padArrayEnd(l1ToL2Messages,Fr.ZERO,1024,"Too many L1 to L2 messages");await db.appendLeaves(MerkleTreeId.L1_TO_L2_MESSAGE_TREE,padded)}__name(appendL1ToL2MessagesToTree,"appendL1ToL2MessagesToTree");var InboxLeaf=class _InboxLeaf{static{__name(this,"InboxLeaf")}index;leaf;constructor(index,leaf){this.index=index,this.leaf=leaf}toBuffer(){return serializeToBuffer([this.index,this.leaf])}fromBuffer(buffer){let reader=BufferReader.asReader(buffer),index=toBigIntBE(reader.readBytes(32)),leaf=reader.readObject(Fr);return new _InboxLeaf(index,leaf)}static smallestIndexForCheckpoint(checkpointNumber){return BigInt(checkpointNumber-INITIAL_CHECKPOINT_NUMBER2)*BigInt(1024)}static indexRangeForCheckpoint(checkpointNumber){let start=this.smallestIndexForCheckpoint(checkpointNumber),end=start+BigInt(1024);return[start,end]}static checkpointNumberFromIndex(index){return CheckpointNumber(Number(index/BigInt(1024))+INITIAL_CHECKPOINT_NUMBER2)}};var L1Actor=class _L1Actor{static{__name(this,"L1Actor")}sender;chainId;constructor(sender,chainId){this.sender=sender,this.chainId=chainId}static empty(){return new _L1Actor(EthAddress.ZERO,0)}toFields(){return[this.sender.toField(),new Fr(BigInt(this.chainId))]}toBuffer(){return serializeToBuffer(this.sender,this.chainId)}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer),ethAddr=reader.readObject(EthAddress),chainId=reader.readNumber();return new _L1Actor(ethAddr,chainId)}static random(){return new _L1Actor(EthAddress.random(),randomInt(1e3))}};var L2Actor=class _L2Actor{static{__name(this,"L2Actor")}recipient;version;constructor(recipient,version2){this.recipient=recipient,this.version=version2}static empty(){return new _L2Actor(AztecAddress.ZERO,0)}toFields(){return[this.recipient.toField(),new Fr(BigInt(this.version))]}toBuffer(){return serializeToBuffer(this.recipient,this.version)}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer),aztecAddr=AztecAddress.fromBuffer(reader),version2=reader.readNumber();return new _L2Actor(aztecAddr,version2)}static async random(){return new _L2Actor(await AztecAddress.random(),randomInt(1e3))}};var L1ToL2Message=class _L1ToL2Message{static{__name(this,"L1ToL2Message")}sender;recipient;content;secretHash;index;constructor(sender,recipient,content,secretHash,index){this.sender=sender,this.recipient=recipient,this.content=content,this.secretHash=secretHash,this.index=index}toFields(){return[...this.sender.toFields(),...this.recipient.toFields(),this.content,this.secretHash,this.index]}toBuffer(){return serializeToBuffer(this.sender,this.recipient,this.content,this.secretHash,this.index)}hash(){return sha256ToField(this.toFields())}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer),sender=reader.readObject(L1Actor),recipient=reader.readObject(L2Actor),content=Fr.fromBuffer(reader),secretHash=Fr.fromBuffer(reader),index=Fr.fromBuffer(reader);return new _L1ToL2Message(sender,recipient,content,secretHash,index)}toString(){return bufferToHex(this.toBuffer())}static fromString(data){let buffer=Buffer.from(data,"hex");return _L1ToL2Message.fromBuffer(buffer)}static empty(){return new _L1ToL2Message(L1Actor.empty(),L2Actor.empty(),Fr.ZERO,Fr.ZERO,Fr.ZERO)}static async random(){return new _L1ToL2Message(L1Actor.random(),await L2Actor.random(),Fr.random(),Fr.random(),Fr.random())}};async function getNonNullifiedL1ToL2MessageWitness(node,contractAddress,messageHash,secret,referenceBlock="latest"){let messageNullifier=await computeL1ToL2MessageNullifier(contractAddress,messageHash,secret),[l1ToL2Response,nullifierResponse]=await Promise.all([node.getL1ToL2MessageMembershipWitness(referenceBlock,messageHash),node.findLeavesIndexes(referenceBlock,MerkleTreeId.NULLIFIER_TREE,[messageNullifier])]);if(!l1ToL2Response)throw new Error(`No L1 to L2 message found for message hash ${messageHash.toString()}`);if(nullifierResponse[0]!==void 0)throw new Error(`No non-nullified L1 to L2 message found for message hash ${messageHash.toString()}`);return l1ToL2Response}__name(getNonNullifiedL1ToL2MessageWitness,"getNonNullifiedL1ToL2MessageWitness");import{strict as assert3}from"assert";var EMPTY_PROOF_SIZE=42,Proof=class _Proof{static{__name(this,"Proof")}buffer;numPublicInputs;__proofBrand;constructor(buffer,numPublicInputs){this.buffer=buffer,this.numPublicInputs=numPublicInputs}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer),size=reader.readNumber(),buf=reader.readBytes(size),numPublicInputs=reader.readNumber();return new _Proof(buf,numPublicInputs)}toBuffer(){return serializeToBuffer(this.buffer.length,this.buffer,this.numPublicInputs)}toString(){return bufferToHex(this.toBuffer())}withoutPublicInputs(){if(this.isEmpty())return this.buffer;assert3(this.numPublicInputs>=8,"Proof does not contain an aggregation object");let proofStart=Fr.SIZE_IN_BYTES*(this.numPublicInputs-8);return assert3(this.buffer.length>=proofStart,"Proof buffer is not appropriately sized to call withoutPublicInputs()"),this.buffer.subarray(proofStart)}extractPublicInputs(){if(this.isEmpty())return new Array(this.numPublicInputs).fill(Fr.zero());assert3(this.numPublicInputs>=8,"Proof does not contain an aggregation object");let numInnerPublicInputs=this.numPublicInputs-8;return BufferReader.asReader(this.buffer.subarray(0,Fr.SIZE_IN_BYTES*numInnerPublicInputs)).readArray(numInnerPublicInputs,Fr)}static fromString(str){return _Proof.fromBuffer(hexToBuffer(str))}isEmpty(){return this.buffer.length===EMPTY_PROOF_SIZE&&this.buffer.every(byte=>byte===0)&&this.numPublicInputs===0}static empty(){return makeEmptyProof()}};function makeEmptyProof(){return new Proof(Buffer.alloc(EMPTY_PROOF_SIZE,0),0)}__name(makeEmptyProof,"makeEmptyProof");var RecursiveProof=class _RecursiveProof{static{__name(this,"RecursiveProof")}proof;binaryProof;fieldsValid;proofLength;constructor(proof,binaryProof,fieldsValid,proofLength){if(this.proof=proof,this.binaryProof=binaryProof,this.fieldsValid=fieldsValid,this.proofLength=proofLength,proof.length!==proofLength)throw new Error(`Proof length ${proof.length} does not match expected length ${proofLength}.`)}static fromBuffer(buffer,expectedSize){let reader=BufferReader.asReader(buffer),size=reader.readNumber();if(typeof expectedSize=="number"&&expectedSize!==size)throw new Error(`Expected proof length ${expectedSize}, got ${size}`);return new _RecursiveProof(reader.readArray(size,Fr),Proof.fromBuffer(reader),reader.readBoolean(),size)}toBuffer(){return serializeToBuffer(this.proof.length,this.proof,this.binaryProof,this.fieldsValid)}toString(){return bufferToHex(this.toBuffer())}static fromString(str,expectedSize){return _RecursiveProof.fromBuffer(hexToBuffer(str),expectedSize)}toJSON(){return this.toBuffer()}static schemaFor(expectedSize){return schemas.Buffer.transform(b=>_RecursiveProof.fromBuffer(b,expectedSize))}};var ProofData=class _ProofData{static{__name(this,"ProofData")}publicInputs;proof;vkData;constructor(publicInputs,proof,vkData){this.publicInputs=publicInputs,this.proof=proof,this.vkData=vkData}toBuffer(){return serializeToBuffer(this.publicInputs,this.proof,this.vkData)}static fromBuffer(buffer,publicInputs){let reader=BufferReader.asReader(buffer);return new _ProofData(reader.readObject(publicInputs),RecursiveProof.fromBuffer(reader),reader.readObject(VkData))}},ProofDataForFixedVk=class _ProofDataForFixedVk{static{__name(this,"ProofDataForFixedVk")}publicInputs;proof;constructor(publicInputs,proof){this.publicInputs=publicInputs,this.proof=proof}toBuffer(){return serializeToBuffer(this.publicInputs,this.proof)}static fromBuffer(buffer,publicInputs){let reader=BufferReader.asReader(buffer);return new _ProofDataForFixedVk(reader.readObject(publicInputs),RecursiveProof.fromBuffer(reader))}};var ProvingRequestType=(function(ProvingRequestType2){return ProvingRequestType2[ProvingRequestType2.PUBLIC_VM=0]="PUBLIC_VM",ProvingRequestType2[ProvingRequestType2.PUBLIC_CHONK_VERIFIER=1]="PUBLIC_CHONK_VERIFIER",ProvingRequestType2[ProvingRequestType2.PRIVATE_TX_BASE_ROLLUP=2]="PRIVATE_TX_BASE_ROLLUP",ProvingRequestType2[ProvingRequestType2.PUBLIC_TX_BASE_ROLLUP=3]="PUBLIC_TX_BASE_ROLLUP",ProvingRequestType2[ProvingRequestType2.TX_MERGE_ROLLUP=4]="TX_MERGE_ROLLUP",ProvingRequestType2[ProvingRequestType2.BLOCK_ROOT_FIRST_ROLLUP=5]="BLOCK_ROOT_FIRST_ROLLUP",ProvingRequestType2[ProvingRequestType2.BLOCK_ROOT_SINGLE_TX_FIRST_ROLLUP=6]="BLOCK_ROOT_SINGLE_TX_FIRST_ROLLUP",ProvingRequestType2[ProvingRequestType2.BLOCK_ROOT_EMPTY_TX_FIRST_ROLLUP=7]="BLOCK_ROOT_EMPTY_TX_FIRST_ROLLUP",ProvingRequestType2[ProvingRequestType2.BLOCK_ROOT_ROLLUP=8]="BLOCK_ROOT_ROLLUP",ProvingRequestType2[ProvingRequestType2.BLOCK_ROOT_SINGLE_TX_ROLLUP=9]="BLOCK_ROOT_SINGLE_TX_ROLLUP",ProvingRequestType2[ProvingRequestType2.BLOCK_MERGE_ROLLUP=10]="BLOCK_MERGE_ROLLUP",ProvingRequestType2[ProvingRequestType2.CHECKPOINT_ROOT_ROLLUP=11]="CHECKPOINT_ROOT_ROLLUP",ProvingRequestType2[ProvingRequestType2.CHECKPOINT_ROOT_SINGLE_BLOCK_ROLLUP=12]="CHECKPOINT_ROOT_SINGLE_BLOCK_ROLLUP",ProvingRequestType2[ProvingRequestType2.CHECKPOINT_PADDING_ROLLUP=13]="CHECKPOINT_PADDING_ROLLUP",ProvingRequestType2[ProvingRequestType2.CHECKPOINT_MERGE_ROLLUP=14]="CHECKPOINT_MERGE_ROLLUP",ProvingRequestType2[ProvingRequestType2.ROOT_ROLLUP=15]="ROOT_ROLLUP",ProvingRequestType2[ProvingRequestType2.PARITY_BASE=16]="PARITY_BASE",ProvingRequestType2[ProvingRequestType2.PARITY_ROOT=17]="PARITY_ROOT",ProvingRequestType2})({});function assertAllowedScope(scope,allowedScopes){if(!allowedScopes.some(allowed=>allowed.equals(scope)))throw new Error(`Scope ${scope.toString()} is not in the allowed scopes list: [${allowedScopes.map(s2=>s2.toString()).join(", ")}]. See https://docs.aztec.network/errors/10`)}__name(assertAllowedScope,"assertAllowedScope");var CapsuleService=class{static{__name(this,"CapsuleService")}capsuleStore;allowedScopes;constructor(capsuleStore,allowedScopes){this.capsuleStore=capsuleStore,this.allowedScopes=[...allowedScopes,AztecAddress.ZERO]}setCapsule(contractAddress,slot,capsule,jobId,scope){assertAllowedScope(scope,this.allowedScopes),this.capsuleStore.setCapsule(contractAddress,slot,capsule,jobId,scope)}async getCapsule(contractAddress,slot,jobId,scope,transientCapsules){return assertAllowedScope(scope,this.allowedScopes),transientCapsules?.find(c2=>c2.contractAddress.equals(contractAddress)&&c2.storageSlot.equals(slot)&&(c2.scope??AztecAddress.ZERO).equals(scope))?.data??await this.capsuleStore.getCapsule(contractAddress,slot,jobId,scope)}deleteCapsule(contractAddress,slot,jobId,scope){assertAllowedScope(scope,this.allowedScopes),this.capsuleStore.deleteCapsule(contractAddress,slot,jobId,scope)}copyCapsule(contractAddress,srcSlot,dstSlot,numEntries,jobId,scope){return assertAllowedScope(scope,this.allowedScopes),this.capsuleStore.copyCapsule(contractAddress,srcSlot,dstSlot,numEntries,jobId,scope)}appendToCapsuleArray(contractAddress,baseSlot,content,jobId,scope){return assertAllowedScope(scope,this.allowedScopes),this.capsuleStore.appendToCapsuleArray(contractAddress,baseSlot,content,jobId,scope)}readCapsuleArray(contractAddress,baseSlot,jobId,scope){return assertAllowedScope(scope,this.allowedScopes),this.capsuleStore.readCapsuleArray(contractAddress,baseSlot,jobId,scope)}setCapsuleArray(contractAddress,baseSlot,content,jobId,scope){return assertAllowedScope(scope,this.allowedScopes),this.capsuleStore.setCapsuleArray(contractAddress,baseSlot,content,jobId,scope)}};function assertNonZeroScope(scope){if(scope.equals(AztecAddress.ZERO))throw new Error("scope must not be the zero address")}__name(assertNonZeroScope,"assertNonZeroScope");var FactCollectionTypeKey=class _FactCollectionTypeKey{static{__name(this,"FactCollectionTypeKey")}contractAddress;scope;factCollectionTypeId;constructor(contractAddress,scope,factCollectionTypeId){this.contractAddress=contractAddress,this.scope=scope,this.factCollectionTypeId=factCollectionTypeId,assertNonZeroScope(scope)}static from(fields){return new _FactCollectionTypeKey(fields.contractAddress,fields.scope,fields.factCollectionTypeId)}toString(){return`${this.contractAddress}:${this.scope}:${this.factCollectionTypeId}`}},FactCollectionKey=class _FactCollectionKey{static{__name(this,"FactCollectionKey")}contractAddress;scope;factCollectionTypeId;factCollectionId;constructor(contractAddress,scope,factCollectionTypeId,factCollectionId){this.contractAddress=contractAddress,this.scope=scope,this.factCollectionTypeId=factCollectionTypeId,this.factCollectionId=factCollectionId,assertNonZeroScope(scope)}static from(fields){return new _FactCollectionKey(fields.contractAddress,fields.scope,fields.factCollectionTypeId,fields.factCollectionId)}static fromString(str){let[contractAddress,scope,factCollectionTypeId,factCollectionId]=str.split(":");return new _FactCollectionKey(AztecAddress.fromStringUnsafe(contractAddress),AztecAddress.fromStringUnsafe(scope),Fr.fromString(factCollectionTypeId),Fr.fromString(factCollectionId))}factCollectionTypeKey(){return new FactCollectionTypeKey(this.contractAddress,this.scope,this.factCollectionTypeId)}toString(){return`${this.contractAddress}:${this.scope}:${this.factCollectionTypeId}:${this.factCollectionId}`}};var StoredFact=class _StoredFact{static{__name(this,"StoredFact")}factCollectionKey;factTypeId;payload;originBlock;constructor(factCollectionKey,factTypeId,payload,originBlock){this.factCollectionKey=factCollectionKey,this.factTypeId=factTypeId,this.payload=payload,this.originBlock=originBlock}get isRetractable(){return this.originBlock!==void 0}payloadHash(){return sha256ToField([this.payload.length,...this.payload])}toFact(){return{factTypeId:this.factTypeId,payload:this.payload,originBlock:this.originBlock}}toBuffer(){return serializeToBuffer(this.factCollectionKey.contractAddress,this.factCollectionKey.scope,this.factCollectionKey.factCollectionTypeId,this.factCollectionKey.factCollectionId,this.factTypeId,this.payload.length,...this.payload,this.originBlock!==void 0,this.originBlock?this.originBlock.blockNumber:0,this.originBlock?this.originBlock.blockHash:Fr.ZERO)}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer),contractAddress=reader.readObject(AztecAddress),scope=reader.readObject(AztecAddress),factCollectionTypeId=reader.readObject(Fr),factCollectionId=reader.readObject(Fr),factTypeId=reader.readObject(Fr),payloadLen=reader.readNumber(),payload=reader.readArray(payloadLen,Fr),hasOriginBlock=reader.readBoolean(),blockNumber=reader.readNumber(),blockHash=reader.readObject(Fr),originBlock=hasOriginBlock?{blockNumber,blockHash}:void 0;return new _StoredFact(new FactCollectionKey(contractAddress,scope,factCollectionTypeId,factCollectionId),factTypeId,[...payload],originBlock)}};function factKeyStrOf(fact){let origin=fact.originBlock?`${fact.originBlock.blockNumber}:${fact.originBlock.blockHash}`:"none";return`${fact.factCollectionKey}:${fact.factTypeId}:${fact.payloadHash()}:${origin}`}__name(factKeyStrOf,"factKeyStrOf");var FactStore=class{static{__name(this,"FactStore")}storeName="fact";#store;#facts;#factsByCollection;#factsByBlock;#opsForJob;#jobLocks;logger=createLogger("fact_store");constructor(store){this.#store=store,this.#facts=store.openMap("facts"),this.#factsByCollection=store.openMultiMap("facts_by_collection"),this.#factsByBlock=store.openMultiMap("facts_by_block"),this.#opsForJob=new Map,this.#jobLocks=new Map}recordFact(factCollectionKey,factTypeId,payload,originBlock,jobId){return this.#withJobLock(jobId,()=>(this.#stagedOpsFor(jobId).push({kind:"recordFact",fact:new StoredFact(factCollectionKey,factTypeId,payload,originBlock)}),Promise.resolve()))}deleteFactCollection(factCollectionKey,jobId){return this.#withJobLock(jobId,()=>(this.#stagedOpsFor(jobId).push({kind:"deleteFactCollection",key:factCollectionKey}),Promise.resolve()))}async getFactCollection(factCollectionKey,jobId){let collectionKey=factCollectionKey.toString(),committed=await this.#store.transactionAsync(()=>this.#readCollectionsFromDb([factCollectionKey])),collection=this.#foldStagedOps(committed,jobId).get(collectionKey);if(!collection)return;let facts=[...collection.facts.values()];return facts.length>0?{key:factCollectionKey,facts}:void 0}async getFactCollectionsByType(factCollectionTypeKey,jobId){let typeKey=factCollectionTypeKey.toString(),committed=await this.#readCollectionsFromDbByType(typeKey);return Array.from(this.#foldStagedOps(committed,jobId,typeKey).values()).map(collection=>({key:collection.key,facts:[...collection.facts.values()]})).filter(collection=>collection.facts.length>0)}async commit(jobId){for(let op of this.#stagedOpsFor(jobId))switch(op.kind){case"recordFact":await this.#commitFact(op.fact);break;case"deleteFactCollection":await this.#deleteCollection(op.key.toString());break;default:{let _exhaustive=op;throw new Error(`Unhandled FactStore staged op kind: ${JSON.stringify(_exhaustive)}`)}}this.#clearJobData(jobId)}discardStaged(jobId){return this.#clearJobData(jobId),Promise.resolve()}async rollback(toBlock){if(this.#opsForJob.size>0)throw new Error("PXE fact store rollback is not allowed while jobs are running");let removedFacts=await this.#retractFacts(toBlock);this.logger.verbose("rolled back fact store",{removedFacts,toBlock})}async#retractFacts(toBlock){let factReads=new Map;for await(let[,factKey]of this.#factsByBlock.entriesAsync({start:toBlock+1}))factReads.set(factKey,this.#facts.getAsync(factKey));return await Promise.all(Array.from(factReads,async([factKey,read2])=>{let buf=await read2;if(!buf){this.logger.warn("Skipping retraction of a fact missing from the primary store: by-block index is stale",{factKey});return}await this.#deleteFact(factKey,StoredFact.fromBuffer(buf))})),factReads.size}async#readCollectionsFromDb(keys){let result=new Map;for(let key of keys){let collection=await this.#loadCommittedCollection(key);collection&&result.set(key.toString(),collection)}return result}#readCollectionsFromDbByType(typeKey){return this.#store.transactionAsync(async()=>{let factReadsByCollection=new Map;for await(let[collectionKey,factKey]of this.#factsByCollection.entriesAsync({start:`${typeKey}:`,end:`${typeKey};`})){let reads=factReadsByCollection.get(collectionKey);reads||(reads=new Map,factReadsByCollection.set(collectionKey,reads)),reads.set(factKey,this.#facts.getAsync(factKey))}let result=new Map;for(let[collectionKey,reads]of factReadsByCollection){let collection=await this.#assembleCollection(FactCollectionKey.fromString(collectionKey),reads);result.set(collectionKey,collection)}return result})}async#loadCommittedCollection(collectionKey){let factReads=new Map;for await(let factKey of this.#factsByCollection.getValuesAsync(collectionKey.toString()))factReads.set(factKey,this.#facts.getAsync(factKey));if(factReads.size!==0)return this.#assembleCollection(collectionKey,factReads)}async#assembleCollection(collectionKey,reads){let factKeys=[...reads.keys()],bufs=await Promise.all(reads.values()),facts=new Map;for(let i=0;i<factKeys.length;i++){let factKey=factKeys[i],buf=bufs[i];if(!buf)throw new Error(`Fact not found for factKey ${factKey}`);let stored=StoredFact.fromBuffer(buf);if(stored.factCollectionKey.toString()!==collectionKey.toString())throw new Error(`Fact ${factKey} does not belong to collection ${collectionKey}`);facts.set(factKey,stored.toFact())}return{key:collectionKey,facts}}#foldStagedOps(committed,jobId,typeKey){let result=new Map;for(let[collectionKey,{key,facts}]of committed)result.set(collectionKey,{key,facts:new Map(facts)});for(let op of this.#stagedOpsFor(jobId))switch(op.kind){case"recordFact":this.#foldRecordFact(result,op,typeKey);break;case"deleteFactCollection":this.#foldDeleteFactCollection(result,op);break;default:{let _exhaustive=op;throw new Error(`Unhandled FactStore staged op kind: ${JSON.stringify(_exhaustive)}`)}}return result}#foldRecordFact(result,op,typeKey){let key=op.fact.factCollectionKey;if(typeKey!==void 0&&key.factCollectionTypeKey().toString()!==typeKey)return;let collectionKey=key.toString(),collection=result.get(collectionKey);collection||(collection={key,facts:new Map},result.set(collectionKey,collection));let fKey=factKeyStrOf(op.fact);collection.facts.has(fKey)||collection.facts.set(fKey,op.fact.toFact())}#foldDeleteFactCollection(result,op){result.delete(op.key.toString())}async#commitFact(fact){let factKey=factKeyStrOf(fact);if(await this.#facts.hasAsync(factKey)){this.logger.debug("Ignoring already recorded fact",{factKey});return}await this.#facts.set(factKey,fact.toBuffer()),await this.#factsByCollection.set(fact.factCollectionKey.toString(),factKey),fact.originBlock!==void 0&&await this.#factsByBlock.set(fact.originBlock.blockNumber,factKey)}async#deleteCollection(collectionKey){let factReads=new Map;for await(let factKey of this.#factsByCollection.getValuesAsync(collectionKey))factReads.set(factKey,this.#facts.getAsync(factKey));await Promise.all(Array.from(factReads,async([factKey,read2])=>{let buf=await read2;if(!buf)throw new Error(`Fact not found for factKey ${factKey}`);await this.#deleteFact(factKey,StoredFact.fromBuffer(buf))}))}async#deleteFact(factKey,fact){await this.#facts.delete(factKey),await this.#factsByCollection.deleteValue(fact.factCollectionKey.toString(),factKey),fact.originBlock!==void 0&&await this.#factsByBlock.deleteValue(fact.originBlock.blockNumber,factKey)}#stagedOpsFor(jobId){let ops=this.#opsForJob.get(jobId);return ops===void 0&&(ops=[],this.#opsForJob.set(jobId,ops)),ops}#clearJobData(jobId){this.#opsForJob.delete(jobId),this.#jobLocks.delete(jobId)}async#withJobLock(jobId,fn){let lock=this.#jobLocks.get(jobId);lock||(lock=new Semaphore(1),this.#jobLocks.set(jobId,lock)),await lock.acquire();try{return await fn()}finally{lock.release()}}};var OriginBlockState=(function(OriginBlockState2){return OriginBlockState2[OriginBlockState2.Pending=1]="Pending",OriginBlockState2[OriginBlockState2.Proven=2]="Proven",OriginBlockState2[OriginBlockState2.Finalized=3]="Finalized",OriginBlockState2})({});function anchoredTipBlockNumbers(tips,anchorBlockNumber){return{provenBlockNumber:Math.min(tips.proven.block.number,anchorBlockNumber),finalizedBlockNumber:Math.min(tips.finalized.block.number,anchorBlockNumber)}}__name(anchoredTipBlockNumbers,"anchoredTipBlockNumbers");function classifyOriginBlockState(blockNumber,tips){return blockNumber<=tips.finalizedBlockNumber?3:blockNumber<=tips.provenBlockNumber?2:1}__name(classifyOriginBlockState,"classifyOriginBlockState");function toFactWithOriginState(fact,tips){let originBlock=fact.originBlock?{blockNumber:fact.originBlock.blockNumber,blockHash:fact.originBlock.blockHash,blockState:classifyOriginBlockState(fact.originBlock.blockNumber,tips)}:void 0;return{factTypeId:fact.factTypeId,payload:fact.payload,originBlock}}__name(toFactWithOriginState,"toFactWithOriginState");var FactService=class{static{__name(this,"FactService")}factStore;allowedScopes;constructor(factStore,allowedScopes){this.factStore=factStore,this.allowedScopes=allowedScopes}recordFact(factCollectionKey,factTypeId,payload,originBlock,jobId){return assertAllowedScope(factCollectionKey.scope,this.allowedScopes),this.factStore.recordFact(factCollectionKey,factTypeId,payload,originBlock,jobId)}deleteFactCollection(factCollectionKey,jobId){return assertAllowedScope(factCollectionKey.scope,this.allowedScopes),this.factStore.deleteFactCollection(factCollectionKey,jobId)}async getFactCollection(factCollectionKey,tips,jobId){assertAllowedScope(factCollectionKey.scope,this.allowedScopes);let collection=await this.factStore.getFactCollection(factCollectionKey,jobId);if(collection)return{key:collection.key,facts:this.#annotate(collection.facts,tips)}}async getFactCollectionsByType(factCollectionTypeKey,tips,jobId){return assertAllowedScope(factCollectionTypeKey.scope,this.allowedScopes),(await this.factStore.getFactCollectionsByType(factCollectionTypeKey,jobId)).map(collection=>({key:collection.key,facts:this.#annotate(collection.facts,tips)}))}#annotate(facts,tips){return facts.map(fact=>toFactWithOriginState(fact,tips))}};var AnchoredContractData=class{static{__name(this,"AnchoredContractData")}store;contractClassService;anchorBlockHeader;overrides;constructor(store,contractClassService,anchorBlockHeader,overrides){this.store=store,this.contractClassService=contractClassService,this.anchorBlockHeader=anchorBlockHeader,this.overrides=overrides}getContractInstance(address){let override=this.overrides?.[address.toString()];return override?Promise.resolve(override.instance):this.store.getContractInstance(address)}getCurrentClassId(address){let override=this.overrides?.[address.toString()];return override?Promise.resolve(override.instance.currentContractClassId):this.contractClassService.getCurrentClassId(address,this.anchorBlockHeader)}async getFunctionArtifact(address,selector){let classId=await this.getCurrentClassId(address);return classId?this.store.getFunctionArtifact(classId,selector):void 0}async getFunctionArtifactWithDebugMetadata(address,selector){let classId=await this.getCurrentClassId(address);return classId?this.store.getFunctionArtifactWithDebugMetadata(classId,selector):void 0}async getDebugContractName(address){let classId=await this.getCurrentClassId(address);return classId?this.store.getDebugContractName(classId):void 0}async getDebugFunctionName(address,selector){let classId=await this.getCurrentClassId(address);return classId?this.store.getDebugFunctionName(classId,selector):`${address}:${selector}`}};var ExecutionNoteCache=class{static{__name(this,"ExecutionNoteCache")}protocolNullifier;notes;noteMap;nullifierMap;emittedNullifiers;minRevertibleSideEffectCounter;inRevertiblePhase;usedProtocolNullifierForNonces;constructor(protocolNullifier){this.protocolNullifier=protocolNullifier,this.notes=[],this.noteMap=new Map,this.nullifierMap=new Map,this.emittedNullifiers=new Set,this.minRevertibleSideEffectCounter=0,this.inRevertiblePhase=!1}async setMinRevertibleSideEffectCounter(minRevertibleSideEffectCounter){if(this.inRevertiblePhase)throw new Error(`Cannot enter the revertible phase twice. Current counter: ${minRevertibleSideEffectCounter}. Previous enter counter: ${this.minRevertibleSideEffectCounter}`);this.inRevertiblePhase=!0,this.minRevertibleSideEffectCounter=minRevertibleSideEffectCounter;let nullifiers=this.getEmittedNullifiers();this.usedProtocolNullifierForNonces=nullifiers.length===0;let nonceGenerator=this.usedProtocolNullifierForNonces?this.protocolNullifier:new Fr(nullifiers[0]),updatedNotes=await Promise.all(this.notes.map(async({note,counter},i)=>{let noteNonce=await computeNoteHashNonce(nonceGenerator,i),uniqueNoteHash=await computeUniqueNoteHash(noteNonce,await siloNoteHash(note.contractAddress,note.noteHash));return{counter,note:{...note,noteNonce},noteHashForConsumption:uniqueNoteHash}}));this.notes=[],this.noteMap=new Map,updatedNotes.forEach(n=>this.#addNote(n))}isSideEffectCounterRevertible(sideEffectCounter){return this.inRevertiblePhase?sideEffectCounter>=this.minRevertibleSideEffectCounter:!1}finish(){this.inRevertiblePhase||(this.usedProtocolNullifierForNonces=this.getEmittedNullifiers().length===0)}addNewNote(note,counter){let previousNote=this.notes[this.notes.length-1];if(previousNote&&previousNote.counter>=counter)throw new Error(`Note hash counters must be strictly increasing. Current counter: ${counter}. Previous counter: ${previousNote.counter}.`);this.#addNote({note,counter,noteHashForConsumption:note.noteHash})}async nullifyNote(contractAddress,innerNullifier,noteHash){let siloedNullifier=(await siloNullifier(contractAddress,innerNullifier)).toBigInt(),nullifiedNoteHashCounter;if(noteHash.isEmpty())this.#recordNullifier(contractAddress,siloedNullifier);else{let notesInContract=this.noteMap.get(contractAddress.toBigInt())??[],noteIndexToRemove=notesInContract.findIndex(n=>n.noteHashForConsumption.equals(noteHash));if(noteIndexToRemove===-1)throw new Error("Attempt to remove a pending note that does not exist.");let note=notesInContract.splice(noteIndexToRemove,1)[0];nullifiedNoteHashCounter=note.counter,this.noteMap.set(contractAddress.toBigInt(),notesInContract),this.notes=this.notes.filter(n=>n.counter!==note.counter),this.inRevertiblePhase&¬e.counter<this.minRevertibleSideEffectCounter&&this.#recordNullifier(contractAddress,siloedNullifier)}return nullifiedNoteHashCounter}async nullifierCreated(contractAddress,innerNullifier){let siloedNullifier=(await siloNullifier(contractAddress,innerNullifier)).toBigInt();this.#recordNullifier(contractAddress,siloedNullifier)}getNotes(contractAddress,owner,storageSlot){return(this.noteMap.get(contractAddress.toBigInt())??[]).filter(n=>owner===void 0||n.note.owner.equals(owner)).filter(n=>n.note.storageSlot.equals(storageSlot)).map(n=>n.note)}checkNoteExists(contractAddress,noteHash){return(this.noteMap.get(contractAddress.toBigInt())??[]).some(n=>n.note.noteHash.equals(noteHash))}getNullifiers(contractAddress){return this.nullifierMap.get(contractAddress.toBigInt())??new Set}#addNote(note){this.notes.push(note);let notes=this.noteMap.get(note.note.contractAddress.toBigInt())??[];notes.push(note),this.noteMap.set(note.note.contractAddress.toBigInt(),notes)}getAllNotes(){return this.notes}getEmittedNullifiers(){return[...this.emittedNullifiers].map(n=>new Fr(n))}getAllNullifiers(){if(this.usedProtocolNullifierForNonces===void 0)throw new Error("usedProtocolNullifierForNonces is not set yet. Call finish() to complete the transaction.");let allNullifiers=this.getEmittedNullifiers();return[...this.usedProtocolNullifierForNonces?[this.protocolNullifier]:[],...allNullifiers]}getNonceGenerator(){return this.getAllNullifiers()[0]}#recordNullifier(contractAddress,siloedNullifier){let nullifiers=this.getNullifiers(contractAddress);if(nullifiers.has(siloedNullifier))throw new Error(`Duplicate siloed nullifier ${siloedNullifier} emitted by contract ${contractAddress}`);nullifiers.add(siloedNullifier),this.nullifierMap.set(contractAddress.toBigInt(),nullifiers),this.emittedNullifiers.add(siloedNullifier)}};var ExecutionTaggingIndexCache=class{static{__name(this,"ExecutionTaggingIndexCache")}taggingIndexMap=new Map;getLastUsedIndex(secret){return this.taggingIndexMap.get(secret.toString())?.highestIndex}setLastUsedIndex(secret,index){let currentValue=this.taggingIndexMap.get(secret.toString());if(currentValue!==void 0&¤tValue.highestIndex!==index-1)throw new Error(`Invalid tagging index update. Current value: ${currentValue.highestIndex}, new value: ${index}`);currentValue!==void 0?currentValue.highestIndex=index:this.taggingIndexMap.set(secret.toString(),{lowestIndex:index,highestIndex:index})}getUsedTaggingIndexRanges(){return Array.from(this.taggingIndexMap.entries()).map(([secret,{lowestIndex,highestIndex}])=>({extendedSecret:AppTaggingSecret.fromString(secret),lowestIndex,highestIndex}))}};var HashedValuesCache=class _HashedValuesCache{static{__name(this,"HashedValuesCache")}cache;constructor(initialArguments=[]){this.cache=new Map;for(let initialArg of initialArguments)this.cache.set(initialArg.hash.toBigInt(),initialArg.values)}static create(initialArguments=[]){return new _HashedValuesCache(initialArguments)}getPreimage(hash5){return hash5.isEmpty()?[]:this.cache.get(hash5.toBigInt())}store(values,hash5){this.cache.set(hash5.toBigInt(),values)}};var BoundedVec=class _BoundedVec{static{__name(this,"BoundedVec")}data;maxLength;elementSize;constructor(data,maxLength,elementSize){this.data=data,this.maxLength=maxLength,this.elementSize=elementSize}static from({data,maxLength,elementSize=1}){return new _BoundedVec(data,maxLength,elementSize)}equals(other,innerEquals){return this.maxLength===other.maxLength&&this.data.length===other.data.length&&this.data.every((value,i)=>innerEquals(value,other.data[i]))}};var EphemeralArray=class _EphemeralArray{static{__name(this,"EphemeralArray")}state;constructor(state){this.state=state}static fromValues(service,values){return new _EphemeralArray({kind:"output",service,values})}static fromSlot(slot,mapping){return new _EphemeralArray({kind:"input",slot,mapping})}materializeSlot(serializeItem){return this.state.kind==="input"?this.state.slot:(this.state.cachedSlot===void 0&&(this.state.cachedSlot=this.state.service.newArray(this.state.values.map(serializeItem))),this.state.cachedSlot)}readAll(service){if(this.state.kind==="output")return this.state.values;let mapping=this.state.mapping;return service.readArrayAt(this.state.slot).map(fields=>mapping.deserialization.fn([FieldReader.asReader(fields)]))}};var EventValidationRequest=class _EventValidationRequest{static{__name(this,"EventValidationRequest")}contractAddress;eventTypeId;randomness;serializedEvent;eventCommitment;txHash;constructor(contractAddress,eventTypeId,randomness,serializedEvent,eventCommitment,txHash){this.contractAddress=contractAddress,this.eventTypeId=eventTypeId,this.randomness=randomness,this.serializedEvent=serializedEvent,this.eventCommitment=eventCommitment,this.txHash=txHash}static fromFields(fields){let reader=FieldReader.asReader(fields),contractAddress=AztecAddress.fromFieldUnsafe(reader.readField()),eventTypeId=EventSelector.fromField(reader.readField()),randomness=reader.readField(),maxEventSerializedLen=reader.readField().toNumber(),eventStorage=reader.readFieldArray(maxEventSerializedLen),eventLen=reader.readField().toNumber(),serializedEvent=eventStorage.slice(0,eventLen),eventCommitment=reader.readField(),txHash=TxHash.fromField(reader.readField());if(reader.remainingFields()!==0)throw new Error(`Error converting array of fields to EventValidationRequest: expected ${reader.cursor} fields but received ${reader.cursor+reader.remainingFields()} (maxEventSerializedLen=${maxEventSerializedLen}).`);return new _EventValidationRequest(contractAddress,eventTypeId,randomness,serializedEvent,eventCommitment,txHash)}};var LogSource=(function(LogSource2){return LogSource2[LogSource2.PRIVATE=0]="PRIVATE",LogSource2[LogSource2.PUBLIC=1]="PUBLIC",LogSource2[LogSource2.PUBLIC_AND_PRIVATE=2]="PUBLIC_AND_PRIVATE",LogSource2})({});function logSourceFromField(field){let sourceNum=field.toNumber();if(!(sourceNum in LogSource)){let validNames=Object.keys(LogSource).filter(k=>isNaN(Number(k)));throw new Error(`Invalid LogSource value ${sourceNum}, expected one of ${validNames.join(", ")}`)}return sourceNum}__name(logSourceFromField,"logSourceFromField");var NoteValidationRequest=class _NoteValidationRequest{static{__name(this,"NoteValidationRequest")}contractAddress;owner;storageSlot;randomness;noteNonce;content;noteHash;nullifier;txHash;constructor(contractAddress,owner,storageSlot,randomness,noteNonce,content,noteHash,nullifier,txHash){this.contractAddress=contractAddress,this.owner=owner,this.storageSlot=storageSlot,this.randomness=randomness,this.noteNonce=noteNonce,this.content=content,this.noteHash=noteHash,this.nullifier=nullifier,this.txHash=txHash}static fromFields(fields){let reader=FieldReader.asReader(fields),contractAddress=AztecAddress.fromFieldUnsafe(reader.readField()),owner=AztecAddress.fromFieldUnsafe(reader.readField()),storageSlot=reader.readField(),randomness=reader.readField(),noteNonce=reader.readField(),maxNotePackedLen=reader.readField().toNumber(),contentStorage=reader.readFieldArray(maxNotePackedLen),contentLen=reader.readField().toNumber(),content=contentStorage.slice(0,contentLen),noteHash=reader.readField(),nullifier=reader.readField(),txHash=TxHash.fromField(reader.readField());if(reader.remainingFields()!==0)throw new Error(`Error converting array of fields to NoteValidationRequest: expected ${reader.cursor} fields but received ${reader.cursor+reader.remainingFields()} (maxNotePackedLen=${maxNotePackedLen}).`);return new _NoteValidationRequest(contractAddress,owner,storageSlot,randomness,noteNonce,content,noteHash,nullifier,txHash)}};var Option=class _Option{static{__name(this,"Option")}value;size;constructor(value,size){this.value=value,this.size=size}static some(value){return new _Option(value,void 0)}static none(size){return new _Option(void 0,size)}isSome(){return this.value!==void 0}isNone(){return this.value===void 0}equals(other,innerEquals){return this.isSome()&&other.isSome()?innerEquals(this.value,other.value):this.isNone()&&other.isNone()}};var NON_INTERACTIVE_HANDSHAKE=1,UNCONSTRAINED_SECRET=2;function resolvedTaggingStrategyToFields(resolved){switch(resolved.type){case"non-interactive-handshake":return[new Fr(NON_INTERACTIVE_HANDSHAKE),Fr.ZERO];case"unconstrained-secret":return[new Fr(UNCONSTRAINED_SECRET),resolved.secret]}}__name(resolvedTaggingStrategyToFields,"resolvedTaggingStrategyToFields");function resolvedTaggingStrategyFromFields(kind,secret){switch(kind){case NON_INTERACTIVE_HANDSHAKE:return{type:"non-interactive-handshake"};case UNCONSTRAINED_SECRET:return{type:"unconstrained-secret",secret};default:throw new Error(`Unrecognized resolved tagging strategy kind: ${kind}`)}}__name(resolvedTaggingStrategyFromFields,"resolvedTaggingStrategyFromFields");function fromRawData(nonzeroNoteHashCounter,maybeNoteNonce){if(nonzeroNoteHashCounter)return maybeNoteNonce.equals(Fr.ZERO)?{stage:1,maybeNoteNonce}:{stage:2,maybeNoteNonce};if(maybeNoteNonce.equals(Fr.ZERO))throw new Error("Note has a zero note hash counter and no nonce - existence cannot be proven");return{stage:3,maybeNoteNonce}}__name(fromRawData,"fromRawData");function packAsHintedNote({contractAddress,owner,randomness,storageSlot,noteNonce,isPending,note}){let noteMetadata=fromRawData(isPending,noteNonce);return[...note.items,contractAddress.toField(),owner.toField(),randomness,storageSlot,new Fr(noteMetadata.stage),noteMetadata.maybeNoteNonce]}__name(packAsHintedNote,"packAsHintedNote");function assertReadersConsumed(readers){readers.forEach((reader,slot)=>{if(!reader.isFinished())throw new Error(`Malformed oracle input: ${reader.remainingFields()} unexpected trailing field(s) in slot ${slot}`)})}__name(assertReadersConsumed,"assertReadersConsumed");var FIELD={serialization:{fn:__name(v=>[v],"fn")},deserialization:{fn:__name(([reader])=>reader.readField(),"fn")},shape:["scalar"]},BOOL={serialization:{fn:__name(v=>[new Fr(v?1n:0n)],"fn")},deserialization:{fn:__name(([reader])=>!reader.readField().isZero(),"fn")},shape:["scalar"]},U32={serialization:{fn:__name(v=>[new Fr(v)],"fn")},deserialization:{fn:__name(([reader])=>{let value=reader.readField().toBigInt();if(value>0xffffffffn)throw new Error(`U32 overflow: value ${value} exceeds u32 max (${0xffffffffn})`);return Number(value)},"fn")},shape:["scalar"]},BLOCK_NUMBER={serialization:{fn:__name(v=>[new Fr(v)],"fn")},deserialization:{fn:__name(([reader])=>BlockNumber(reader.readField().toNumber()),"fn")},shape:["scalar"]},BYTE={serialization:{fn:__name(byte=>[new Fr(byte)],"fn")},deserialization:{fn:__name(([reader])=>{let value=reader.readField().toBigInt();if(value>0xffn)throw new Error(`BYTE overflow: value ${value} exceeds u8 max (255)`);return Number(value)},"fn")},shape:["scalar"]},DELIVERY_MODE={deserialization:{fn:__name(readers=>appTaggingSecretKindFromDeliveryMode(BYTE.deserialization.fn(readers)),"fn")},shape:BYTE.shape},RESOLVED_TAGGING_STRATEGY={serialization:{fn:__name(resolved=>resolvedTaggingStrategyToFields(resolved),"fn")},deserialization:{fn:__name(([kindReader,secretReader])=>resolvedTaggingStrategyFromFields(kindReader.readField().toNumber(),secretReader.readField()),"fn")},shape:["scalar","scalar"]},BIGINT={serialization:{fn:__name(v=>[new Fr(v)],"fn")},deserialization:{fn:__name(([reader])=>reader.readField().toBigInt(),"fn")},shape:["scalar"]},STR={serialization:{fn:__name(str=>[Array.from(Buffer.from(str,"utf-8")).map(b=>new Fr(b))],"fn")},deserialization:{fn:__name(([reader])=>{let chars=[];for(;!reader.isFinished();)chars.push(String.fromCharCode(reader.readField().toNumber()));return chars.join("")},"fn")},shape:["variable"]},AZTEC_ADDRESS={serialization:{fn:__name(v=>[v.toField()],"fn")},deserialization:{fn:__name(([reader])=>AztecAddress.fromFieldUnsafe(reader.readField()),"fn")},shape:["scalar"]},BLOCK_HASH={serialization:{fn:__name(v=>[new Fr(v.toBuffer())],"fn")},deserialization:{fn:__name(([reader])=>new BlockHash(reader.readField()),"fn")},shape:["scalar"]},FUNCTION_SELECTOR={serialization:{fn:__name(v=>[v.toField()],"fn")},deserialization:{fn:__name(([reader])=>FunctionSelector.fromField(reader.readField()),"fn")},shape:["scalar"]},NOTE_SELECTOR={serialization:{fn:__name(v=>[v.toField()],"fn")},deserialization:{fn:__name(([reader])=>NoteSelector.fromField(reader.readField()),"fn")},shape:["scalar"]},TX_HASH={serialization:{fn:__name(v=>[v.hash],"fn")},deserialization:{fn:__name(([reader])=>TxHash.fromField(reader.readField()),"fn")},shape:["scalar"]},TAG={serialization:{fn:__name(v=>[v.value],"fn")},deserialization:{fn:__name(([reader])=>new Tag(reader.readField()),"fn")},shape:["scalar"]},POINT=STRUCT([{name:"x",type:FIELD},{name:"y",type:FIELD}]),LOG_SOURCE={serialization:{fn:__name(v=>[new Fr(v)],"fn")},deserialization:{fn:__name(([reader])=>logSourceFromField(reader.readField()),"fn")},shape:["scalar"]},ETH_ADDRESS={serialization:{fn:__name(v=>[v.toField()],"fn")},deserialization:{fn:__name(([reader])=>EthAddress.fromField(reader.readField()),"fn")},shape:["scalar"]},SLOT_NUMBER={serialization:{fn:__name(v=>[new Fr(v)],"fn")},shape:["scalar"]},APPEND_ONLY_TREE_SNAPSHOT=STRUCT([{name:"root",type:FIELD},{name:"nextAvailableLeafIndex",type:U32}]),PARTIAL_STATE_REFERENCE=STRUCT([{name:"noteHashTree",type:APPEND_ONLY_TREE_SNAPSHOT},{name:"nullifierTree",type:APPEND_ONLY_TREE_SNAPSHOT},{name:"publicDataTree",type:APPEND_ONLY_TREE_SNAPSHOT}]),STATE_REFERENCE=STRUCT([{name:"l1ToL2MessageTree",type:APPEND_ONLY_TREE_SNAPSHOT},{name:"partial",type:PARTIAL_STATE_REFERENCE}]),GAS_FEES=STRUCT([{name:"feePerDaGas",type:BIGINT},{name:"feePerL2Gas",type:BIGINT}]),GLOBAL_VARIABLES=STRUCT([{name:"chainId",type:FIELD},{name:"version",type:FIELD},{name:"blockNumber",type:BLOCK_NUMBER},{name:"slotNumber",type:SLOT_NUMBER},{name:"timestamp",type:BIGINT},{name:"coinbase",type:ETH_ADDRESS},{name:"feeRecipient",type:AZTEC_ADDRESS},{name:"gasFees",type:GAS_FEES}]),BLOCK_HEADER=STRUCT([{name:"lastArchive",type:APPEND_ONLY_TREE_SNAPSHOT},{name:"state",type:STATE_REFERENCE},{name:"spongeBlobHash",type:FIELD},{name:"globalVariables",type:GLOBAL_VARIABLES},{name:"totalFees",type:FIELD},{name:"totalManaUsed",type:FIELD}]),KEY_VALIDATION_REQUEST=STRUCT([{name:"pkMHash",type:FIELD},{name:"skApp",type:FIELD}]),PUBLIC_KEYS=STRUCT([{name:"npkMHash",type:FIELD},{name:"ivpkM",type:POINT},{name:"ovpkMHash",type:FIELD},{name:"tpkMHash",type:FIELD},{name:"mspkMHash",type:FIELD},{name:"fbpkMHash",type:FIELD}]),CONTRACT_INSTANCE=STRUCT([{name:"salt",type:FIELD},{name:"deployer",type:AZTEC_ADDRESS},{name:"originalContractClassId",type:FIELD},{name:"initializationHash",type:FIELD},{name:"immutablesHash",type:FIELD},{name:"publicKeys",type:PUBLIC_KEYS}]),NULLIFIER_LEAF=STRUCT([{name:"nullifier",type:FIELD}]),NULLIFIER_LEAF_PREIMAGE=STRUCT([{name:"leaf",type:NULLIFIER_LEAF},{name:"nextKey",type:FIELD},{name:"nextIndex",type:BIGINT}]),NULLIFIER_MEMBERSHIP_WITNESS=STRUCT([{name:"leafPreimage",type:NULLIFIER_LEAF_PREIMAGE},{name:"index",type:BIGINT},{name:"siblingPath",type:SIBLING_PATH(42)}]),PUBLIC_DATA_LEAF=STRUCT([{name:"slot",type:FIELD},{name:"value",type:FIELD}]),PUBLIC_DATA_LEAF_PREIMAGE=STRUCT([{name:"leaf",type:PUBLIC_DATA_LEAF},{name:"nextKey",type:FIELD},{name:"nextIndex",type:BIGINT}]),PUBLIC_DATA_WITNESS=STRUCT([{name:"index",type:BIGINT},{name:"leafPreimage",type:PUBLIC_DATA_LEAF_PREIMAGE},{name:"siblingPath",type:SIBLING_PATH(40)}]),MESSAGE_LOAD_ORACLE_INPUTS=STRUCT([{name:"index",type:BIGINT},{name:"siblingPath",type:SIBLING_PATH(36)}]),UTILITY_CONTEXT=STRUCT([{name:"blockHeader",type:BLOCK_HEADER},{name:"contractAddress",type:AZTEC_ADDRESS},{name:"msgSender",type:AZTEC_ADDRESS}]),CALL_PRIVATE_RESULT=STRUCT([{name:"endSideEffectCounter",type:FIELD},{name:"returnsHash",type:FIELD}]),PUBLIC_KEYS_AND_PARTIAL_ADDRESS=STRUCT([{name:"publicKeys",type:PUBLIC_KEYS},{name:"partialAddress",type:FIELD}]),CONTRACT_CLASS_LOG=STRUCT([{name:"contractAddress",type:AZTEC_ADDRESS},{name:"fields",type:FIXED_ARRAY(FIELD,3023)},{name:"emittedLength",type:U32}]),REVERT_CODE={serialization:{fn:__name(rc=>[rc.toField()],"fn")},shape:["scalar"]},PUBLIC_DATA_WRITE=STRUCT([{name:"leafSlot",type:FIELD},{name:"value",type:FIELD}]),PRIVATE_LOG=STRUCT([{name:"fields",type:FIXED_ARRAY(FIELD,16)},{name:"emittedLength",type:U32}]),FLAT_PUBLIC_LOGS=STRUCT([{name:"length",type:U32},{name:"payload",type:FIXED_ARRAY(FIELD,4096)}]),CONTRACT_CLASS_LOG_ENTRY=STRUCT([{name:"fields",type:FIXED_ARRAY(FIELD,3023)},{name:"emittedLength",type:U32},{name:"contractAddress",type:AZTEC_ADDRESS}]),CONTRACT_CLASS_LOGS=FIXED_ARRAY(CONTRACT_CLASS_LOG_ENTRY,1),TX_EFFECT=STRUCT([{name:"revertCode",type:REVERT_CODE},{name:"txHash",type:TX_HASH},{name:"transactionFee",type:FIELD},{name:"noteHashes",type:FIXED_ARRAY(FIELD,64)},{name:"nullifiers",type:FIXED_ARRAY(FIELD,64)},{name:"l2ToL1Msgs",type:FIXED_ARRAY(FIELD,8)},{name:"publicDataWrites",type:FIXED_ARRAY(PUBLIC_DATA_WRITE,64)},{name:"privateLogs",type:FIXED_ARRAY(PRIVATE_LOG,64)},{name:"publicLogs",type:FLAT_PUBLIC_LOGS},{name:"contractClassLogs",type:CONTRACT_CLASS_LOGS}]),NOTE={serialization:{fn:__name(noteData=>packAsHintedNote({contractAddress:noteData.contractAddress,owner:noteData.owner,randomness:noteData.randomness,storageSlot:noteData.storageSlot,noteNonce:noteData.noteNonce,isPending:noteData.isPending,note:noteData.note}),"fn")},shape:["variable"]},NOTE_VALIDATION_REQUEST={deserialization:{fn:__name(([reader])=>NoteValidationRequest.fromFields(reader),"fn")},shape:["variable"]},EVENT_VALIDATION_REQUEST={deserialization:{fn:__name(([reader])=>EventValidationRequest.fromFields(reader),"fn")},shape:["variable"]},LOG_RETRIEVAL_REQUEST=STRUCT([{name:"contractAddress",type:AZTEC_ADDRESS},{name:"tag",type:TAG},{name:"source",type:LOG_SOURCE},{name:"fromBlock",type:OPTION(BLOCK_NUMBER)},{name:"toBlock",type:OPTION(BLOCK_NUMBER)}]),LOG_RETRIEVAL_RESPONSE=STRUCT([{name:"logPayload",type:FIXED_BOUNDED_VEC(FIELD,15)},{name:"txHash",type:TX_HASH},{name:"uniqueNoteHashesInTx",type:FIXED_BOUNDED_VEC(FIELD,64)},{name:"firstNullifierInTx",type:FIELD},{name:"blockNumber",type:BLOCK_NUMBER},{name:"blockTimestamp",type:BIGINT},{name:"blockHash",type:BLOCK_HASH}]),MESSAGE_CONTEXT=STRUCT([{name:"txHash",type:TX_HASH},{name:"uniqueNoteHashesInTx",type:FIXED_BOUNDED_VEC(FIELD,64)},{name:"firstNullifierInTx",type:FIELD}]),PENDING_TAGGED_LOG=STRUCT([{name:"log",type:FIXED_BOUNDED_VEC(FIELD,16)},{name:"context",type:MESSAGE_CONTEXT}]),RESOLVED_TX={serialization:{fn:__name(resolved=>[resolved.toFields()],"fn")},shape:[{len:69}]},ORIGIN_BLOCK={serialization:{fn:__name(ob=>[new Fr(ob.blockNumber),ob.blockHash],"fn")},deserialization:{fn:__name(([blockNumberReader,blockHashReader])=>({blockNumber:blockNumberReader.readField().toNumber(),blockHash:blockHashReader.readField()}),"fn")},shape:["scalar","scalar"]},RETRACTABLE_FACT_ORIGIN={serialization:{fn:__name(o=>[new Fr(o.blockNumber),o.blockHash,new Fr(o.blockState)],"fn")},shape:["scalar","scalar","scalar"]},FACT={serialization:{fn:__name(f=>[f.factTypeId,f.payload.materializeSlot(v=>FIELD.serialization.fn(v).flat()),...OPTION(RETRACTABLE_FACT_ORIGIN).serialization.fn(f.originBlock)],"fn")},shape:["scalar","scalar","scalar","scalar","scalar","scalar"]},FACT_COLLECTION={serialization:{fn:__name(c2=>[c2.contractAddress.toField(),c2.scope.toField(),c2.factCollectionTypeId,c2.factCollectionId,c2.facts.materializeSlot(v=>FACT.serialization.fn(v).flat())],"fn")},shape:["scalar","scalar","scalar","scalar","scalar"]},PROVIDED_SECRET={deserialization:{fn:__name(([reader])=>({secret:reader.readField(),mode:appTaggingSecretKindFromDeliveryMode(BYTE.deserialization.fn([reader]))}),"fn")},shape:[{len:2}]};function SIBLING_PATH(height){return{serialization:{fn:__name(sp=>[sp.toFields()],"fn")},shape:[{len:height}]}}__name(SIBLING_PATH,"SIBLING_PATH");function MEMBERSHIP_WITNESS(height){return STRUCT([{name:"leafIndex",type:BIGINT},{name:"siblingPath",type:FIXED_ARRAY(FIELD,height)}])}__name(MEMBERSHIP_WITNESS,"MEMBERSHIP_WITNESS");function ARRAY(inner){return{kind:"array",inner,serialization:inner.serialization?{fn:__name(values=>[packElements(inner,values)],"fn")}:void 0,deserialization:inner.deserialization?{fn:__name(([reader])=>unpackElements(inner,reader,reader.remainingFields()/fieldWidth(inner.shape)),"fn")}:void 0,shape:[{lenFrom:__name(size=>size.length*fieldWidth(inner.shape),"lenFrom")}]}}__name(ARRAY,"ARRAY");function FIXED_ARRAY(element,maxLength){let elementWidth=fieldWidth(element.shape);return{serialization:element.serialization?{fn:__name(values=>[padArrayEnd(packElements(element,values),Fr.ZERO,maxLength*elementWidth)],"fn")}:void 0,deserialization:element.deserialization?{fn:__name(([reader])=>unpackElements(element,reader,maxLength),"fn")}:void 0,shape:[{len:maxLength*elementWidth}]}}__name(FIXED_ARRAY,"FIXED_ARRAY");function BOUNDED_VEC(inner){return{kind:"bounded-vec",inner,serialization:inner.serialization?{fn:__name(bv=>{if(bv.data.length>bv.maxLength)throw new Error(`Got ${bv.data.length} items, but maxLength is ${bv.maxLength}`);let elementWidth=tryFieldWidth(inner.shape)??bv.elementSize;return[padArrayEnd(packElements(inner,bv.data),Fr.ZERO,bv.maxLength*elementWidth),new Fr(bv.data.length)]},"fn")}:void 0,deserialization:inner.deserialization?{fn:__name(([storageReader,lengthReader])=>{let maxLength=storageReader.remainingFields()/fieldWidth(inner.shape),length=lengthReader.readField().toNumber(),elements=unpackElements(inner,storageReader,length);return storageReader.skip(storageReader.remainingFields()),BoundedVec.from({data:elements,maxLength})},"fn")}:void 0,shape:[{lenFrom:__name(size=>size.maxLength*fieldWidth(inner.shape),"lenFrom")},"scalar"]}}__name(BOUNDED_VEC,"BOUNDED_VEC");function FIXED_BOUNDED_VEC(element,maxLength){let width=fieldWidth(element.shape);return{serialization:element.serialization?{fn:__name(values=>{if(values.length>maxLength)throw new Error(`Got ${values.length} items, but maxLength is ${maxLength}`);return[[...padArrayEnd(packElements(element,values),Fr.ZERO,maxLength*width),new Fr(values.length)]]},"fn")}:void 0,shape:[{len:maxLength*width+1}]}}__name(FIXED_BOUNDED_VEC,"FIXED_BOUNDED_VEC");function OPTION(inner){return{kind:"option",inner,serialization:inner.serialization?{fn:__name(opt=>opt.isSome()?[Fr.ONE,...inner.serialization.fn(opt.value)]:[Fr.ZERO,...zeroSlotsFromShape(inner.shape,opt.size)],"fn")}:void 0,deserialization:inner.deserialization?{fn:__name(([discriminant,...innerReaders])=>discriminant.readField().isZero()?(innerReaders.forEach(reader=>reader.skip(reader.remainingFields())),Option.none()):Option.some(inner.deserialization.fn(innerReaders)),"fn")}:void 0,shape:["scalar",...inner.shape]}}__name(OPTION,"OPTION");function BUFFER(bitSize,length){return{serialization:{fn:__name(buf=>[Array.from(buf).map(b=>new Fr(b))],"fn")},deserialization:{fn:__name(([reader])=>fromUintArray(reader.readFieldArray(length).map(f=>f.toString()),bitSize),"fn")},shape:[{len:length}]}}__name(BUFFER,"BUFFER");function EPHEMERAL_ARRAY(element){let rowElement=element.deserialization?{deserialization:{fn:__name(([rowReader])=>deserializeElement(element,rowReader.readFieldArray(rowReader.remainingFields())),"fn")},shape:["variable"]}:void 0;return{serialization:element.serialization?{fn:__name(ea=>[ea.materializeSlot(v=>serializeElement(element,v))],"fn")}:void 0,deserialization:rowElement?{fn:__name(([reader])=>EphemeralArray.fromSlot(reader.readField(),rowElement),"fn")}:void 0,shape:["scalar"]}}__name(EPHEMERAL_ARRAY,"EPHEMERAL_ARRAY");function STRUCT(fields){return{serialization:fields.every(f=>f.type.serialization)?{fn:__name(value=>{let props=value;return fields.flatMap(f=>f.type.serialization.fn(props[f.name]))},"fn")}:void 0,deserialization:fields.every(f=>f.type.deserialization)?{fn:__name(readers=>{let props={},slot=0;for(let f of fields){let slotCount=f.type.shape.length;props[f.name]=f.type.deserialization.fn(readers.slice(slot,slot+slotCount)),slot+=slotCount}return props},"fn")}:void 0,shape:fields.flatMap(f=>f.type.shape)}}__name(STRUCT,"STRUCT");function slotsOf(mapping){return mapping.shape.length}__name(slotsOf,"slotsOf");function tryFieldWidth(shape){let total=0;for(let slot of shape)if(slot==="scalar")total+=1;else if(typeof slot=="object"&&"len"in slot)total+=slot.len;else return;return total}__name(tryFieldWidth,"tryFieldWidth");function fieldWidth(shape){let width=tryFieldWidth(shape);if(width===void 0)throw new Error("Cannot compute a fixed field width for a variable-width shape");return width}__name(fieldWidth,"fieldWidth");function splitByShape(fields,shape){let readers=[],cursor=0;if(shape.forEach((slot,i)=>{if(slot==="scalar"||typeof slot=="object"&&"len"in slot){let width=slot==="scalar"?1:slot.len;if(cursor+width>fields.length)throw new Error(`Not enough fields to reconstruct shape: needed ${width}, had ${fields.length-cursor}`);readers.push(new FieldReader(fields.slice(cursor,cursor+width))),cursor+=width}else{if(i!==shape.length-1)throw new Error("A variable-width slot must be last to be reconstructed from a flat field array");readers.push(new FieldReader(fields.slice(cursor))),cursor=fields.length}}),cursor!==fields.length)throw new Error(`Malformed flattened value: ${fields.length-cursor} unexpected trailing field(s)`);return readers}__name(splitByShape,"splitByShape");function serializeElement(element,value){return element.serialization.fn(value).flat()}__name(serializeElement,"serializeElement");function deserializeElement(element,fields){let readers=splitByShape(fields,element.shape),value=element.deserialization.fn(readers);return assertReadersConsumed(readers),value}__name(deserializeElement,"deserializeElement");function packElements(element,values){return values.flatMap(v=>serializeElement(element,v))}__name(packElements,"packElements");function unpackElements(element,reader,count2){let elementWidth=fieldWidth(element.shape);return Array.from({length:count2},()=>deserializeElement(element,reader.readFieldArray(elementWidth)))}__name(unpackElements,"unpackElements");function zeroSlotsFromShape(shape,size){return shape.map(slot=>{if(slot==="scalar")return Fr.ZERO;if(slot==="variable")throw new Error("Cannot zero-fill an unsized variable-width slot");if("len"in slot)return Array(slot.len).fill(Fr.ZERO);if(size===void 0)throw new Error("Serializing Option.none() over a variable-size inner needs a size, e.g. Option.none({ length: n })");return Array(slot.lenFrom(size)).fill(Fr.ZERO)})}__name(zeroSlotsFromShape,"zeroSlotsFromShape");var LEGACY_LOG_RETRIEVAL_RESPONSE=STRUCT([{name:"logPayload",type:FIXED_BOUNDED_VEC(FIELD,15)},{name:"txHash",type:TX_HASH},{name:"uniqueNoteHashesInTx",type:FIXED_BOUNDED_VEC(FIELD,64)},{name:"firstNullifierInTx",type:FIELD}]),LEGACY_ORACLE_REGISTRY={aztec_utl_getLogsByTag:{modernOracle:"aztec_utl_getLogsByTagV2",returnType:{legacyType:EPHEMERAL_ARRAY(EPHEMERAL_ARRAY(LEGACY_LOG_RETRIEVAL_RESPONSE)),mapping:__name(result=>result,"mapping")}}};var ORACLE_REGISTRY={aztec_misc_assertCompatibleOracleVersion:makeEntry({params:[{name:"major",type:U32},{name:"minor",type:U32}]}),aztec_misc_getRandomField:makeEntry({returnType:FIELD}),aztec_misc_log:makeEntry({params:[{name:"level",type:U32},{name:"message",type:STR},{name:"fieldsSize",type:U32},{name:"fields",type:ARRAY(FIELD)}]}),aztec_utl_getUtilityContext:makeEntry({returnType:UTILITY_CONTEXT}),aztec_utl_getKeyValidationRequest:makeEntry({params:[{name:"pkMHash",type:FIELD},{name:"keyIndex",type:FIELD}],returnType:KEY_VALIDATION_REQUEST}),aztec_utl_getContractInstance:makeEntry({params:[{name:"address",type:AZTEC_ADDRESS}],returnType:CONTRACT_INSTANCE}),aztec_utl_getNoteHashMembershipWitness:makeEntry({params:[{name:"anchorBlockHash",type:BLOCK_HASH},{name:"noteHash",type:FIELD}],returnType:MEMBERSHIP_WITNESS(42)}),aztec_utl_getBlockHashMembershipWitness:makeEntry({params:[{name:"anchorBlockHash",type:BLOCK_HASH},{name:"blockHash",type:BLOCK_HASH}],returnType:OPTION(MEMBERSHIP_WITNESS(30))}),aztec_utl_getNullifierMembershipWitness:makeEntry({params:[{name:"blockHash",type:BLOCK_HASH},{name:"nullifier",type:FIELD}],returnType:NULLIFIER_MEMBERSHIP_WITNESS}),aztec_utl_getLowNullifierMembershipWitness:makeEntry({params:[{name:"blockHash",type:BLOCK_HASH},{name:"nullifier",type:FIELD}],returnType:NULLIFIER_MEMBERSHIP_WITNESS}),aztec_utl_getPublicDataWitness:makeEntry({params:[{name:"blockHash",type:BLOCK_HASH},{name:"leafSlot",type:FIELD}],returnType:PUBLIC_DATA_WITNESS}),aztec_utl_getBlockHeader:makeEntry({params:[{name:"blockNumber",type:BLOCK_NUMBER}],returnType:BLOCK_HEADER}),aztec_utl_getAuthWitness:makeEntry({params:[{name:"messageHash",type:FIELD}],returnType:ARRAY(FIELD)}),aztec_utl_getPublicKeysAndPartialAddress:makeEntry({params:[{name:"address",type:AZTEC_ADDRESS}],returnType:OPTION(PUBLIC_KEYS_AND_PARTIAL_ADDRESS)}),aztec_utl_doesNullifierExist:makeEntry({params:[{name:"innerNullifier",type:FIELD}],returnType:BOOL}),aztec_utl_getL1ToL2MembershipWitness:makeEntry({params:[{name:"contractAddress",type:AZTEC_ADDRESS},{name:"messageHash",type:FIELD},{name:"secret",type:FIELD}],returnType:MESSAGE_LOAD_ORACLE_INPUTS}),aztec_utl_getFromPublicStorage:makeEntry({params:[{name:"blockHash",type:BLOCK_HASH},{name:"contractAddress",type:AZTEC_ADDRESS},{name:"startStorageSlot",type:FIELD},{name:"numberOfElements",type:U32}],returnType:ARRAY(FIELD)}),aztec_utl_getNotes:makeEntry({params:[{name:"owner",type:OPTION(AZTEC_ADDRESS)},{name:"storageSlot",type:FIELD},{name:"numSelects",type:U32},{name:"selectByIndexes",type:ARRAY(U32)},{name:"selectByOffsets",type:ARRAY(U32)},{name:"selectByLengths",type:ARRAY(U32)},{name:"selectValues",type:ARRAY(FIELD)},{name:"selectComparators",type:ARRAY(U32)},{name:"sortByIndexes",type:ARRAY(U32)},{name:"sortByOffsets",type:ARRAY(U32)},{name:"sortByLengths",type:ARRAY(U32)},{name:"sortOrder",type:ARRAY(U32)},{name:"limit",type:U32},{name:"offset",type:U32},{name:"status",type:U32},{name:"maxNotes",type:U32},{name:"packedHintedNoteLength",type:U32}],returnType:BOUNDED_VEC(NOTE)}),aztec_utl_getPendingTaggedLogs:makeEntry({params:[{name:"scope",type:AZTEC_ADDRESS},{name:"providedSecrets",type:EPHEMERAL_ARRAY(PROVIDED_SECRET)}],returnType:EPHEMERAL_ARRAY(PENDING_TAGGED_LOG)}),aztec_utl_validateAndStoreEnqueuedNotesAndEvents:makeEntry({params:[{name:"noteValidationRequests",type:EPHEMERAL_ARRAY(NOTE_VALIDATION_REQUEST)},{name:"eventValidationRequests",type:EPHEMERAL_ARRAY(EVENT_VALIDATION_REQUEST)},{name:"scope",type:AZTEC_ADDRESS}]}),aztec_utl_getLogsByTagV2:makeEntry({params:[{name:"requests",type:EPHEMERAL_ARRAY(LOG_RETRIEVAL_REQUEST)}],returnType:EPHEMERAL_ARRAY(EPHEMERAL_ARRAY(LOG_RETRIEVAL_RESPONSE))}),aztec_utl_getResolvedTxs:makeEntry({params:[{name:"requests",type:EPHEMERAL_ARRAY(FIELD)}],returnType:EPHEMERAL_ARRAY(OPTION(RESOLVED_TX))}),aztec_utl_getTxEffect:makeEntry({params:[{name:"txHash",type:TX_HASH}],returnType:OPTION(TX_EFFECT)}),aztec_utl_setCapsule:makeEntry({params:[{name:"contractAddress",type:AZTEC_ADDRESS},{name:"slot",type:FIELD},{name:"capsule",type:ARRAY(FIELD)},{name:"scope",type:AZTEC_ADDRESS}]}),aztec_utl_getCapsule:makeEntry({params:[{name:"contractAddress",type:AZTEC_ADDRESS},{name:"slot",type:FIELD},{name:"tSize",type:U32},{name:"scope",type:AZTEC_ADDRESS}],returnType:OPTION(ARRAY(FIELD))}),aztec_utl_deleteCapsule:makeEntry({params:[{name:"contractAddress",type:AZTEC_ADDRESS},{name:"slot",type:FIELD},{name:"scope",type:AZTEC_ADDRESS}]}),aztec_utl_copyCapsule:makeEntry({params:[{name:"contractAddress",type:AZTEC_ADDRESS},{name:"srcSlot",type:FIELD},{name:"dstSlot",type:FIELD},{name:"numEntries",type:U32},{name:"scope",type:AZTEC_ADDRESS}]}),aztec_utl_decryptAes128:makeEntry({params:[{name:"ciphertext",type:BOUNDED_VEC(BYTE)},{name:"iv",type:BUFFER(8,16)},{name:"symKey",type:BUFFER(8,16)}],returnType:OPTION(BOUNDED_VEC(BYTE))}),aztec_utl_getSharedSecrets:makeEntry({params:[{name:"address",type:AZTEC_ADDRESS},{name:"ephPks",type:EPHEMERAL_ARRAY(POINT)},{name:"contractAddress",type:AZTEC_ADDRESS}],returnType:EPHEMERAL_ARRAY(FIELD)}),aztec_utl_setContractSyncCacheInvalid:makeEntry({params:[{name:"contractAddress",type:AZTEC_ADDRESS},{name:"scopes",type:BOUNDED_VEC(AZTEC_ADDRESS)}]}),aztec_utl_emitOffchainEffect:makeEntry({params:[{name:"data",type:ARRAY(FIELD)}]}),aztec_utl_recordFact:makeEntry({params:[{name:"contractAddress",type:AZTEC_ADDRESS},{name:"scope",type:AZTEC_ADDRESS},{name:"factCollectionTypeId",type:FIELD},{name:"factCollectionId",type:FIELD},{name:"factTypeId",type:FIELD},{name:"payload",type:EPHEMERAL_ARRAY(FIELD)},{name:"originBlock",type:OPTION(ORIGIN_BLOCK)}]}),aztec_utl_deleteFactCollection:makeEntry({params:[{name:"contractAddress",type:AZTEC_ADDRESS},{name:"scope",type:AZTEC_ADDRESS},{name:"factCollectionTypeId",type:FIELD},{name:"factCollectionId",type:FIELD}]}),aztec_utl_getFactCollection:makeEntry({params:[{name:"contractAddress",type:AZTEC_ADDRESS},{name:"scope",type:AZTEC_ADDRESS},{name:"factCollectionTypeId",type:FIELD},{name:"factCollectionId",type:FIELD}],returnType:OPTION(FACT_COLLECTION)}),aztec_utl_getFactCollectionsByType:makeEntry({params:[{name:"contractAddress",type:AZTEC_ADDRESS},{name:"scope",type:AZTEC_ADDRESS},{name:"factCollectionTypeId",type:FIELD}],returnType:EPHEMERAL_ARRAY(FACT_COLLECTION)}),aztec_utl_callUtilityFunction:makeEntry({params:[{name:"contractAddress",type:AZTEC_ADDRESS},{name:"functionSelector",type:FUNCTION_SELECTOR},{name:"args",type:ARRAY(FIELD)}],returnType:ARRAY(FIELD)}),aztec_utl_pushEphemeral:makeEntry({params:[{name:"slot",type:FIELD},{name:"elements",type:ARRAY(FIELD)}],returnType:U32}),aztec_utl_popEphemeral:makeEntry({params:[{name:"slot",type:FIELD}],returnType:ARRAY(FIELD)}),aztec_utl_getEphemeral:makeEntry({params:[{name:"slot",type:FIELD},{name:"index",type:U32}],returnType:ARRAY(FIELD)}),aztec_utl_setEphemeral:makeEntry({params:[{name:"slot",type:FIELD},{name:"index",type:U32},{name:"elements",type:ARRAY(FIELD)}]}),aztec_utl_getEphemeralLen:makeEntry({params:[{name:"slot",type:FIELD}],returnType:U32}),aztec_utl_removeEphemeral:makeEntry({params:[{name:"slot",type:FIELD},{name:"index",type:U32}]}),aztec_utl_clearEphemeral:makeEntry({params:[{name:"slot",type:FIELD}]}),aztec_utl_pushTransient:makeEntry({params:[{name:"slot",type:FIELD},{name:"elements",type:ARRAY(FIELD)}],returnType:U32}),aztec_utl_popTransient:makeEntry({params:[{name:"slot",type:FIELD}],returnType:ARRAY(FIELD)}),aztec_utl_getTransient:makeEntry({params:[{name:"slot",type:FIELD},{name:"index",type:U32}],returnType:ARRAY(FIELD)}),aztec_utl_setTransient:makeEntry({params:[{name:"slot",type:FIELD},{name:"index",type:U32},{name:"elements",type:ARRAY(FIELD)}]}),aztec_utl_getTransientLen:makeEntry({params:[{name:"slot",type:FIELD}],returnType:U32}),aztec_utl_removeTransient:makeEntry({params:[{name:"slot",type:FIELD},{name:"index",type:U32}]}),aztec_utl_clearTransient:makeEntry({params:[{name:"slot",type:FIELD}]}),aztec_prv_setHashPreimage:makeEntry({params:[{name:"values",type:ARRAY(FIELD)},{name:"hash",type:FIELD}]}),aztec_prv_getHashPreimage:makeEntry({params:[{name:"returnsHash",type:FIELD}],returnType:ARRAY(FIELD)}),aztec_prv_notifyCreatedNote:makeEntry({params:[{name:"owner",type:AZTEC_ADDRESS},{name:"storageSlot",type:FIELD},{name:"randomness",type:FIELD},{name:"noteTypeId",type:NOTE_SELECTOR},{name:"note",type:ARRAY(FIELD)},{name:"noteHash",type:FIELD},{name:"counter",type:U32}]}),aztec_prv_notifyNullifiedNote:makeEntry({params:[{name:"innerNullifier",type:FIELD},{name:"noteHash",type:FIELD},{name:"counter",type:U32}]}),aztec_prv_notifyCreatedNullifier:makeEntry({params:[{name:"innerNullifier",type:FIELD}]}),aztec_prv_isNullifierPending:makeEntry({params:[{name:"innerNullifier",type:FIELD},{name:"contractAddress",type:AZTEC_ADDRESS}],returnType:BOOL}),aztec_prv_notifyCreatedContractClassLog:makeEntry({params:[{name:"log",type:CONTRACT_CLASS_LOG},{name:"counter",type:U32}]}),aztec_prv_callPrivateFunction:makeEntry({params:[{name:"contractAddress",type:AZTEC_ADDRESS},{name:"functionSelector",type:FUNCTION_SELECTOR},{name:"argsHash",type:FIELD},{name:"sideEffectCounter",type:U32},{name:"isStaticCall",type:BOOL}],returnType:CALL_PRIVATE_RESULT}),aztec_prv_assertValidPublicCalldata:makeEntry({params:[{name:"calldataHash",type:FIELD}]}),aztec_prv_notifyRevertiblePhaseStart:makeEntry({params:[{name:"minRevertibleSideEffectCounter",type:U32}]}),aztec_prv_isExecutionInRevertiblePhase:makeEntry({params:[{name:"sideEffectCounter",type:U32}],returnType:BOOL}),aztec_prv_getAppTaggingSecret:makeEntry({params:[{name:"sender",type:AZTEC_ADDRESS},{name:"recipient",type:AZTEC_ADDRESS}],returnType:OPTION(FIELD)}),aztec_prv_getNextTaggingIndex:makeEntry({params:[{name:"secret",type:FIELD},{name:"deliveryMode",type:DELIVERY_MODE}],returnType:U32}),aztec_prv_getSenderForTags:makeEntry({returnType:OPTION(AZTEC_ADDRESS)}),aztec_prv_resolveTaggingStrategy:makeEntry({params:[{name:"sender",type:AZTEC_ADDRESS},{name:"recipient",type:AZTEC_ADDRESS},{name:"deliveryMode",type:DELIVERY_MODE}],returnType:RESOLVED_TAGGING_STRATEGY}),aztec_prv_resolveCustomRequest:makeEntry({params:[{name:"kind",type:FIELD},{name:"payload",type:ARRAY(FIELD)}],returnType:ARRAY(FIELD)})};function makeEntry({params,returnType}={}){return{params:params??[],returnType,deserializeParams(inputs){let resolvedParams=params??[],offset=0,named=resolvedParams.map(param=>{if(!param.type.deserialization)throw new Error(`Param '${param.name}' has no deserialization defined`);let slotCount=slotsOf(param.type),readers=inputs.slice(offset,offset+slotCount).map(slot=>new FieldReader(slot.map(hex3=>Fr.fromString(hex3))));offset+=slotCount;let value=param.type.deserialization.fn(readers);return assertReadersConsumed(readers),{name:param.name,value}});if(offset!==inputs.length)throw new Error(`Oracle received ${inputs.length} input slot(s) but the registry specifies ${offset}`);return named},serializeReturn(result){return returnType?.serialization===void 0?[]:returnType.serialization.fn(result).map(slot=>Array.isArray(slot)?slot.map(toACVMField):toACVMField(slot))}}}__name(makeEntry,"makeEntry");var UnavailableOracleError=class extends Error{static{__name(this,"UnavailableOracleError")}constructor(oracleName){super(`${oracleName} oracles not available with the current handler`)}};function buildACIRCallback(handler,registries={}){let{real=ORACLE_REGISTRY,legacy:legacyRegistry=LEGACY_ORACLE_REGISTRY}=registries,target2={};for(let[oracleKey,entry]of Object.entries(real)){let{scope,methodName}=parseOracleName(oracleKey,"Oracle");target2[oracleKey]=async(...inputs)=>{assertHandlerSupportsScope(handler,scope);let positional=entry.deserializeParams(inputs).map(p=>p.value),result=await handler[methodName](...positional);return entry.serializeReturn(result)}}for(let[legacyKey,legacy]of Object.entries(legacyRegistry)){let{scope}=parseOracleName(legacyKey,"Legacy oracle");if(legacyKey in target2)throw new Error(`Legacy oracle "${legacyKey}" collides with a live oracle of the same name in the registry`);let modernEntry=real[legacy.modernOracle],{methodName}=parseOracleName(legacy.modernOracle,"Oracle"),paramOverride=legacy.params,paramSource=paramOverride?makeEntry({params:[...paramOverride.legacyType]}):modernEntry,returnOverride=legacy.returnType,returnSource=returnOverride?makeEntry({returnType:returnOverride.legacyType}):modernEntry;target2[legacyKey]=async(...inputs)=>{assertHandlerSupportsScope(handler,scope);let legacyArgs=paramSource.deserializeParams(inputs).map(p=>p.value),positional=paramOverride?paramOverride.mapping(legacyArgs):legacyArgs,result=await handler[methodName](...positional);return returnSource.serializeReturn(returnOverride?returnOverride.mapping(result):result)}}return new Proxy(target2,makeUnknownOracleTrap(handler))}__name(buildACIRCallback,"buildACIRCallback");function parseOracleName(key,label){let match=key.match(/^aztec_(\w+?)_(.+)$/);if(!match)throw new Error(`${label} "${key}" does not follow the aztec_{scope}_{method} convention`);return{scope:match[1],methodName:match[2]}}__name(parseOracleName,"parseOracleName");function makeUnknownOracleTrap(handler){return{get(obj,prop){return Object.hasOwn(obj,prop)?obj[prop]:()=>{let contractVersion;throw"nonOracleFunctionGetContractOracleVersion"in handler&&(contractVersion=handler.nonOracleFunctionGetContractOracleVersion()),contractVersion?contractVersion.minor>4?new Error(`Oracle '${prop}' not found. This usually means the contract requires a newer private execution environment than you have. Upgrade your private execution environment to a compatible version. The contract was compiled with Aztec.nr oracle version ${contractVersion.major}.${contractVersion.minor}, but this private execution environment only supports up to ${30}.${4}. See https://docs.aztec.network/errors/8`):new Error(`Oracle '${prop}' not found. The contract's oracle version (${contractVersion.major}.${contractVersion.minor}) is compatible with this private execution environment (${30}.${4}), so all standard oracles should be available. This could mean the contract was compiled against a modified version of Aztec.nr, or that it references an oracle that does not exist. See https://docs.aztec.network/errors/8`):new Error(`Oracle '${prop}' not found and the contract's oracle version is unknown (the version check oracle was not called before '${prop}'). This usually means the contract was not compiled with the #[aztec] macro, which injects the version check as the first oracle call in every private/utility external function. If you're using a custom entry point, ensure assert_compatible_oracle_version() is called before any other oracle calls. See https://docs.aztec.network/errors/8`)}}}}__name(makeUnknownOracleTrap,"makeUnknownOracleTrap");function assertHandlerSupportsScope(handler,scope){switch(scope){case"misc":if(!("isMisc"in handler))throw new UnavailableOracleError("Misc");break;case"utl":if(!("isUtility"in handler))throw new UnavailableOracleError("Utility");break;case"prv":if(!("isPrivate"in handler))throw new UnavailableOracleError("Private");break;default:throw new Error(`Unknown oracle scope: ${scope}`)}}__name(assertHandlerSupportsScope,"assertHandlerSupportsScope");async function executePrivateFunction(simulator,privateExecutionOracle,artifact,contractAddress,functionSelector,log2=createLogger("simulator:private_execution")){let functionName=await privateExecutionOracle.getDebugFunctionName();log2.verbose(`Executing private function ${functionName}`,{contract:contractAddress});let initialWitness=privateExecutionOracle.getInitialWitness(artifact),timer=new Timer,acirExecutionResult=await simulator.executeUserCircuit(initialWitness,artifact,buildACIRCallback(privateExecutionOracle)).catch(err=>{throw err.message=resolveAssertionMessageFromError(err,artifact),new ExecutionError(err.message,{contractAddress,functionSelector},extractCallStack(err,artifact.debug),{cause:err})}),duration3=timer.ms(),partialWitness=acirExecutionResult.partialWitness,publicInputs=extractPrivateCircuitPublicInputs(artifact,partialWitness),initialWitnessSize=witnessMapToFields(initialWitness).length*Fr.SIZE_IN_BYTES;log2.debug(`Ran external function ${contractAddress.toString()}:${functionSelector}`,{circuitName:"app-circuit",duration:duration3,eventName:"circuit-witness-generation",inputSize:initialWitnessSize,outputSize:publicInputs.toBuffer().length,appCircuitName:functionName});let contractClassLogs=privateExecutionOracle.getContractClassLogs(),rawReturnValues=await privateExecutionOracle.getHashPreimage(publicInputs.returnsHash),newNotes=privateExecutionOracle.getNewNotes(),noteHashNullifierCounterMap=privateExecutionOracle.getNoteHashNullifierCounterMap(),offchainEffects=privateExecutionOracle.getOffchainEffects(),taggingIndexRanges=privateExecutionOracle.getUsedTaggingIndexRanges(),nestedExecutionResults=privateExecutionOracle.getNestedExecutionResults(),timerSubtractionList=nestedExecutionResults,witgenTime=duration3;for(;timerSubtractionList.length>0;)witgenTime-=timerSubtractionList.reduce((acc,nested)=>acc+(nested.profileResult?.timings.witgen??0),0),timerSubtractionList=timerSubtractionList.flatMap(nested=>nested.nestedExecutionResults??[]);return log2.debug(`Returning from call to ${contractAddress.toString()}:${functionSelector}`),new PrivateCallExecutionResult(artifact.bytecode,Buffer.from(artifact.verificationKey,"base64"),partialWitness,publicInputs,newNotes,noteHashNullifierCounterMap,rawReturnValues,offchainEffects.map(e2=>({data:e2.data})),taggingIndexRanges,nestedExecutionResults,contractClassLogs,{timings:{witgen:witgenTime,oracles:acirExecutionResult.oracles}})}__name(executePrivateFunction,"executePrivateFunction");function extractPrivateCircuitPublicInputs(artifact,partialWitness){let parametersSize=countArgumentsSize(artifact)+37,returnsSize=838,returnData=[];for(let i=parametersSize;i<parametersSize+returnsSize;i++){let returnedField=partialWitness.get(i);if(returnedField===void 0)throw new Error(`Missing return value for index ${i}`);returnData.push(Fr.fromString(returnedField))}return PrivateCircuitPublicInputs.fromFields(returnData)}__name(extractPrivateCircuitPublicInputs,"extractPrivateCircuitPublicInputs");var UNFINALIZED_TAGGING_INDEXES_WINDOW_LEN=64;async function getAllPagesInBatches(tags,fetchAllPagesForBatch){if(tags.length===0)return[];if(tags.length<=100)return fetchAllPagesForBatch(tags);let batches=[];for(let i=0;i<tags.length;i+=100)batches.push(tags.slice(i,i+100));return(await Promise.all(batches.map(fetchAllPagesForBatch))).flat()}__name(getAllPagesInBatches,"getAllPagesInBatches");function getAllPrivateLogsByTags(aztecNode,tags,anchorBlockHash,options={}){return getAllPagesInBatches(tags,batch=>queryAllPrivateLogsByTags(aztecNode,{tags:batch,referenceBlock:anchorBlockHash,fromBlock:options.fromBlock,toBlock:options.toBlock,includeEffects:options.includeEffects??!1,limitPerTag:options.limitPerTag}))}__name(getAllPrivateLogsByTags,"getAllPrivateLogsByTags");function getAllPublicLogsByTagsFromContract(aztecNode,contractAddress,tags,anchorBlockHash,options={}){return getAllPagesInBatches(tags,batch=>queryAllPublicLogsByTags(aztecNode,{contractAddress,tags:batch,referenceBlock:anchorBlockHash,fromBlock:options.fromBlock,toBlock:options.toBlock,includeEffects:options.includeEffects??!1,limitPerTag:options.limitPerTag}))}__name(getAllPublicLogsByTagsFromContract,"getAllPublicLogsByTagsFromContract");function findHighestIndexes(privateLogsWithIndexes,currentTimestamp,finalizedBlockNumber){let highestAgedIndex,highestFinalizedIndex;for(let{log:log2,taggingIndex}of privateLogsWithIndexes)currentTimestamp-log2.blockTimestamp>=BigInt(86400)&&(highestAgedIndex===void 0||taggingIndex>highestAgedIndex)&&(highestAgedIndex=taggingIndex),log2.blockNumber<=finalizedBlockNumber&&(highestFinalizedIndex===void 0||taggingIndex>highestFinalizedIndex)&&(highestFinalizedIndex=taggingIndex);return{highestAgedIndex,highestFinalizedIndex}}__name(findHighestIndexes,"findHighestIndexes");async function syncTaggedPrivateLogs(secrets,aztecNode,taggingStore,anchorBlockHeader,finalizedBlockNumber,jobId){if(secrets.length===0)return[];let anchorBlockNumber=anchorBlockHeader.getBlockNumber(),anchorBlockHash=await anchorBlockHeader.hash(),currentTimestamp=anchorBlockHeader.globalVariables.timestamp,pending=await getIndexRangesForSecrets(secrets,taggingStore,jobId),allLogs=[];for(;pending.length>0;){let logsPerSecret=await fetchLogsForSecrets(pending,aztecNode,anchorBlockNumber,anchorBlockHash);pending=(await Promise.all(pending.map(async(pendingSecret,i)=>{let logsFoundWithSecret=logsPerSecret[i];return logsFoundWithSecret.length===0?void 0:(allLogs.push(...logsFoundWithSecret.map(({log:log2})=>log2)),await(pendingSecret.secret.kind===AppTaggingSecretKind.CONSTRAINED?processConstrainedResults:processUnconstrainedResults)(pendingSecret,logsFoundWithSecret,taggingStore,currentTimestamp,finalizedBlockNumber,jobId))}))).filter(isDefined)}return allLogs}__name(syncTaggedPrivateLogs,"syncTaggedPrivateLogs");function getIndexRangesForSecrets(secrets,taggingStore,jobId){return Promise.all(secrets.map(async secret=>{let currentHighestFinalizedIndex=await taggingStore.getHighestFinalizedIndex(secret,jobId),highestIndexBeforeStart=secret.kind===AppTaggingSecretKind.CONSTRAINED?currentHighestFinalizedIndex:await taggingStore.getHighestAgedIndex(secret,jobId),start=highestIndexBeforeStart===void 0?0:highestIndexBeforeStart+1,end=(currentHighestFinalizedIndex??0)+UNFINALIZED_TAGGING_INDEXES_WINDOW_LEN+1;return{secret,start,end}}))}__name(getIndexRangesForSecrets,"getIndexRangesForSecrets");async function fetchLogsForSecrets(pending,aztecNode,anchorBlockNumber,anchorBlockHash){let indexesPerSecret=pending.map(({start,end})=>Array.from({length:end-start},(_,i)=>start+i)),allTags=(await Promise.all(pending.map(({secret},i)=>Promise.all(indexesPerSecret[i].map(index=>SiloedTag.compute({extendedSecret:secret,index})))))).flat(),allResults=await getAllPrivateLogsByTags(aztecNode,allTags,anchorBlockHash,{includeEffects:!0,toBlock:BlockNumber(anchorBlockNumber+1)}),logsPerSecret=[],offset=0;for(let indexes of indexesPerSecret){let logsForSecret=[];for(let i=0;i<indexes.length;i++)for(let log2 of allResults[offset+i])logsForSecret.push({log:log2,taggingIndex:indexes[i]});logsPerSecret.push(logsForSecret),offset+=indexes.length}return logsPerSecret}__name(fetchLogsForSecrets,"fetchLogsForSecrets");async function processConstrainedResults(pending,logsWithIndexes,taggingStore,currentTimestamp,finalizedBlockNumber,jobId){let indexesWithLogs=new Set(logsWithIndexes.map(l=>l.taggingIndex)),firstMissingIndex=pending.start;for(;firstMissingIndex<pending.end&&indexesWithLogs.has(firstMissingIndex);)firstMissingIndex++;let{highestFinalizedIndex}=findHighestIndexes(logsWithIndexes,currentTimestamp,finalizedBlockNumber);if(highestFinalizedIndex!==void 0&&(await taggingStore.updateHighestFinalizedIndex(pending.secret,highestFinalizedIndex,jobId),firstMissingIndex>=pending.end))return{secret:pending.secret,start:pending.end,end:highestFinalizedIndex+UNFINALIZED_TAGGING_INDEXES_WINDOW_LEN+1}}__name(processConstrainedResults,"processConstrainedResults");async function processUnconstrainedResults(pending,logsWithIndexes,taggingStore,currentTimestamp,finalizedBlockNumber,jobId){let{highestAgedIndex,highestFinalizedIndex}=findHighestIndexes(logsWithIndexes,currentTimestamp,finalizedBlockNumber);if(highestAgedIndex!==void 0&&await taggingStore.updateHighestAgedIndex(pending.secret,highestAgedIndex,jobId),highestFinalizedIndex!==void 0){if(highestAgedIndex!==void 0&&highestAgedIndex>highestFinalizedIndex)throw new Error(`Highest aged index (${highestAgedIndex}) must not exceed highest finalized index (${highestFinalizedIndex})`);return await taggingStore.updateHighestFinalizedIndex(pending.secret,highestFinalizedIndex,jobId),{secret:pending.secret,start:pending.end,end:highestFinalizedIndex+UNFINALIZED_TAGGING_INDEXES_WINDOW_LEN+1}}}__name(processUnconstrainedResults,"processUnconstrainedResults");var EMPTY_STATUS_CHANGE={txHashesToFinalize:[],txHashesToDrop:[],txHashesWithExecutionReverted:[]};function mergeStatusChanges(a,b){return{txHashesToFinalize:[...a.txHashesToFinalize,...b.txHashesToFinalize],txHashesToDrop:[...a.txHashesToDrop,...b.txHashesToDrop],txHashesWithExecutionReverted:[...a.txHashesWithExecutionReverted,...b.txHashesWithExecutionReverted]}}__name(mergeStatusChanges,"mergeStatusChanges");async function getStatusChangeOfPending(pending,aztecNode){let receipts=await Promise.all(pending.map(pendingTxHash=>aztecNode.getTxReceipt(pendingTxHash))),txHashesToFinalize=[],txHashesToDrop=[],txHashesWithExecutionReverted=[];for(let i=0;i<receipts.length;i++){let receipt=receipts[i],txHash=pending[i];if(receipt.status===TxStatus.FINALIZED)if(receipt.hasExecutionSucceeded())txHashesToFinalize.push(txHash);else if(receipt.hasExecutionReverted())txHashesWithExecutionReverted.push(txHash);else throw new Error("Both hasExecutionSucceeded and hasExecutionReverted on the receipt returned false. This should never happen and it implies a bug. Please open an issue.");else receipt.isDropped()&&txHashesToDrop.push(txHash)}return{txHashesToFinalize,txHashesToDrop,txHashesWithExecutionReverted}}__name(getStatusChangeOfPending,"getStatusChangeOfPending");async function loadAndStoreNewTaggingIndexes(extendedSecret,start,end,aztecNode,taggingStore,anchorBlockHash,jobId){let siloedTagsForWindow=await Promise.all(Array.from({length:end-start},(_,i)=>SiloedTag.compute({extendedSecret,index:start+i}))),txsForTags=await getTxsContainingTags(siloedTagsForWindow,aztecNode,anchorBlockHash),txIndexesMap=getTxIndexesMap(txsForTags,start,siloedTagsForWindow.length);for(let[txHashStr,indexes]of txIndexesMap.entries()){let txHash=TxHash.fromString(txHashStr),ranges=[{extendedSecret,lowestIndex:Math.min(...indexes),highestIndex:Math.max(...indexes)}];await taggingStore.storePendingIndexes(ranges,txHash,jobId)}}__name(loadAndStoreNewTaggingIndexes,"loadAndStoreNewTaggingIndexes");async function getTxsContainingTags(tags,aztecNode,anchorBlockHash){return(await getAllPrivateLogsByTags(aztecNode,tags,anchorBlockHash)).map(logs=>logs.map(log2=>log2.txHash))}__name(getTxsContainingTags,"getTxsContainingTags");function getTxIndexesMap(txHashesForTags,start,count2){if(txHashesForTags.length!==count2)throw new Error(`Number of tx hashes arrays does not match number of tags. ${txHashesForTags.length} !== ${count2}`);let indexesMap=new Map;for(let i=0;i<txHashesForTags.length;i++){let taggingIndex=start+i,txHashesForTag=txHashesForTags[i];for(let txHash of txHashesForTag){let key=txHash.toString(),existing=indexesMap.get(key);existing?existing.push(taggingIndex):indexesMap.set(key,[taggingIndex])}}return indexesMap}__name(getTxIndexesMap,"getTxIndexesMap");async function syncSenderTaggingIndexes(secret,aztecNode,taggingStore,anchorBlockHash,jobId){let finalizedIndex=await taggingStore.getLastFinalizedIndex(secret,jobId),start=finalizedIndex===void 0?0:finalizedIndex+1,end=start+UNFINALIZED_TAGGING_INDEXES_WINDOW_LEN,previousFinalizedIndex=finalizedIndex,newFinalizedIndex;for(;;){let knownPendingTxHashes=await taggingStore.getTxHashesOfPendingIndexes(secret,start,end,jobId),[,statusOfKnown]=await Promise.all([loadAndStoreNewTaggingIndexes(secret,start,end,aztecNode,taggingStore,anchorBlockHash,jobId),knownPendingTxHashes.length>0?getStatusChangeOfPending(knownPendingTxHashes,aztecNode):Promise.resolve(EMPTY_STATUS_CHANGE)]),allPendingTxHashes=await taggingStore.getTxHashesOfPendingIndexes(secret,start,end,jobId);if(allPendingTxHashes.length===0)break;let knownSet=new Set(knownPendingTxHashes.map(h=>h.toString())),newPendingTxHashes=allPendingTxHashes.filter(h=>!knownSet.has(h.toString())),statusOfNew=newPendingTxHashes.length>0?await getStatusChangeOfPending(newPendingTxHashes,aztecNode):EMPTY_STATUS_CHANGE,{txHashesToFinalize,txHashesToDrop,txHashesWithExecutionReverted}=mergeStatusChanges(statusOfKnown,statusOfNew);if(await taggingStore.dropPendingIndexes(txHashesToDrop,jobId),await taggingStore.finalizePendingIndexes(txHashesToFinalize,jobId),txHashesWithExecutionReverted.length>0){let receipts=await Promise.all(txHashesWithExecutionReverted.map(txHash=>aztecNode.getTxReceipt(txHash,{includeTxEffect:!0})));for(let receipt of receipts){if(!receipt.isMined()||!receipt.txEffect)throw new Error("TxEffect not found for execution-reverted tx. This is either a bug or a reorg has occurred.");await taggingStore.finalizePendingIndexesOfAPartiallyRevertedTx(receipt.txEffect,jobId)}}if(newFinalizedIndex=await taggingStore.getLastFinalizedIndex(secret,jobId),previousFinalizedIndex!==newFinalizedIndex){let previousEnd=end;end=newFinalizedIndex+UNFINALIZED_TAGGING_INDEXES_WINDOW_LEN+1,start=previousEnd,previousFinalizedIndex=newFinalizedIndex}else break}}__name(syncSenderTaggingIndexes,"syncSenderTaggingIndexes");var selectPropertyFromPackedNoteContent=__name((noteData,selector)=>{if(selector.index>=noteData.length)throw new Error(`Property selector index ${selector.index} out of bounds for note with ${noteData.length} fields`);if(selector.offset+selector.length>Fr.SIZE_IN_BYTES)throw new Error(`Property selector range (offset=${selector.offset}, length=${selector.length}) exceeds Fr buffer size of ${Fr.SIZE_IN_BYTES} bytes`);let noteValueBuffer=noteData[selector.index].toBuffer(),start=Fr.SIZE_IN_BYTES-selector.offset-selector.length,end=Fr.SIZE_IN_BYTES-selector.offset,noteValue=noteValueBuffer.subarray(start,end),padded=Buffer.alloc(Fr.SIZE_IN_BYTES);return noteValue.copy(padded,Fr.SIZE_IN_BYTES-noteValue.length),Fr.fromBuffer(padded)},"selectPropertyFromPackedNoteContent"),selectNotes=__name((noteDatas,selects)=>noteDatas.filter(noteData=>selects.every(({selector,value,comparator})=>{let noteValueFr=selectPropertyFromPackedNoteContent(noteData.note.items,selector),fn={[Comparator.EQ]:()=>noteValueFr.equals(value),[Comparator.NEQ]:()=>!noteValueFr.equals(value),[Comparator.LT]:()=>noteValueFr.lt(value),[Comparator.LTE]:()=>noteValueFr.lt(value)||noteValueFr.equals(value),[Comparator.GT]:()=>!noteValueFr.lt(value)&&!noteValueFr.equals(value),[Comparator.GTE]:()=>!noteValueFr.lt(value)}[comparator];if(!fn)throw new Error(`Invalid comparator value: ${comparator}`);return fn()})),"selectNotes"),sortNotes=__name((a,b,sorts,level=0)=>{if(sorts[level]===void 0)return 0;let{selector,order}=sorts[level];if(order===0)return 0;let aValue=selectPropertyFromPackedNoteContent(a,selector),bValue=selectPropertyFromPackedNoteContent(b,selector),dir=order===1?[-1,1]:[1,-1];return aValue.toBigInt()===bValue.toBigInt()?sortNotes(a,b,sorts,level+1):aValue.toBigInt()>bValue.toBigInt()?dir[0]:dir[1]},"sortNotes");function pickNotes(noteDatas,{selects=[],sorts=[],limit=0,offset=0}){return selectNotes(noteDatas,selects).sort((a,b)=>sortNotes(a.note.items,b.note.items,sorts)).slice(offset,limit?offset+limit:void 0)}__name(pickNotes,"pickNotes");import{BarretenbergSync as BarretenbergSync7}from"@aztec/bb.js";import{Buffer as Buffer3}from"buffer";var Aes128=class{static{__name(this,"Aes128")}async encryptBufferCBC(data,iv,key){let numPaddingBytes=16-data.length%16,paddingBuffer=Buffer3.alloc(numPaddingBytes);paddingBuffer.fill(numPaddingBytes);let input=Buffer3.concat([data,paddingBuffer]);await BarretenbergSync7.initSingleton();let response=BarretenbergSync7.getSingleton().aesEncrypt({plaintext:input,iv,key,length:input.length});return Buffer3.from(response.ciphertext)}async decryptBufferCBCKeepPadding(data,iv,key){await BarretenbergSync7.initSingleton();let response=BarretenbergSync7.getSingleton().aesDecrypt({ciphertext:data,iv,key,length:data.length});return Buffer3.from(response.plaintext)}async decryptBufferCBC(data,iv,key){let paddedBuffer=await this.decryptBufferCBCKeepPadding(data,iv,key),paddingLen=paddedBuffer[paddedBuffer.length-1];if(paddingLen===0||paddingLen>16)throw new Error(`Invalid PKCS#7 padding length: ${paddingLen}`);for(let i=paddedBuffer.length-paddingLen;i<paddedBuffer.length;i++)if(paddedBuffer[i]!==paddingLen)throw new Error("Invalid PKCS#7 padding");return paddedBuffer.subarray(0,paddedBuffer.length-paddingLen)}};var StandardContractSalt={AuthRegistry:new Fr(1),MultiCallEntrypoint:new Fr(1),PublicChecks:new Fr(1),HandshakeRegistry:new Fr(1)},StandardContractAddress={AuthRegistry:AztecAddress.fromStringUnsafe("0x0564d5361fd6d7501baa1706a59bbebd2035d1c2565c9e5daf8f1567da547a23"),MultiCallEntrypoint:AztecAddress.fromStringUnsafe("0x126ab69e8161771b52273d00dbf5d7252ef6a92724d15f1ec2dcc967118a0c7b"),PublicChecks:AztecAddress.fromStringUnsafe("0x077341cf79b91db9c440c49786fc4d4508ef3ab623c30fa3be7031ffcad4754c"),HandshakeRegistry:AztecAddress.fromStringUnsafe("0x2f8592fb5b1620f33d21d9b67a34002f0e5392d93807a684584af388e0d70741")},StandardContractClassId={AuthRegistry:Fr.fromString("0x197cba16b38c5408694cec7188b9128e80d247596050e31a0d12249b60b360e1"),MultiCallEntrypoint:Fr.fromString("0x24e025d7b0d3158d69197dbabf2baf18db0b1dd4ff3c87ec2ed418fecb0f192d"),PublicChecks:Fr.fromString("0x000a3012fd5d88921976565891e19c0b9a6a753eaf773e9493f47c890089bd08"),HandshakeRegistry:Fr.fromString("0x20e14f4a6ada38f27144ceedbfbb7417aca6c679ee1ea09b9435886ed7faf3d2")},StandardContractClassIdPreimage={AuthRegistry:{artifactHash:Fr.fromString("0x17bd6a48fb22fb700a16d5767f93e08b2b21bf83c280cb61abe763567179601f"),privateFunctionsRoot:Fr.fromString("0x17b584350f4c3ccafd8f688729afb9feab8976114fb40012e9dee65022c072a4"),publicBytecodeCommitment:Fr.fromString("0x2545f39893766508ce37bb5cea5e4dcab04c6f7f79f3089b1c076876e9d268b2")},MultiCallEntrypoint:{artifactHash:Fr.fromString("0x13dfb7aaca5d32bb876650f6afa5531d7c2c946f1cf927bde230755017af91d3"),privateFunctionsRoot:Fr.fromString("0x0e68dfbb256e80b08b3aef47aca1f2669e97a9c6259787893c1223ac083ad5d5"),publicBytecodeCommitment:Fr.fromString("0x0ce4c618c3ed7f3a20410e618c06bb701e150af7fe28a3e92f68e7733809f33e")},PublicChecks:{artifactHash:Fr.fromString("0x212730544c282ed52485a69d91a2d46adb5a5e6cd23e8c26c3abc6de4bcc3714"),privateFunctionsRoot:Fr.fromString("0x202860adb1b8975971eeaf571aaaa88a27f4035290d58532ae7d60b0dfaad54c"),publicBytecodeCommitment:Fr.fromString("0x013c4f854a5c87c9daf86c5f9bc07a42c2a061f1d924a5b3564ec7edc8e18cb7")},HandshakeRegistry:{artifactHash:Fr.fromString("0x01b39b7d8576cbea4e4eae792c4538a710d0ac2ea0361364c57d0e2b4b1a3474"),privateFunctionsRoot:Fr.fromString("0x02a4dba36389845b8ef0108562f7536d3284f07ca678558fc3c3bce3b24ee821"),publicBytecodeCommitment:Fr.fromString("0x0ce4c618c3ed7f3a20410e618c06bb701e150af7fe28a3e92f68e7733809f33e")}},StandardContractInitializationHash={AuthRegistry:Fr.fromString("0x0000000000000000000000000000000000000000000000000000000000000000"),MultiCallEntrypoint:Fr.fromString("0x0000000000000000000000000000000000000000000000000000000000000000"),PublicChecks:Fr.fromString("0x0000000000000000000000000000000000000000000000000000000000000000"),HandshakeRegistry:Fr.fromString("0x0000000000000000000000000000000000000000000000000000000000000000")},StandardContractPrivateFunctions={AuthRegistry:[{selector:FunctionSelector.fromField(Fr.fromString("0x0000000000000000000000000000000000000000000000000000000079a3d418")),vkHash:Fr.fromString("0x06a5c1b3a636c954a90be43cb56a4bdd9dc8aec764151a012e0018753694ff54")}],MultiCallEntrypoint:[{selector:FunctionSelector.fromField(Fr.fromString("0x00000000000000000000000000000000000000000000000000000000f04908a9")),vkHash:Fr.fromString("0x0b19b2f937f2581922c2ead5411ad9ff4ed9710efe9849bde494d9a0f94812ec")}],PublicChecks:[],HandshakeRegistry:[{selector:FunctionSelector.fromField(Fr.fromString("0x0000000000000000000000000000000000000000000000000000000019f8b409")),vkHash:Fr.fromString("0x25d87da668c7c52b9c521579f191bb02486b3598d1ec0063927d5c0af2608daf")},{selector:FunctionSelector.fromField(Fr.fromString("0x00000000000000000000000000000000000000000000000000000000db548fcf")),vkHash:Fr.fromString("0x0f59fe525df9ff4a400e33dec33fd1dc07e25d95f860734a35b909085cf07809")},{selector:FunctionSelector.fromField(Fr.fromString("0x00000000000000000000000000000000000000000000000000000000f1ff839b")),vkHash:Fr.fromString("0x12f43f384aa64661b012b52b1d80eb1d2202b8e459b50f56cfe270b0672c16ff")}]};var STANDARD_HANDSHAKE_REGISTRY_ADDRESS=StandardContractAddress.HandshakeRegistry,STANDARD_HANDSHAKE_REGISTRY_CLASS_ID=StandardContractClassId.HandshakeRegistry,STANDARD_HANDSHAKE_REGISTRY_SALT=StandardContractSalt.HandshakeRegistry;async function createContractLogger(contractAddress,getContractName,kind,options){let addrAbbrev=contractAddress.toString().slice(0,10),name=await getContractName(contractAddress),prefix=kind=="aztecnr"?"aztecnr":"contract",module=name?`${prefix}:${name}(${addrAbbrev})`:`${prefix}:Unknown(${addrAbbrev})`;return createLogger(module,options)}__name(createContractLogger,"createContractLogger");function logContractMessage(logger3,level,message,fields){logger3[level](applyStringFormatting(message,fields))}__name(logContractMessage,"logContractMessage");function stripAztecnrLogPrefix(message){return message.startsWith("[aztec-nr] ")?{kind:"aztecnr",message:message.slice(11)}:{kind:"user",message}}__name(stripAztecnrLogPrefix,"stripAztecnrLogPrefix");var EventService=class{static{__name(this,"EventService")}anchorBlockHeader;aztecNode;privateEventStore;jobId;log;constructor(anchorBlockHeader,aztecNode,privateEventStore,jobId,log2=createLogger("pxe:event_service")){this.anchorBlockHeader=anchorBlockHeader,this.aztecNode=aztecNode,this.privateEventStore=privateEventStore,this.jobId=jobId,this.log=log2}async validateAndStoreEvents(requests,scope,txEffects){if(requests.length===0)return;let anchorBlockNumber=this.anchorBlockHeader.getBlockNumber();await Promise.all(requests.map(req=>this.#validateAndStoreEvent(req,scope,txEffects,anchorBlockNumber)))}async#validateAndStoreEvent(request,scope,txEffects,anchorBlockNumber){let{contractAddress,eventTypeId:selector,randomness,serializedEvent:content,eventCommitment,txHash}=request,recomputedCommitment=await computePrivateEventCommitment(randomness,selector.toField(),content);if(!recomputedCommitment.equals(eventCommitment)){this.log.warn(`Skipping event whose content does not hash to the provided commitment. contract=${contractAddress}, selector=${selector}, eventCommitment=${eventCommitment}, txHash=${txHash}, recomputedCommitment=${recomputedCommitment}`);return}let siloedEventCommitment=await siloNullifier(contractAddress,eventCommitment),txEffect=txEffects.get(txHash.toString());if(!txEffect)throw new Error(`Could not find tx effect for tx hash ${txHash} when processing an event.`);if(txEffect.l2BlockNumber>anchorBlockNumber)throw new Error(`Obtained a newer tx effect for ${txHash} for an event validation request than the anchor block ${anchorBlockNumber}. This is a bug as smart contracts should not issue event validation requests for events from blocks newer than the anchor block.`);let eventIndexInTx=txEffect.data.nullifiers.findIndex(n=>n.equals(siloedEventCommitment));if(eventIndexInTx===-1){this.log.warn(`Skipping event whose commitment is not present in its tx. siloedEventCommitment=${siloedEventCommitment}, contract=${contractAddress}, selector=${selector}, eventCommitment=${eventCommitment}, txHash=${txHash}`);return}return this.privateEventStore.storePrivateEventLog(selector,randomness,content,siloedEventCommitment,{contractAddress,scope,txHash,l2BlockNumber:txEffect.l2BlockNumber,l2BlockHash:txEffect.l2BlockHash,txIndexInBlock:txEffect.txIndexInBlock,eventIndexInTx},this.jobId)}};var rangeKey=__name((fromBlock,toBlock)=>`${fromBlock??""}-${toBlock??""}`,"rangeKey"),LogService=class _LogService{static{__name(this,"LogService")}aztecNode;anchorBlockHeader;l2TipsStore;keyStore;recipientTaggingStore;taggingSecretSourcesStore;addressStore;jobId;log;constructor(aztecNode,anchorBlockHeader,l2TipsStore,keyStore,recipientTaggingStore,taggingSecretSourcesStore,addressStore,jobId,bindings){this.aztecNode=aztecNode,this.anchorBlockHeader=anchorBlockHeader,this.l2TipsStore=l2TipsStore,this.keyStore=keyStore,this.recipientTaggingStore=recipientTaggingStore,this.taggingSecretSourcesStore=taggingSecretSourcesStore,this.addressStore=addressStore,this.jobId=jobId,this.log=createLogger("pxe:log_service",bindings)}async fetchLogsByTag(contractAddress,logRetrievalRequests){for(let request of logRetrievalRequests)if(!contractAddress.equals(request.contractAddress))throw new Error(`Got a log retrieval request from ${request.contractAddress}, expected ${contractAddress}`);if(logRetrievalRequests.length===0)return[];let anchorBlockHash=await this.anchorBlockHeader.hash(),[publicLogsPerRequest,privateLogsPerRequest]=await Promise.all([this.#fetchPublicLogs(contractAddress,logRetrievalRequests,anchorBlockHash),this.#fetchPrivateLogs(logRetrievalRequests,anchorBlockHash)]);return logRetrievalRequests.map((_request,i)=>[...publicLogsPerRequest[i].map(_LogService.#toLogRetrievalResponse),...privateLogsPerRequest[i].map(_LogService.#toLogRetrievalResponse)])}async#fetchPublicLogs(contractAddress,requests,anchorBlockHash){let indices=requests.flatMap((r2,i)=>r2.source!==LogSource.PRIVATE?[i]:[]);if(indices.length===0)return requests.map(()=>[]);let resultsPerRequest=requests.map(()=>[]),groups=_LogService.#groupByRange(indices.map(i=>({index:i,request:requests[i]})));return await Promise.all(Array.from(groups.values()).map(async group=>{let tags=group.entries.map(e2=>e2.request.tag),results=await getAllPublicLogsByTagsFromContract(this.aztecNode,contractAddress,tags,anchorBlockHash,{fromBlock:group.fromBlock,toBlock:group.toBlock,includeEffects:!0});group.entries.forEach((entry,i)=>{resultsPerRequest[entry.index]=results[i]})})),resultsPerRequest}async#fetchPrivateLogs(requests,anchorBlockHash){let indices=requests.flatMap((r2,i)=>r2.source!==LogSource.PUBLIC?[i]:[]);if(indices.length===0)return requests.map(()=>[]);let resultsPerRequest=requests.map(()=>[]),groups=_LogService.#groupByRange(indices.map(i=>({index:i,request:requests[i]})));return await Promise.all(Array.from(groups.values()).map(async group=>{let siloedTags=await Promise.all(group.entries.map(e2=>SiloedTag.computeFromTagAndApp(e2.request.tag,e2.request.contractAddress))),results=await getAllPrivateLogsByTags(this.aztecNode,siloedTags,anchorBlockHash,{fromBlock:group.fromBlock,toBlock:group.toBlock,includeEffects:!0});group.entries.forEach((entry,i)=>{resultsPerRequest[entry.index]=results[i]})})),resultsPerRequest}static#groupByRange(entries){let groups=new Map;for(let entry of entries){let fromBlock=entry.request.fromBlock.value,toBlock=entry.request.toBlock.value,key=rangeKey(fromBlock,toBlock),existing=groups.get(key);existing?existing.entries.push(entry):groups.set(key,{fromBlock,toBlock,entries:[entry]})}return groups}static#toLogRetrievalResponse(log2){let noteHashes=log2.noteHashes,nullifiers=log2.nullifiers;if(nullifiers.length===0)throw new Error(`Log for tx ${log2.txHash} returned no nullifiers from the node`);return{logPayload:log2.logData.slice(1,16),txHash:log2.txHash,uniqueNoteHashesInTx:noteHashes,firstNullifierInTx:nullifiers[0],blockNumber:log2.blockNumber,blockTimestamp:log2.blockTimestamp,blockHash:log2.blockHash}}async fetchTaggedLogs(contractAddress,recipient,providedSecrets){this.log.verbose(`Fetching tagged logs for contract ${contractAddress.toString()} and recipient ${recipient.toString()}`);let l2Tips=await this.l2TipsStore.getL2Tips(),combinedSecrets=[...await this.#getPointDerivedSecrets(contractAddress,recipient),...providedSecrets],secrets=Array.from(new Map(combinedSecrets.map(secret=>[secret.toString(),secret])).values());return(await syncTaggedPrivateLogs(secrets,this.aztecNode,this.recipientTaggingStore,this.anchorBlockHeader,l2Tips.finalized.block.number,this.jobId)).map(log2=>{let noteHashes=log2.noteHashes,nullifiers=log2.nullifiers;if(nullifiers.length===0)throw new Error(`Log for tx ${log2.txHash} returned no nullifiers from the node`);return{log:log2.logData,context:{txHash:log2.txHash,uniqueNoteHashesInTx:noteHashes,firstNullifierInTx:nullifiers[0]}}})}async#getPointDerivedSecrets(contractAddress,recipient){let recipientCompleteAddress=await this.addressStore.getCompleteAddress(recipient);if(!recipientCompleteAddress||!await this.keyStore.hasAccount(recipient))return this.log.warn(`Skipping sender-derived tag retrieval for ${recipient.toString()} due to unknown address preimage`),[];let recipientIvsk=await this.keyStore.getMasterIncomingViewingSecretKey(recipient),points=[...await this.#getSecretsForSenders(recipientCompleteAddress,recipientIvsk),...await this.taggingSecretSourcesStore.getSharedSecretsForRecipient(recipient)];return Promise.all(points.map(secret=>AppTaggingSecret.computeDirectional(secret,contractAddress,recipient)))}async#getSecretsForSenders(recipientCompleteAddress,recipientIvsk){let allSenders=[...await this.taggingSecretSourcesStore.getSenders(),...await this.keyStore.getAccounts()];return Promise.all(allSenders.map(async sender=>{let taggingSecretPoint=await computeSharedTaggingSecret(recipientCompleteAddress,recipientIvsk,sender);if(!taggingSecretPoint)throw new Error(`Failed to compute a tagging secret for sender ${sender} - this implies this is an invalid address, which should not happen as they have been previously registered in PXE.`);return taggingSecretPoint}))}};var EphemeralArrayService=class{static{__name(this,"EphemeralArrayService")}#arrays=new Map;readArrayAt(slot){return this.#arrays.get(slot.toString())??[]}#setArray(slot,array2){this.#arrays.set(slot.toString(),array2)}len(slot){return this.readArrayAt(slot).length}push(slot,elements){let array2=this.readArrayAt(slot);return array2.push(elements),this.#setArray(slot,array2),array2.length}pop(slot){let array2=this.readArrayAt(slot);if(array2.length===0)throw new Error(`Ephemeral array at slot ${slot} is empty`);let element=array2.pop();return this.#setArray(slot,array2),element}get(slot,index){let array2=this.readArrayAt(slot);if(index<0||index>=array2.length)throw new Error(`Ephemeral array index ${index} out of bounds for array of length ${array2.length} at slot ${slot}`);return array2[index]}set(slot,index,value){let array2=this.readArrayAt(slot);if(index<0||index>=array2.length)throw new Error(`Ephemeral array index ${index} out of bounds for array of length ${array2.length} at slot ${slot}`);array2[index]=value}remove(slot,index){let array2=this.readArrayAt(slot);if(index<0||index>=array2.length)throw new Error(`Ephemeral array index ${index} out of bounds for array of length ${array2.length} at slot ${slot}`);array2.splice(index,1)}clear(slot){this.#arrays.delete(slot.toString())}allocateSlot(){let slot;do slot=Fr.random();while(this.#arrays.has(slot.toString()));return slot}newArray(elements){let slot=this.allocateSlot();return this.#setArray(slot,elements),slot}copy(srcSlot,dstSlot,count2){let srcArray=this.readArrayAt(srcSlot);if(count2>srcArray.length)throw new Error(`Cannot copy ${count2} elements from ephemeral array of length ${srcArray.length} at slot ${srcSlot}`);let copied=srcArray.slice(0,count2).map(el=>[...el]);this.#setArray(dstSlot,copied)}};function toNoirFactCollection(service,contractAddress,scope,factCollectionTypeId,factCollectionId,facts){return{contractAddress,scope,factCollectionTypeId,factCollectionId,facts:EphemeralArray.fromValues(service,facts.map(fact=>({factTypeId:fact.factTypeId,payload:EphemeralArray.fromValues(service,fact.payload),originBlock:fact.originBlock?Option.some(fact.originBlock):Option.none({blockNumber:0,blockHash:Fr.ZERO,blockState:OriginBlockState.Pending})})))}}__name(toNoirFactCollection,"toNoirFactCollection");function emptyFactCollection(service){return toNoirFactCollection(service,AztecAddress.ZERO,AztecAddress.ZERO,Fr.ZERO,Fr.ZERO,[])}__name(emptyFactCollection,"emptyFactCollection");var UtilityExecutionOracle=class _UtilityExecutionOracle{static{__name(this,"UtilityExecutionOracle")}isMisc=!0;isUtility=!0;contractLogger;aztecnrLogger;offchainEffects=[];ephemeralArrayService=new EphemeralArrayService;transientArrayService;contractOracleVersion;callContext;authWitnesses;capsules;anchorBlockHeader;anchoredContractData;noteStore;keyStore;addressStore;aztecNode;recipientTaggingStore;taggingSecretSourcesStore;capsuleService;factService;privateEventStore;txResolver;contractSyncService;l2TipsStore;jobId;logger;scopes;simulator;hooks;utilityExecutor;constructor(args){this.callContext=args.callContext,this.authWitnesses=args.authWitnesses,this.capsules=args.capsules,this.anchorBlockHeader=args.anchorBlockHeader,this.anchoredContractData=args.anchoredContractData,this.noteStore=args.noteStore,this.keyStore=args.keyStore,this.addressStore=args.addressStore,this.aztecNode=args.aztecNode,this.recipientTaggingStore=args.recipientTaggingStore,this.taggingSecretSourcesStore=args.taggingSecretSourcesStore,this.capsuleService=args.capsuleService,this.factService=args.factService,this.privateEventStore=args.privateEventStore,this.txResolver=args.txResolver,this.contractSyncService=args.contractSyncService,this.l2TipsStore=args.l2TipsStore,this.jobId=args.jobId,this.logger=args.log??createLogger("simulator:client_view_context"),this.scopes=args.scopes,this.simulator=args.simulator,this.hooks=args.hooks,this.utilityExecutor=args.utilityExecutor,this.transientArrayService=args.transientArrayService}assertCompatibleOracleVersion(major2,minor){if(major2!==30){let hint=major2>30?"The contract was compiled with a newer version of Aztec.nr than your private environment supports. Upgrade your private environment to a compatible version.":"The contract was compiled with an older version of Aztec.nr than your private environment supports. Recompile the contract with a compatible version of Aztec.nr.";throw new Error(`Incompatible private environment version: ${hint} See https://docs.aztec.network/errors/8 (expected oracle major version ${30}, got ${major2})`)}this.contractOracleVersion={major:major2,minor}}nonOracleFunctionGetContractOracleVersion(){return this.contractOracleVersion}getRandomField(){return Fr.random()}getUtilityContext(){return{blockHeader:this.anchorBlockHeader,contractAddress:this.callContext.contractAddress,msgSender:this.callContext.msgSender}}async getKeyValidationRequest(pkMHash,_keyIndex){let hasAccess=!1;for(let i=0;i<this.scopes.length&&!hasAccess;i++)await this.keyStore.accountHasKey(this.scopes[i],pkMHash)&&(hasAccess=!0);if(!hasAccess)throw new Error(`Key validation request denied: no scoped account has a key with hash ${pkMHash.toString()}.`);return this.keyStore.getKeyValidationRequest(pkMHash,this.contractAddress)}async getNoteHashMembershipWitness(blockHash,noteHash){let witness=await this.#queryWithBlockHashNotAfterAnchor(blockHash,()=>this.aztecNode.getNoteHashMembershipWitness(blockHash,noteHash));if(!witness)throw new Error(`Note hash ${noteHash} not found in the note hash tree at block ${blockHash.toString()}.`);return witness}async getBlockHashMembershipWitness(referenceBlockHash,blockHash){let witness=await this.#queryWithBlockHashNotAfterAnchor(referenceBlockHash,()=>this.aztecNode.getBlockHashMembershipWitness(referenceBlockHash,blockHash));return witness?Option.some(witness):Option.none()}async getNullifierMembershipWitness(blockHash,nullifier){let witness=await this.#queryWithBlockHashNotAfterAnchor(blockHash,()=>this.aztecNode.getNullifierMembershipWitness(blockHash,nullifier));if(!witness)throw new Error(`Nullifier membership witness not found at block ${blockHash.toString()}.`);return witness}async getLowNullifierMembershipWitness(blockHash,nullifier){let witness=await this.#queryWithBlockHashNotAfterAnchor(blockHash,()=>this.aztecNode.getLowNullifierMembershipWitness(blockHash,nullifier));if(!witness)throw new Error(`Low nullifier witness not found for nullifier ${nullifier} at block hash ${blockHash.toString()}.`);return witness}async getPublicDataWitness(blockHash,leafSlot){let witness=await this.#queryWithBlockHashNotAfterAnchor(blockHash,()=>this.aztecNode.getPublicDataWitness(blockHash,leafSlot));if(!witness)throw new Error(`Public data witness not found for slot ${leafSlot} at block hash ${blockHash.toString()}.`);return witness}async getBlockHeader(blockNumber){let anchorBlockNumber=this.anchorBlockHeader.getBlockNumber();if(blockNumber>anchorBlockNumber)throw new Error(`Block number ${blockNumber} is higher than current block ${anchorBlockNumber}`);if(blockNumber===anchorBlockNumber)return this.anchorBlockHeader;let block=await this.aztecNode.getBlock(blockNumber);if(!block?.header)throw new Error(`Block header not found for block ${blockNumber}.`);return block.header}async getPublicKeysAndPartialAddress(account){let completeAddress=await this.addressStore.getCompleteAddress(account);return completeAddress?Option.some({publicKeys:completeAddress.publicKeys,partialAddress:completeAddress.partialAddress}):Option.none()}async getCompleteAddressOrFail(account){let completeAddress=await this.addressStore.getCompleteAddress(account);if(!completeAddress)throw new Error(`No public key registered for address ${account}.
|
|
210
|
+
}`}};var ReadRequestActionEnum=(function(ReadRequestActionEnum2){return ReadRequestActionEnum2[ReadRequestActionEnum2.SKIP=0]="SKIP",ReadRequestActionEnum2[ReadRequestActionEnum2.READ_AS_PENDING=1]="READ_AS_PENDING",ReadRequestActionEnum2[ReadRequestActionEnum2.READ_AS_SETTLED=2]="READ_AS_SETTLED",ReadRequestActionEnum2})({});var PendingReadHint=class _PendingReadHint{static{__name(this,"PendingReadHint")}readRequestIndex;pendingValueIndex;constructor(readRequestIndex,pendingValueIndex){this.readRequestIndex=readRequestIndex,this.pendingValueIndex=pendingValueIndex}static nada(readRequestLen){return new _PendingReadHint(readRequestLen,0)}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _PendingReadHint(reader.readNumber(),reader.readNumber())}toBuffer(){return serializeToBuffer(this.readRequestIndex,this.pendingValueIndex)}};var ReadRequestResetActions=class _ReadRequestResetActions{static{__name(this,"ReadRequestResetActions")}actions;pendingReadHints;constructor(actions,pendingReadHints){this.actions=actions,this.pendingReadHints=pendingReadHints}static empty(numReads){return new _ReadRequestResetActions(makeTuple(numReads,()=>0),[])}};function isValidNoteHashReadRequest(readRequest,noteHash){return noteHash.value.equals(readRequest.value)&¬eHash.contractAddress.equals(readRequest.contractAddress)&&readRequest.counter>noteHash.counter}__name(isValidNoteHashReadRequest,"isValidNoteHashReadRequest");function getNoteHashReadRequestResetActions(noteHashReadRequests,noteHashes){let resetActions=ReadRequestResetActions.empty(64),noteHashMap=new Map;noteHashes.getActiveItems().forEach((noteHash,index)=>{let value=noteHash.value.toBigInt(),arr=noteHashMap.get(value)??[];arr.push({noteHash,index}),noteHashMap.set(value,arr)});for(let i=0;i<noteHashReadRequests.claimedLength;++i){let readRequest=noteHashReadRequests.array[i];if(readRequest.contractAddress.isZero())resetActions.actions[i]=ReadRequestActionEnum.READ_AS_SETTLED;else{let pendingNoteHash=noteHashMap.get(readRequest.value.toBigInt())?.find(n=>isValidNoteHashReadRequest(readRequest,n.noteHash));pendingNoteHash&&(resetActions.actions[i]=ReadRequestActionEnum.READ_AS_PENDING,resetActions.pendingReadHints.push(new PendingReadHint(i,pendingNoteHash.index)))}}return resetActions}__name(getNoteHashReadRequestResetActions,"getNoteHashReadRequestResetActions");function isValidNullifierReadRequest(readRequest,nullifier){return readRequest.value.equals(nullifier.value)&&nullifier.contractAddress.equals(readRequest.contractAddress)&&readRequest.counter>nullifier.counter}__name(isValidNullifierReadRequest,"isValidNullifierReadRequest");function getNullifierReadRequestResetActions(nullifierReadRequests,nullifiers){let resetActions=ReadRequestResetActions.empty(64),nullifierMap=new Map;nullifiers.getActiveItems().forEach((nullifier,index)=>{let value=nullifier.value.toBigInt(),arr=nullifierMap.get(value)??[];arr.push({nullifier,index}),nullifierMap.set(value,arr)});for(let i=0;i<nullifierReadRequests.claimedLength;++i){let readRequest=nullifierReadRequests.array[i];if(readRequest.contractAddress.isZero())resetActions.actions[i]=ReadRequestActionEnum.READ_AS_SETTLED;else{let pendingNullifier=nullifierMap.get(readRequest.value.toBigInt())?.find(({nullifier})=>isValidNullifierReadRequest(readRequest,nullifier));pendingNullifier&&(resetActions.actions[i]=ReadRequestActionEnum.READ_AS_PENDING,resetActions.pendingReadHints.push(new PendingReadHint(i,pendingNullifier.index)))}}return resetActions}__name(getNullifierReadRequestResetActions,"getNullifierReadRequestResetActions");var ScopedValueCache=class{static{__name(this,"ScopedValueCache")}cache=new Map;constructor(items){items.forEach(item=>{let value=item.value.toBigInt(),arr=this.cache.get(value)??[];arr.push(item),this.cache.set(value,arr)})}get(matcher){return this.cache.get(matcher.value.toBigInt())??[]}};import{inspect as inspect35}from"util";var _computedKey35;_computedKey35=inspect35.custom;var TransientDataSquashingHint=class _TransientDataSquashingHint{static{__name(this,"TransientDataSquashingHint")}nullifierIndex;noteHashIndex;constructor(nullifierIndex,noteHashIndex){this.nullifierIndex=nullifierIndex,this.noteHashIndex=noteHashIndex}toFields(){return[new Fr(this.nullifierIndex),new Fr(this.noteHashIndex)]}static fromFields(fields){let reader=FieldReader.asReader(fields);return new _TransientDataSquashingHint(reader.readU32(),reader.readU32())}isEmpty(){return!this.nullifierIndex&&!this.noteHashIndex}static empty(){return new _TransientDataSquashingHint(0,0)}toBuffer(){return serializeToBuffer(this.nullifierIndex,this.noteHashIndex)}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _TransientDataSquashingHint(reader.readNumber(),reader.readNumber())}toString(){return`nullifierIndex=${this.nullifierIndex} noteHashIndex=${this.noteHashIndex}`}[_computedKey35](){return`TransientDataSquashingHint { ${this.toString()} }`}};function buildTransientDataHints(noteHashes,nullifiers,futureNoteHashReads,futureNullifierReads,futureLogs,noteHashNullifierCounterMap,splitCounter){let futureNoteHashReadsMap=new ScopedValueCache(futureNoteHashReads),futureNullifierReadsMap=new ScopedValueCache(futureNullifierReads),futureLogNoteHashCounters=new Set(futureLogs.filter(l=>l.noteHashCounter>0).map(l=>l.noteHashCounter)),nullifierIndexMap=new Map;nullifiers.getActiveItems().forEach((n,i)=>nullifierIndexMap.set(n.counter,i));let hints=[];for(let noteHashIndex=0;noteHashIndex<noteHashes.claimedLength;noteHashIndex++){let noteHash=noteHashes.array[noteHashIndex],noteHashNullifierCounter=noteHashNullifierCounterMap.get(noteHash.counter);if(!noteHashNullifierCounter||futureNoteHashReadsMap.get(noteHash).find(read2=>isValidNoteHashReadRequest(read2,noteHash))||futureLogNoteHashCounters.has(noteHash.counter))continue;let nullifierIndex=nullifierIndexMap.get(noteHashNullifierCounter);if(nullifierIndex===void 0)continue;let nullifier=nullifiers.array[nullifierIndex];if(!(noteHash.counter<splitCounter&&nullifier.counter>=splitCounter)){if(nullifier.counter<noteHash.counter)throw new Error("Hinted nullifier has smaller counter than note hash.");if(!nullifier.contractAddress.equals(noteHash.contractAddress))throw new Error("Contract address of hinted note hash does not match.");nullifier.nullifiedNoteHash.equals(noteHash.value)&&(futureNullifierReadsMap.get(nullifier).find(read2=>isValidNullifierReadRequest(read2,nullifier))||hints.push(new TransientDataSquashingHint(nullifierIndex,noteHashIndex)))}}let noActionHint=new TransientDataSquashingHint(nullifiers.array.length,noteHashes.array.length);return{numTransientData:hints.length,hints:padArrayEnd(hints,noActionHint,nullifiers.array.length)}}__name(buildTransientDataHints,"buildTransientDataHints");var PrivateContextInputs=class _PrivateContextInputs{static{__name(this,"PrivateContextInputs")}callContext;anchorBlockHeader;txContext;startSideEffectCounter;constructor(callContext,anchorBlockHeader,txContext,startSideEffectCounter){this.callContext=callContext,this.anchorBlockHeader=anchorBlockHeader,this.txContext=txContext,this.startSideEffectCounter=startSideEffectCounter}static empty(){return new _PrivateContextInputs(CallContext.empty(),BlockHeader.empty(),TxContext.empty(),0)}toFields(){return serializeToFields([this.callContext,this.anchorBlockHeader,this.txContext,this.startSideEffectCounter])}};async function appendL1ToL2MessagesToTree(db,l1ToL2Messages){let padded=padArrayEnd(l1ToL2Messages,Fr.ZERO,1024,"Too many L1 to L2 messages");await db.appendLeaves(MerkleTreeId.L1_TO_L2_MESSAGE_TREE,padded)}__name(appendL1ToL2MessagesToTree,"appendL1ToL2MessagesToTree");var InboxLeaf=class _InboxLeaf{static{__name(this,"InboxLeaf")}index;leaf;constructor(index,leaf){this.index=index,this.leaf=leaf}toBuffer(){return serializeToBuffer([this.index,this.leaf])}fromBuffer(buffer){let reader=BufferReader.asReader(buffer),index=toBigIntBE(reader.readBytes(32)),leaf=reader.readObject(Fr);return new _InboxLeaf(index,leaf)}static smallestIndexForCheckpoint(checkpointNumber){return BigInt(checkpointNumber-INITIAL_CHECKPOINT_NUMBER2)*BigInt(1024)}static indexRangeForCheckpoint(checkpointNumber){let start=this.smallestIndexForCheckpoint(checkpointNumber),end=start+BigInt(1024);return[start,end]}static checkpointNumberFromIndex(index){return CheckpointNumber(Number(index/BigInt(1024))+INITIAL_CHECKPOINT_NUMBER2)}};var L1Actor=class _L1Actor{static{__name(this,"L1Actor")}sender;chainId;constructor(sender,chainId){this.sender=sender,this.chainId=chainId}static empty(){return new _L1Actor(EthAddress.ZERO,0)}toFields(){return[this.sender.toField(),new Fr(BigInt(this.chainId))]}toBuffer(){return serializeToBuffer(this.sender,this.chainId)}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer),ethAddr=reader.readObject(EthAddress),chainId=reader.readNumber();return new _L1Actor(ethAddr,chainId)}static random(){return new _L1Actor(EthAddress.random(),randomInt(1e3))}};var L2Actor=class _L2Actor{static{__name(this,"L2Actor")}recipient;version;constructor(recipient,version2){this.recipient=recipient,this.version=version2}static empty(){return new _L2Actor(AztecAddress.ZERO,0)}toFields(){return[this.recipient.toField(),new Fr(BigInt(this.version))]}toBuffer(){return serializeToBuffer(this.recipient,this.version)}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer),aztecAddr=AztecAddress.fromBuffer(reader),version2=reader.readNumber();return new _L2Actor(aztecAddr,version2)}static async random(){return new _L2Actor(await AztecAddress.random(),randomInt(1e3))}};var L1ToL2Message=class _L1ToL2Message{static{__name(this,"L1ToL2Message")}sender;recipient;content;secretHash;index;constructor(sender,recipient,content,secretHash,index){this.sender=sender,this.recipient=recipient,this.content=content,this.secretHash=secretHash,this.index=index}toFields(){return[...this.sender.toFields(),...this.recipient.toFields(),this.content,this.secretHash,this.index]}toBuffer(){return serializeToBuffer(this.sender,this.recipient,this.content,this.secretHash,this.index)}hash(){return sha256ToField(this.toFields())}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer),sender=reader.readObject(L1Actor),recipient=reader.readObject(L2Actor),content=Fr.fromBuffer(reader),secretHash=Fr.fromBuffer(reader),index=Fr.fromBuffer(reader);return new _L1ToL2Message(sender,recipient,content,secretHash,index)}toString(){return bufferToHex(this.toBuffer())}static fromString(data){let buffer=Buffer.from(data,"hex");return _L1ToL2Message.fromBuffer(buffer)}static empty(){return new _L1ToL2Message(L1Actor.empty(),L2Actor.empty(),Fr.ZERO,Fr.ZERO,Fr.ZERO)}static async random(){return new _L1ToL2Message(L1Actor.random(),await L2Actor.random(),Fr.random(),Fr.random(),Fr.random())}};async function getNonNullifiedL1ToL2MessageWitness(node,contractAddress,messageHash,secret,referenceBlock="latest"){let messageNullifier=await computeL1ToL2MessageNullifier(contractAddress,messageHash,secret),[l1ToL2Response,nullifierResponse]=await Promise.all([node.getL1ToL2MessageMembershipWitness(referenceBlock,messageHash),node.findLeavesIndexes(referenceBlock,MerkleTreeId.NULLIFIER_TREE,[messageNullifier])]);if(!l1ToL2Response)throw new Error(`No L1 to L2 message found for message hash ${messageHash.toString()}`);if(nullifierResponse[0]!==void 0)throw new Error(`No non-nullified L1 to L2 message found for message hash ${messageHash.toString()}`);return l1ToL2Response}__name(getNonNullifiedL1ToL2MessageWitness,"getNonNullifiedL1ToL2MessageWitness");import{strict as assert3}from"assert";var EMPTY_PROOF_SIZE=42,Proof=class _Proof{static{__name(this,"Proof")}buffer;numPublicInputs;__proofBrand;constructor(buffer,numPublicInputs){this.buffer=buffer,this.numPublicInputs=numPublicInputs}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer),size=reader.readNumber(),buf=reader.readBytes(size),numPublicInputs=reader.readNumber();return new _Proof(buf,numPublicInputs)}toBuffer(){return serializeToBuffer(this.buffer.length,this.buffer,this.numPublicInputs)}toString(){return bufferToHex(this.toBuffer())}withoutPublicInputs(){if(this.isEmpty())return this.buffer;assert3(this.numPublicInputs>=8,"Proof does not contain an aggregation object");let proofStart=Fr.SIZE_IN_BYTES*(this.numPublicInputs-8);return assert3(this.buffer.length>=proofStart,"Proof buffer is not appropriately sized to call withoutPublicInputs()"),this.buffer.subarray(proofStart)}extractPublicInputs(){if(this.isEmpty())return new Array(this.numPublicInputs).fill(Fr.zero());assert3(this.numPublicInputs>=8,"Proof does not contain an aggregation object");let numInnerPublicInputs=this.numPublicInputs-8;return BufferReader.asReader(this.buffer.subarray(0,Fr.SIZE_IN_BYTES*numInnerPublicInputs)).readArray(numInnerPublicInputs,Fr)}static fromString(str){return _Proof.fromBuffer(hexToBuffer(str))}isEmpty(){return this.buffer.length===EMPTY_PROOF_SIZE&&this.buffer.every(byte=>byte===0)&&this.numPublicInputs===0}static empty(){return makeEmptyProof()}};function makeEmptyProof(){return new Proof(Buffer.alloc(EMPTY_PROOF_SIZE,0),0)}__name(makeEmptyProof,"makeEmptyProof");var RecursiveProof=class _RecursiveProof{static{__name(this,"RecursiveProof")}proof;binaryProof;fieldsValid;proofLength;constructor(proof,binaryProof,fieldsValid,proofLength){if(this.proof=proof,this.binaryProof=binaryProof,this.fieldsValid=fieldsValid,this.proofLength=proofLength,proof.length!==proofLength)throw new Error(`Proof length ${proof.length} does not match expected length ${proofLength}.`)}static fromBuffer(buffer,expectedSize){let reader=BufferReader.asReader(buffer),size=reader.readNumber();if(typeof expectedSize=="number"&&expectedSize!==size)throw new Error(`Expected proof length ${expectedSize}, got ${size}`);return new _RecursiveProof(reader.readArray(size,Fr),Proof.fromBuffer(reader),reader.readBoolean(),size)}toBuffer(){return serializeToBuffer(this.proof.length,this.proof,this.binaryProof,this.fieldsValid)}toString(){return bufferToHex(this.toBuffer())}static fromString(str,expectedSize){return _RecursiveProof.fromBuffer(hexToBuffer(str),expectedSize)}toJSON(){return this.toBuffer()}static schemaFor(expectedSize){return schemas.Buffer.transform(b=>_RecursiveProof.fromBuffer(b,expectedSize))}};var ProofData=class _ProofData{static{__name(this,"ProofData")}publicInputs;proof;vkData;constructor(publicInputs,proof,vkData){this.publicInputs=publicInputs,this.proof=proof,this.vkData=vkData}toBuffer(){return serializeToBuffer(this.publicInputs,this.proof,this.vkData)}static fromBuffer(buffer,publicInputs){let reader=BufferReader.asReader(buffer);return new _ProofData(reader.readObject(publicInputs),RecursiveProof.fromBuffer(reader),reader.readObject(VkData))}},ProofDataForFixedVk=class _ProofDataForFixedVk{static{__name(this,"ProofDataForFixedVk")}publicInputs;proof;constructor(publicInputs,proof){this.publicInputs=publicInputs,this.proof=proof}toBuffer(){return serializeToBuffer(this.publicInputs,this.proof)}static fromBuffer(buffer,publicInputs){let reader=BufferReader.asReader(buffer);return new _ProofDataForFixedVk(reader.readObject(publicInputs),RecursiveProof.fromBuffer(reader))}};var ProvingRequestType=(function(ProvingRequestType2){return ProvingRequestType2[ProvingRequestType2.PUBLIC_VM=0]="PUBLIC_VM",ProvingRequestType2[ProvingRequestType2.PUBLIC_CHONK_VERIFIER=1]="PUBLIC_CHONK_VERIFIER",ProvingRequestType2[ProvingRequestType2.PRIVATE_TX_BASE_ROLLUP=2]="PRIVATE_TX_BASE_ROLLUP",ProvingRequestType2[ProvingRequestType2.PUBLIC_TX_BASE_ROLLUP=3]="PUBLIC_TX_BASE_ROLLUP",ProvingRequestType2[ProvingRequestType2.TX_MERGE_ROLLUP=4]="TX_MERGE_ROLLUP",ProvingRequestType2[ProvingRequestType2.BLOCK_ROOT_FIRST_ROLLUP=5]="BLOCK_ROOT_FIRST_ROLLUP",ProvingRequestType2[ProvingRequestType2.BLOCK_ROOT_SINGLE_TX_FIRST_ROLLUP=6]="BLOCK_ROOT_SINGLE_TX_FIRST_ROLLUP",ProvingRequestType2[ProvingRequestType2.BLOCK_ROOT_EMPTY_TX_FIRST_ROLLUP=7]="BLOCK_ROOT_EMPTY_TX_FIRST_ROLLUP",ProvingRequestType2[ProvingRequestType2.BLOCK_ROOT_ROLLUP=8]="BLOCK_ROOT_ROLLUP",ProvingRequestType2[ProvingRequestType2.BLOCK_ROOT_SINGLE_TX_ROLLUP=9]="BLOCK_ROOT_SINGLE_TX_ROLLUP",ProvingRequestType2[ProvingRequestType2.BLOCK_MERGE_ROLLUP=10]="BLOCK_MERGE_ROLLUP",ProvingRequestType2[ProvingRequestType2.CHECKPOINT_ROOT_ROLLUP=11]="CHECKPOINT_ROOT_ROLLUP",ProvingRequestType2[ProvingRequestType2.CHECKPOINT_ROOT_SINGLE_BLOCK_ROLLUP=12]="CHECKPOINT_ROOT_SINGLE_BLOCK_ROLLUP",ProvingRequestType2[ProvingRequestType2.CHECKPOINT_PADDING_ROLLUP=13]="CHECKPOINT_PADDING_ROLLUP",ProvingRequestType2[ProvingRequestType2.CHECKPOINT_MERGE_ROLLUP=14]="CHECKPOINT_MERGE_ROLLUP",ProvingRequestType2[ProvingRequestType2.ROOT_ROLLUP=15]="ROOT_ROLLUP",ProvingRequestType2[ProvingRequestType2.PARITY_BASE=16]="PARITY_BASE",ProvingRequestType2[ProvingRequestType2.PARITY_ROOT=17]="PARITY_ROOT",ProvingRequestType2})({});function assertAllowedScope(scope,allowedScopes){if(!allowedScopes.some(allowed=>allowed.equals(scope)))throw new Error(`Scope ${scope.toString()} is not in the allowed scopes list: [${allowedScopes.map(s2=>s2.toString()).join(", ")}]. See https://docs.aztec.network/errors/10`)}__name(assertAllowedScope,"assertAllowedScope");var CapsuleService=class{static{__name(this,"CapsuleService")}capsuleStore;allowedScopes;constructor(capsuleStore,allowedScopes){this.capsuleStore=capsuleStore,this.allowedScopes=[...allowedScopes,AztecAddress.ZERO]}setCapsule(contractAddress,slot,capsule,jobId,scope){assertAllowedScope(scope,this.allowedScopes),this.capsuleStore.setCapsule(contractAddress,slot,capsule,jobId,scope)}async getCapsule(contractAddress,slot,jobId,scope,transientCapsules){return assertAllowedScope(scope,this.allowedScopes),transientCapsules?.find(c2=>c2.contractAddress.equals(contractAddress)&&c2.storageSlot.equals(slot)&&(c2.scope??AztecAddress.ZERO).equals(scope))?.data??await this.capsuleStore.getCapsule(contractAddress,slot,jobId,scope)}deleteCapsule(contractAddress,slot,jobId,scope){assertAllowedScope(scope,this.allowedScopes),this.capsuleStore.deleteCapsule(contractAddress,slot,jobId,scope)}copyCapsule(contractAddress,srcSlot,dstSlot,numEntries,jobId,scope){return assertAllowedScope(scope,this.allowedScopes),this.capsuleStore.copyCapsule(contractAddress,srcSlot,dstSlot,numEntries,jobId,scope)}appendToCapsuleArray(contractAddress,baseSlot,content,jobId,scope){return assertAllowedScope(scope,this.allowedScopes),this.capsuleStore.appendToCapsuleArray(contractAddress,baseSlot,content,jobId,scope)}readCapsuleArray(contractAddress,baseSlot,jobId,scope){return assertAllowedScope(scope,this.allowedScopes),this.capsuleStore.readCapsuleArray(contractAddress,baseSlot,jobId,scope)}setCapsuleArray(contractAddress,baseSlot,content,jobId,scope){return assertAllowedScope(scope,this.allowedScopes),this.capsuleStore.setCapsuleArray(contractAddress,baseSlot,content,jobId,scope)}};function assertNonZeroScope(scope){if(scope.equals(AztecAddress.ZERO))throw new Error("scope must not be the zero address")}__name(assertNonZeroScope,"assertNonZeroScope");var FactCollectionTypeKey=class _FactCollectionTypeKey{static{__name(this,"FactCollectionTypeKey")}contractAddress;scope;factCollectionTypeId;constructor(contractAddress,scope,factCollectionTypeId){this.contractAddress=contractAddress,this.scope=scope,this.factCollectionTypeId=factCollectionTypeId,assertNonZeroScope(scope)}static from(fields){return new _FactCollectionTypeKey(fields.contractAddress,fields.scope,fields.factCollectionTypeId)}toString(){return`${this.contractAddress}:${this.scope}:${this.factCollectionTypeId}`}},FactCollectionKey=class _FactCollectionKey{static{__name(this,"FactCollectionKey")}contractAddress;scope;factCollectionTypeId;factCollectionId;constructor(contractAddress,scope,factCollectionTypeId,factCollectionId){this.contractAddress=contractAddress,this.scope=scope,this.factCollectionTypeId=factCollectionTypeId,this.factCollectionId=factCollectionId,assertNonZeroScope(scope)}static from(fields){return new _FactCollectionKey(fields.contractAddress,fields.scope,fields.factCollectionTypeId,fields.factCollectionId)}static fromString(str){let[contractAddress,scope,factCollectionTypeId,factCollectionId]=str.split(":");return new _FactCollectionKey(AztecAddress.fromStringUnsafe(contractAddress),AztecAddress.fromStringUnsafe(scope),Fr.fromString(factCollectionTypeId),Fr.fromString(factCollectionId))}factCollectionTypeKey(){return new FactCollectionTypeKey(this.contractAddress,this.scope,this.factCollectionTypeId)}toString(){return`${this.contractAddress}:${this.scope}:${this.factCollectionTypeId}:${this.factCollectionId}`}};var StoredFact=class _StoredFact{static{__name(this,"StoredFact")}factCollectionKey;factTypeId;payload;originBlock;constructor(factCollectionKey,factTypeId,payload,originBlock){this.factCollectionKey=factCollectionKey,this.factTypeId=factTypeId,this.payload=payload,this.originBlock=originBlock}get isRetractable(){return this.originBlock!==void 0}payloadHash(){return sha256ToField([this.payload.length,...this.payload])}toFact(){return{factTypeId:this.factTypeId,payload:this.payload,originBlock:this.originBlock}}toBuffer(){return serializeToBuffer(this.factCollectionKey.contractAddress,this.factCollectionKey.scope,this.factCollectionKey.factCollectionTypeId,this.factCollectionKey.factCollectionId,this.factTypeId,this.payload.length,...this.payload,this.originBlock!==void 0,this.originBlock?this.originBlock.blockNumber:0,this.originBlock?this.originBlock.blockHash:Fr.ZERO)}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer),contractAddress=reader.readObject(AztecAddress),scope=reader.readObject(AztecAddress),factCollectionTypeId=reader.readObject(Fr),factCollectionId=reader.readObject(Fr),factTypeId=reader.readObject(Fr),payloadLen=reader.readNumber(),payload=reader.readArray(payloadLen,Fr),hasOriginBlock=reader.readBoolean(),blockNumber=reader.readNumber(),blockHash=reader.readObject(Fr),originBlock=hasOriginBlock?{blockNumber,blockHash}:void 0;return new _StoredFact(new FactCollectionKey(contractAddress,scope,factCollectionTypeId,factCollectionId),factTypeId,[...payload],originBlock)}};function factKeyStrOf(fact){let origin=fact.originBlock?`${fact.originBlock.blockNumber}:${fact.originBlock.blockHash}`:"none";return`${fact.factCollectionKey}:${fact.factTypeId}:${fact.payloadHash()}:${origin}`}__name(factKeyStrOf,"factKeyStrOf");var FactStore=class{static{__name(this,"FactStore")}storeName="fact";#store;#facts;#factsByCollection;#factsByBlock;#opsForJob;#jobLocks;logger=createLogger("fact_store");constructor(store){this.#store=store,this.#facts=store.openMap("facts"),this.#factsByCollection=store.openMultiMap("facts_by_collection"),this.#factsByBlock=store.openMultiMap("facts_by_block"),this.#opsForJob=new Map,this.#jobLocks=new Map}recordFact(factCollectionKey,factTypeId,payload,originBlock,jobId){return this.#withJobLock(jobId,()=>(this.#stagedOpsFor(jobId).push({kind:"recordFact",fact:new StoredFact(factCollectionKey,factTypeId,payload,originBlock)}),Promise.resolve()))}deleteFactCollection(factCollectionKey,jobId){return this.#withJobLock(jobId,()=>(this.#stagedOpsFor(jobId).push({kind:"deleteFactCollection",key:factCollectionKey}),Promise.resolve()))}async getFactCollection(factCollectionKey,jobId){let collectionKey=factCollectionKey.toString(),committed=await this.#store.transactionAsync(()=>this.#readCollectionsFromDb([factCollectionKey])),collection=this.#foldStagedOps(committed,jobId).get(collectionKey);if(!collection)return;let facts=[...collection.facts.values()];return facts.length>0?{key:factCollectionKey,facts}:void 0}async getFactCollectionsByType(factCollectionTypeKey,jobId){let typeKey=factCollectionTypeKey.toString(),committed=await this.#readCollectionsFromDbByType(typeKey);return Array.from(this.#foldStagedOps(committed,jobId,typeKey).values()).map(collection=>({key:collection.key,facts:[...collection.facts.values()]})).filter(collection=>collection.facts.length>0)}async commit(jobId){for(let op of this.#stagedOpsFor(jobId))switch(op.kind){case"recordFact":await this.#commitFact(op.fact);break;case"deleteFactCollection":await this.#deleteCollection(op.key.toString());break;default:{let _exhaustive=op;throw new Error(`Unhandled FactStore staged op kind: ${JSON.stringify(_exhaustive)}`)}}this.#clearJobData(jobId)}discardStaged(jobId){return this.#clearJobData(jobId),Promise.resolve()}async rollback(toBlock){if(this.#opsForJob.size>0)throw new Error("PXE fact store rollback is not allowed while jobs are running");let removedFacts=await this.#retractFacts(toBlock);this.logger.verbose("rolled back fact store",{removedFacts,toBlock})}async#retractFacts(toBlock){let factReads=new Map;for await(let[,factKey]of this.#factsByBlock.entriesAsync({start:toBlock+1}))factReads.set(factKey,this.#facts.getAsync(factKey));return await Promise.all(Array.from(factReads,async([factKey,read2])=>{let buf=await read2;if(!buf){this.logger.warn("Skipping retraction of a fact missing from the primary store: by-block index is stale",{factKey});return}await this.#deleteFact(factKey,StoredFact.fromBuffer(buf))})),factReads.size}async#readCollectionsFromDb(keys){let result=new Map;for(let key of keys){let collection=await this.#loadCommittedCollection(key);collection&&result.set(key.toString(),collection)}return result}#readCollectionsFromDbByType(typeKey){return this.#store.transactionAsync(async()=>{let factReadsByCollection=new Map;for await(let[collectionKey,factKey]of this.#factsByCollection.entriesAsync({start:`${typeKey}:`,end:`${typeKey};`})){let reads=factReadsByCollection.get(collectionKey);reads||(reads=new Map,factReadsByCollection.set(collectionKey,reads)),reads.set(factKey,this.#facts.getAsync(factKey))}let result=new Map;for(let[collectionKey,reads]of factReadsByCollection){let collection=await this.#assembleCollection(FactCollectionKey.fromString(collectionKey),reads);result.set(collectionKey,collection)}return result})}async#loadCommittedCollection(collectionKey){let factReads=new Map;for await(let factKey of this.#factsByCollection.getValuesAsync(collectionKey.toString()))factReads.set(factKey,this.#facts.getAsync(factKey));if(factReads.size!==0)return this.#assembleCollection(collectionKey,factReads)}async#assembleCollection(collectionKey,reads){let factKeys=[...reads.keys()],bufs=await Promise.all(reads.values()),facts=new Map;for(let i=0;i<factKeys.length;i++){let factKey=factKeys[i],buf=bufs[i];if(!buf)throw new Error(`Fact not found for factKey ${factKey}`);let stored=StoredFact.fromBuffer(buf);if(stored.factCollectionKey.toString()!==collectionKey.toString())throw new Error(`Fact ${factKey} does not belong to collection ${collectionKey}`);facts.set(factKey,stored.toFact())}return{key:collectionKey,facts}}#foldStagedOps(committed,jobId,typeKey){let result=new Map;for(let[collectionKey,{key,facts}]of committed)result.set(collectionKey,{key,facts:new Map(facts)});for(let op of this.#stagedOpsFor(jobId))switch(op.kind){case"recordFact":this.#foldRecordFact(result,op,typeKey);break;case"deleteFactCollection":this.#foldDeleteFactCollection(result,op);break;default:{let _exhaustive=op;throw new Error(`Unhandled FactStore staged op kind: ${JSON.stringify(_exhaustive)}`)}}return result}#foldRecordFact(result,op,typeKey){let key=op.fact.factCollectionKey;if(typeKey!==void 0&&key.factCollectionTypeKey().toString()!==typeKey)return;let collectionKey=key.toString(),collection=result.get(collectionKey);collection||(collection={key,facts:new Map},result.set(collectionKey,collection));let fKey=factKeyStrOf(op.fact);collection.facts.has(fKey)||collection.facts.set(fKey,op.fact.toFact())}#foldDeleteFactCollection(result,op){result.delete(op.key.toString())}async#commitFact(fact){let factKey=factKeyStrOf(fact);if(await this.#facts.hasAsync(factKey)){this.logger.debug("Ignoring already recorded fact",{factKey});return}await this.#facts.set(factKey,fact.toBuffer()),await this.#factsByCollection.set(fact.factCollectionKey.toString(),factKey),fact.originBlock!==void 0&&await this.#factsByBlock.set(fact.originBlock.blockNumber,factKey)}async#deleteCollection(collectionKey){let factReads=new Map;for await(let factKey of this.#factsByCollection.getValuesAsync(collectionKey))factReads.set(factKey,this.#facts.getAsync(factKey));await Promise.all(Array.from(factReads,async([factKey,read2])=>{let buf=await read2;if(!buf)throw new Error(`Fact not found for factKey ${factKey}`);await this.#deleteFact(factKey,StoredFact.fromBuffer(buf))}))}async#deleteFact(factKey,fact){await this.#facts.delete(factKey),await this.#factsByCollection.deleteValue(fact.factCollectionKey.toString(),factKey),fact.originBlock!==void 0&&await this.#factsByBlock.deleteValue(fact.originBlock.blockNumber,factKey)}#stagedOpsFor(jobId){let ops=this.#opsForJob.get(jobId);return ops===void 0&&(ops=[],this.#opsForJob.set(jobId,ops)),ops}#clearJobData(jobId){this.#opsForJob.delete(jobId),this.#jobLocks.delete(jobId)}async#withJobLock(jobId,fn){let lock=this.#jobLocks.get(jobId);lock||(lock=new Semaphore(1),this.#jobLocks.set(jobId,lock)),await lock.acquire();try{return await fn()}finally{lock.release()}}};var OriginBlockState=(function(OriginBlockState2){return OriginBlockState2[OriginBlockState2.Pending=1]="Pending",OriginBlockState2[OriginBlockState2.Proven=2]="Proven",OriginBlockState2[OriginBlockState2.Finalized=3]="Finalized",OriginBlockState2})({});function anchoredTipBlockNumbers(tips,anchorBlockNumber){return{provenBlockNumber:Math.min(tips.proven.block.number,anchorBlockNumber),finalizedBlockNumber:Math.min(tips.finalized.block.number,anchorBlockNumber)}}__name(anchoredTipBlockNumbers,"anchoredTipBlockNumbers");function classifyOriginBlockState(blockNumber,tips){return blockNumber<=tips.finalizedBlockNumber?3:blockNumber<=tips.provenBlockNumber?2:1}__name(classifyOriginBlockState,"classifyOriginBlockState");function toFactWithOriginState(fact,tips){let originBlock=fact.originBlock?{blockNumber:fact.originBlock.blockNumber,blockHash:fact.originBlock.blockHash,blockState:classifyOriginBlockState(fact.originBlock.blockNumber,tips)}:void 0;return{factTypeId:fact.factTypeId,payload:fact.payload,originBlock}}__name(toFactWithOriginState,"toFactWithOriginState");var FactService=class{static{__name(this,"FactService")}factStore;allowedScopes;constructor(factStore,allowedScopes){this.factStore=factStore,this.allowedScopes=allowedScopes}recordFact(factCollectionKey,factTypeId,payload,originBlock,jobId){return assertAllowedScope(factCollectionKey.scope,this.allowedScopes),this.factStore.recordFact(factCollectionKey,factTypeId,payload,originBlock,jobId)}deleteFactCollection(factCollectionKey,jobId){return assertAllowedScope(factCollectionKey.scope,this.allowedScopes),this.factStore.deleteFactCollection(factCollectionKey,jobId)}async getFactCollection(factCollectionKey,tips,jobId){assertAllowedScope(factCollectionKey.scope,this.allowedScopes);let collection=await this.factStore.getFactCollection(factCollectionKey,jobId);if(collection)return{key:collection.key,facts:this.#annotate(collection.facts,tips)}}async getFactCollectionsByType(factCollectionTypeKey,tips,jobId){return assertAllowedScope(factCollectionTypeKey.scope,this.allowedScopes),(await this.factStore.getFactCollectionsByType(factCollectionTypeKey,jobId)).map(collection=>({key:collection.key,facts:this.#annotate(collection.facts,tips)}))}#annotate(facts,tips){return facts.map(fact=>toFactWithOriginState(fact,tips))}};var AnchoredContractData=class{static{__name(this,"AnchoredContractData")}store;contractClassService;anchorBlockHeader;overrides;constructor(store,contractClassService,anchorBlockHeader,overrides){this.store=store,this.contractClassService=contractClassService,this.anchorBlockHeader=anchorBlockHeader,this.overrides=overrides}getContractInstance(address){let override=this.overrides?.[address.toString()];return override?Promise.resolve(override.instance):this.store.getContractInstance(address)}getCurrentClassId(address){let override=this.overrides?.[address.toString()];return override?Promise.resolve(override.instance.currentContractClassId):this.contractClassService.getCurrentClassId(address,this.anchorBlockHeader)}async getFunctionArtifact(address,selector){let classId=await this.getCurrentClassId(address);return classId?this.store.getFunctionArtifact(classId,selector):void 0}async getFunctionArtifactWithDebugMetadata(address,selector){let classId=await this.getCurrentClassId(address);return classId?this.store.getFunctionArtifactWithDebugMetadata(classId,selector):void 0}async getDebugContractName(address){let classId=await this.getCurrentClassId(address);return classId?this.store.getDebugContractName(classId):void 0}async getDebugFunctionName(address,selector){let classId=await this.getCurrentClassId(address);return classId?this.store.getDebugFunctionName(classId,selector):`${address}:${selector}`}};var ExecutionNoteCache=class{static{__name(this,"ExecutionNoteCache")}protocolNullifier;notes;noteMap;nullifierMap;emittedNullifiers;minRevertibleSideEffectCounter;inRevertiblePhase;usedProtocolNullifierForNonces;constructor(protocolNullifier){this.protocolNullifier=protocolNullifier,this.notes=[],this.noteMap=new Map,this.nullifierMap=new Map,this.emittedNullifiers=new Set,this.minRevertibleSideEffectCounter=0,this.inRevertiblePhase=!1}async setMinRevertibleSideEffectCounter(minRevertibleSideEffectCounter){if(this.inRevertiblePhase)throw new Error(`Cannot enter the revertible phase twice. Current counter: ${minRevertibleSideEffectCounter}. Previous enter counter: ${this.minRevertibleSideEffectCounter}`);this.inRevertiblePhase=!0,this.minRevertibleSideEffectCounter=minRevertibleSideEffectCounter;let nullifiers=this.getEmittedNullifiers();this.usedProtocolNullifierForNonces=nullifiers.length===0;let nonceGenerator=this.usedProtocolNullifierForNonces?this.protocolNullifier:new Fr(nullifiers[0]),updatedNotes=await Promise.all(this.notes.map(async({note,counter},i)=>{let noteNonce=await computeNoteHashNonce(nonceGenerator,i),uniqueNoteHash=await computeUniqueNoteHash(noteNonce,await siloNoteHash(note.contractAddress,note.noteHash));return{counter,note:{...note,noteNonce},noteHashForConsumption:uniqueNoteHash}}));this.notes=[],this.noteMap=new Map,updatedNotes.forEach(n=>this.#addNote(n))}isSideEffectCounterRevertible(sideEffectCounter){return this.inRevertiblePhase?sideEffectCounter>=this.minRevertibleSideEffectCounter:!1}finish(){this.inRevertiblePhase||(this.usedProtocolNullifierForNonces=this.getEmittedNullifiers().length===0)}addNewNote(note,counter){let previousNote=this.notes[this.notes.length-1];if(previousNote&&previousNote.counter>=counter)throw new Error(`Note hash counters must be strictly increasing. Current counter: ${counter}. Previous counter: ${previousNote.counter}.`);this.#addNote({note,counter,noteHashForConsumption:note.noteHash})}async nullifyNote(contractAddress,innerNullifier,noteHash){let siloedNullifier=(await siloNullifier(contractAddress,innerNullifier)).toBigInt(),nullifiedNoteHashCounter;if(noteHash.isEmpty())this.#recordNullifier(contractAddress,siloedNullifier);else{let notesInContract=this.noteMap.get(contractAddress.toBigInt())??[],noteIndexToRemove=notesInContract.findIndex(n=>n.noteHashForConsumption.equals(noteHash));if(noteIndexToRemove===-1)throw new Error("Attempt to remove a pending note that does not exist.");let note=notesInContract.splice(noteIndexToRemove,1)[0];nullifiedNoteHashCounter=note.counter,this.noteMap.set(contractAddress.toBigInt(),notesInContract),this.notes=this.notes.filter(n=>n.counter!==note.counter),this.inRevertiblePhase&¬e.counter<this.minRevertibleSideEffectCounter&&this.#recordNullifier(contractAddress,siloedNullifier)}return nullifiedNoteHashCounter}async nullifierCreated(contractAddress,innerNullifier){let siloedNullifier=(await siloNullifier(contractAddress,innerNullifier)).toBigInt();this.#recordNullifier(contractAddress,siloedNullifier)}getNotes(contractAddress,owner,storageSlot){return(this.noteMap.get(contractAddress.toBigInt())??[]).filter(n=>owner===void 0||n.note.owner.equals(owner)).filter(n=>n.note.storageSlot.equals(storageSlot)).map(n=>n.note)}checkNoteExists(contractAddress,noteHash){return(this.noteMap.get(contractAddress.toBigInt())??[]).some(n=>n.note.noteHash.equals(noteHash))}getNullifiers(contractAddress){return this.nullifierMap.get(contractAddress.toBigInt())??new Set}#addNote(note){this.notes.push(note);let notes=this.noteMap.get(note.note.contractAddress.toBigInt())??[];notes.push(note),this.noteMap.set(note.note.contractAddress.toBigInt(),notes)}getAllNotes(){return this.notes}getEmittedNullifiers(){return[...this.emittedNullifiers].map(n=>new Fr(n))}getAllNullifiers(){if(this.usedProtocolNullifierForNonces===void 0)throw new Error("usedProtocolNullifierForNonces is not set yet. Call finish() to complete the transaction.");let allNullifiers=this.getEmittedNullifiers();return[...this.usedProtocolNullifierForNonces?[this.protocolNullifier]:[],...allNullifiers]}getNonceGenerator(){return this.getAllNullifiers()[0]}#recordNullifier(contractAddress,siloedNullifier){let nullifiers=this.getNullifiers(contractAddress);if(nullifiers.has(siloedNullifier))throw new Error(`Duplicate siloed nullifier ${siloedNullifier} emitted by contract ${contractAddress}`);nullifiers.add(siloedNullifier),this.nullifierMap.set(contractAddress.toBigInt(),nullifiers),this.emittedNullifiers.add(siloedNullifier)}};var ExecutionTaggingIndexCache=class{static{__name(this,"ExecutionTaggingIndexCache")}taggingIndexMap=new Map;getLastUsedIndex(secret){return this.taggingIndexMap.get(secret.toString())?.highestIndex}setLastUsedIndex(secret,index){let currentValue=this.taggingIndexMap.get(secret.toString());if(currentValue!==void 0&¤tValue.highestIndex!==index-1)throw new Error(`Invalid tagging index update. Current value: ${currentValue.highestIndex}, new value: ${index}`);currentValue!==void 0?currentValue.highestIndex=index:this.taggingIndexMap.set(secret.toString(),{lowestIndex:index,highestIndex:index})}getUsedTaggingIndexRanges(){return Array.from(this.taggingIndexMap.entries()).map(([secret,{lowestIndex,highestIndex}])=>({extendedSecret:AppTaggingSecret.fromString(secret),lowestIndex,highestIndex}))}};var HashedValuesCache=class _HashedValuesCache{static{__name(this,"HashedValuesCache")}cache;constructor(initialArguments=[]){this.cache=new Map;for(let initialArg of initialArguments)this.cache.set(initialArg.hash.toBigInt(),initialArg.values)}static create(initialArguments=[]){return new _HashedValuesCache(initialArguments)}getPreimage(hash5){return hash5.isEmpty()?[]:this.cache.get(hash5.toBigInt())}store(values,hash5){this.cache.set(hash5.toBigInt(),values)}};var BoundedVec=class _BoundedVec{static{__name(this,"BoundedVec")}data;maxLength;elementSize;constructor(data,maxLength,elementSize){this.data=data,this.maxLength=maxLength,this.elementSize=elementSize}static from({data,maxLength,elementSize=1}){return new _BoundedVec(data,maxLength,elementSize)}equals(other,innerEquals){return this.maxLength===other.maxLength&&this.data.length===other.data.length&&this.data.every((value,i)=>innerEquals(value,other.data[i]))}};var EphemeralArray=class _EphemeralArray{static{__name(this,"EphemeralArray")}state;constructor(state){this.state=state}static fromValues(service,values){return new _EphemeralArray({kind:"output",service,values})}static fromSlot(slot,mapping){return new _EphemeralArray({kind:"input",slot,mapping})}materializeSlot(serializeItem){return this.state.kind==="input"?this.state.slot:(this.state.cachedSlot===void 0&&(this.state.cachedSlot=this.state.service.newArray(this.state.values.map(serializeItem))),this.state.cachedSlot)}readAll(service){if(this.state.kind==="output")return this.state.values;let mapping=this.state.mapping;return service.readArrayAt(this.state.slot).map(fields=>mapping.deserialization.fn([FieldReader.asReader(fields)]))}};var EventValidationRequest=class _EventValidationRequest{static{__name(this,"EventValidationRequest")}contractAddress;eventTypeId;randomness;serializedEvent;eventCommitment;txHash;constructor(contractAddress,eventTypeId,randomness,serializedEvent,eventCommitment,txHash){this.contractAddress=contractAddress,this.eventTypeId=eventTypeId,this.randomness=randomness,this.serializedEvent=serializedEvent,this.eventCommitment=eventCommitment,this.txHash=txHash}static fromFields(fields){let reader=FieldReader.asReader(fields),contractAddress=AztecAddress.fromFieldUnsafe(reader.readField()),eventTypeId=EventSelector.fromField(reader.readField()),randomness=reader.readField(),maxEventSerializedLen=reader.readField().toNumber(),eventStorage=reader.readFieldArray(maxEventSerializedLen),eventLen=reader.readField().toNumber(),serializedEvent=eventStorage.slice(0,eventLen),eventCommitment=reader.readField(),txHash=TxHash.fromField(reader.readField());if(reader.remainingFields()!==0)throw new Error(`Error converting array of fields to EventValidationRequest: expected ${reader.cursor} fields but received ${reader.cursor+reader.remainingFields()} (maxEventSerializedLen=${maxEventSerializedLen}).`);return new _EventValidationRequest(contractAddress,eventTypeId,randomness,serializedEvent,eventCommitment,txHash)}};var LogSource=(function(LogSource2){return LogSource2[LogSource2.PRIVATE=0]="PRIVATE",LogSource2[LogSource2.PUBLIC=1]="PUBLIC",LogSource2[LogSource2.PUBLIC_AND_PRIVATE=2]="PUBLIC_AND_PRIVATE",LogSource2})({});function logSourceFromField(field){let sourceNum=field.toNumber();if(!(sourceNum in LogSource)){let validNames=Object.keys(LogSource).filter(k=>isNaN(Number(k)));throw new Error(`Invalid LogSource value ${sourceNum}, expected one of ${validNames.join(", ")}`)}return sourceNum}__name(logSourceFromField,"logSourceFromField");var NoteValidationRequest=class _NoteValidationRequest{static{__name(this,"NoteValidationRequest")}contractAddress;owner;storageSlot;randomness;noteNonce;content;noteHash;nullifier;txHash;constructor(contractAddress,owner,storageSlot,randomness,noteNonce,content,noteHash,nullifier,txHash){this.contractAddress=contractAddress,this.owner=owner,this.storageSlot=storageSlot,this.randomness=randomness,this.noteNonce=noteNonce,this.content=content,this.noteHash=noteHash,this.nullifier=nullifier,this.txHash=txHash}static fromFields(fields){let reader=FieldReader.asReader(fields),contractAddress=AztecAddress.fromFieldUnsafe(reader.readField()),owner=AztecAddress.fromFieldUnsafe(reader.readField()),storageSlot=reader.readField(),randomness=reader.readField(),noteNonce=reader.readField(),maxNotePackedLen=reader.readField().toNumber(),contentStorage=reader.readFieldArray(maxNotePackedLen),contentLen=reader.readField().toNumber(),content=contentStorage.slice(0,contentLen),noteHash=reader.readField(),nullifier=reader.readField(),txHash=TxHash.fromField(reader.readField());if(reader.remainingFields()!==0)throw new Error(`Error converting array of fields to NoteValidationRequest: expected ${reader.cursor} fields but received ${reader.cursor+reader.remainingFields()} (maxNotePackedLen=${maxNotePackedLen}).`);return new _NoteValidationRequest(contractAddress,owner,storageSlot,randomness,noteNonce,content,noteHash,nullifier,txHash)}};var Option=class _Option{static{__name(this,"Option")}value;size;constructor(value,size){this.value=value,this.size=size}static some(value){return new _Option(value,void 0)}static none(size){return new _Option(void 0,size)}isSome(){return this.value!==void 0}isNone(){return this.value===void 0}equals(other,innerEquals){return this.isSome()&&other.isSome()?innerEquals(this.value,other.value):this.isNone()&&other.isNone()}};var NON_INTERACTIVE_HANDSHAKE=1,UNCONSTRAINED_SECRET=2,INTERACTIVE_HANDSHAKE=3;function resolvedTaggingStrategyToFields(resolved){switch(resolved.type){case"non-interactive-handshake":return[new Fr(NON_INTERACTIVE_HANDSHAKE),Fr.ZERO];case"unconstrained-secret":return[new Fr(UNCONSTRAINED_SECRET),resolved.secret];case"interactive-handshake":return[new Fr(INTERACTIVE_HANDSHAKE),Fr.ZERO]}}__name(resolvedTaggingStrategyToFields,"resolvedTaggingStrategyToFields");function resolvedTaggingStrategyFromFields(kind,secret){switch(kind){case NON_INTERACTIVE_HANDSHAKE:return{type:"non-interactive-handshake"};case INTERACTIVE_HANDSHAKE:return{type:"interactive-handshake"};case UNCONSTRAINED_SECRET:return{type:"unconstrained-secret",secret};default:throw new Error(`Unrecognized resolved tagging strategy kind: ${kind}`)}}__name(resolvedTaggingStrategyFromFields,"resolvedTaggingStrategyFromFields");function fromRawData(nonzeroNoteHashCounter,maybeNoteNonce){if(nonzeroNoteHashCounter)return maybeNoteNonce.equals(Fr.ZERO)?{stage:1,maybeNoteNonce}:{stage:2,maybeNoteNonce};if(maybeNoteNonce.equals(Fr.ZERO))throw new Error("Note has a zero note hash counter and no nonce - existence cannot be proven");return{stage:3,maybeNoteNonce}}__name(fromRawData,"fromRawData");function packAsHintedNote({contractAddress,owner,randomness,storageSlot,noteNonce,isPending,note}){let noteMetadata=fromRawData(isPending,noteNonce);return[...note.items,contractAddress.toField(),owner.toField(),randomness,storageSlot,new Fr(noteMetadata.stage),noteMetadata.maybeNoteNonce]}__name(packAsHintedNote,"packAsHintedNote");function assertReadersConsumed(readers){readers.forEach((reader,slot)=>{if(!reader.isFinished())throw new Error(`Malformed oracle input: ${reader.remainingFields()} unexpected trailing field(s) in slot ${slot}`)})}__name(assertReadersConsumed,"assertReadersConsumed");var FIELD={serialization:{fn:__name(v=>[v],"fn")},deserialization:{fn:__name(([reader])=>reader.readField(),"fn")},shape:["scalar"]},BOOL={serialization:{fn:__name(v=>[new Fr(v?1n:0n)],"fn")},deserialization:{fn:__name(([reader])=>!reader.readField().isZero(),"fn")},shape:["scalar"]},U32={serialization:{fn:__name(v=>[new Fr(v)],"fn")},deserialization:{fn:__name(([reader])=>{let value=reader.readField().toBigInt();if(value>0xffffffffn)throw new Error(`U32 overflow: value ${value} exceeds u32 max (${0xffffffffn})`);return Number(value)},"fn")},shape:["scalar"]},BLOCK_NUMBER={serialization:{fn:__name(v=>[new Fr(v)],"fn")},deserialization:{fn:__name(([reader])=>BlockNumber(reader.readField().toNumber()),"fn")},shape:["scalar"]},BYTE={serialization:{fn:__name(byte=>[new Fr(byte)],"fn")},deserialization:{fn:__name(([reader])=>{let value=reader.readField().toBigInt();if(value>0xffn)throw new Error(`BYTE overflow: value ${value} exceeds u8 max (255)`);return Number(value)},"fn")},shape:["scalar"]},DELIVERY_MODE={deserialization:{fn:__name(readers=>appTaggingSecretKindFromDeliveryMode(BYTE.deserialization.fn(readers)),"fn")},shape:BYTE.shape},RESOLVED_TAGGING_STRATEGY={serialization:{fn:__name(resolved=>resolvedTaggingStrategyToFields(resolved),"fn")},deserialization:{fn:__name(([kindReader,secretReader])=>resolvedTaggingStrategyFromFields(kindReader.readField().toNumber(),secretReader.readField()),"fn")},shape:["scalar","scalar"]},BIGINT={serialization:{fn:__name(v=>[new Fr(v)],"fn")},deserialization:{fn:__name(([reader])=>reader.readField().toBigInt(),"fn")},shape:["scalar"]},STR={serialization:{fn:__name(str=>[Array.from(Buffer.from(str,"utf-8")).map(b=>new Fr(b))],"fn")},deserialization:{fn:__name(([reader])=>{let chars=[];for(;!reader.isFinished();)chars.push(String.fromCharCode(reader.readField().toNumber()));return chars.join("")},"fn")},shape:["variable"]},AZTEC_ADDRESS={serialization:{fn:__name(v=>[v.toField()],"fn")},deserialization:{fn:__name(([reader])=>AztecAddress.fromFieldUnsafe(reader.readField()),"fn")},shape:["scalar"]},BLOCK_HASH={serialization:{fn:__name(v=>[new Fr(v.toBuffer())],"fn")},deserialization:{fn:__name(([reader])=>new BlockHash(reader.readField()),"fn")},shape:["scalar"]},FUNCTION_SELECTOR={serialization:{fn:__name(v=>[v.toField()],"fn")},deserialization:{fn:__name(([reader])=>FunctionSelector.fromField(reader.readField()),"fn")},shape:["scalar"]},NOTE_SELECTOR={serialization:{fn:__name(v=>[v.toField()],"fn")},deserialization:{fn:__name(([reader])=>NoteSelector.fromField(reader.readField()),"fn")},shape:["scalar"]},TX_HASH={serialization:{fn:__name(v=>[v.hash],"fn")},deserialization:{fn:__name(([reader])=>TxHash.fromField(reader.readField()),"fn")},shape:["scalar"]},TAG={serialization:{fn:__name(v=>[v.value],"fn")},deserialization:{fn:__name(([reader])=>new Tag(reader.readField()),"fn")},shape:["scalar"]},POINT=STRUCT([{name:"x",type:FIELD},{name:"y",type:FIELD}]),LOG_SOURCE={serialization:{fn:__name(v=>[new Fr(v)],"fn")},deserialization:{fn:__name(([reader])=>logSourceFromField(reader.readField()),"fn")},shape:["scalar"]},ETH_ADDRESS={serialization:{fn:__name(v=>[v.toField()],"fn")},deserialization:{fn:__name(([reader])=>EthAddress.fromField(reader.readField()),"fn")},shape:["scalar"]},SLOT_NUMBER={serialization:{fn:__name(v=>[new Fr(v)],"fn")},shape:["scalar"]},APPEND_ONLY_TREE_SNAPSHOT=STRUCT([{name:"root",type:FIELD},{name:"nextAvailableLeafIndex",type:U32}]),PARTIAL_STATE_REFERENCE=STRUCT([{name:"noteHashTree",type:APPEND_ONLY_TREE_SNAPSHOT},{name:"nullifierTree",type:APPEND_ONLY_TREE_SNAPSHOT},{name:"publicDataTree",type:APPEND_ONLY_TREE_SNAPSHOT}]),STATE_REFERENCE=STRUCT([{name:"l1ToL2MessageTree",type:APPEND_ONLY_TREE_SNAPSHOT},{name:"partial",type:PARTIAL_STATE_REFERENCE}]),GAS_FEES=STRUCT([{name:"feePerDaGas",type:BIGINT},{name:"feePerL2Gas",type:BIGINT}]),GLOBAL_VARIABLES=STRUCT([{name:"chainId",type:FIELD},{name:"version",type:FIELD},{name:"blockNumber",type:BLOCK_NUMBER},{name:"slotNumber",type:SLOT_NUMBER},{name:"timestamp",type:BIGINT},{name:"coinbase",type:ETH_ADDRESS},{name:"feeRecipient",type:AZTEC_ADDRESS},{name:"gasFees",type:GAS_FEES}]),BLOCK_HEADER=STRUCT([{name:"lastArchive",type:APPEND_ONLY_TREE_SNAPSHOT},{name:"state",type:STATE_REFERENCE},{name:"spongeBlobHash",type:FIELD},{name:"globalVariables",type:GLOBAL_VARIABLES},{name:"totalFees",type:FIELD},{name:"totalManaUsed",type:FIELD}]),KEY_VALIDATION_REQUEST=STRUCT([{name:"pkMHash",type:FIELD},{name:"skApp",type:FIELD}]),PUBLIC_KEYS=STRUCT([{name:"npkMHash",type:FIELD},{name:"ivpkM",type:POINT},{name:"ovpkMHash",type:FIELD},{name:"tpkMHash",type:FIELD},{name:"mspkMHash",type:FIELD},{name:"fbpkMHash",type:FIELD}]),CONTRACT_INSTANCE=STRUCT([{name:"salt",type:FIELD},{name:"deployer",type:AZTEC_ADDRESS},{name:"originalContractClassId",type:FIELD},{name:"initializationHash",type:FIELD},{name:"immutablesHash",type:FIELD},{name:"publicKeys",type:PUBLIC_KEYS}]),NULLIFIER_LEAF=STRUCT([{name:"nullifier",type:FIELD}]),NULLIFIER_LEAF_PREIMAGE=STRUCT([{name:"leaf",type:NULLIFIER_LEAF},{name:"nextKey",type:FIELD},{name:"nextIndex",type:BIGINT}]),NULLIFIER_MEMBERSHIP_WITNESS=STRUCT([{name:"leafPreimage",type:NULLIFIER_LEAF_PREIMAGE},{name:"index",type:BIGINT},{name:"siblingPath",type:SIBLING_PATH(42)}]),PUBLIC_DATA_LEAF=STRUCT([{name:"slot",type:FIELD},{name:"value",type:FIELD}]),PUBLIC_DATA_LEAF_PREIMAGE=STRUCT([{name:"leaf",type:PUBLIC_DATA_LEAF},{name:"nextKey",type:FIELD},{name:"nextIndex",type:BIGINT}]),PUBLIC_DATA_WITNESS=STRUCT([{name:"index",type:BIGINT},{name:"leafPreimage",type:PUBLIC_DATA_LEAF_PREIMAGE},{name:"siblingPath",type:SIBLING_PATH(40)}]),MESSAGE_LOAD_ORACLE_INPUTS=STRUCT([{name:"index",type:BIGINT},{name:"siblingPath",type:SIBLING_PATH(36)}]),UTILITY_CONTEXT=STRUCT([{name:"blockHeader",type:BLOCK_HEADER},{name:"contractAddress",type:AZTEC_ADDRESS},{name:"msgSender",type:AZTEC_ADDRESS}]),CALL_PRIVATE_RESULT=STRUCT([{name:"endSideEffectCounter",type:FIELD},{name:"returnsHash",type:FIELD}]),PUBLIC_KEYS_AND_PARTIAL_ADDRESS=STRUCT([{name:"publicKeys",type:PUBLIC_KEYS},{name:"partialAddress",type:FIELD}]),CONTRACT_CLASS_LOG=STRUCT([{name:"contractAddress",type:AZTEC_ADDRESS},{name:"fields",type:FIXED_ARRAY(FIELD,3023)},{name:"emittedLength",type:U32}]),REVERT_CODE={serialization:{fn:__name(rc=>[rc.toField()],"fn")},shape:["scalar"]},PUBLIC_DATA_WRITE=STRUCT([{name:"leafSlot",type:FIELD},{name:"value",type:FIELD}]),PRIVATE_LOG=STRUCT([{name:"fields",type:FIXED_ARRAY(FIELD,16)},{name:"emittedLength",type:U32}]),FLAT_PUBLIC_LOGS=STRUCT([{name:"length",type:U32},{name:"payload",type:FIXED_ARRAY(FIELD,4096)}]),CONTRACT_CLASS_LOG_ENTRY=STRUCT([{name:"fields",type:FIXED_ARRAY(FIELD,3023)},{name:"emittedLength",type:U32},{name:"contractAddress",type:AZTEC_ADDRESS}]),CONTRACT_CLASS_LOGS=FIXED_ARRAY(CONTRACT_CLASS_LOG_ENTRY,1),TX_EFFECT=STRUCT([{name:"revertCode",type:REVERT_CODE},{name:"txHash",type:TX_HASH},{name:"transactionFee",type:FIELD},{name:"noteHashes",type:FIXED_ARRAY(FIELD,64)},{name:"nullifiers",type:FIXED_ARRAY(FIELD,64)},{name:"l2ToL1Msgs",type:FIXED_ARRAY(FIELD,8)},{name:"publicDataWrites",type:FIXED_ARRAY(PUBLIC_DATA_WRITE,64)},{name:"privateLogs",type:FIXED_ARRAY(PRIVATE_LOG,64)},{name:"publicLogs",type:FLAT_PUBLIC_LOGS},{name:"contractClassLogs",type:CONTRACT_CLASS_LOGS}]),NOTE={serialization:{fn:__name(noteData=>packAsHintedNote({contractAddress:noteData.contractAddress,owner:noteData.owner,randomness:noteData.randomness,storageSlot:noteData.storageSlot,noteNonce:noteData.noteNonce,isPending:noteData.isPending,note:noteData.note}),"fn")},shape:["variable"]},NOTE_VALIDATION_REQUEST={deserialization:{fn:__name(([reader])=>NoteValidationRequest.fromFields(reader),"fn")},shape:["variable"]},EVENT_VALIDATION_REQUEST={deserialization:{fn:__name(([reader])=>EventValidationRequest.fromFields(reader),"fn")},shape:["variable"]},LOG_RETRIEVAL_REQUEST=STRUCT([{name:"contractAddress",type:AZTEC_ADDRESS},{name:"tag",type:TAG},{name:"source",type:LOG_SOURCE},{name:"fromBlock",type:OPTION(BLOCK_NUMBER)},{name:"toBlock",type:OPTION(BLOCK_NUMBER)}]),LOG_RETRIEVAL_RESPONSE=STRUCT([{name:"logPayload",type:FIXED_BOUNDED_VEC(FIELD,15)},{name:"txHash",type:TX_HASH},{name:"uniqueNoteHashesInTx",type:FIXED_BOUNDED_VEC(FIELD,64)},{name:"firstNullifierInTx",type:FIELD},{name:"blockNumber",type:BLOCK_NUMBER},{name:"blockTimestamp",type:BIGINT},{name:"blockHash",type:BLOCK_HASH}]),RESOLVED_TX={serialization:{fn:__name(resolved=>[resolved.toFields()],"fn")},shape:[{len:69}]},PENDING_TAGGED_LOG=STRUCT([{name:"log",type:FIXED_BOUNDED_VEC(FIELD,16)},{name:"context",type:RESOLVED_TX}]),ORIGIN_BLOCK={serialization:{fn:__name(ob=>[new Fr(ob.blockNumber),ob.blockHash],"fn")},deserialization:{fn:__name(([blockNumberReader,blockHashReader])=>({blockNumber:blockNumberReader.readField().toNumber(),blockHash:blockHashReader.readField()}),"fn")},shape:["scalar","scalar"]},RETRACTABLE_FACT_ORIGIN={serialization:{fn:__name(o=>[new Fr(o.blockNumber),o.blockHash,new Fr(o.blockState)],"fn")},shape:["scalar","scalar","scalar"]},FACT={serialization:{fn:__name(f=>[f.factTypeId,f.payload.materializeSlot(v=>FIELD.serialization.fn(v).flat()),...OPTION(RETRACTABLE_FACT_ORIGIN).serialization.fn(f.originBlock)],"fn")},shape:["scalar","scalar","scalar","scalar","scalar","scalar"]},FACT_COLLECTION={serialization:{fn:__name(c2=>[c2.contractAddress.toField(),c2.scope.toField(),c2.factCollectionTypeId,c2.factCollectionId,c2.facts.materializeSlot(v=>FACT.serialization.fn(v).flat())],"fn")},shape:["scalar","scalar","scalar","scalar","scalar"]},PROVIDED_SECRET={deserialization:{fn:__name(([reader])=>({secret:reader.readField(),mode:appTaggingSecretKindFromDeliveryMode(BYTE.deserialization.fn([reader]))}),"fn")},shape:[{len:2}]};function SIBLING_PATH(height){return{serialization:{fn:__name(sp=>[sp.toFields()],"fn")},shape:[{len:height}]}}__name(SIBLING_PATH,"SIBLING_PATH");function MEMBERSHIP_WITNESS(height){return STRUCT([{name:"leafIndex",type:BIGINT},{name:"siblingPath",type:FIXED_ARRAY(FIELD,height)}])}__name(MEMBERSHIP_WITNESS,"MEMBERSHIP_WITNESS");function ARRAY(inner){return{kind:"array",inner,serialization:inner.serialization?{fn:__name(values=>[packElements(inner,values)],"fn")}:void 0,deserialization:inner.deserialization?{fn:__name(([reader])=>unpackElements(inner,reader,reader.remainingFields()/fieldWidth(inner.shape)),"fn")}:void 0,shape:[{lenFrom:__name(size=>size.length*fieldWidth(inner.shape),"lenFrom")}]}}__name(ARRAY,"ARRAY");function FIXED_ARRAY(element,length){let elementWidth=fieldWidth(element.shape);return{kind:"fixed-array",inner:element,length,serialization:element.serialization?{fn:__name(values=>[padArrayEnd(packElements(element,values),Fr.ZERO,length*elementWidth)],"fn")}:void 0,deserialization:element.deserialization?{fn:__name(([reader])=>unpackElements(element,reader,length),"fn")}:void 0,shape:[{len:length*elementWidth}]}}__name(FIXED_ARRAY,"FIXED_ARRAY");function BOUNDED_VEC(inner){return{kind:"bounded-vec",inner,serialization:inner.serialization?{fn:__name(bv=>{if(bv.data.length>bv.maxLength)throw new Error(`Got ${bv.data.length} items, but maxLength is ${bv.maxLength}`);let elementWidth=tryFieldWidth(inner.shape)??bv.elementSize;return[padArrayEnd(packElements(inner,bv.data),Fr.ZERO,bv.maxLength*elementWidth),new Fr(bv.data.length)]},"fn")}:void 0,deserialization:inner.deserialization?{fn:__name(([storageReader,lengthReader])=>{let maxLength=storageReader.remainingFields()/fieldWidth(inner.shape),length=lengthReader.readField().toNumber(),elements=unpackElements(inner,storageReader,length);return storageReader.skip(storageReader.remainingFields()),BoundedVec.from({data:elements,maxLength})},"fn")}:void 0,shape:[{lenFrom:__name(size=>size.maxLength*fieldWidth(inner.shape),"lenFrom")},"scalar"]}}__name(BOUNDED_VEC,"BOUNDED_VEC");function FIXED_BOUNDED_VEC(element,maxLength){let width=fieldWidth(element.shape);return{kind:"fixed-bounded-vec",inner:element,maxLength,serialization:element.serialization?{fn:__name(values=>{if(values.length>maxLength)throw new Error(`Got ${values.length} items, but maxLength is ${maxLength}`);return[[...padArrayEnd(packElements(element,values),Fr.ZERO,maxLength*width),new Fr(values.length)]]},"fn")}:void 0,shape:[{len:maxLength*width+1}]}}__name(FIXED_BOUNDED_VEC,"FIXED_BOUNDED_VEC");function OPTION(inner){return{kind:"option",inner,serialization:inner.serialization?{fn:__name(opt=>opt.isSome()?[Fr.ONE,...inner.serialization.fn(opt.value)]:[Fr.ZERO,...zeroSlotsFromShape(inner.shape,opt.size)],"fn")}:void 0,deserialization:inner.deserialization?{fn:__name(([discriminant,...innerReaders])=>discriminant.readField().isZero()?(innerReaders.forEach(reader=>reader.skip(reader.remainingFields())),Option.none()):Option.some(inner.deserialization.fn(innerReaders)),"fn")}:void 0,shape:["scalar",...inner.shape]}}__name(OPTION,"OPTION");function BUFFER(bitSize,length){return{serialization:{fn:__name(buf=>[Array.from(buf).map(b=>new Fr(b))],"fn")},deserialization:{fn:__name(([reader])=>fromUintArray(reader.readFieldArray(length).map(f=>f.toString()),bitSize),"fn")},shape:[{len:length}]}}__name(BUFFER,"BUFFER");function EPHEMERAL_ARRAY(element){let rowElement=element.deserialization?{deserialization:{fn:__name(([rowReader])=>deserializeElement(element,rowReader.readFieldArray(rowReader.remainingFields())),"fn")},shape:["variable"]}:void 0;return{serialization:element.serialization?{fn:__name(ea=>[ea.materializeSlot(v=>serializeElement(element,v))],"fn")}:void 0,deserialization:rowElement?{fn:__name(([reader])=>EphemeralArray.fromSlot(reader.readField(),rowElement),"fn")}:void 0,shape:["scalar"]}}__name(EPHEMERAL_ARRAY,"EPHEMERAL_ARRAY");function STRUCT(fields){return{kind:"struct",fields,serialization:fields.every(f=>f.type.serialization)?{fn:__name(value=>{let props=value;return fields.flatMap(f=>f.type.serialization.fn(props[f.name]))},"fn")}:void 0,deserialization:fields.every(f=>f.type.deserialization)?{fn:__name(readers=>{let props={},slot=0;for(let f of fields){let slotCount=f.type.shape.length;props[f.name]=f.type.deserialization.fn(readers.slice(slot,slot+slotCount)),slot+=slotCount}return props},"fn")}:void 0,shape:fields.flatMap(f=>f.type.shape)}}__name(STRUCT,"STRUCT");function slotsOf(mapping){return mapping.shape.length}__name(slotsOf,"slotsOf");function tryFieldWidth(shape){let total=0;for(let slot of shape)if(slot==="scalar")total+=1;else if(typeof slot=="object"&&"len"in slot)total+=slot.len;else return;return total}__name(tryFieldWidth,"tryFieldWidth");function fieldWidth(shape){let width=tryFieldWidth(shape);if(width===void 0)throw new Error("Cannot compute a fixed field width for a variable-width shape");return width}__name(fieldWidth,"fieldWidth");function splitByShape(fields,shape){let readers=[],cursor=0;if(shape.forEach((slot,i)=>{if(slot==="scalar"||typeof slot=="object"&&"len"in slot){let width=slot==="scalar"?1:slot.len;if(cursor+width>fields.length)throw new Error(`Not enough fields to reconstruct shape: needed ${width}, had ${fields.length-cursor}`);readers.push(new FieldReader(fields.slice(cursor,cursor+width))),cursor+=width}else{if(i!==shape.length-1)throw new Error("A variable-width slot must be last to be reconstructed from a flat field array");readers.push(new FieldReader(fields.slice(cursor))),cursor=fields.length}}),cursor!==fields.length)throw new Error(`Malformed flattened value: ${fields.length-cursor} unexpected trailing field(s)`);return readers}__name(splitByShape,"splitByShape");function serializeElement(element,value){return element.serialization.fn(value).flat()}__name(serializeElement,"serializeElement");function deserializeElement(element,fields){let readers=splitByShape(fields,element.shape),value=element.deserialization.fn(readers);return assertReadersConsumed(readers),value}__name(deserializeElement,"deserializeElement");function packElements(element,values){return values.flatMap(v=>serializeElement(element,v))}__name(packElements,"packElements");function unpackElements(element,reader,count2){let elementWidth=fieldWidth(element.shape);return Array.from({length:count2},()=>deserializeElement(element,reader.readFieldArray(elementWidth)))}__name(unpackElements,"unpackElements");function zeroSlotsFromShape(shape,size){return shape.map(slot=>{if(slot==="scalar")return Fr.ZERO;if(slot==="variable")throw new Error("Cannot zero-fill an unsized variable-width slot");if("len"in slot)return Array(slot.len).fill(Fr.ZERO);if(size===void 0)throw new Error("Serializing Option.none() over a variable-size inner needs a size, e.g. Option.none({ length: n })");return Array(slot.lenFrom(size)).fill(Fr.ZERO)})}__name(zeroSlotsFromShape,"zeroSlotsFromShape");var LEGACY_LOG_RETRIEVAL_RESPONSE=STRUCT([{name:"logPayload",type:FIXED_BOUNDED_VEC(FIELD,15)},{name:"txHash",type:TX_HASH},{name:"uniqueNoteHashesInTx",type:FIXED_BOUNDED_VEC(FIELD,64)},{name:"firstNullifierInTx",type:FIELD}]),LEGACY_MESSAGE_CONTEXT=STRUCT([{name:"txHash",type:TX_HASH},{name:"uniqueNoteHashesInTx",type:FIXED_BOUNDED_VEC(FIELD,64)},{name:"firstNullifierInTx",type:FIELD}]),LEGACY_PENDING_TAGGED_LOG=STRUCT([{name:"log",type:FIXED_BOUNDED_VEC(FIELD,16)},{name:"context",type:LEGACY_MESSAGE_CONTEXT}]),LEGACY_ORACLE_REGISTRY={aztec_utl_getLogsByTag:{modernOracle:"aztec_utl_getLogsByTagV2",returnType:{legacyType:EPHEMERAL_ARRAY(EPHEMERAL_ARRAY(LEGACY_LOG_RETRIEVAL_RESPONSE)),mapping:__name(result=>result,"mapping")}},aztec_utl_getPendingTaggedLogs:{modernOracle:"aztec_utl_getPendingTaggedLogsV2",returnType:{legacyType:EPHEMERAL_ARRAY(LEGACY_PENDING_TAGGED_LOG),mapping:__name(result=>result,"mapping")}}};var ORACLE_REGISTRY={aztec_misc_assertCompatibleOracleVersion:makeEntry({params:[{name:"major",type:U32},{name:"minor",type:U32}]}),aztec_misc_getRandomField:makeEntry({returnType:FIELD}),aztec_misc_log:makeEntry({params:[{name:"level",type:U32},{name:"message",type:STR},{name:"fieldsSize",type:U32},{name:"fields",type:ARRAY(FIELD)}]}),aztec_utl_getUtilityContext:makeEntry({returnType:UTILITY_CONTEXT}),aztec_utl_getKeyValidationRequest:makeEntry({params:[{name:"pkMHash",type:FIELD},{name:"keyIndex",type:FIELD}],returnType:KEY_VALIDATION_REQUEST}),aztec_utl_getContractInstance:makeEntry({params:[{name:"address",type:AZTEC_ADDRESS}],returnType:CONTRACT_INSTANCE}),aztec_utl_getNoteHashMembershipWitness:makeEntry({params:[{name:"anchorBlockHash",type:BLOCK_HASH},{name:"noteHash",type:FIELD}],returnType:MEMBERSHIP_WITNESS(42)}),aztec_utl_getBlockHashMembershipWitness:makeEntry({params:[{name:"anchorBlockHash",type:BLOCK_HASH},{name:"blockHash",type:BLOCK_HASH}],returnType:OPTION(MEMBERSHIP_WITNESS(30))}),aztec_utl_getNullifierMembershipWitness:makeEntry({params:[{name:"blockHash",type:BLOCK_HASH},{name:"nullifier",type:FIELD}],returnType:NULLIFIER_MEMBERSHIP_WITNESS}),aztec_utl_getLowNullifierMembershipWitness:makeEntry({params:[{name:"blockHash",type:BLOCK_HASH},{name:"nullifier",type:FIELD}],returnType:NULLIFIER_MEMBERSHIP_WITNESS}),aztec_utl_getPublicDataWitness:makeEntry({params:[{name:"blockHash",type:BLOCK_HASH},{name:"leafSlot",type:FIELD}],returnType:PUBLIC_DATA_WITNESS}),aztec_utl_getBlockHeader:makeEntry({params:[{name:"blockNumber",type:BLOCK_NUMBER}],returnType:BLOCK_HEADER}),aztec_utl_getAuthWitness:makeEntry({params:[{name:"messageHash",type:FIELD}],returnType:ARRAY(FIELD)}),aztec_utl_getPublicKeysAndPartialAddress:makeEntry({params:[{name:"address",type:AZTEC_ADDRESS}],returnType:OPTION(PUBLIC_KEYS_AND_PARTIAL_ADDRESS)}),aztec_utl_doesNullifierExist:makeEntry({params:[{name:"innerNullifier",type:FIELD}],returnType:BOOL}),aztec_utl_getL1ToL2MembershipWitness:makeEntry({params:[{name:"contractAddress",type:AZTEC_ADDRESS},{name:"messageHash",type:FIELD},{name:"secret",type:FIELD}],returnType:MESSAGE_LOAD_ORACLE_INPUTS}),aztec_utl_getFromPublicStorage:makeEntry({params:[{name:"blockHash",type:BLOCK_HASH},{name:"contractAddress",type:AZTEC_ADDRESS},{name:"startStorageSlot",type:FIELD},{name:"numberOfElements",type:U32}],returnType:ARRAY(FIELD)}),aztec_utl_getNotes:makeEntry({params:[{name:"owner",type:OPTION(AZTEC_ADDRESS)},{name:"storageSlot",type:FIELD},{name:"numSelects",type:U32},{name:"selectByIndexes",type:ARRAY(U32)},{name:"selectByOffsets",type:ARRAY(U32)},{name:"selectByLengths",type:ARRAY(U32)},{name:"selectValues",type:ARRAY(FIELD)},{name:"selectComparators",type:ARRAY(U32)},{name:"sortByIndexes",type:ARRAY(U32)},{name:"sortByOffsets",type:ARRAY(U32)},{name:"sortByLengths",type:ARRAY(U32)},{name:"sortOrder",type:ARRAY(U32)},{name:"limit",type:U32},{name:"offset",type:U32},{name:"status",type:U32},{name:"maxNotes",type:U32},{name:"packedHintedNoteLength",type:U32}],returnType:BOUNDED_VEC(NOTE)}),aztec_utl_getPendingTaggedLogsV2:makeEntry({params:[{name:"scope",type:AZTEC_ADDRESS},{name:"providedSecrets",type:EPHEMERAL_ARRAY(PROVIDED_SECRET)}],returnType:EPHEMERAL_ARRAY(PENDING_TAGGED_LOG)}),aztec_utl_validateAndStoreEnqueuedNotesAndEvents:makeEntry({params:[{name:"noteValidationRequests",type:EPHEMERAL_ARRAY(NOTE_VALIDATION_REQUEST)},{name:"eventValidationRequests",type:EPHEMERAL_ARRAY(EVENT_VALIDATION_REQUEST)},{name:"scope",type:AZTEC_ADDRESS}]}),aztec_utl_getLogsByTagV2:makeEntry({params:[{name:"requests",type:EPHEMERAL_ARRAY(LOG_RETRIEVAL_REQUEST)}],returnType:EPHEMERAL_ARRAY(EPHEMERAL_ARRAY(LOG_RETRIEVAL_RESPONSE))}),aztec_utl_getResolvedTxs:makeEntry({params:[{name:"requests",type:EPHEMERAL_ARRAY(FIELD)}],returnType:EPHEMERAL_ARRAY(OPTION(RESOLVED_TX))}),aztec_utl_getTxEffect:makeEntry({params:[{name:"txHash",type:TX_HASH}],returnType:OPTION(TX_EFFECT)}),aztec_utl_setCapsule:makeEntry({params:[{name:"contractAddress",type:AZTEC_ADDRESS},{name:"slot",type:FIELD},{name:"capsule",type:ARRAY(FIELD)},{name:"scope",type:AZTEC_ADDRESS}]}),aztec_utl_getCapsule:makeEntry({params:[{name:"contractAddress",type:AZTEC_ADDRESS},{name:"slot",type:FIELD},{name:"tSize",type:U32},{name:"scope",type:AZTEC_ADDRESS}],returnType:OPTION(ARRAY(FIELD))}),aztec_utl_deleteCapsule:makeEntry({params:[{name:"contractAddress",type:AZTEC_ADDRESS},{name:"slot",type:FIELD},{name:"scope",type:AZTEC_ADDRESS}]}),aztec_utl_copyCapsule:makeEntry({params:[{name:"contractAddress",type:AZTEC_ADDRESS},{name:"srcSlot",type:FIELD},{name:"dstSlot",type:FIELD},{name:"numEntries",type:U32},{name:"scope",type:AZTEC_ADDRESS}]}),aztec_utl_decryptAes128:makeEntry({params:[{name:"ciphertext",type:BOUNDED_VEC(BYTE)},{name:"iv",type:BUFFER(8,16)},{name:"symKey",type:BUFFER(8,16)}],returnType:OPTION(BOUNDED_VEC(BYTE))}),aztec_utl_getSharedSecrets:makeEntry({params:[{name:"address",type:AZTEC_ADDRESS},{name:"ephPks",type:EPHEMERAL_ARRAY(POINT)},{name:"contractAddress",type:AZTEC_ADDRESS}],returnType:EPHEMERAL_ARRAY(FIELD)}),aztec_utl_setContractSyncCacheInvalid:makeEntry({params:[{name:"contractAddress",type:AZTEC_ADDRESS},{name:"scopes",type:BOUNDED_VEC(AZTEC_ADDRESS)}]}),aztec_utl_emitOffchainEffect:makeEntry({params:[{name:"data",type:ARRAY(FIELD)}]}),aztec_utl_recordFact:makeEntry({params:[{name:"contractAddress",type:AZTEC_ADDRESS},{name:"scope",type:AZTEC_ADDRESS},{name:"factCollectionTypeId",type:FIELD},{name:"factCollectionId",type:FIELD},{name:"factTypeId",type:FIELD},{name:"payload",type:EPHEMERAL_ARRAY(FIELD)},{name:"originBlock",type:OPTION(ORIGIN_BLOCK)}]}),aztec_utl_deleteFactCollection:makeEntry({params:[{name:"contractAddress",type:AZTEC_ADDRESS},{name:"scope",type:AZTEC_ADDRESS},{name:"factCollectionTypeId",type:FIELD},{name:"factCollectionId",type:FIELD}]}),aztec_utl_getFactCollection:makeEntry({params:[{name:"contractAddress",type:AZTEC_ADDRESS},{name:"scope",type:AZTEC_ADDRESS},{name:"factCollectionTypeId",type:FIELD},{name:"factCollectionId",type:FIELD}],returnType:OPTION(FACT_COLLECTION)}),aztec_utl_getFactCollectionsByType:makeEntry({params:[{name:"contractAddress",type:AZTEC_ADDRESS},{name:"scope",type:AZTEC_ADDRESS},{name:"factCollectionTypeId",type:FIELD}],returnType:EPHEMERAL_ARRAY(FACT_COLLECTION)}),aztec_utl_callUtilityFunction:makeEntry({params:[{name:"contractAddress",type:AZTEC_ADDRESS},{name:"functionSelector",type:FUNCTION_SELECTOR},{name:"args",type:ARRAY(FIELD)}],returnType:ARRAY(FIELD)}),aztec_utl_pushEphemeral:makeEntry({params:[{name:"slot",type:FIELD},{name:"elements",type:ARRAY(FIELD)}],returnType:U32}),aztec_utl_popEphemeral:makeEntry({params:[{name:"slot",type:FIELD}],returnType:ARRAY(FIELD)}),aztec_utl_getEphemeral:makeEntry({params:[{name:"slot",type:FIELD},{name:"index",type:U32}],returnType:ARRAY(FIELD)}),aztec_utl_setEphemeral:makeEntry({params:[{name:"slot",type:FIELD},{name:"index",type:U32},{name:"elements",type:ARRAY(FIELD)}]}),aztec_utl_getEphemeralLen:makeEntry({params:[{name:"slot",type:FIELD}],returnType:U32}),aztec_utl_removeEphemeral:makeEntry({params:[{name:"slot",type:FIELD},{name:"index",type:U32}]}),aztec_utl_clearEphemeral:makeEntry({params:[{name:"slot",type:FIELD}]}),aztec_utl_pushTransient:makeEntry({params:[{name:"slot",type:FIELD},{name:"elements",type:ARRAY(FIELD)}],returnType:U32}),aztec_utl_popTransient:makeEntry({params:[{name:"slot",type:FIELD}],returnType:ARRAY(FIELD)}),aztec_utl_getTransient:makeEntry({params:[{name:"slot",type:FIELD},{name:"index",type:U32}],returnType:ARRAY(FIELD)}),aztec_utl_setTransient:makeEntry({params:[{name:"slot",type:FIELD},{name:"index",type:U32},{name:"elements",type:ARRAY(FIELD)}]}),aztec_utl_getTransientLen:makeEntry({params:[{name:"slot",type:FIELD}],returnType:U32}),aztec_utl_removeTransient:makeEntry({params:[{name:"slot",type:FIELD},{name:"index",type:U32}]}),aztec_utl_clearTransient:makeEntry({params:[{name:"slot",type:FIELD}]}),aztec_prv_setHashPreimage:makeEntry({params:[{name:"values",type:ARRAY(FIELD)},{name:"hash",type:FIELD}]}),aztec_prv_getHashPreimage:makeEntry({params:[{name:"returnsHash",type:FIELD}],returnType:ARRAY(FIELD)}),aztec_prv_notifyCreatedNote:makeEntry({params:[{name:"owner",type:AZTEC_ADDRESS},{name:"storageSlot",type:FIELD},{name:"randomness",type:FIELD},{name:"noteTypeId",type:NOTE_SELECTOR},{name:"note",type:ARRAY(FIELD)},{name:"noteHash",type:FIELD},{name:"counter",type:U32}]}),aztec_prv_notifyNullifiedNote:makeEntry({params:[{name:"innerNullifier",type:FIELD},{name:"noteHash",type:FIELD},{name:"counter",type:U32}]}),aztec_prv_notifyCreatedNullifier:makeEntry({params:[{name:"innerNullifier",type:FIELD}]}),aztec_prv_isNullifierPending:makeEntry({params:[{name:"innerNullifier",type:FIELD},{name:"contractAddress",type:AZTEC_ADDRESS}],returnType:BOOL}),aztec_prv_notifyCreatedContractClassLog:makeEntry({params:[{name:"log",type:CONTRACT_CLASS_LOG},{name:"counter",type:U32}]}),aztec_prv_callPrivateFunction:makeEntry({params:[{name:"contractAddress",type:AZTEC_ADDRESS},{name:"functionSelector",type:FUNCTION_SELECTOR},{name:"argsHash",type:FIELD},{name:"sideEffectCounter",type:U32},{name:"isStaticCall",type:BOOL}],returnType:CALL_PRIVATE_RESULT}),aztec_prv_assertValidPublicCalldata:makeEntry({params:[{name:"calldataHash",type:FIELD}]}),aztec_prv_notifyRevertiblePhaseStart:makeEntry({params:[{name:"minRevertibleSideEffectCounter",type:U32}]}),aztec_prv_isExecutionInRevertiblePhase:makeEntry({params:[{name:"sideEffectCounter",type:U32}],returnType:BOOL}),aztec_prv_getAppTaggingSecret:makeEntry({params:[{name:"sender",type:AZTEC_ADDRESS},{name:"recipient",type:AZTEC_ADDRESS}],returnType:OPTION(FIELD)}),aztec_prv_getNextTaggingIndex:makeEntry({params:[{name:"secret",type:FIELD},{name:"deliveryMode",type:DELIVERY_MODE}],returnType:U32}),aztec_prv_getSenderForTags:makeEntry({returnType:OPTION(AZTEC_ADDRESS)}),aztec_prv_resolveTaggingStrategy:makeEntry({params:[{name:"sender",type:AZTEC_ADDRESS},{name:"recipient",type:AZTEC_ADDRESS},{name:"deliveryMode",type:DELIVERY_MODE}],returnType:RESOLVED_TAGGING_STRATEGY}),aztec_prv_resolveCustomRequest:makeEntry({params:[{name:"kind",type:FIELD},{name:"payload",type:ARRAY(FIELD)}],returnType:ARRAY(FIELD)})};function makeEntry({params,returnType}={}){return{params:params??[],returnType,deserializeParams(inputs){let resolvedParams=params??[],offset=0,named=resolvedParams.map(param=>{if(!param.type.deserialization)throw new Error(`Param '${param.name}' has no deserialization defined`);let slotCount=slotsOf(param.type),readers=inputs.slice(offset,offset+slotCount).map(slot=>new FieldReader(slot.map(hex3=>Fr.fromString(hex3))));offset+=slotCount;let value=param.type.deserialization.fn(readers);return assertReadersConsumed(readers),{name:param.name,value}});if(offset!==inputs.length)throw new Error(`Oracle received ${inputs.length} input slot(s) but the registry specifies ${offset}`);return named},serializeReturn(result){return returnType?.serialization===void 0?[]:returnType.serialization.fn(result).map(slot=>Array.isArray(slot)?slot.map(toACVMField):toACVMField(slot))}}}__name(makeEntry,"makeEntry");var UnavailableOracleError=class extends Error{static{__name(this,"UnavailableOracleError")}constructor(oracleName){super(`${oracleName} oracles not available with the current handler`)}};function buildACIRCallback(handler,registries={}){let{real=ORACLE_REGISTRY,legacy:legacyRegistry=LEGACY_ORACLE_REGISTRY}=registries,target2={};for(let[oracleKey,entry]of Object.entries(real)){let{scope,methodName}=parseOracleName(oracleKey,"Oracle");target2[oracleKey]=async(...inputs)=>{assertHandlerSupportsScope(handler,scope);let positional=entry.deserializeParams(inputs).map(p=>p.value),result=await handler[methodName](...positional);return entry.serializeReturn(result)}}for(let[legacyKey,legacy]of Object.entries(legacyRegistry)){let{scope}=parseOracleName(legacyKey,"Legacy oracle");if(legacyKey in target2)throw new Error(`Legacy oracle "${legacyKey}" collides with a live oracle of the same name in the registry`);let modernEntry=real[legacy.modernOracle],{methodName}=parseOracleName(legacy.modernOracle,"Oracle"),paramOverride=legacy.params,paramSource=paramOverride?makeEntry({params:[...paramOverride.legacyType]}):modernEntry,returnOverride=legacy.returnType,returnSource=returnOverride?makeEntry({returnType:returnOverride.legacyType}):modernEntry;target2[legacyKey]=async(...inputs)=>{assertHandlerSupportsScope(handler,scope);let legacyArgs=paramSource.deserializeParams(inputs).map(p=>p.value),positional=paramOverride?paramOverride.mapping(legacyArgs):legacyArgs,result=await handler[methodName](...positional);return returnSource.serializeReturn(returnOverride?returnOverride.mapping(result):result)}}return new Proxy(target2,makeUnknownOracleTrap(handler))}__name(buildACIRCallback,"buildACIRCallback");function parseOracleName(key,label){let match=key.match(/^aztec_(\w+?)_(.+)$/);if(!match)throw new Error(`${label} "${key}" does not follow the aztec_{scope}_{method} convention`);return{scope:match[1],methodName:match[2]}}__name(parseOracleName,"parseOracleName");function makeUnknownOracleTrap(handler){return{get(obj,prop){return Object.hasOwn(obj,prop)?obj[prop]:()=>{let contractVersion;throw"nonOracleFunctionGetContractOracleVersion"in handler&&(contractVersion=handler.nonOracleFunctionGetContractOracleVersion()),contractVersion?contractVersion.minor>5?new Error(`Oracle '${prop}' not found. This usually means the contract requires a newer private execution environment than you have. Upgrade your private execution environment to a compatible version. The contract was compiled with Aztec.nr oracle version ${contractVersion.major}.${contractVersion.minor}, but this private execution environment only supports up to ${30}.${5}. See https://docs.aztec.network/errors/8`):new Error(`Oracle '${prop}' not found. The contract's oracle version (${contractVersion.major}.${contractVersion.minor}) is compatible with this private execution environment (${30}.${5}), so all standard oracles should be available. This could mean the contract was compiled against a modified version of Aztec.nr, or that it references an oracle that does not exist. See https://docs.aztec.network/errors/8`):new Error(`Oracle '${prop}' not found and the contract's oracle version is unknown (the version check oracle was not called before '${prop}'). This usually means the contract was not compiled with the #[aztec] macro, which injects the version check as the first oracle call in every private/utility external function. If you're using a custom entry point, ensure assert_compatible_oracle_version() is called before any other oracle calls. See https://docs.aztec.network/errors/8`)}}}}__name(makeUnknownOracleTrap,"makeUnknownOracleTrap");function assertHandlerSupportsScope(handler,scope){switch(scope){case"misc":if(!("isMisc"in handler))throw new UnavailableOracleError("Misc");break;case"utl":if(!("isUtility"in handler))throw new UnavailableOracleError("Utility");break;case"prv":if(!("isPrivate"in handler))throw new UnavailableOracleError("Private");break;default:throw new Error(`Unknown oracle scope: ${scope}`)}}__name(assertHandlerSupportsScope,"assertHandlerSupportsScope");async function executePrivateFunction(simulator,privateExecutionOracle,artifact,contractAddress,functionSelector,log2=createLogger("simulator:private_execution")){let functionName=await privateExecutionOracle.getDebugFunctionName();log2.verbose(`Executing private function ${functionName}`,{contract:contractAddress});let initialWitness=privateExecutionOracle.getInitialWitness(artifact),timer=new Timer,acirExecutionResult=await simulator.executeUserCircuit(initialWitness,artifact,buildACIRCallback(privateExecutionOracle)).catch(err=>{throw err.message=resolveAssertionMessageFromError(err,artifact),new ExecutionError(err.message,{contractAddress,functionSelector},extractCallStack(err,artifact.debug),{cause:err})}),duration3=timer.ms(),partialWitness=acirExecutionResult.partialWitness,publicInputs=extractPrivateCircuitPublicInputs(artifact,partialWitness),initialWitnessSize=witnessMapToFields(initialWitness).length*Fr.SIZE_IN_BYTES;log2.debug(`Ran external function ${contractAddress.toString()}:${functionSelector}`,{circuitName:"app-circuit",duration:duration3,eventName:"circuit-witness-generation",inputSize:initialWitnessSize,outputSize:publicInputs.toBuffer().length,appCircuitName:functionName});let contractClassLogs=privateExecutionOracle.getContractClassLogs(),rawReturnValues=await privateExecutionOracle.getHashPreimage(publicInputs.returnsHash),newNotes=privateExecutionOracle.getNewNotes(),noteHashNullifierCounterMap=privateExecutionOracle.getNoteHashNullifierCounterMap(),offchainEffects=privateExecutionOracle.getOffchainEffects(),taggingIndexRanges=privateExecutionOracle.getUsedTaggingIndexRanges(),nestedExecutionResults=privateExecutionOracle.getNestedExecutionResults(),timerSubtractionList=nestedExecutionResults,witgenTime=duration3;for(;timerSubtractionList.length>0;)witgenTime-=timerSubtractionList.reduce((acc,nested)=>acc+(nested.profileResult?.timings.witgen??0),0),timerSubtractionList=timerSubtractionList.flatMap(nested=>nested.nestedExecutionResults??[]);return log2.debug(`Returning from call to ${contractAddress.toString()}:${functionSelector}`),new PrivateCallExecutionResult(artifact.bytecode,Buffer.from(artifact.verificationKey,"base64"),partialWitness,publicInputs,newNotes,noteHashNullifierCounterMap,rawReturnValues,offchainEffects.map(e2=>({data:e2.data})),taggingIndexRanges,nestedExecutionResults,contractClassLogs,{timings:{witgen:witgenTime,oracles:acirExecutionResult.oracles}})}__name(executePrivateFunction,"executePrivateFunction");function extractPrivateCircuitPublicInputs(artifact,partialWitness){let parametersSize=countArgumentsSize(artifact)+37,returnsSize=838,returnData=[];for(let i=parametersSize;i<parametersSize+returnsSize;i++){let returnedField=partialWitness.get(i);if(returnedField===void 0)throw new Error(`Missing return value for index ${i}`);returnData.push(Fr.fromString(returnedField))}return PrivateCircuitPublicInputs.fromFields(returnData)}__name(extractPrivateCircuitPublicInputs,"extractPrivateCircuitPublicInputs");var UNFINALIZED_TAGGING_INDEXES_WINDOW_LEN=84;async function getAllPagesInBatches(tags,fetchAllPagesForBatch){if(tags.length===0)return[];if(tags.length<=100)return fetchAllPagesForBatch(tags);let batches=[];for(let i=0;i<tags.length;i+=100)batches.push(tags.slice(i,i+100));return(await Promise.all(batches.map(fetchAllPagesForBatch))).flat()}__name(getAllPagesInBatches,"getAllPagesInBatches");function getAllPrivateLogsByTags(aztecNode,tags,anchorBlockHash,options={}){return getAllPagesInBatches(tags,batch=>queryAllPrivateLogsByTags(aztecNode,{tags:batch,referenceBlock:anchorBlockHash,fromBlock:options.fromBlock,toBlock:options.toBlock,includeEffects:options.includeEffects??!1,limitPerTag:options.limitPerTag}))}__name(getAllPrivateLogsByTags,"getAllPrivateLogsByTags");function getAllPublicLogsByTagsFromContract(aztecNode,contractAddress,tags,anchorBlockHash,options={}){return getAllPagesInBatches(tags,batch=>queryAllPublicLogsByTags(aztecNode,{contractAddress,tags:batch,referenceBlock:anchorBlockHash,fromBlock:options.fromBlock,toBlock:options.toBlock,includeEffects:options.includeEffects??!1,limitPerTag:options.limitPerTag}))}__name(getAllPublicLogsByTagsFromContract,"getAllPublicLogsByTagsFromContract");function findHighestIndexes(privateLogsWithIndexes,currentTimestamp,finalizedBlockNumber){let highestAgedIndex,highestFinalizedIndex;for(let{log:log2,taggingIndex}of privateLogsWithIndexes)currentTimestamp-log2.blockTimestamp>=BigInt(86400)&&(highestAgedIndex===void 0||taggingIndex>highestAgedIndex)&&(highestAgedIndex=taggingIndex),log2.blockNumber<=finalizedBlockNumber&&(highestFinalizedIndex===void 0||taggingIndex>highestFinalizedIndex)&&(highestFinalizedIndex=taggingIndex);return{highestAgedIndex,highestFinalizedIndex}}__name(findHighestIndexes,"findHighestIndexes");async function syncTaggedPrivateLogs(secrets,aztecNode,taggingStore,anchorBlockHeader,finalizedBlockNumber,jobId){if(secrets.length===0)return[];let anchorBlockNumber=anchorBlockHeader.getBlockNumber(),anchorBlockHash=await anchorBlockHeader.hash(),currentTimestamp=anchorBlockHeader.globalVariables.timestamp,pending=await getIndexRangesForSecrets(secrets,taggingStore,jobId),allLogs=[];for(;pending.length>0;){let logsPerSecret=await fetchLogsForSecrets(pending,aztecNode,anchorBlockNumber,anchorBlockHash);pending=(await Promise.all(pending.map(async(pendingSecret,i)=>{let logsFoundWithSecret=logsPerSecret[i];return logsFoundWithSecret.length===0?void 0:(allLogs.push(...logsFoundWithSecret.map(({log:log2})=>log2)),await(pendingSecret.secret.kind===AppTaggingSecretKind.CONSTRAINED?processConstrainedResults:processUnconstrainedResults)(pendingSecret,logsFoundWithSecret,taggingStore,currentTimestamp,finalizedBlockNumber,jobId))}))).filter(isDefined)}return allLogs}__name(syncTaggedPrivateLogs,"syncTaggedPrivateLogs");function getIndexRangesForSecrets(secrets,taggingStore,jobId){return Promise.all(secrets.map(async secret=>{let currentHighestFinalizedIndex=await taggingStore.getHighestFinalizedIndex(secret,jobId),highestIndexBeforeStart=secret.kind===AppTaggingSecretKind.CONSTRAINED?currentHighestFinalizedIndex:await taggingStore.getHighestAgedIndex(secret,jobId),start=highestIndexBeforeStart===void 0?0:highestIndexBeforeStart+1,end=(currentHighestFinalizedIndex??0)+UNFINALIZED_TAGGING_INDEXES_WINDOW_LEN+1;return{secret,start,end}}))}__name(getIndexRangesForSecrets,"getIndexRangesForSecrets");async function fetchLogsForSecrets(pending,aztecNode,anchorBlockNumber,anchorBlockHash){let indexesPerSecret=pending.map(({start,end})=>Array.from({length:end-start},(_,i)=>start+i)),allTags=(await Promise.all(pending.map(({secret},i)=>Promise.all(indexesPerSecret[i].map(index=>SiloedTag.compute({extendedSecret:secret,index})))))).flat(),allResults=await getAllPrivateLogsByTags(aztecNode,allTags,anchorBlockHash,{includeEffects:!0,toBlock:BlockNumber(anchorBlockNumber+1)}),logsPerSecret=[],offset=0;for(let indexes of indexesPerSecret){let logsForSecret=[];for(let i=0;i<indexes.length;i++)for(let log2 of allResults[offset+i])logsForSecret.push({log:log2,taggingIndex:indexes[i]});logsPerSecret.push(logsForSecret),offset+=indexes.length}return logsPerSecret}__name(fetchLogsForSecrets,"fetchLogsForSecrets");async function processConstrainedResults(pending,logsWithIndexes,taggingStore,currentTimestamp,finalizedBlockNumber,jobId){let indexesWithLogs=new Set(logsWithIndexes.map(l=>l.taggingIndex)),firstMissingIndex=pending.start;for(;firstMissingIndex<pending.end&&indexesWithLogs.has(firstMissingIndex);)firstMissingIndex++;let{highestFinalizedIndex}=findHighestIndexes(logsWithIndexes,currentTimestamp,finalizedBlockNumber);if(highestFinalizedIndex!==void 0&&(await taggingStore.updateHighestFinalizedIndex(pending.secret,highestFinalizedIndex,jobId),firstMissingIndex>=pending.end))return{secret:pending.secret,start:pending.end,end:highestFinalizedIndex+UNFINALIZED_TAGGING_INDEXES_WINDOW_LEN+1}}__name(processConstrainedResults,"processConstrainedResults");async function processUnconstrainedResults(pending,logsWithIndexes,taggingStore,currentTimestamp,finalizedBlockNumber,jobId){let{highestAgedIndex,highestFinalizedIndex}=findHighestIndexes(logsWithIndexes,currentTimestamp,finalizedBlockNumber);if(highestAgedIndex!==void 0&&await taggingStore.updateHighestAgedIndex(pending.secret,highestAgedIndex,jobId),highestFinalizedIndex!==void 0){if(highestAgedIndex!==void 0&&highestAgedIndex>highestFinalizedIndex)throw new Error(`Highest aged index (${highestAgedIndex}) must not exceed highest finalized index (${highestFinalizedIndex})`);return await taggingStore.updateHighestFinalizedIndex(pending.secret,highestFinalizedIndex,jobId),{secret:pending.secret,start:pending.end,end:highestFinalizedIndex+UNFINALIZED_TAGGING_INDEXES_WINDOW_LEN+1}}}__name(processUnconstrainedResults,"processUnconstrainedResults");var EMPTY_STATUS_CHANGE={txHashesToFinalize:[],txHashesToDrop:[],txHashesWithExecutionReverted:[]};function mergeStatusChanges(a,b){return{txHashesToFinalize:[...a.txHashesToFinalize,...b.txHashesToFinalize],txHashesToDrop:[...a.txHashesToDrop,...b.txHashesToDrop],txHashesWithExecutionReverted:[...a.txHashesWithExecutionReverted,...b.txHashesWithExecutionReverted]}}__name(mergeStatusChanges,"mergeStatusChanges");async function getStatusChangeOfPending(pending,aztecNode){let receipts=await Promise.all(pending.map(pendingTxHash=>aztecNode.getTxReceipt(pendingTxHash))),txHashesToFinalize=[],txHashesToDrop=[],txHashesWithExecutionReverted=[];for(let i=0;i<receipts.length;i++){let receipt=receipts[i],txHash=pending[i];if(receipt.status===TxStatus.FINALIZED)if(receipt.hasExecutionSucceeded())txHashesToFinalize.push(txHash);else if(receipt.hasExecutionReverted())txHashesWithExecutionReverted.push(txHash);else throw new Error("Both hasExecutionSucceeded and hasExecutionReverted on the receipt returned false. This should never happen and it implies a bug. Please open an issue.");else receipt.isDropped()&&txHashesToDrop.push(txHash)}return{txHashesToFinalize,txHashesToDrop,txHashesWithExecutionReverted}}__name(getStatusChangeOfPending,"getStatusChangeOfPending");async function loadAndStoreNewTaggingIndexes(extendedSecret,start,end,aztecNode,taggingStore,anchorBlockHash,jobId){let siloedTagsForWindow=await Promise.all(Array.from({length:end-start},(_,i)=>SiloedTag.compute({extendedSecret,index:start+i}))),txsForTags=await getTxsContainingTags(siloedTagsForWindow,aztecNode,anchorBlockHash),txIndexesMap=getTxIndexesMap(txsForTags,start,siloedTagsForWindow.length);for(let[txHashStr,indexes]of txIndexesMap.entries()){let txHash=TxHash.fromString(txHashStr),ranges=[{extendedSecret,lowestIndex:Math.min(...indexes),highestIndex:Math.max(...indexes)}];await taggingStore.storePendingIndexes(ranges,txHash,jobId)}}__name(loadAndStoreNewTaggingIndexes,"loadAndStoreNewTaggingIndexes");async function getTxsContainingTags(tags,aztecNode,anchorBlockHash){return(await getAllPrivateLogsByTags(aztecNode,tags,anchorBlockHash)).map(logs=>logs.map(log2=>log2.txHash))}__name(getTxsContainingTags,"getTxsContainingTags");function getTxIndexesMap(txHashesForTags,start,count2){if(txHashesForTags.length!==count2)throw new Error(`Number of tx hashes arrays does not match number of tags. ${txHashesForTags.length} !== ${count2}`);let indexesMap=new Map;for(let i=0;i<txHashesForTags.length;i++){let taggingIndex=start+i,txHashesForTag=txHashesForTags[i];for(let txHash of txHashesForTag){let key=txHash.toString(),existing=indexesMap.get(key);existing?existing.push(taggingIndex):indexesMap.set(key,[taggingIndex])}}return indexesMap}__name(getTxIndexesMap,"getTxIndexesMap");async function syncSenderTaggingIndexes(secret,aztecNode,taggingStore,anchorBlockHash,jobId){let finalizedIndex=await taggingStore.getLastFinalizedIndex(secret,jobId),start=finalizedIndex===void 0?0:finalizedIndex+1,end=start+UNFINALIZED_TAGGING_INDEXES_WINDOW_LEN,previousFinalizedIndex=finalizedIndex,newFinalizedIndex;for(;;){let knownPendingTxHashes=await taggingStore.getTxHashesOfPendingIndexes(secret,start,end,jobId),[,statusOfKnown]=await Promise.all([loadAndStoreNewTaggingIndexes(secret,start,end,aztecNode,taggingStore,anchorBlockHash,jobId),knownPendingTxHashes.length>0?getStatusChangeOfPending(knownPendingTxHashes,aztecNode):Promise.resolve(EMPTY_STATUS_CHANGE)]),allPendingTxHashes=await taggingStore.getTxHashesOfPendingIndexes(secret,start,end,jobId);if(allPendingTxHashes.length===0)break;let knownSet=new Set(knownPendingTxHashes.map(h=>h.toString())),newPendingTxHashes=allPendingTxHashes.filter(h=>!knownSet.has(h.toString())),statusOfNew=newPendingTxHashes.length>0?await getStatusChangeOfPending(newPendingTxHashes,aztecNode):EMPTY_STATUS_CHANGE,{txHashesToFinalize,txHashesToDrop,txHashesWithExecutionReverted}=mergeStatusChanges(statusOfKnown,statusOfNew);if(await taggingStore.dropPendingIndexes(txHashesToDrop,jobId),await taggingStore.finalizePendingIndexes(txHashesToFinalize,jobId),txHashesWithExecutionReverted.length>0){let receipts=await Promise.all(txHashesWithExecutionReverted.map(txHash=>aztecNode.getTxReceipt(txHash,{includeTxEffect:!0})));for(let receipt of receipts){if(!receipt.isMined()||!receipt.txEffect)throw new Error("TxEffect not found for execution-reverted tx. This is either a bug or a reorg has occurred.");await taggingStore.finalizePendingIndexesOfAPartiallyRevertedTx(receipt.txEffect,jobId)}}if(newFinalizedIndex=await taggingStore.getLastFinalizedIndex(secret,jobId),previousFinalizedIndex!==newFinalizedIndex){let previousEnd=end;end=newFinalizedIndex+UNFINALIZED_TAGGING_INDEXES_WINDOW_LEN+1,start=previousEnd,previousFinalizedIndex=newFinalizedIndex}else break}}__name(syncSenderTaggingIndexes,"syncSenderTaggingIndexes");var selectPropertyFromPackedNoteContent=__name((noteData,selector)=>{if(selector.index>=noteData.length)throw new Error(`Property selector index ${selector.index} out of bounds for note with ${noteData.length} fields`);if(selector.offset+selector.length>Fr.SIZE_IN_BYTES)throw new Error(`Property selector range (offset=${selector.offset}, length=${selector.length}) exceeds Fr buffer size of ${Fr.SIZE_IN_BYTES} bytes`);let noteValueBuffer=noteData[selector.index].toBuffer(),start=Fr.SIZE_IN_BYTES-selector.offset-selector.length,end=Fr.SIZE_IN_BYTES-selector.offset,noteValue=noteValueBuffer.subarray(start,end),padded=Buffer.alloc(Fr.SIZE_IN_BYTES);return noteValue.copy(padded,Fr.SIZE_IN_BYTES-noteValue.length),Fr.fromBuffer(padded)},"selectPropertyFromPackedNoteContent"),selectNotes=__name((noteDatas,selects)=>noteDatas.filter(noteData=>selects.every(({selector,value,comparator})=>{let noteValueFr=selectPropertyFromPackedNoteContent(noteData.note.items,selector),fn={[Comparator.EQ]:()=>noteValueFr.equals(value),[Comparator.NEQ]:()=>!noteValueFr.equals(value),[Comparator.LT]:()=>noteValueFr.lt(value),[Comparator.LTE]:()=>noteValueFr.lt(value)||noteValueFr.equals(value),[Comparator.GT]:()=>!noteValueFr.lt(value)&&!noteValueFr.equals(value),[Comparator.GTE]:()=>!noteValueFr.lt(value)}[comparator];if(!fn)throw new Error(`Invalid comparator value: ${comparator}`);return fn()})),"selectNotes"),sortNotes=__name((a,b,sorts,level=0)=>{if(sorts[level]===void 0)return 0;let{selector,order}=sorts[level];if(order===0)return 0;let aValue=selectPropertyFromPackedNoteContent(a,selector),bValue=selectPropertyFromPackedNoteContent(b,selector),dir=order===1?[-1,1]:[1,-1];return aValue.toBigInt()===bValue.toBigInt()?sortNotes(a,b,sorts,level+1):aValue.toBigInt()>bValue.toBigInt()?dir[0]:dir[1]},"sortNotes");function pickNotes(noteDatas,{selects=[],sorts=[],limit=0,offset=0}){return selectNotes(noteDatas,selects).sort((a,b)=>sortNotes(a.note.items,b.note.items,sorts)).slice(offset,limit?offset+limit:void 0)}__name(pickNotes,"pickNotes");import{BarretenbergSync as BarretenbergSync7}from"@aztec/bb.js";import{Buffer as Buffer3}from"buffer";var Aes128=class{static{__name(this,"Aes128")}async encryptBufferCBC(data,iv,key){let numPaddingBytes=16-data.length%16,paddingBuffer=Buffer3.alloc(numPaddingBytes);paddingBuffer.fill(numPaddingBytes);let input=Buffer3.concat([data,paddingBuffer]);await BarretenbergSync7.initSingleton();let response=BarretenbergSync7.getSingleton().aesEncrypt({plaintext:input,iv,key,length:input.length});return Buffer3.from(response.ciphertext)}async decryptBufferCBCKeepPadding(data,iv,key){await BarretenbergSync7.initSingleton();let response=BarretenbergSync7.getSingleton().aesDecrypt({ciphertext:data,iv,key,length:data.length});return Buffer3.from(response.plaintext)}async decryptBufferCBC(data,iv,key){let paddedBuffer=await this.decryptBufferCBCKeepPadding(data,iv,key),paddingLen=paddedBuffer[paddedBuffer.length-1];if(paddingLen===0||paddingLen>16)throw new Error(`Invalid PKCS#7 padding length: ${paddingLen}`);for(let i=paddedBuffer.length-paddingLen;i<paddedBuffer.length;i++)if(paddedBuffer[i]!==paddingLen)throw new Error("Invalid PKCS#7 padding");return paddedBuffer.subarray(0,paddedBuffer.length-paddingLen)}};var StandardContractSalt={AuthRegistry:new Fr(1),MultiCallEntrypoint:new Fr(1),PublicChecks:new Fr(1),HandshakeRegistry:new Fr(1)},StandardContractAddress={AuthRegistry:AztecAddress.fromStringUnsafe("0x0292b01f4e566555534c40ed729eb023cc08afaca647b8c3642738449673480c"),MultiCallEntrypoint:AztecAddress.fromStringUnsafe("0x18470168ca7a775b442cde110b668732f7b6390a505f3784b50f39993c5f3dce"),PublicChecks:AztecAddress.fromStringUnsafe("0x2d7745526508f5ceb278bb773a49f776842d1d2f0854c4a385bb661a2fabb9a8"),HandshakeRegistry:AztecAddress.fromStringUnsafe("0x0bd62e76a9a3a103dae2e73040e05d3970ac900baff5637ae9f183396745ec7e")},StandardContractClassId={AuthRegistry:Fr.fromString("0x1f8810cff8690ef53281da87fcda9d4820154d6dcd76012c90bf459b3ba3ab7a"),MultiCallEntrypoint:Fr.fromString("0x282930170063677f616bcf9dc9fbfd4968a577dbbcdec0ea3c06283a44bcc743"),PublicChecks:Fr.fromString("0x2a0f1592c7f4c979b328ed030039a4e9a469aab30afa3a036735c338067abbcd"),HandshakeRegistry:Fr.fromString("0x10fbd0602fe72a04c86e25728c8c2b94a359c684738768cbe4e44fb05f6a908c")},StandardContractClassIdPreimage={AuthRegistry:{artifactHash:Fr.fromString("0x1bfa3469d2f70892f9ba54117abcf4ca52bb758e66be19b5d0ab86600202ab73"),privateFunctionsRoot:Fr.fromString("0x17b584350f4c3ccafd8f688729afb9feab8976114fb40012e9dee65022c072a4"),publicBytecodeCommitment:Fr.fromString("0x2545f39893766508ce37bb5cea5e4dcab04c6f7f79f3089b1c076876e9d268b2")},MultiCallEntrypoint:{artifactHash:Fr.fromString("0x05d7e89374f90684063f132a79de9b0f9553508de9ec1b83b8f6110d6ebbc21f"),privateFunctionsRoot:Fr.fromString("0x0e68dfbb256e80b08b3aef47aca1f2669e97a9c6259787893c1223ac083ad5d5"),publicBytecodeCommitment:Fr.fromString("0x0ce4c618c3ed7f3a20410e618c06bb701e150af7fe28a3e92f68e7733809f33e")},PublicChecks:{artifactHash:Fr.fromString("0x0636977743e164f84fbd38ca408ad33794768c994f28dd8609729a8406d352dc"),privateFunctionsRoot:Fr.fromString("0x202860adb1b8975971eeaf571aaaa88a27f4035290d58532ae7d60b0dfaad54c"),publicBytecodeCommitment:Fr.fromString("0x013c4f854a5c87c9daf86c5f9bc07a42c2a061f1d924a5b3564ec7edc8e18cb7")},HandshakeRegistry:{artifactHash:Fr.fromString("0x2fc28e54f5f227307378f4620d793db72a4e1a7937e8cb31396b61a48ea7abef"),privateFunctionsRoot:Fr.fromString("0x14f4bfbedd0d76e9b66d1f836a71457cb0f5b4f40280eec4a3ed40439440e252"),publicBytecodeCommitment:Fr.fromString("0x0ce4c618c3ed7f3a20410e618c06bb701e150af7fe28a3e92f68e7733809f33e")}},StandardContractInitializationHash={AuthRegistry:Fr.fromString("0x0000000000000000000000000000000000000000000000000000000000000000"),MultiCallEntrypoint:Fr.fromString("0x0000000000000000000000000000000000000000000000000000000000000000"),PublicChecks:Fr.fromString("0x0000000000000000000000000000000000000000000000000000000000000000"),HandshakeRegistry:Fr.fromString("0x0000000000000000000000000000000000000000000000000000000000000000")},StandardContractPrivateFunctions={AuthRegistry:[{selector:FunctionSelector.fromField(Fr.fromString("0x0000000000000000000000000000000000000000000000000000000079a3d418")),vkHash:Fr.fromString("0x06a5c1b3a636c954a90be43cb56a4bdd9dc8aec764151a012e0018753694ff54")}],MultiCallEntrypoint:[{selector:FunctionSelector.fromField(Fr.fromString("0x00000000000000000000000000000000000000000000000000000000f04908a9")),vkHash:Fr.fromString("0x0b19b2f937f2581922c2ead5411ad9ff4ed9710efe9849bde494d9a0f94812ec")}],PublicChecks:[],HandshakeRegistry:[{selector:FunctionSelector.fromField(Fr.fromString("0x0000000000000000000000000000000000000000000000000000000019f8b409")),vkHash:Fr.fromString("0x0b9ec5c76f08f8025800691659d7ba1432ddb8a30e40fdbd4d8f5c398b8c9ab7")},{selector:FunctionSelector.fromField(Fr.fromString("0x00000000000000000000000000000000000000000000000000000000db548fcf")),vkHash:Fr.fromString("0x1c0f79ad358fc72c0f8cbac535d2d67f49dcea2f7d6c658eb38c7669f8ae2f93")},{selector:FunctionSelector.fromField(Fr.fromString("0x00000000000000000000000000000000000000000000000000000000f1ff839b")),vkHash:Fr.fromString("0x2c2961a5e83daa909242c9ce441526c0a95379fda0976877acba4ffe7be949f3")}]};var STANDARD_HANDSHAKE_REGISTRY_ADDRESS=StandardContractAddress.HandshakeRegistry,STANDARD_HANDSHAKE_REGISTRY_CLASS_ID=StandardContractClassId.HandshakeRegistry,STANDARD_HANDSHAKE_REGISTRY_SALT=StandardContractSalt.HandshakeRegistry;async function createContractLogger(contractAddress,getContractName,kind,options){let addrAbbrev=contractAddress.toString().slice(0,10),name=await getContractName(contractAddress),prefix=kind=="aztecnr"?"aztecnr":"contract",module=name?`${prefix}:${name}(${addrAbbrev})`:`${prefix}:Unknown(${addrAbbrev})`;return createLogger(module,options)}__name(createContractLogger,"createContractLogger");function logContractMessage(logger3,level,message,fields){logger3[level](applyStringFormatting(message,fields))}__name(logContractMessage,"logContractMessage");function stripAztecnrLogPrefix(message){return message.startsWith("[aztec-nr] ")?{kind:"aztecnr",message:message.slice(11)}:{kind:"user",message}}__name(stripAztecnrLogPrefix,"stripAztecnrLogPrefix");var EventService=class{static{__name(this,"EventService")}anchorBlockHeader;aztecNode;privateEventStore;jobId;log;constructor(anchorBlockHeader,aztecNode,privateEventStore,jobId,log2=createLogger("pxe:event_service")){this.anchorBlockHeader=anchorBlockHeader,this.aztecNode=aztecNode,this.privateEventStore=privateEventStore,this.jobId=jobId,this.log=log2}async validateAndStoreEvents(requests,scope,txEffects){if(requests.length===0)return;let anchorBlockNumber=this.anchorBlockHeader.getBlockNumber();await Promise.all(requests.map(req=>this.#validateAndStoreEvent(req,scope,txEffects,anchorBlockNumber)))}async#validateAndStoreEvent(request,scope,txEffects,anchorBlockNumber){let{contractAddress,eventTypeId:selector,randomness,serializedEvent:content,eventCommitment,txHash}=request,recomputedCommitment=await computePrivateEventCommitment(randomness,selector.toField(),content);if(!recomputedCommitment.equals(eventCommitment)){this.log.warn(`Skipping event whose content does not hash to the provided commitment. contract=${contractAddress}, selector=${selector}, eventCommitment=${eventCommitment}, txHash=${txHash}, recomputedCommitment=${recomputedCommitment}`);return}let siloedEventCommitment=await siloNullifier(contractAddress,eventCommitment),txEffect=txEffects.get(txHash.toString());if(!txEffect)throw new Error(`Could not find tx effect for tx hash ${txHash} when processing an event.`);if(txEffect.l2BlockNumber>anchorBlockNumber)throw new Error(`Obtained a newer tx effect for ${txHash} for an event validation request than the anchor block ${anchorBlockNumber}. This is a bug as smart contracts should not issue event validation requests for events from blocks newer than the anchor block.`);let eventIndexInTx=txEffect.data.nullifiers.findIndex(n=>n.equals(siloedEventCommitment));if(eventIndexInTx===-1){this.log.warn(`Skipping event whose commitment is not present in its tx. siloedEventCommitment=${siloedEventCommitment}, contract=${contractAddress}, selector=${selector}, eventCommitment=${eventCommitment}, txHash=${txHash}`);return}return this.privateEventStore.storePrivateEventLog(selector,randomness,content,siloedEventCommitment,{contractAddress,scope,txHash,l2BlockNumber:txEffect.l2BlockNumber,l2BlockHash:txEffect.l2BlockHash,txIndexInBlock:txEffect.txIndexInBlock,eventIndexInTx},this.jobId)}};var ResolvedTx=class _ResolvedTx{static{__name(this,"ResolvedTx")}txHash;uniqueNoteHashesInTx;firstNullifierInTx;blockNumber;blockHash;constructor(txHash,uniqueNoteHashesInTx,firstNullifierInTx,blockNumber,blockHash){this.txHash=txHash,this.uniqueNoteHashesInTx=uniqueNoteHashesInTx,this.firstNullifierInTx=firstNullifierInTx,this.blockNumber=blockNumber,this.blockHash=blockHash}toFields(){return[this.txHash.hash,...serializeBoundedVec(this.uniqueNoteHashesInTx,64),this.firstNullifierInTx,new Fr(this.blockNumber),this.blockHash]}static empty(){return new _ResolvedTx(TxHash.zero(),[],Fr.ZERO,0,Fr.ZERO)}};function serializeBoundedVec(values,maxLength){return[...padArrayEnd(values,Fr.ZERO,maxLength,`Attempted to serialize ${values} values into a BoundedVec with max length ${maxLength}`),new Fr(values.length)]}__name(serializeBoundedVec,"serializeBoundedVec");var rangeKey=__name((fromBlock,toBlock)=>`${fromBlock??""}-${toBlock??""}`,"rangeKey"),LogService=class _LogService{static{__name(this,"LogService")}aztecNode;anchorBlockHeader;l2TipsStore;keyStore;recipientTaggingStore;taggingSecretSourcesStore;addressStore;jobId;log;constructor(aztecNode,anchorBlockHeader,l2TipsStore,keyStore,recipientTaggingStore,taggingSecretSourcesStore,addressStore,jobId,bindings){this.aztecNode=aztecNode,this.anchorBlockHeader=anchorBlockHeader,this.l2TipsStore=l2TipsStore,this.keyStore=keyStore,this.recipientTaggingStore=recipientTaggingStore,this.taggingSecretSourcesStore=taggingSecretSourcesStore,this.addressStore=addressStore,this.jobId=jobId,this.log=createLogger("pxe:log_service",bindings)}async fetchLogsByTag(contractAddress,logRetrievalRequests){for(let request of logRetrievalRequests)if(!contractAddress.equals(request.contractAddress))throw new Error(`Got a log retrieval request from ${request.contractAddress}, expected ${contractAddress}`);if(logRetrievalRequests.length===0)return[];let anchorBlockHash=await this.anchorBlockHeader.hash(),[publicLogsPerRequest,privateLogsPerRequest]=await Promise.all([this.#fetchPublicLogs(contractAddress,logRetrievalRequests,anchorBlockHash),this.#fetchPrivateLogs(logRetrievalRequests,anchorBlockHash)]);return logRetrievalRequests.map((_request,i)=>[...publicLogsPerRequest[i].map(_LogService.#toLogRetrievalResponse),...privateLogsPerRequest[i].map(_LogService.#toLogRetrievalResponse)])}async#fetchPublicLogs(contractAddress,requests,anchorBlockHash){let indices=requests.flatMap((r2,i)=>r2.source!==LogSource.PRIVATE?[i]:[]);if(indices.length===0)return requests.map(()=>[]);let resultsPerRequest=requests.map(()=>[]),groups=_LogService.#groupByRange(indices.map(i=>({index:i,request:requests[i]})));return await Promise.all(Array.from(groups.values()).map(async group=>{let tags=group.entries.map(e2=>e2.request.tag),results=await getAllPublicLogsByTagsFromContract(this.aztecNode,contractAddress,tags,anchorBlockHash,{fromBlock:group.fromBlock,toBlock:group.toBlock,includeEffects:!0});group.entries.forEach((entry,i)=>{resultsPerRequest[entry.index]=results[i]})})),resultsPerRequest}async#fetchPrivateLogs(requests,anchorBlockHash){let indices=requests.flatMap((r2,i)=>r2.source!==LogSource.PUBLIC?[i]:[]);if(indices.length===0)return requests.map(()=>[]);let resultsPerRequest=requests.map(()=>[]),groups=_LogService.#groupByRange(indices.map(i=>({index:i,request:requests[i]})));return await Promise.all(Array.from(groups.values()).map(async group=>{let siloedTags=await Promise.all(group.entries.map(e2=>SiloedTag.computeFromTagAndApp(e2.request.tag,e2.request.contractAddress))),results=await getAllPrivateLogsByTags(this.aztecNode,siloedTags,anchorBlockHash,{fromBlock:group.fromBlock,toBlock:group.toBlock,includeEffects:!0});group.entries.forEach((entry,i)=>{resultsPerRequest[entry.index]=results[i]})})),resultsPerRequest}static#groupByRange(entries){let groups=new Map;for(let entry of entries){let fromBlock=entry.request.fromBlock.value,toBlock=entry.request.toBlock.value,key=rangeKey(fromBlock,toBlock),existing=groups.get(key);existing?existing.entries.push(entry):groups.set(key,{fromBlock,toBlock,entries:[entry]})}return groups}static#toLogRetrievalResponse(log2){let noteHashes=log2.noteHashes,nullifiers=log2.nullifiers;if(nullifiers.length===0)throw new Error(`Log for tx ${log2.txHash} returned no nullifiers from the node`);return{logPayload:log2.logData.slice(1,16),txHash:log2.txHash,uniqueNoteHashesInTx:noteHashes,firstNullifierInTx:nullifiers[0],blockNumber:log2.blockNumber,blockTimestamp:log2.blockTimestamp,blockHash:log2.blockHash}}async fetchTaggedLogs(contractAddress,recipient,providedSecrets){this.log.verbose(`Fetching tagged logs for contract ${contractAddress.toString()} and recipient ${recipient.toString()}`);let l2Tips=await this.l2TipsStore.getL2Tips(),combinedSecrets=[...await this.#getPointDerivedSecrets(contractAddress,recipient),...providedSecrets],secrets=Array.from(new Map(combinedSecrets.map(secret=>[secret.toString(),secret])).values());return(await syncTaggedPrivateLogs(secrets,this.aztecNode,this.recipientTaggingStore,this.anchorBlockHeader,l2Tips.finalized.block.number,this.jobId)).map(log2=>{let noteHashes=log2.noteHashes,nullifiers=log2.nullifiers;if(nullifiers.length===0)throw new Error(`Log for tx ${log2.txHash} returned no nullifiers from the node`);return{log:log2.logData,context:new ResolvedTx(log2.txHash,noteHashes,nullifiers[0],log2.blockNumber,log2.blockHash.toFr())}})}async#getPointDerivedSecrets(contractAddress,recipient){let recipientCompleteAddress=await this.addressStore.getCompleteAddress(recipient);if(!recipientCompleteAddress||!await this.keyStore.hasAccount(recipient))return this.log.warn(`Skipping sender-derived tag retrieval for ${recipient.toString()} due to unknown address preimage`),[];let recipientIvsk=await this.keyStore.getMasterIncomingViewingSecretKey(recipient),[senderPoints,registeredSecrets]=await Promise.all([this.#getSecretsForSenders(recipientCompleteAddress,recipientIvsk),this.taggingSecretSourcesStore.getSharedSecretsForRecipient(recipient)]);return Promise.all([...senderPoints.map(secret=>AppTaggingSecret.computeDirectional(secret,contractAddress,recipient)),...registeredSecrets.flatMap(({kind,secret})=>{switch(kind){case"arbitrary-secret":return[AppTaggingSecret.computeDirectional(secret,contractAddress,recipient)];case"handshake":return[AppTaggingSecret.computeAppSiloed(secret,contractAddress,AppTaggingSecretKind.UNCONSTRAINED),AppTaggingSecret.computeAppSiloed(secret,contractAddress,AppTaggingSecretKind.CONSTRAINED)]}})])}async#getSecretsForSenders(recipientCompleteAddress,recipientIvsk){let allSenders=[...await this.taggingSecretSourcesStore.getSenders(),...await this.keyStore.getAccounts()];return Promise.all(allSenders.map(async sender=>{let taggingSecretPoint=await computeSharedTaggingSecret(recipientCompleteAddress,recipientIvsk,sender);if(!taggingSecretPoint)throw new Error(`Failed to compute a tagging secret for sender ${sender} - this implies this is an invalid address, which should not happen as they have been previously registered in PXE.`);return taggingSecretPoint}))}};var EphemeralArrayService=class{static{__name(this,"EphemeralArrayService")}#arrays=new Map;readArrayAt(slot){return this.#arrays.get(slot.toString())??[]}#setArray(slot,array2){this.#arrays.set(slot.toString(),array2)}len(slot){return this.readArrayAt(slot).length}push(slot,elements){let array2=this.readArrayAt(slot);return array2.push(elements),this.#setArray(slot,array2),array2.length}pop(slot){let array2=this.readArrayAt(slot);if(array2.length===0)throw new Error(`Ephemeral array at slot ${slot} is empty`);let element=array2.pop();return this.#setArray(slot,array2),element}get(slot,index){let array2=this.readArrayAt(slot);if(index<0||index>=array2.length)throw new Error(`Ephemeral array index ${index} out of bounds for array of length ${array2.length} at slot ${slot}`);return array2[index]}set(slot,index,value){let array2=this.readArrayAt(slot);if(index<0||index>=array2.length)throw new Error(`Ephemeral array index ${index} out of bounds for array of length ${array2.length} at slot ${slot}`);array2[index]=value}remove(slot,index){let array2=this.readArrayAt(slot);if(index<0||index>=array2.length)throw new Error(`Ephemeral array index ${index} out of bounds for array of length ${array2.length} at slot ${slot}`);array2.splice(index,1)}clear(slot){this.#arrays.delete(slot.toString())}allocateSlot(){let slot;do slot=Fr.random();while(this.#arrays.has(slot.toString()));return slot}newArray(elements){let slot=this.allocateSlot();return this.#setArray(slot,elements),slot}copy(srcSlot,dstSlot,count2){let srcArray=this.readArrayAt(srcSlot);if(count2>srcArray.length)throw new Error(`Cannot copy ${count2} elements from ephemeral array of length ${srcArray.length} at slot ${srcSlot}`);let copied=srcArray.slice(0,count2).map(el=>[...el]);this.#setArray(dstSlot,copied)}};function toNoirFactCollection(service,contractAddress,scope,factCollectionTypeId,factCollectionId,facts){return{contractAddress,scope,factCollectionTypeId,factCollectionId,facts:EphemeralArray.fromValues(service,facts.map(fact=>({factTypeId:fact.factTypeId,payload:EphemeralArray.fromValues(service,fact.payload),originBlock:fact.originBlock?Option.some(fact.originBlock):Option.none({blockNumber:0,blockHash:Fr.ZERO,blockState:OriginBlockState.Pending})})))}}__name(toNoirFactCollection,"toNoirFactCollection");function emptyFactCollection(service){return toNoirFactCollection(service,AztecAddress.ZERO,AztecAddress.ZERO,Fr.ZERO,Fr.ZERO,[])}__name(emptyFactCollection,"emptyFactCollection");var UtilityExecutionOracle=class _UtilityExecutionOracle{static{__name(this,"UtilityExecutionOracle")}isMisc=!0;isUtility=!0;contractLogger;aztecnrLogger;offchainEffects=[];ephemeralArrayService=new EphemeralArrayService;transientArrayService;contractOracleVersion;callContext;authWitnesses;capsules;anchorBlockHeader;anchoredContractData;noteStore;keyStore;addressStore;aztecNode;recipientTaggingStore;taggingSecretSourcesStore;capsuleService;factService;privateEventStore;txResolver;contractSyncService;l2TipsStore;jobId;logger;scopes;simulator;hooks;utilityExecutor;constructor(args){this.callContext=args.callContext,this.authWitnesses=args.authWitnesses,this.capsules=args.capsules,this.anchorBlockHeader=args.anchorBlockHeader,this.anchoredContractData=args.anchoredContractData,this.noteStore=args.noteStore,this.keyStore=args.keyStore,this.addressStore=args.addressStore,this.aztecNode=args.aztecNode,this.recipientTaggingStore=args.recipientTaggingStore,this.taggingSecretSourcesStore=args.taggingSecretSourcesStore,this.capsuleService=args.capsuleService,this.factService=args.factService,this.privateEventStore=args.privateEventStore,this.txResolver=args.txResolver,this.contractSyncService=args.contractSyncService,this.l2TipsStore=args.l2TipsStore,this.jobId=args.jobId,this.logger=args.log??createLogger("simulator:client_view_context"),this.scopes=args.scopes,this.simulator=args.simulator,this.hooks=args.hooks,this.utilityExecutor=args.utilityExecutor,this.transientArrayService=args.transientArrayService}assertCompatibleOracleVersion(major2,minor){if(major2!==30){let hint=major2>30?"The contract was compiled with a newer version of Aztec.nr than your private environment supports. Upgrade your private environment to a compatible version.":"The contract was compiled with an older version of Aztec.nr than your private environment supports. Recompile the contract with a compatible version of Aztec.nr.";throw new Error(`Incompatible private environment version: ${hint} See https://docs.aztec.network/errors/8 (expected oracle major version ${30}, got ${major2})`)}this.contractOracleVersion={major:major2,minor}}nonOracleFunctionGetContractOracleVersion(){return this.contractOracleVersion}getRandomField(){return Fr.random()}getUtilityContext(){return{blockHeader:this.anchorBlockHeader,contractAddress:this.callContext.contractAddress,msgSender:this.callContext.msgSender}}async getKeyValidationRequest(pkMHash,_keyIndex){let hasAccess=!1;for(let i=0;i<this.scopes.length&&!hasAccess;i++)await this.keyStore.accountHasKey(this.scopes[i],pkMHash)&&(hasAccess=!0);if(!hasAccess)throw new Error(`Key validation request denied: no scoped account has a key with hash ${pkMHash.toString()}.`);return this.keyStore.getKeyValidationRequest(pkMHash,this.contractAddress)}async getNoteHashMembershipWitness(blockHash,noteHash){let witness=await this.#queryWithBlockHashNotAfterAnchor(blockHash,()=>this.aztecNode.getNoteHashMembershipWitness(blockHash,noteHash));if(!witness)throw new Error(`Note hash ${noteHash} not found in the note hash tree at block ${blockHash.toString()}.`);return witness}async getBlockHashMembershipWitness(referenceBlockHash,blockHash){let witness=await this.#queryWithBlockHashNotAfterAnchor(referenceBlockHash,()=>this.aztecNode.getBlockHashMembershipWitness(referenceBlockHash,blockHash));return witness?Option.some(witness):Option.none()}async getNullifierMembershipWitness(blockHash,nullifier){let witness=await this.#queryWithBlockHashNotAfterAnchor(blockHash,()=>this.aztecNode.getNullifierMembershipWitness(blockHash,nullifier));if(!witness)throw new Error(`Nullifier membership witness not found at block ${blockHash.toString()}.`);return witness}async getLowNullifierMembershipWitness(blockHash,nullifier){let witness=await this.#queryWithBlockHashNotAfterAnchor(blockHash,()=>this.aztecNode.getLowNullifierMembershipWitness(blockHash,nullifier));if(!witness)throw new Error(`Low nullifier witness not found for nullifier ${nullifier} at block hash ${blockHash.toString()}.`);return witness}async getPublicDataWitness(blockHash,leafSlot){let witness=await this.#queryWithBlockHashNotAfterAnchor(blockHash,()=>this.aztecNode.getPublicDataWitness(blockHash,leafSlot));if(!witness)throw new Error(`Public data witness not found for slot ${leafSlot} at block hash ${blockHash.toString()}.`);return witness}async getBlockHeader(blockNumber){let anchorBlockNumber=this.anchorBlockHeader.getBlockNumber();if(blockNumber>anchorBlockNumber)throw new Error(`Block number ${blockNumber} is higher than current block ${anchorBlockNumber}`);if(blockNumber===anchorBlockNumber)return this.anchorBlockHeader;let block=await this.aztecNode.getBlock(blockNumber);if(!block?.header)throw new Error(`Block header not found for block ${blockNumber}.`);return block.header}async getPublicKeysAndPartialAddress(account){let completeAddress=await this.addressStore.getCompleteAddress(account);return completeAddress?Option.some({publicKeys:completeAddress.publicKeys,partialAddress:completeAddress.partialAddress}):Option.none()}async getCompleteAddressOrFail(account){let completeAddress=await this.addressStore.getCompleteAddress(account);if(!completeAddress)throw new Error(`No public key registered for address ${account}.
|
|
211
211
|
Register it by calling wallet.registerSender(...).
|
|
212
|
-
See docs for context: https://docs.aztec.network/errors/14`);return completeAddress}async getContractInstance(address){let instance=await this.anchoredContractData.getContractInstance(address);if(!instance)throw new Error(`No contract instance found for address ${address.toString()}`);return instance}getAuthWitness(messageHash){let witness=this.authWitnesses.find(w=>w.requestHash.equals(messageHash))?.witness;if(!witness)throw new Error(`Unknown auth witness for message hash ${messageHash}`);return Promise.resolve(witness)}async getNotes(owner,storageSlot,numSelects,selectByIndexes,selectByOffsets,selectByLengths,selectValues,selectComparators,sortByIndexes,sortByOffsets,sortByLengths,sortOrder,limit,offset,status,maxNotes,packedHintedNoteLength){let dbNotes=await new NoteService(this.noteStore,this.aztecNode,this.anchorBlockHeader,this.jobId).getNotes(this.contractAddress,owner.value,storageSlot,status,this.scopes),picked=pickNotes(dbNotes,{selects:selectByIndexes.slice(0,numSelects).map((index,i)=>({selector:{index,offset:selectByOffsets[i],length:selectByLengths[i]},value:selectValues[i],comparator:selectComparators[i]})),sorts:sortByIndexes.map((index,i)=>({selector:{index,offset:sortByOffsets[i],length:sortByLengths[i]},order:sortOrder[i]})),limit,offset});return BoundedVec.from({data:picked,maxLength:maxNotes,elementSize:packedHintedNoteLength})}async doesNullifierExist(innerNullifier){let[nullifier,anchorBlockHash]=await Promise.all([siloNullifier(this.contractAddress,innerNullifier),this.anchorBlockHeader.hash()]),[leafIndex]=await this.aztecNode.findLeavesIndexes(anchorBlockHash,MerkleTreeId.NULLIFIER_TREE,[nullifier]);return leafIndex?.data!==void 0}async getL1ToL2MembershipWitness(contractAddress,messageHash,secret){let[messageIndex,siblingPath]=await getNonNullifiedL1ToL2MessageWitness(this.aztecNode,contractAddress,messageHash,secret,await this.anchorBlockHeader.hash());return{index:messageIndex,siblingPath}}getFromPublicStorage(blockHash,contractAddress,startStorageSlot,numberOfElements){return this.#queryWithBlockHashNotAfterAnchor(blockHash,async()=>{let slots=Array(numberOfElements).fill(0).map((_,i)=>new Fr(startStorageSlot.value+BigInt(i))),values=await Promise.all(slots.map(storageSlot=>this.aztecNode.getPublicStorageAt(blockHash,contractAddress,storageSlot)));return this.logger.debug(`Oracle storage read: slots=[${slots.map(slot=>slot.toString()).join(", ")}] address=${contractAddress.toString()} values=[${values.join(", ")}]`),values})}async#getContractLogger(){return this.contractLogger||(this.contractLogger=await createContractLogger(this.contractAddress,addr=>this.anchoredContractData.getDebugContractName(addr),"user",{instanceId:this.jobId})),this.contractLogger}async#getAztecnrLogger(){return this.aztecnrLogger||(this.aztecnrLogger=await createContractLogger(this.contractAddress,addr=>this.anchoredContractData.getDebugContractName(addr),"aztecnr",{instanceId:this.jobId})),this.aztecnrLogger}async log(level,message,_fieldsSize,fields){if(!LogLevels[level])throw new Error(`Invalid log level: ${level}`);let{kind,message:strippedMessage}=stripAztecnrLogPrefix(message),logger3=kind=="aztecnr"?await this.#getAztecnrLogger():await this.#getContractLogger();logContractMessage(logger3,LogLevels[level],strippedMessage,fields)}async getPendingTaggedLogs(scope,providedSecrets){let secrets=providedSecrets.readAll(this.ephemeralArrayService).map(ps=>new AppTaggingSecret(ps.secret,this.contractAddress,ps.mode)),logs=await this.#createLogService().fetchTaggedLogs(this.contractAddress,scope,secrets);return EphemeralArray.fromValues(this.ephemeralArrayService,logs)}#createLogService(){return new LogService(this.aztecNode,this.anchorBlockHeader,this.l2TipsStore,this.keyStore,this.recipientTaggingStore,this.taggingSecretSourcesStore,this.addressStore,this.jobId,this.logger.getBindings())}async validateAndStoreEnqueuedNotesAndEvents(noteValidationRequests,eventValidationRequests,scope){await this.#processValidationRequests(noteValidationRequests.readAll(this.ephemeralArrayService),eventValidationRequests.readAll(this.ephemeralArrayService),scope)}async#processValidationRequests(noteValidationRequests,eventValidationRequests,scope){let txEffects=await this.#fetchTxEffects([...noteValidationRequests.map(r2=>r2.txHash),...eventValidationRequests.map(r2=>r2.txHash)]),noteService=new NoteService(this.noteStore,this.aztecNode,this.anchorBlockHeader,this.jobId),eventService=new EventService(this.anchorBlockHeader,this.aztecNode,this.privateEventStore,this.jobId);await Promise.all([noteService.validateAndStoreNotes(noteValidationRequests,scope,txEffects),eventService.validateAndStoreEvents(eventValidationRequests,scope,txEffects)])}async getLogsByTagV2(requests){let logRetrievalRequests=requests.readAll(this.ephemeralArrayService),innerArrays=(await this.#createLogService().fetchLogsByTag(this.contractAddress,logRetrievalRequests)).map(responses=>EphemeralArray.fromValues(this.ephemeralArrayService,responses));return EphemeralArray.fromValues(this.ephemeralArrayService,innerArrays)}async getResolvedTxs(requests){let txHashes=requests.readAll(this.ephemeralArrayService),options=(await this.txResolver.resolveTxs(txHashes,this.anchorBlockHeader.getBlockNumber())).map(r2=>r2?Option.some(r2):Option.none());return EphemeralArray.fromValues(this.ephemeralArrayService,options)}async getTxEffect(txHash){if(txHash.hash.isZero())throw new Error("Invalid tx hash passed into aztec_utl_getTxEffect oracle handler");let receipt=await this.aztecNode.getTxReceipt(txHash,{includeTxEffect:!0});if(!receipt.isMined()||!receipt.txEffect||receipt.blockNumber>this.anchorBlockHeader.getBlockNumber())return Option.none();let txEffect=receipt.txEffect;return Option.some({...txEffect,publicLogs:FlatPublicLogs.fromLogs(txEffect.publicLogs),contractClassLogs:txEffect.contractClassLogs.map(log2=>({contractAddress:log2.contractAddress,fields:log2.fields.toFields(),emittedLength:log2.emittedLength}))})}setCapsule(contractAddress,slot,capsule,scope){this.#assertOwnContract(contractAddress),this.capsuleService.setCapsule(contractAddress,slot,capsule,this.jobId,scope)}async getCapsule(contractAddress,slot,tSize,scope){this.#assertOwnContract(contractAddress);let values=await this.capsuleService.getCapsule(contractAddress,slot,this.jobId,scope,this.capsules);return values?Option.some(values):Option.none({length:tSize})}deleteCapsule(contractAddress,slot,scope){this.#assertOwnContract(contractAddress),this.capsuleService.deleteCapsule(contractAddress,slot,this.jobId,scope)}copyCapsule(contractAddress,srcSlot,dstSlot,numEntries,scope){return this.#assertOwnContract(contractAddress),this.capsuleService.copyCapsule(contractAddress,srcSlot,dstSlot,numEntries,this.jobId,scope)}#assertOwnContract(contractAddress){if(!contractAddress.equals(this.contractAddress))throw new Error(`Contract ${contractAddress} is not allowed to access ${this.contractAddress}'s PXE DB`)}recordFact(contractAddress,scope,factCollectionTypeId,factCollectionId,factTypeId,payload,originBlock){return this.#assertOwnContract(contractAddress),this.factService.recordFact(new FactCollectionKey(contractAddress,scope,factCollectionTypeId,factCollectionId),factTypeId,payload.readAll(this.ephemeralArrayService),originBlock.isSome()?originBlock.value:void 0,this.jobId)}deleteFactCollection(contractAddress,scope,factCollectionTypeId,factCollectionId){return this.#assertOwnContract(contractAddress),this.factService.deleteFactCollection(new FactCollectionKey(contractAddress,scope,factCollectionTypeId,factCollectionId),this.jobId)}async getFactCollection(contractAddress,scope,factCollectionTypeId,factCollectionId){this.#assertOwnContract(contractAddress);let tips=anchoredTipBlockNumbers(await this.l2TipsStore.getL2Tips(),this.anchorBlockHeader.getBlockNumber()),collection=await this.factService.getFactCollection(new FactCollectionKey(contractAddress,scope,factCollectionTypeId,factCollectionId),tips,this.jobId);return collection?Option.some(toNoirFactCollection(this.ephemeralArrayService,contractAddress,scope,factCollectionTypeId,factCollectionId,collection.facts)):Option.none(emptyFactCollection(this.ephemeralArrayService))}async getFactCollectionsByType(contractAddress,scope,factCollectionTypeId){this.#assertOwnContract(contractAddress);let tips=anchoredTipBlockNumbers(await this.l2TipsStore.getL2Tips(),this.anchorBlockHeader.getBlockNumber()),collections=await this.factService.getFactCollectionsByType(new FactCollectionTypeKey(contractAddress,scope,factCollectionTypeId),tips,this.jobId);return EphemeralArray.fromValues(this.ephemeralArrayService,collections.map(collection=>toNoirFactCollection(this.ephemeralArrayService,collection.key.contractAddress,collection.key.scope,collection.key.factCollectionTypeId,collection.key.factCollectionId,collection.facts)))}setContractSyncCacheInvalid(contractAddress,scopes){if(!contractAddress.equals(this.contractAddress))throw new Error(`Contract ${this.contractAddress} cannot invalidate sync cache of ${contractAddress}`);this.contractSyncService.invalidateContractForScopes(contractAddress,scopes.data)}async decryptAes128(ciphertext,iv,symKey){let capacity=ciphertext.maxLength;try{let plaintext=await new Aes128().decryptBufferCBC(Buffer.from(ciphertext.data),iv,symKey);return Option.some(BoundedVec.from({data:[...plaintext],maxLength:capacity}))}catch{return Option.none({maxLength:capacity})}}async getSharedSecrets(address,ephPks,contractAddress){if(!contractAddress.equals(this.contractAddress))throw new Error(`getSharedSecrets called with contract address ${contractAddress}, expected ${this.contractAddress}`);let recipientCompleteAddress=await this.addressStore.getCompleteAddress(address);if(!recipientCompleteAddress)return this.logger.warn(`Computing shared secrets for address ${address} whose keys are not held - returning no secrets`,{address,contractAddress:this.contractAddress}),EphemeralArray.fromValues(this.ephemeralArrayService,[]);let ivpkMHash=await hashPublicKey(recipientCompleteAddress.publicKeys.ivpkM),ivskM=await this.keyStore.getMasterSecretKey(ivpkMHash),addressSecret=await computeAddressSecret(await recipientCompleteAddress.getPreaddress(),ivskM),ephPkPoints=ephPks.readAll(this.ephemeralArrayService),secrets=await Promise.all(ephPkPoints.map(({x,y})=>appSiloEcdhSharedSecret(addressSecret,new Point(x,y),this.contractAddress)));return EphemeralArray.fromValues(this.ephemeralArrayService,secrets)}pushEphemeral(slot,elements){return this.ephemeralArrayService.push(slot,elements)}popEphemeral(slot){return this.ephemeralArrayService.pop(slot)}getEphemeral(slot,index){return this.ephemeralArrayService.get(slot,index)}setEphemeral(slot,index,elements){this.ephemeralArrayService.set(slot,index,elements)}getEphemeralLen(slot){return this.ephemeralArrayService.len(slot)}removeEphemeral(slot,index){this.ephemeralArrayService.remove(slot,index)}clearEphemeral(slot){this.ephemeralArrayService.clear(slot)}pushTransient(slot,elements){return this.transientArrayService.push(this.contractAddress,slot,elements)}popTransient(slot){return this.transientArrayService.pop(this.contractAddress,slot)}getTransient(slot,index){return this.transientArrayService.get(this.contractAddress,slot,index)}setTransient(slot,index,elements){this.transientArrayService.set(this.contractAddress,slot,index,elements)}getTransientLen(slot){return this.transientArrayService.len(this.contractAddress,slot)}removeTransient(slot,index){this.transientArrayService.remove(this.contractAddress,slot,index)}clearTransient(slot){this.transientArrayService.clear(this.contractAddress,slot)}emitOffchainEffect(data){return this.offchainEffects.push({data,contractAddress:this.contractAddress}),Promise.resolve()}async callUtilityFunction(targetContractAddress,functionSelector,args){let targetArtifact=await this.anchoredContractData.getFunctionArtifactWithDebugMetadata(targetContractAddress,functionSelector);if(!targetArtifact)throw new Error(`Cannot call ${targetContractAddress}:${functionSelector}: the contract is not registered. Register it via wallet.registerContract(...).`);if(!targetContractAddress.equals(this.contractAddress)){if(!await isStandardHandshakeRegistryUtilityRead(targetContractAddress,functionSelector)){let[callerClassId,targetClassId]=await Promise.all([this.anchoredContractData.getCurrentClassId(this.contractAddress),this.anchoredContractData.getCurrentClassId(targetContractAddress)]);if(!callerClassId||!targetClassId)throw new Error(`Cannot authorize utility call from ${this.contractAddress} to ${targetContractAddress}: ${callerClassId?targetContractAddress:this.contractAddress} is not registered.`);let request={caller:this.contractAddress,callerClassId,target:targetContractAddress,targetClassId,functionSelector,functionName:targetArtifact.name,args,callerContext:this.callerContext},response=this.hooks?.authorizeUtilityCall?await this.hooks.authorizeUtilityCall(request):{authorized:!1,reason:"No authorizeUtilityCall hook configured"};if(!response.authorized){let reason=response.reason?`: ${response.reason}`:"";throw new Error(`Cross-contract utility call denied${reason}. ${this.contractAddress} attempted to call ${targetContractAddress}:${functionSelector} (${targetArtifact.name}). See https://docs.aztec.network/errors/11`)}}await this.contractSyncService.ensureContractSynced(targetContractAddress,functionSelector,this.utilityExecutor,this.anchorBlockHeader,this.jobId,this.scopes)}this.logger.debug(`Calling nested utility function ${targetContractAddress}:${functionSelector} from ${this.contractAddress}`);let nestedOracle=new _UtilityExecutionOracle({callContext:CallContext.from({msgSender:this.contractAddress,contractAddress:targetContractAddress,functionSelector,isStaticCall:!0}),authWitnesses:this.authWitnesses,capsules:this.capsules,anchorBlockHeader:this.anchorBlockHeader,anchoredContractData:this.anchoredContractData,noteStore:this.noteStore,keyStore:this.keyStore,addressStore:this.addressStore,aztecNode:this.aztecNode,recipientTaggingStore:this.recipientTaggingStore,taggingSecretSourcesStore:this.taggingSecretSourcesStore,capsuleService:this.capsuleService,factService:this.factService,privateEventStore:this.privateEventStore,txResolver:this.txResolver,contractSyncService:this.contractSyncService,l2TipsStore:this.l2TipsStore,jobId:this.jobId,scopes:this.scopes,simulator:this.simulator,hooks:this.hooks,utilityExecutor:this.utilityExecutor,log:this.logger,transientArrayService:this.transientArrayService}),initialWitness=toACVMWitness(0,args),acirExecutionResult=await this.simulator.executeUserCircuit(initialWitness,targetArtifact,buildACIRCallback(nestedOracle)).catch(err=>{throw err.message=resolveAssertionMessageFromError(err,targetArtifact),new ExecutionError(err.message,{contractAddress:targetContractAddress,functionSelector},extractCallStack(err,targetArtifact.debug),{cause:err})});return witnessMapToFields(acirExecutionResult.returnWitness)}getOffchainEffects(){return this.offchainEffects}async#fetchTxEffects(txHashes){let uniqueTxHashes=uniqueBy(txHashes,h=>h.toString()),fetched=await Promise.all(uniqueTxHashes.map(h=>this.aztecNode.getTxReceipt(h,{includeTxEffect:!0})));return new Map(uniqueTxHashes.map((h,i)=>{let receipt=fetched[i];return!receipt.isMined()||!receipt.txEffect?[h.toString(),void 0]:[h.toString(),{data:receipt.txEffect,l2BlockNumber:receipt.blockNumber,l2BlockHash:receipt.blockHash,txIndexInBlock:receipt.txIndexInBlock,slotNumber:receipt.slotNumber}]}).filter(entry=>entry[1]!==void 0))}async#queryWithBlockHashNotAfterAnchor(blockHash,query){let anchorHash=await this.anchorBlockHeader.hash();if(blockHash.equals(anchorHash))return query();let[response]=await Promise.all([query(),(async()=>{let header=(await this.aztecNode.getBlock(blockHash))?.header;if(!header)throw new Error(`Could not find block header for block hash ${blockHash}`);if(header.getBlockNumber()>this.anchorBlockHeader.getBlockNumber())throw new Error(`Made a node query with a reference block hash ${blockHash} with block number ${header.getBlockNumber()}, which is ahead of the anchor block number ${this.anchorBlockHeader.getBlockNumber()} (from anchor block hash ${anchorHash}).`)})()]);return response}get callerContext(){return"utility"}get contractAddress(){return this.callContext.contractAddress}},STANDARD_HANDSHAKE_REGISTRY_DEFAULT_AUTHORIZED_READ_SIGNATURES=["get_handshakes((Field),u32)","get_app_siloed_secrets((Field),(Field))"];async function doesSelectorHaveSignature(functionSelector,signature){return functionSelector.equals(await FunctionSelector.fromSignature(signature))}__name(doesSelectorHaveSignature,"doesSelectorHaveSignature");async function isStandardHandshakeRegistryUtilityRead(targetContractAddress,functionSelector){return targetContractAddress.equals(STANDARD_HANDSHAKE_REGISTRY_ADDRESS)?(await Promise.all(STANDARD_HANDSHAKE_REGISTRY_DEFAULT_AUTHORIZED_READ_SIGNATURES.map(signature=>doesSelectorHaveSignature(functionSelector,signature)))).some(Boolean):!1}__name(isStandardHandshakeRegistryUtilityRead,"isStandardHandshakeRegistryUtilityRead");var PrivateExecutionOracle=class _PrivateExecutionOracle extends UtilityExecutionOracle{static{__name(this,"PrivateExecutionOracle")}isPrivate=!0;newNotes=[];noteHashNullifierCounterMap=new Map;contractClassLogs=[];nestedExecutionResults=[];argsHash;txContext;executionCache;noteCache;taggingIndexCache;senderTaggingStore;totalPublicCalldataCount;initialSideEffectCounter;defaultSenderForTags;constructor(args){super({...args,log:args.log??createLogger("simulator:client_execution_context")}),this.argsHash=args.argsHash,this.txContext=args.txContext,this.executionCache=args.executionCache,this.noteCache=args.noteCache,this.taggingIndexCache=args.taggingIndexCache,this.senderTaggingStore=args.senderTaggingStore,this.totalPublicCalldataCount=args.totalPublicCalldataCount??0,this.initialSideEffectCounter=args.sideEffectCounter??0,this.defaultSenderForTags=args.senderForTags}getPrivateContextInputs(){return new PrivateContextInputs(this.callContext,this.anchorBlockHeader,this.txContext,this.initialSideEffectCounter)}getInitialWitness(abi){let argumentsSize=countArgumentsSize(abi),args=this.executionCache.getPreimage(this.argsHash);if(args?.length!==argumentsSize)throw new Error(`Invalid arguments size: expected ${argumentsSize}, got ${args?.length}`);let privateContextInputsAsFields=this.getPrivateContextInputs().toFields();if(privateContextInputsAsFields.length!==37)throw new Error("Invalid private context inputs size");let fields=[...privateContextInputsAsFields,...args];return toACVMWitness(0,fields)}getNewNotes(){return this.newNotes}getNoteHashNullifierCounterMap(){return this.noteHashNullifierCounterMap}getContractClassLogs(){return this.contractClassLogs}getUsedTaggingIndexRanges(){return this.taggingIndexCache.getUsedTaggingIndexRanges()}getNestedExecutionResults(){return this.nestedExecutionResults}getSenderForTags(){return Promise.resolve(this.defaultSenderForTags?Option.some(this.defaultSenderForTags):Option.none())}async resolveCustomRequest(kind,payload){let hook=this.hooks?.resolveCustomRequest;if(!hook)throw new Error("Cannot serve a request: no resolveCustomRequest hook is configured");let contractClassId=await this.#getCurrentContractClassId(this.contractAddress);return hook({contractAddress:this.contractAddress,contractClassId,kind,payload})}async resolveTaggingStrategy(sender,recipient,deliveryMode){let[isUnconstrainedSelfSend,chosenStrategy]=await Promise.all([this.#isUnconstrainedSelfSend(recipient,deliveryMode),this.#chooseTaggingSecretStrategy(sender,recipient,deliveryMode)]),strategy=isUnconstrainedSelfSend?{type:"address-derived"}:chosenStrategy;return this.#resolveTaggingSecretStrategy(strategy,sender,recipient)}async#chooseTaggingSecretStrategy(sender,recipient,deliveryMode){let hook=this.hooks?.resolveTaggingSecretStrategy;if(!hook)return{type:"non-interactive-handshake"};let contractClassId=await this.#getCurrentContractClassId(this.contractAddress);return hook({contractAddress:this.contractAddress,contractClassId,sender,recipient,deliveryMode})}async#getCurrentContractClassId(address){let classId=await this.anchoredContractData.getCurrentClassId(address);if(classId===void 0)throw new Error(`Cannot resolve the current contract class for ${address}`);return classId}#isUnconstrainedSelfSend(recipient,deliveryMode){return deliveryMode===AppTaggingSecretKind.UNCONSTRAINED?this.keyStore.hasAccount(recipient):Promise.resolve(!1)}async#resolveTaggingSecretStrategy(strategy,sender,recipient){switch(strategy.type){case"non-interactive-handshake":return{type:"non-interactive-handshake"};case"address-derived":return this.#addressDerivedSecret(sender,recipient);case"arbitrary-secret":return{type:"unconstrained-secret",secret:(await AppTaggingSecret.computeDirectional(strategy.secret,this.contractAddress,recipient)).secret}}}async#addressDerivedSecret(sender,recipient){let secret=await this.getAppTaggingSecret(sender,recipient);if(!secret.isSome())throw new Error(`Cannot derive an address-derived tagging secret for invalid recipient ${recipient}`);return{type:"unconstrained-secret",secret:secret.value}}async getAppTaggingSecret(sender,recipient){let extendedSecret=await this.#calculateAppTaggingSecret(this.contractAddress,sender,recipient);return extendedSecret?Option.some(extendedSecret.secret):(this.logger.warn(`Computing a tagging secret for invalid recipient ${recipient} - returning no secret`,{contractAddress:this.contractAddress}),Option.none())}async getNextTaggingIndex(secret,kind){let appTaggingSecret=new AppTaggingSecret(secret,this.contractAddress,kind),index=await this.#reserveNextIndexForSecret(appTaggingSecret);return this.logger.debug(`Incrementing ${kind} tagging index for secret in contract ${this.contractAddress} to ${index}`),index}async#reserveNextIndexForSecret(secret){let index=await this.#getIndexToUseForSecret(secret);return this.taggingIndexCache.setLastUsedIndex(secret,index),index}async#calculateAppTaggingSecret(contractAddress,sender,recipient){let senderCompleteAddress=await this.getCompleteAddressOrFail(sender),senderIvsk=await this.keyStore.getMasterIncomingViewingSecretKey(sender);return AppTaggingSecret.computeViaEcdh(senderCompleteAddress,senderIvsk,recipient,contractAddress,recipient)}async#getIndexToUseForSecret(secret){let lastUsedIndexInTx=this.taggingIndexCache.getLastUsedIndex(secret);if(lastUsedIndexInTx!==void 0)return lastUsedIndexInTx+1;{await syncSenderTaggingIndexes(secret,this.aztecNode,this.senderTaggingStore,await this.anchorBlockHeader.hash(),this.jobId);let lastUsedIndex=await this.senderTaggingStore.getLastUsedIndex(secret,this.jobId);return lastUsedIndex===void 0?0:lastUsedIndex+1}}setHashPreimage(values,hash5){return this.executionCache.store(values,hash5)}getHashPreimage(hash5){let preimage=this.executionCache.getPreimage(hash5);if(!preimage)throw new Error(`Preimage for hash ${hash5.toString()} not found in cache`);return Promise.resolve(preimage)}async doesNullifierExist(innerNullifier){this.logger.debug(`Checking existence of inner nullifier ${innerNullifier}`,{contractAddress:this.contractAddress});let nullifier=(await siloNullifier(this.contractAddress,innerNullifier)).toBigInt();return this.noteCache.getNullifiers(this.contractAddress).has(nullifier)||await super.doesNullifierExist(innerNullifier)}async getNotes(owner,storageSlot,numSelects,selectByIndexes,selectByOffsets,selectByLengths,selectValues,selectComparators,sortByIndexes,sortByOffsets,sortByLengths,sortOrder,limit,offset,status,maxNotes,packedHintedNoteLength){let pendingNotes=this.noteCache.getNotes(this.callContext.contractAddress,owner.value,storageSlot),pendingNullifiers=this.noteCache.getNullifiers(this.callContext.contractAddress),dbNotesFiltered=(await new NoteService(this.noteStore,this.aztecNode,this.anchorBlockHeader,this.jobId).getNotes(this.callContext.contractAddress,owner.value,storageSlot,status,this.scopes)).filter(n=>!pendingNullifiers.has(n.siloedNullifier.value)),notes=pickNotes([...dbNotesFiltered,...pendingNotes],{selects:selectByIndexes.slice(0,numSelects).map((index,i)=>({selector:{index,offset:selectByOffsets[i],length:selectByLengths[i]},value:selectValues[i],comparator:selectComparators[i]})),sorts:sortByIndexes.map((index,i)=>({selector:{index,offset:sortByOffsets[i],length:sortByLengths[i]},order:sortOrder[i]})),limit,offset});return this.logger.debug(`Returning ${notes.length} notes for ${this.callContext.contractAddress} at ${storageSlot}: ${notes.map(n=>`${n.noteNonce.toString()}:[${n.note.items.map(i=>i.toString()).join(",")}]`).join(", ")}`),BoundedVec.from({data:notes,maxLength:maxNotes,elementSize:packedHintedNoteLength})}notifyCreatedNote(owner,storageSlot,randomness,noteTypeId,noteItems,noteHash,counter){this.logger.debug(`Notified of new note with inner hash ${noteHash}`,{contractAddress:this.callContext.contractAddress,storageSlot,randomness,noteTypeId,counter});let note=new Note(noteItems);this.noteCache.addNewNote({contractAddress:this.callContext.contractAddress,owner,storageSlot,randomness,noteNonce:Fr.ZERO,note,siloedNullifier:void 0,noteHash,isPending:!0},counter),this.newNotes.push(NoteAndSlot.from({note,storageSlot,randomness,noteTypeId}))}async notifyNullifiedNote(innerNullifier,noteHash,counter){let nullifiedNoteHashCounter=await this.noteCache.nullifyNote(this.callContext.contractAddress,innerNullifier,noteHash);nullifiedNoteHashCounter!==void 0&&this.noteHashNullifierCounterMap.set(nullifiedNoteHashCounter,counter)}notifyCreatedNullifier(innerNullifier){return this.logger.debug(`Notified of new inner nullifier ${innerNullifier}`,{contractAddress:this.contractAddress}),this.noteCache.nullifierCreated(this.callContext.contractAddress,innerNullifier)}async isNullifierPending(innerNullifier,contractAddress){let siloedNullifier=await siloNullifier(contractAddress,innerNullifier),isNullifierPending=this.noteCache.getNullifiers(contractAddress).has(siloedNullifier.toBigInt());return Promise.resolve(isNullifierPending)}notifyCreatedContractClassLog(logData,counter){let log2=ContractClassLog.from({contractAddress:logData.contractAddress,fields:new ContractClassLogFields(logData.fields),emittedLength:logData.emittedLength});this.contractClassLogs.push(new CountedContractClassLog(log2,counter));let text=log2.toBuffer().toString("hex");this.logger.verbose(`Emitted log from ContractClassRegistry: "${text.length>100?text.slice(0,100)+"...":text}"`)}#checkValidStaticCall(childExecutionResult){if(childExecutionResult.publicInputs.noteHashes.claimedLength>0||childExecutionResult.publicInputs.nullifiers.claimedLength>0||childExecutionResult.publicInputs.l2ToL1Msgs.claimedLength>0||childExecutionResult.publicInputs.privateLogs.claimedLength>0||childExecutionResult.publicInputs.contractClassLogsHashes.claimedLength>0)throw new Error("Static call cannot update the state, emit L2->L1 messages or generate logs")}async callPrivateFunction(targetContractAddress,functionSelector,argsHash,sideEffectCounter,isStaticCall){if(!this.simulator)throw new Error("No simulator provided, cannot perform a nested private call");let simulatorSetupTimer=new Timer;this.logger.debug(`Calling private function ${targetContractAddress}:${functionSelector} from ${this.callContext.contractAddress}`),isStaticCall=isStaticCall||this.callContext.isStaticCall,await this.contractSyncService.ensureContractSynced(targetContractAddress,functionSelector,this.utilityExecutor,this.anchorBlockHeader,this.jobId,this.scopes);let targetArtifact=await this.anchoredContractData.getFunctionArtifactWithDebugMetadata(targetContractAddress,functionSelector);if(!targetArtifact)throw new Error(`Cannot call ${targetContractAddress}:${functionSelector}: the contract is not registered. Register it via wallet.registerContract(...).`);let derivedTxContext=this.txContext.clone(),derivedCallContext=await this.deriveCallContext(targetContractAddress,targetArtifact,isStaticCall),privateExecutionOracle=new _PrivateExecutionOracle({argsHash,txContext:derivedTxContext,callContext:derivedCallContext,anchorBlockHeader:this.anchorBlockHeader,utilityExecutor:this.utilityExecutor,authWitnesses:this.authWitnesses,capsules:this.capsules,executionCache:this.executionCache,noteCache:this.noteCache,taggingIndexCache:this.taggingIndexCache,anchoredContractData:this.anchoredContractData,noteStore:this.noteStore,keyStore:this.keyStore,addressStore:this.addressStore,aztecNode:this.aztecNode,senderTaggingStore:this.senderTaggingStore,recipientTaggingStore:this.recipientTaggingStore,taggingSecretSourcesStore:this.taggingSecretSourcesStore,capsuleService:this.capsuleService,factService:this.factService,privateEventStore:this.privateEventStore,txResolver:this.txResolver,contractSyncService:this.contractSyncService,jobId:this.jobId,totalPublicCalldataCount:this.totalPublicCalldataCount,sideEffectCounter,log:this.logger,scopes:this.scopes,senderForTags:this.defaultSenderForTags,simulator:this.simulator,hooks:this.hooks,l2TipsStore:this.l2TipsStore,transientArrayService:this.transientArrayService}),setupTime=simulatorSetupTimer.ms(),childExecutionResult=await executePrivateFunction(this.simulator,privateExecutionOracle,targetArtifact,targetContractAddress,functionSelector);this.totalPublicCalldataCount=privateExecutionOracle.getTotalPublicCalldataCount(),isStaticCall&&this.#checkValidStaticCall(childExecutionResult),this.nestedExecutionResults.push(childExecutionResult);let publicInputs=childExecutionResult.publicInputs;return childExecutionResult.profileResult&&(childExecutionResult.profileResult.timings.witgen+=setupTime),{endSideEffectCounter:publicInputs.endSideEffectCounter,returnsHash:publicInputs.returnsHash}}assertValidPublicCalldata(calldataHash){let calldata=this.executionCache.getPreimage(calldataHash);if(!calldata)throw new Error("Calldata for public call not found in cache");if(this.totalPublicCalldataCount+=calldata.length,this.totalPublicCalldataCount>16e3)throw new Error(`Too many total args to all enqueued public calls! (> ${16e3})`);return Promise.resolve()}getTotalPublicCalldataCount(){return this.totalPublicCalldataCount}notifyRevertiblePhaseStart(minRevertibleSideEffectCounter){return this.noteCache.setMinRevertibleSideEffectCounter(minRevertibleSideEffectCounter)}isExecutionInRevertiblePhase(sideEffectCounter){return Promise.resolve(this.noteCache.isSideEffectCounterRevertible(sideEffectCounter))}async deriveCallContext(targetContractAddress,targetArtifact,isStaticCall=!1){return new CallContext(this.contractAddress,targetContractAddress,await FunctionSelector.fromNameAndParameters(targetArtifact.name,targetArtifact.parameters),isStaticCall)}getDebugFunctionName(){return this.anchoredContractData.getDebugFunctionName(this.contractAddress,this.callContext.functionSelector)}get callerContext(){return this.callContext.isStaticCall?"private view":"private"}};var TransientArrayService=class{static{__name(this,"TransientArrayService")}#arrays=new Map;#key(contractAddress,slot){return`${contractAddress.toString()}:${slot.toString()}`}readArrayAt(contractAddress,slot){return this.#arrays.get(this.#key(contractAddress,slot))??[]}#setArray(contractAddress,slot,array2){this.#arrays.set(this.#key(contractAddress,slot),array2)}len(contractAddress,slot){return this.readArrayAt(contractAddress,slot).length}push(contractAddress,slot,elements){let array2=this.readArrayAt(contractAddress,slot);return array2.push(elements),this.#setArray(contractAddress,slot,array2),array2.length}pop(contractAddress,slot){let array2=this.readArrayAt(contractAddress,slot);if(array2.length===0)throw new Error(`Transient array at slot ${slot} is empty`);let element=array2.pop();return this.#setArray(contractAddress,slot,array2),element}get(contractAddress,slot,index){let array2=this.readArrayAt(contractAddress,slot);if(index<0||index>=array2.length)throw new Error(`Transient array index ${index} out of bounds for array of length ${array2.length} at slot ${slot}`);return array2[index]}set(contractAddress,slot,index,value){let array2=this.readArrayAt(contractAddress,slot);if(index<0||index>=array2.length)throw new Error(`Transient array index ${index} out of bounds for array of length ${array2.length} at slot ${slot}`);array2[index]=value}remove(contractAddress,slot,index){let array2=this.readArrayAt(contractAddress,slot);if(index<0||index>=array2.length)throw new Error(`Transient array index ${index} out of bounds for array of length ${array2.length} at slot ${slot}`);array2.splice(index,1)}clear(contractAddress,slot){this.#arrays.delete(this.#key(contractAddress,slot))}};var OrderedSideEffect=class{static{__name(this,"OrderedSideEffect")}sideEffect;counter;constructor(sideEffect,counter){this.sideEffect=sideEffect,this.counter=counter}};async function generateSimulatedProvingResult(privateExecutionResult,debugFunctionNameGetter,node,minRevertibleSideEffectCounterOverride){let taggedPrivateLogs=[],l2ToL1Messages=[],contractClassLogsHashes=[],publicCallRequests=[],executionSteps=[],scopedNoteHashes=[],scopedNullifiers=[],noteHashReadRequests=[],nullifierReadRequests=[],publicTeardownCallRequest,expirationTimestamp=privateExecutionResult.entrypoint.publicInputs.anchorBlockHeader.globalVariables.timestamp+BigInt(86400),feePayer=AztecAddress.zero(),executions=[privateExecutionResult.entrypoint];for(;executions.length!==0;){let execution=executions.shift();executions.unshift(...execution.nestedExecutionResults);let callExpirationTimestamp=execution.publicInputs.expirationTimestamp;callExpirationTimestamp!==0n&&callExpirationTimestamp<expirationTimestamp&&(expirationTimestamp=callExpirationTimestamp);let{contractAddress}=execution.publicInputs.callContext;if(execution.publicInputs.isFeePayer){if(!feePayer.isZero())throw new Error("Multiple fee payers found in private execution result");feePayer=contractAddress}if(scopedNoteHashes.push(...execution.publicInputs.noteHashes.getActiveItems().filter(nh=>!nh.isEmpty()).map(nh=>nh.scope(contractAddress))),scopedNullifiers.push(...execution.publicInputs.nullifiers.getActiveItems().map(n=>n.scope(contractAddress))),taggedPrivateLogs.push(...await Promise.all(execution.publicInputs.privateLogs.getActiveItems().map(async metadata=>(metadata.log.fields[0]=await computeSiloedPrivateLogFirstField(contractAddress,metadata.log.fields[0]),new OrderedSideEffect(metadata,metadata.counter))))),noteHashReadRequests.push(...execution.publicInputs.noteHashReadRequests.getActiveItems()),nullifierReadRequests.push(...execution.publicInputs.nullifierReadRequests.getActiveItems()),l2ToL1Messages.push(...execution.publicInputs.l2ToL1Msgs.getActiveItems().map(message=>new OrderedSideEffect(message.message.scope(contractAddress),message.counter))),contractClassLogsHashes.push(...execution.publicInputs.contractClassLogsHashes.getActiveItems().map(contractClassLogHash=>new OrderedSideEffect(contractClassLogHash.logHash.scope(contractAddress),contractClassLogHash.counter))),publicCallRequests.push(...execution.publicInputs.publicCallRequests.getActiveItems().map(callRequest=>new OrderedSideEffect(callRequest.inner,callRequest.counter))),publicTeardownCallRequest!==void 0&&!execution.publicInputs.publicTeardownCallRequest.isEmpty())throw new Error("Trying to set multiple teardown requests");publicTeardownCallRequest=execution.publicInputs.publicTeardownCallRequest.isEmpty()?publicTeardownCallRequest:execution.publicInputs.publicTeardownCallRequest,executionSteps.push({functionName:await debugFunctionNameGetter(execution.publicInputs.callContext.contractAddress,execution.publicInputs.callContext.functionSelector),timings:execution.profileResult?.timings??{witgen:0,oracles:{}},bytecode:execution.acir,vk:execution.vk,witness:execution.partialWitness})}let noteHashNullifierCounterMap=collectNoteHashNullifierCounterMap(privateExecutionResult),minRevertibleSideEffectCounter=minRevertibleSideEffectCounterOverride??getFinalMinRevertibleSideEffectCounter(privateExecutionResult),scopedNoteHashesCLA=new ClaimedLengthArray(padArrayEnd(scopedNoteHashes,ScopedNoteHash.empty(),64),scopedNoteHashes.length),scopedNullifiersCLA=new ClaimedLengthArray(padArrayEnd(scopedNullifiers,ScopedNullifier.empty(),64),scopedNullifiers.length),{filteredNoteHashes,filteredNullifiers,filteredPrivateLogs}=squashTransientSideEffects(taggedPrivateLogs,scopedNoteHashesCLA,scopedNullifiersCLA,noteHashNullifierCounterMap,minRevertibleSideEffectCounter);await verifyReadRequests(node,await privateExecutionResult.entrypoint.publicInputs.anchorBlockHeader.hash(),noteHashReadRequests,nullifierReadRequests,scopedNoteHashesCLA,scopedNullifiersCLA);let siloedNoteHashes=await Promise.all(filteredNoteHashes.sort((a,b)=>a.counter-b.counter).map(async nh=>new OrderedSideEffect(await siloNoteHash(nh.contractAddress,nh.value),nh.counter))),siloedNullifiers=await Promise.all(filteredNullifiers.sort((a,b)=>a.counter-b.counter).map(async n=>new OrderedSideEffect(await siloNullifier(n.contractAddress,n.value),n.counter))),constantData=new TxConstantData(privateExecutionResult.entrypoint.publicInputs.anchorBlockHeader,privateExecutionResult.entrypoint.publicInputs.txContext,getVKTreeRoot(),protocolContractsHash),hasPublicCalls=privateExecutionResult.publicFunctionCalldata.length!==0,inputsForRollup,inputsForPublic,gasUsed,sortByCounter2=__name((a,b)=>a.counter-b.counter,"sortByCounter"),getEffect=__name(orderedSideEffect=>orderedSideEffect.sideEffect,"getEffect"),isPrivateOnlyTx=privateExecutionResult.publicFunctionCalldata.length===0,[nonRevertibleNullifiers,revertibleNullifiers]=splitOrderedSideEffects(siloedNullifiers,minRevertibleSideEffectCounter),nonceGenerator=privateExecutionResult.firstNullifier;if(nonRevertibleNullifiers.length===0)nonRevertibleNullifiers.push(nonceGenerator);else if(!nonRevertibleNullifiers[0].equals(nonceGenerator))throw new Error("The first non revertible nullifier should be equal to the nonce generator. This is a bug!");if(isPrivateOnlyTx){let uniqueNoteHashes=await Promise.all(siloedNoteHashes.map(async(orderedSideEffect,i)=>{let siloedNoteHash=orderedSideEffect.sideEffect,nonce=await computeNoteHashNonce(nonceGenerator,i);return await computeUniqueNoteHash(nonce,siloedNoteHash)})),accumulatedDataForRollup=new PrivateToRollupAccumulatedData(padArrayEnd(uniqueNoteHashes,Fr.ZERO,64),padArrayEnd(nonRevertibleNullifiers.concat(revertibleNullifiers),Fr.ZERO,64),padArrayEnd(l2ToL1Messages.sort(sortByCounter2).map(getEffect),ScopedL2ToL1Message.empty(),8),padArrayEnd(filteredPrivateLogs.sort(sortByCounter2).map(getEffect),PrivateLog.empty(),64),padArrayEnd(contractClassLogsHashes.sort(sortByCounter2).map(getEffect),ScopedLogHash.empty(),1));gasUsed=meterGasUsed(accumulatedDataForRollup,isPrivateOnlyTx),inputsForRollup=new PartialPrivateTailPublicInputsForRollup(accumulatedDataForRollup)}else{let[nonRevertibleNoteHashes,revertibleNoteHashes]=splitOrderedSideEffects(siloedNoteHashes,minRevertibleSideEffectCounter),nonRevertibleUniqueNoteHashes=await Promise.all(nonRevertibleNoteHashes.map(async(noteHash,i)=>{let nonce=await computeNoteHashNonce(nonceGenerator,i);return await computeUniqueNoteHash(nonce,noteHash)})),[nonRevertibleL2ToL1Messages,revertibleL2ToL1Messages]=splitOrderedSideEffects(l2ToL1Messages.sort(sortByCounter2),minRevertibleSideEffectCounter),[nonRevertibleTaggedPrivateLogs,revertibleTaggedPrivateLogs]=splitOrderedSideEffects(filteredPrivateLogs,minRevertibleSideEffectCounter),[nonRevertibleContractClassLogHashes,revertibleContractClassLogHashes]=splitOrderedSideEffects(contractClassLogsHashes.sort(sortByCounter2),minRevertibleSideEffectCounter),[nonRevertiblePublicCallRequests,revertiblePublicCallRequests]=splitOrderedSideEffects(publicCallRequests.sort(sortByCounter2),minRevertibleSideEffectCounter),nonRevertibleData=new PrivateToPublicAccumulatedData(padArrayEnd(nonRevertibleUniqueNoteHashes,Fr.ZERO,64),padArrayEnd(nonRevertibleNullifiers,Fr.ZERO,64),padArrayEnd(nonRevertibleL2ToL1Messages,ScopedL2ToL1Message.empty(),8),padArrayEnd(nonRevertibleTaggedPrivateLogs,PrivateLog.empty(),64),padArrayEnd(nonRevertibleContractClassLogHashes,ScopedLogHash.empty(),1),padArrayEnd(nonRevertiblePublicCallRequests,PublicCallRequest.empty(),32)),revertibleData=new PrivateToPublicAccumulatedData(padArrayEnd(revertibleNoteHashes,Fr.ZERO,64),padArrayEnd(revertibleNullifiers,Fr.ZERO,64),padArrayEnd(revertibleL2ToL1Messages,ScopedL2ToL1Message.empty(),8),padArrayEnd(revertibleTaggedPrivateLogs,PrivateLog.empty(),64),padArrayEnd(revertibleContractClassLogHashes,ScopedLogHash.empty(),1),padArrayEnd(revertiblePublicCallRequests,PublicCallRequest.empty(),32));gasUsed=meterGasUsed(revertibleData,isPrivateOnlyTx).add(meterGasUsed(nonRevertibleData,isPrivateOnlyTx)),publicTeardownCallRequest&&(gasUsed=gasUsed.add(privateExecutionResult.entrypoint.publicInputs.txContext.gasSettings.teardownGasLimits)),inputsForPublic=new PartialPrivateTailPublicInputsForPublic(nonRevertibleData,revertibleData,publicTeardownCallRequest??PublicCallRequest.empty())}return{publicInputs:new PrivateKernelTailCircuitPublicInputs(constantData,gasUsed.add(Gas.from({l2Gas:isPrivateOnlyTx?44e4:54e4,daGas:96})),feePayer,expirationTimestamp,hasPublicCalls?inputsForPublic:void 0,hasPublicCalls?void 0:inputsForRollup),chonkProof:ChonkProof.empty(),executionSteps}}__name(generateSimulatedProvingResult,"generateSimulatedProvingResult");function squashTransientSideEffects(taggedPrivateLogs,scopedNoteHashesCLA,scopedNullifiersCLA,noteHashNullifierCounterMap,minRevertibleSideEffectCounter){let{numTransientData,hints:transientDataHints}=buildTransientDataHints(scopedNoteHashesCLA,scopedNullifiersCLA,[],[],[],noteHashNullifierCounterMap,minRevertibleSideEffectCounter),squashedNoteHashCounters=new Set,squashedNullifierCounters=new Set;for(let i=0;i<numTransientData;i++){let hint=transientDataHints[i];squashedNoteHashCounters.add(scopedNoteHashesCLA.array[hint.noteHashIndex].counter),squashedNullifierCounters.add(scopedNullifiersCLA.array[hint.nullifierIndex].counter)}return{filteredNoteHashes:scopedNoteHashesCLA.getActiveItems().filter(nh=>!squashedNoteHashCounters.has(nh.counter)),filteredNullifiers:scopedNullifiersCLA.getActiveItems().filter(n=>!squashedNullifierCounters.has(n.counter)),filteredPrivateLogs:taggedPrivateLogs.filter(item=>!squashedNoteHashCounters.has(item.sideEffect.noteHashCounter)).map(item=>new OrderedSideEffect(item.sideEffect.log,item.counter))}}__name(squashTransientSideEffects,"squashTransientSideEffects");async function verifyReadRequests(node,anchorBlockHash,noteHashReadRequests,nullifierReadRequests,scopedNoteHashesCLA,scopedNullifiersCLA){let noteHashReadRequestsCLA=new ClaimedLengthArray(padArrayEnd(noteHashReadRequests,ScopedReadRequest.empty(),64),noteHashReadRequests.length),nullifierReadRequestsCLA=new ClaimedLengthArray(padArrayEnd(nullifierReadRequests,ScopedReadRequest.empty(),64),nullifierReadRequests.length),noteHashResetActions=getNoteHashReadRequestResetActions(noteHashReadRequestsCLA,scopedNoteHashesCLA),nullifierResetActions=getNullifierReadRequestResetActions(nullifierReadRequestsCLA,scopedNullifiersCLA),settledNoteHashReads=[];for(let i=0;i<noteHashResetActions.actions.length;i++)noteHashResetActions.actions[i]===ReadRequestActionEnum.READ_AS_SETTLED&&settledNoteHashReads.push({index:i,value:noteHashReadRequests[i].value});let settledNullifierReads=[];for(let i=0;i<nullifierResetActions.actions.length;i++)nullifierResetActions.actions[i]===ReadRequestActionEnum.READ_AS_SETTLED&&settledNullifierReads.push({index:i,value:nullifierReadRequests[i].value});let[noteHashResults,nullifierResults]=await Promise.all([settledNoteHashReads.length>0?node.findLeavesIndexes(anchorBlockHash,MerkleTreeId.NOTE_HASH_TREE,settledNoteHashReads.map(({value})=>value)):[],settledNullifierReads.length>0?node.findLeavesIndexes(anchorBlockHash,MerkleTreeId.NULLIFIER_TREE,settledNullifierReads.map(({value})=>value)):[]]);for(let i=0;i<settledNoteHashReads.length;i++)if(!noteHashResults[i])throw new Error(`Note hash read request at index ${settledNoteHashReads[i].index} is reading an unknown note hash: ${settledNoteHashReads[i].value}`);for(let i=0;i<settledNullifierReads.length;i++)if(!nullifierResults[i])throw new Error(`Nullifier read request at index ${settledNullifierReads[i].index} is reading an unknown nullifier: ${settledNullifierReads[i].value}`)}__name(verifyReadRequests,"verifyReadRequests");function splitOrderedSideEffects(effects,minRevertibleSideEffectCounter){let revertibleSideEffects=[],nonRevertibleSideEffects=[];return effects.forEach(effect=>{minRevertibleSideEffectCounter===0||effect.counter<minRevertibleSideEffectCounter?nonRevertibleSideEffects.push(effect.sideEffect):revertibleSideEffects.push(effect.sideEffect)}),[nonRevertibleSideEffects,revertibleSideEffects]}__name(splitOrderedSideEffects,"splitOrderedSideEffects");function meterGasUsed(data,isPrivateOnlyTx){let meteredDAFields=0,meteredL2Gas=0,numNoteHashes=arrayNonEmptyLength(data.noteHashes,hash5=>hash5.isEmpty());meteredDAFields+=numNoteHashes,meteredL2Gas+=numNoteHashes*(isPrivateOnlyTx?9200:19275);let numNullifiers=arrayNonEmptyLength(data.nullifiers,nullifier=>nullifier.isEmpty());meteredDAFields+=numNullifiers,meteredL2Gas+=numNullifiers*(isPrivateOnlyTx?16e3:30800);let numL2toL1Messages=arrayNonEmptyLength(data.l2ToL1Msgs,msg=>msg.isEmpty());meteredDAFields+=numL2toL1Messages,meteredL2Gas+=numL2toL1Messages*(isPrivateOnlyTx?5200:5239);let numPrivatelogs=arrayNonEmptyLength(data.privateLogs,log2=>log2.isEmpty());meteredDAFields+=data.privateLogs.reduce((acc,log2)=>log2.isEmpty()?acc:acc+log2.emittedLength+1,0),meteredL2Gas+=numPrivatelogs*2500;let numContractClassLogs=arrayNonEmptyLength(data.contractClassLogsHashes,log2=>log2.isEmpty());meteredDAFields+=data.contractClassLogsHashes.reduce((acc,log2)=>log2.isEmpty()?acc:acc+log2.logHash.length+1,0),meteredL2Gas+=numContractClassLogs*73e3;let meteredDAGas=meteredDAFields*32;if(data.publicCallRequests){let numPublicCallRequests=arrayNonEmptyLength(data.publicCallRequests,req=>req.isEmpty());meteredL2Gas+=numPublicCallRequests*2e4}return Gas.from({l2Gas:meteredL2Gas,daGas:meteredDAGas})}__name(meterGasUsed,"meterGasUsed");async function enrichSimulationError(err,contractStore,contractClassService,anchorHeader,logger3){let mentionedFunctions=new Map;err.getCallStack().forEach(({contractAddress,functionSelector})=>{mentionedFunctions.has(contractAddress.toString())||mentionedFunctions.set(contractAddress.toString(),new Set),functionSelector&&mentionedFunctions.get(contractAddress.toString()).add(functionSelector)}),await Promise.all([...mentionedFunctions.entries()].map(async([contractAddress,fnSelectors])=>{let parsedContractAddress=AztecAddress.fromStringUnsafe(contractAddress),classId=await contractClassService.getCurrentClassId(parsedContractAddress,anchorHeader),artifact=classId&&await contractStore.getContractArtifact(classId);if(artifact){err.enrichWithContractName(parsedContractAddress,artifact.name);let selectorToNameMap=new Map;await Promise.all(artifact.functions.map(async fn=>{let selector=await FunctionSelector.fromNameAndParameters(fn);selectorToNameMap.set(selector.toString(),fn.name)}));for(let fnSelector of fnSelectors)selectorToNameMap.has(fnSelector.toString())?err.enrichWithFunctionName(parsedContractAddress,fnSelector,selectorToNameMap.get(fnSelector.toString())):logger3.warn(`Could not find function artifact in contract ${artifact.name} for function '${fnSelector}' when enriching error callstack`)}else logger3.warn(`Could not find contract in database for address: ${parsedContractAddress} when enriching error callstack`)}))}__name(enrichSimulationError,"enrichSimulationError");async function enrichPublicSimulationError(err,contractStore,contractClassService,anchorHeader,logger3){let callStack=err.getCallStack(),originalFailingFunction=callStack[callStack.length-1];if(!originalFailingFunction)throw new Error("Original failing function not found when enriching public simulation, missing callstack");let classId=await contractClassService.getCurrentClassId(originalFailingFunction.contractAddress,anchorHeader),artifact=classId&&await contractStore.getPublicFunctionArtifact(classId);if(!artifact)throw new Error(`Artifact not found when enriching public simulation error. Contract address: ${originalFailingFunction.contractAddress}.`);let assertionMessage=resolveAssertionMessageFromRevertData(err.revertData,artifact);assertionMessage&&err.setOriginalMessage(err.getOriginalMessage()+`${assertionMessage}`);let debugInfo=await contractStore.getPublicFunctionDebugMetadata(classId),noirCallStack=err.getNoirCallStack();if(debugInfo){if(isNoirCallStackUnresolved(noirCallStack))try{let parsedCallStack=resolveOpcodeLocations(noirCallStack,debugInfo.debugSymbols,debugInfo.files,0);err.setNoirCallStack(parsedCallStack)}catch(err2){logger3.warn(`Could not resolve noir call stack for ${originalFailingFunction.contractAddress.toString()}:${originalFailingFunction.functionName?.toString()??""}: ${err2}`)}await enrichSimulationError(err,contractStore,contractClassService,anchorHeader,logger3)}}__name(enrichPublicSimulationError,"enrichPublicSimulationError");var JobCoordinator=class{static{__name(this,"JobCoordinator")}log;kvStore;#currentJobId;#stores=new Map;constructor(kvStore,bindings){this.kvStore=kvStore,this.log=createLogger("pxe:job_coordinator",bindings)}registerStore(store){if(this.#stores.has(store.storeName))throw new Error(`Store "${store.storeName}" is already registered`);this.#stores.set(store.storeName,store),this.log.debug(`Registered staged store: ${store.storeName}`)}registerStores(stores){for(let store of stores)this.registerStore(store)}beginJob(){if(this.#currentJobId)throw new Error(`Cannot begin job: job ${this.#currentJobId} is already in progress. This should not happen - ensure jobs are properly committed or aborted.`);let jobId=randomBytes(8).toString("hex");return this.#currentJobId=jobId,this.log.debug(`Started job ${jobId}`),jobId}async commitJob(jobId){if(!this.#currentJobId||this.#currentJobId!==jobId)throw new Error(`Cannot commit job ${jobId}: no matching job in progress. Current job: ${this.#currentJobId??"none"}`);this.log.debug(`Committing job ${jobId}`),await this.kvStore.transactionAsync(async()=>{for(let store of this.#stores.values())await store.commit(jobId)}),this.#currentJobId=void 0,this.log.debug(`Job ${jobId} committed successfully`)}async abortJob(jobId){(!this.#currentJobId||this.#currentJobId!==jobId)&&this.log.warn(`Abort called for job ${jobId} but current job is ${this.#currentJobId??"none"}`),this.log.debug(`Aborting job ${jobId}`);for(let store of this.#stores.values())await store.discardStaged(jobId);this.#currentJobId=void 0,this.log.debug(`Job ${jobId} aborted`)}hasJobInProgress(){return this.#currentJobId!==void 0}};var ResolvedTx=class _ResolvedTx{static{__name(this,"ResolvedTx")}txHash;uniqueNoteHashesInTx;firstNullifierInTx;blockNumber;blockHash;constructor(txHash,uniqueNoteHashesInTx,firstNullifierInTx,blockNumber,blockHash){this.txHash=txHash,this.uniqueNoteHashesInTx=uniqueNoteHashesInTx,this.firstNullifierInTx=firstNullifierInTx,this.blockNumber=blockNumber,this.blockHash=blockHash}toFields(){return[this.txHash.hash,...serializeBoundedVec(this.uniqueNoteHashesInTx,64),this.firstNullifierInTx,new Fr(this.blockNumber),this.blockHash]}static empty(){return new _ResolvedTx(TxHash.zero(),[],Fr.ZERO,0,Fr.ZERO)}};function serializeBoundedVec(values,maxLength){return[...padArrayEnd(values,Fr.ZERO,maxLength,`Attempted to serialize ${values} values into a BoundedVec with max length ${maxLength}`),new Fr(values.length)]}__name(serializeBoundedVec,"serializeBoundedVec");var TxResolverService=class{static{__name(this,"TxResolverService")}aztecNode;constructor(aztecNode){this.aztecNode=aztecNode}async resolveTxs(txHashes,anchorBlockNumber){let nonZeroTxHashes=txHashes.filter(h=>!h.isZero()).map(h=>TxHash.fromField(h)),uniqueTxHashes=uniqueBy(nonZeroTxHashes,h=>h.toString()),fetched=await Promise.all(uniqueTxHashes.map(h=>this.aztecNode.getTxReceipt(h,{includeTxEffect:!0}))),txEffects=new Map(uniqueTxHashes.map((h,i)=>{let receipt=fetched[i];return!receipt.isMined()||!receipt.txEffect?[h.toString(),void 0]:[h.toString(),{data:receipt.txEffect,l2BlockNumber:receipt.blockNumber,l2BlockHash:receipt.blockHash,txIndexInBlock:receipt.txIndexInBlock,slotNumber:receipt.slotNumber}]}).filter(entry=>entry[1]!==void 0));return txHashes.map(txHashField=>{let txHash=TxHash.fromField(txHashField),txEffect=txEffects.get(txHash.toString());if(!txEffect||txEffect.l2BlockNumber>anchorBlockNumber)return null;let data=txEffect.data;if(data.nullifiers.length===0)throw new Error(`Tx effect for ${txHash} has no nullifiers`);return new ResolvedTx(data.txHash,data.noteHashes,data.nullifiers[0],txEffect.l2BlockNumber,txEffect.l2BlockHash.toFr())})}};import{getVKTreeRoot as getVKTreeRoot2}from"@aztec/noir-protocol-circuits-types/vk-tree";import{privateKernelResetDimensionsConfig}from"@aztec/noir-protocol-circuits-types/client";var NULL_SIMULATE_OUTPUT={publicInputs:PrivateKernelCircuitPublicInputs.empty(),verificationKey:VerificationKeyData.empty(),outputWitness:new Map,bytecode:Buffer.from([])};import{getVKIndex,getVKSiblingPath}from"@aztec/noir-protocol-circuits-types/vk-tree";var DelayedPublicMutableValuesWithHash=class{static{__name(this,"DelayedPublicMutableValuesWithHash")}dpmv;constructor(svc,sdc){this.dpmv=new DelayedPublicMutableValues(svc,sdc)}async toFields(){return[...this.dpmv.toFields(),await this.dpmv.hash()]}async writeToTree(delayedPublicMutableSlot,storageWrite){let fields=await this.toFields();for(let i=0;i<fields.length;i++)await storageWrite(delayedPublicMutableSlot.add(new Fr(i)),fields[i])}static async getContractUpdateSlots(contractAddress){let delayedPublicMutableSlot=await deriveStorageSlotInMap(new Fr(1),contractAddress),delayedPublicMutableHashSlot=delayedPublicMutableSlot.add(new Fr(DELAYED_PUBLIC_MUTABLE_VALUES_LEN));return{delayedPublicMutableSlot,delayedPublicMutableHashSlot}}};async function toArray(iterator){let arr=[];for await(let i of iterator)arr.push(i);return arr}__name(toArray,"toArray");function secretKeyStorageSuffix(prefix){return prefix==="n"?"nhk_m":`${prefix}sk_m`}__name(secretKeyStorageSuffix,"secretKeyStorageSuffix");async function completeAccountKeys(keys){let{masterNullifierHidingSecretKey,masterIncomingViewingSecretKey,masterOutgoingViewingSecretKey,masterTaggingSecretKey,masterMessageSigningPublicKey,masterFallbackPublicKey}=keys,masterNullifierHidingPublicKey=await derivePublicKeyFromSecretKey(masterNullifierHidingSecretKey),masterIncomingViewingPublicKey=await derivePublicKeyFromSecretKey(masterIncomingViewingSecretKey),masterOutgoingViewingPublicKey=await derivePublicKeyFromSecretKey(masterOutgoingViewingSecretKey),masterTaggingPublicKey=await derivePublicKeyFromSecretKey(masterTaggingSecretKey);for(let[name,publicKey]of Object.entries({masterNullifierHidingPublicKey,masterIncomingViewingPublicKey,masterOutgoingViewingPublicKey,masterTaggingPublicKey,masterMessageSigningPublicKey,masterFallbackPublicKey}))if(publicKey.isInfinite)throw new Error(`Cannot register an account with an infinity ${name}.`);let publicKeys=new PublicKeys(await hashPublicKey(masterNullifierHidingPublicKey),masterIncomingViewingPublicKey,await hashPublicKey(masterOutgoingViewingPublicKey),await hashPublicKey(masterTaggingPublicKey),await hashPublicKey(masterMessageSigningPublicKey),await hashPublicKey(masterFallbackPublicKey));return{masterNullifierHidingSecretKey,masterIncomingViewingSecretKey,masterOutgoingViewingSecretKey,masterTaggingSecretKey,masterNullifierHidingPublicKey,masterOutgoingViewingPublicKey,masterTaggingPublicKey,publicKeys}}__name(completeAccountKeys,"completeAccountKeys");var KeyStore=class{static{__name(this,"KeyStore")}static SCHEMA_VERSION=1;#db;#keys;constructor(database){this.#db=database,this.#keys=database.openMap("key_store")}async addAccount(keys,partialAddress){let accountKeys=await completeAccountKeys(keys);return this.#storeAccountKeys(accountKeys,partialAddress)}async getAccounts(){return(await this.#db.transactionAsync(()=>toArray(this.#keys.keysAsync()))).filter(key=>key.endsWith("-ivsk_m")).map(key=>key.split("-")[0]).map(account=>AztecAddress.fromStringUnsafe(account))}async hasAccount(account){return!!await this.#db.transactionAsync(()=>this.#keys.getAsync(`${account.toString()}-ivsk_m`))}getKeyValidationRequest(pkMHash,contractAddress){return this.#db.transactionAsync(async()=>{let[keyPrefix,account]=await this.getKeyPrefixAndAccount(pkMHash),pkMBuffer=await this.#keys.getAsync(`${account.toString()}-${keyPrefix}pk_m`);if(!pkMBuffer)throw new Error(`Could not find ${keyPrefix}pk_m for account ${account.toString()} whose address was successfully obtained with ${keyPrefix}pk_m_hash ${pkMHash.toString()}.`);let pkM=Point.fromBuffer(pkMBuffer),skStorageSuffix=secretKeyStorageSuffix(keyPrefix),skMBuffer=await this.#keys.getAsync(`${account.toString()}-${skStorageSuffix}`);if(!skMBuffer)throw new Error(`Could not find ${skStorageSuffix} for account ${account.toString()} whose address was successfully obtained with ${keyPrefix}pk_m_hash ${pkMHash.toString()}.`);let skM=GrumpkinScalar.fromBuffer(skMBuffer);if(!(await hashPublicKey(pkM)).equals(pkMHash))throw new Error(`Could not find ${keyPrefix}pkM for ${keyPrefix}pk_m_hash ${pkMHash.toString()}.`);if(!(await derivePublicKeyFromSecretKey(skM)).equals(pkM))throw new Error(`Could not derive ${keyPrefix}pkM from ${keyPrefix}skM.`);let skApp=await computeAppSecretKey(skM,contractAddress,keyPrefix);return new KeyValidationRequest(pkMHash,skApp)})}async getMasterNullifierHidingPublicKey(account){return Point.fromBuffer(await this.#getMasterKeyBuffer(account,"npk_m"))}async getMasterIncomingViewingPublicKey(account){return Point.fromBuffer(await this.#getMasterKeyBuffer(account,"ivpk_m"))}async getMasterOutgoingViewingPublicKey(account){return Point.fromBuffer(await this.#getMasterKeyBuffer(account,"ovpk_m"))}async getMasterTaggingPublicKey(account){return Point.fromBuffer(await this.#getMasterKeyBuffer(account,"tpk_m"))}async getMasterIncomingViewingSecretKey(account){return GrumpkinScalar.fromBuffer(await this.#getMasterKeyBuffer(account,"ivsk_m"))}async getAccountSecretKeys(account){let[nhkM,ivskM,ovskM,tskM]=await this.#getMasterKeyBuffers(account,["nhk_m","ivsk_m","ovsk_m","tsk_m"]);return{masterNullifierHidingSecretKey:GrumpkinScalar.fromBuffer(nhkM),masterIncomingViewingSecretKey:GrumpkinScalar.fromBuffer(ivskM),masterOutgoingViewingSecretKey:GrumpkinScalar.fromBuffer(ovskM),masterTaggingSecretKey:GrumpkinScalar.fromBuffer(tskM)}}async getAppOutgoingViewingSecretKey(account,app){let masterOutgoingViewingSecretKey=GrumpkinScalar.fromBuffer(await this.#getMasterKeyBuffer(account,"ovsk_m"));return poseidon2HashWithSeparator([masterOutgoingViewingSecretKey.hi,masterOutgoingViewingSecretKey.lo,app],DomainSeparator.OVSK_M)}getMasterSecretKey(pkMHash){return this.#db.transactionAsync(async()=>{let[keyPrefix,account]=await this.getKeyPrefixAndAccount(pkMHash),skStorageSuffix=secretKeyStorageSuffix(keyPrefix),secretKeyBuffer=await this.#keys.getAsync(`${account.toString()}-${skStorageSuffix}`);if(!secretKeyBuffer)throw new Error(`Could not find ${skStorageSuffix} for ${keyPrefix}pk_m_hash ${pkMHash.toString()}. This should not happen.`);let skM=GrumpkinScalar.fromBuffer(secretKeyBuffer),derivedPkM=await derivePublicKeyFromSecretKey(skM);if(!(await hashPublicKey(derivedPkM)).equals(pkMHash))throw new Error(`Could not find ${skStorageSuffix} for ${keyPrefix}pk_m_hash ${pkMHash.toString()} in secret keys buffer.`);return skM})}accountHasKey(account,pkMHash){return this.#db.transactionAsync(async()=>{let pkMHashBuffer=serializeToBuffer(pkMHash);for(let prefix of KEY_PREFIXES){let stored=await this.#keys.getAsync(`${account.toString()}-${prefix}pk_m_hash`);if(stored&&Buffer.from(stored).equals(pkMHashBuffer))return!0}return!1})}async getKeyPrefixAndAccount(value){let valueBuffer=serializeToBuffer(value);for await(let[key,val]of this.#keys.entriesAsync())if(Buffer.from(val).equals(valueBuffer)){for(let prefix of KEY_PREFIXES)if(key.includes(`-${prefix}`)){let account=AztecAddress.fromStringUnsafe(key.split("-")[0]);return[prefix,account]}}throw new Error("Could not find key prefix.")}async#storeAccountKeys(accountKeys,partialAddress){let{masterNullifierHidingSecretKey,masterIncomingViewingSecretKey,masterOutgoingViewingSecretKey,masterTaggingSecretKey,masterNullifierHidingPublicKey,masterOutgoingViewingPublicKey,masterTaggingPublicKey,publicKeys}=accountKeys,completeAddress=await CompleteAddress.fromPublicKeysAndPartialAddress(publicKeys,partialAddress),{address:account}=completeAddress,masterIncomingViewingPublicKeyHash=await hashPublicKey(publicKeys.ivpkM);return await this.#db.transactionAsync(async()=>{await this.#keys.set(`${account.toString()}-ivsk_m`,masterIncomingViewingSecretKey.toBuffer()),await this.#keys.set(`${account.toString()}-ovsk_m`,masterOutgoingViewingSecretKey.toBuffer()),await this.#keys.set(`${account.toString()}-tsk_m`,masterTaggingSecretKey.toBuffer()),await this.#keys.set(`${account.toString()}-nhk_m`,masterNullifierHidingSecretKey.toBuffer()),await this.#keys.set(`${account.toString()}-npk_m`,masterNullifierHidingPublicKey.toBuffer()),await this.#keys.set(`${account.toString()}-ivpk_m`,publicKeys.ivpkM.toBuffer()),await this.#keys.set(`${account.toString()}-ovpk_m`,masterOutgoingViewingPublicKey.toBuffer()),await this.#keys.set(`${account.toString()}-tpk_m`,masterTaggingPublicKey.toBuffer()),await this.#keys.set(`${account.toString()}-npk_m_hash`,publicKeys.npkMHash.toBuffer()),await this.#keys.set(`${account.toString()}-ivpk_m_hash`,masterIncomingViewingPublicKeyHash.toBuffer()),await this.#keys.set(`${account.toString()}-ovpk_m_hash`,publicKeys.ovpkMHash.toBuffer()),await this.#keys.set(`${account.toString()}-tpk_m_hash`,publicKeys.tpkMHash.toBuffer())}),completeAddress}async#getMasterKeyBuffer(account,suffix){let[buffer]=await this.#getMasterKeyBuffers(account,[suffix]);return buffer}async#getMasterKeyBuffers(account,suffixes){let buffers=await this.#db.transactionAsync(()=>Promise.all(suffixes.map(suffix=>this.#keys.getAsync(`${account.toString()}-${suffix}`))));if(!buffers.every(buffer=>buffer!==void 0))throw new Error(`Account ${account.toString()} does not exist. Registered accounts: ${await this.getAccounts()}.`);return buffers}};var AddressStore=class{static{__name(this,"AddressStore")}#store;#completeAddresses;#completeAddressIndex;constructor(store){this.#store=store,this.#completeAddresses=this.#store.openArray("complete_addresses"),this.#completeAddressIndex=this.#store.openMap("complete_address_index")}addCompleteAddress(completeAddress){return this.#store.transactionAsync(async()=>{let addressString=completeAddress.address.toString(),buffer=completeAddress.toBuffer(),existing=await this.#completeAddressIndex.getAsync(addressString);if(existing===void 0){let index=await this.#completeAddresses.lengthAsync();return await this.#completeAddresses.push(buffer),await this.#completeAddressIndex.set(addressString,index),!0}else{let existingBuffer=await this.#completeAddresses.atAsync(existing);if(existingBuffer&&Buffer.from(existingBuffer).equals(buffer))return!1;throw new Error(`Complete address with aztec address ${addressString} but different public key or partial key already exists in memory database`)}})}getCompleteAddress(account){return this.#store.transactionAsync(async()=>{let index=await this.#completeAddressIndex.getAsync(account.toString());if(index===void 0)return;let value=await this.#completeAddresses.atAsync(index);return value?await CompleteAddress.fromBuffer(value):void 0})}getCompleteAddresses(){return this.#store.transactionAsync(async()=>await Promise.all((await toArray(this.#completeAddresses.valuesAsync())).map(v=>CompleteAddress.fromBuffer(v))))}};var AnchorBlockStore=class{static{__name(this,"AnchorBlockStore")}#store;#synchronizedHeader;constructor(store){this.#store=store,this.#synchronizedHeader=this.#store.openSingleton("header")}async setHeader(header){await this.#synchronizedHeader.set(header.toBuffer())}async getBlockHeader(){let headerBuffer=await this.#store.transactionAsync(()=>this.#synchronizedHeader.getAsync());if(!headerBuffer)throw new Error("Trying to get block header with a not-yet-synchronized PXE - this should never happen");return BlockHeader.fromBuffer(headerBuffer)}};var CapsuleStore=class{static{__name(this,"CapsuleStore")}storeName="capsule";#store;#capsules;#stagedCapsules;logger;constructor(store){this.#store=store,this.#capsules=this.#store.openMap("capsules"),this.#stagedCapsules=new Map,this.logger=createLogger("pxe:capsule-data-provider")}#getJobStagedCapsules(jobId){let jobStagedCapsules=this.#stagedCapsules.get(jobId);return jobStagedCapsules||(jobStagedCapsules=new Map,this.#stagedCapsules.set(jobId,jobStagedCapsules)),jobStagedCapsules}async#getFromStage(jobId,dbSlotKey){let staged=this.#getJobStagedCapsules(jobId).get(dbSlotKey),dbValue=await this.#loadCapsuleFromDb(dbSlotKey);return staged!==void 0?staged:dbValue}#setOnStage(jobId,dbSlotKey,capsuleData){this.#getJobStagedCapsules(jobId).set(dbSlotKey,capsuleData)}#deleteOnStage(jobId,dbSlotKey){this.#getJobStagedCapsules(jobId).set(dbSlotKey,null)}async#loadCapsuleFromDb(dbSlotKey){let dataBuffer=await this.#capsules.getAsync(dbSlotKey);return dataBuffer||null}async commit(jobId){let jobStagedCapsules=this.#getJobStagedCapsules(jobId);for(let[key,value]of jobStagedCapsules)value===null?await this.#capsules.delete(key):await this.#capsules.set(key,value);this.#stagedCapsules.delete(jobId)}discardStaged(jobId){return this.#stagedCapsules.delete(jobId),Promise.resolve()}setCapsule(contractAddress,slot,capsule,jobId,scope){let dbSlotKey=dbSlotToKey(contractAddress,slot,scope);this.#setOnStage(jobId,dbSlotKey,Buffer.concat(capsule.map(value=>value.toBuffer())))}getCapsule(contractAddress,slot,jobId,scope){return this.#store.transactionAsync(()=>this.#getCapsuleInternal(contractAddress,slot,jobId,scope))}async#getCapsuleInternal(contractAddress,slot,jobId,scope){let dataBuffer=await this.#getFromStage(jobId,dbSlotToKey(contractAddress,slot,scope));if(!dataBuffer)return this.logger.trace(`Data not found for contract ${contractAddress.toString()} and slot ${slot.toString()}`),null;let capsule=[];for(let i=0;i<dataBuffer.length;i+=Fr.SIZE_IN_BYTES)capsule.push(Fr.fromBuffer(dataBuffer.subarray(i,i+Fr.SIZE_IN_BYTES)));return capsule}deleteCapsule(contractAddress,slot,jobId,scope){this.#deleteOnStage(jobId,dbSlotToKey(contractAddress,slot,scope))}copyCapsule(contractAddress,srcSlot,dstSlot,numEntries,jobId,scope){return this.#store.transactionAsync(async()=>{let indexes=Array.from(Array(numEntries).keys());srcSlot.lt(dstSlot)&&indexes.reverse();for(let i of indexes){let currentSrcSlot=dbSlotToKey(contractAddress,srcSlot.add(new Fr(i)),scope),currentDstSlot=dbSlotToKey(contractAddress,dstSlot.add(new Fr(i)),scope),toCopy=await this.#getFromStage(jobId,currentSrcSlot);if(!toCopy)throw new Error(`Attempted to copy empty slot ${currentSrcSlot} for contract ${contractAddress.toString()}`);this.#setOnStage(jobId,currentDstSlot,toCopy)}})}appendToCapsuleArray(contractAddress,baseSlot,content,jobId,scope){return this.#store.transactionAsync(async()=>{let lengthData=await this.#getCapsuleInternal(contractAddress,baseSlot,jobId,scope),currentLength=lengthData?lengthData[0].toNumber():0;for(let i=0;i<content.length;i++){let nextSlot=arraySlot(baseSlot,currentLength+i);this.setCapsule(contractAddress,nextSlot,content[i],jobId,scope)}let newLength=currentLength+content.length;this.setCapsule(contractAddress,baseSlot,[new Fr(newLength)],jobId,scope)})}readCapsuleArray(contractAddress,baseSlot,jobId,scope){return this.#store.transactionAsync(async()=>{let maybeLength=await this.#getCapsuleInternal(contractAddress,baseSlot,jobId,scope),length=maybeLength?maybeLength[0].toBigInt():0n,values=[];for(let i=0;i<length;i++){let currentValue=await this.#getCapsuleInternal(contractAddress,arraySlot(baseSlot,i),jobId,scope);if(currentValue==null)throw new Error(`Expected non-empty value at capsule array in base slot ${baseSlot} at index ${i} for contract ${contractAddress}`);values.push(currentValue)}return values})}setCapsuleArray(contractAddress,baseSlot,content,jobId,scope){return this.#store.transactionAsync(async()=>{let maybeLength=await this.#getCapsuleInternal(contractAddress,baseSlot,jobId,scope),originalLength=maybeLength?maybeLength[0].toNumber():0;this.setCapsule(contractAddress,baseSlot,[new Fr(content.length)],jobId,scope);for(let i=0;i<content.length;i++)this.setCapsule(contractAddress,arraySlot(baseSlot,i),content[i],jobId,scope);for(let i=content.length;i<originalLength;i++)this.deleteCapsule(contractAddress,arraySlot(baseSlot,i),jobId,scope)})}};function dbSlotToKey(contractAddress,slot,scope){return[contractAddress.toString(),scope.toString(),slot.toString()].join(":")}__name(dbSlotToKey,"dbSlotToKey");function arraySlot(baseSlot,index){return baseSlot.add(new Fr(1)).add(new Fr(index))}__name(arraySlot,"arraySlot");var PrivateFunctionsTree=class _PrivateFunctionsTree{static{__name(this,"PrivateFunctionsTree")}privateFunctions;tree;constructor(privateFunctions){this.privateFunctions=privateFunctions}static async create(artifact){let privateFunctions=await Promise.all(artifact.functions.filter(fn=>fn.functionType===FunctionType.PRIVATE).map(getContractClassPrivateFunctionFromArtifact));return new _PrivateFunctionsTree(privateFunctions)}async getFunctionMembershipWitness(selector){let fn=this.privateFunctions.find(f=>f.selector.equals(selector));if(!fn)throw new Error(`Private function with selector ${selector.toString()} not found in contract class.`);let leaf=await computePrivateFunctionLeaf(fn),tree=await this.getTree(),index=tree.getIndex(leaf),path=tree.getSiblingPath(index);return new MembershipWitness(7,BigInt(index),assertLength(path.map(Fr.fromBuffer),7))}async getTree(){return this.tree||(this.tree=await computePrivateFunctionsTree(this.privateFunctions)),this.tree}};var VERSION5=1,SerializableContractClassData=class _SerializableContractClassData{static{__name(this,"SerializableContractClassData")}version=VERSION5;id;artifactHash;privateFunctionsRoot;publicBytecodeCommitment;privateFunctions;constructor(data){this.id=data.id,this.artifactHash=data.artifactHash,this.privateFunctionsRoot=data.privateFunctionsRoot,this.publicBytecodeCommitment=data.publicBytecodeCommitment,this.privateFunctions=data.privateFunctions}toBuffer(){return serializeToBuffer(numToUInt8(this.version),this.id,this.artifactHash,this.privateFunctionsRoot,this.publicBytecodeCommitment,this.privateFunctions.length,...this.privateFunctions.map(fn=>serializeToBuffer(fn.selector,fn.vkHash)))}static fromBuffer(bufferOrReader){let reader=BufferReader.asReader(bufferOrReader),version2=reader.readUInt8();if(version2!==VERSION5)throw new Error(`Unexpected contract class data version ${version2}`);return new _SerializableContractClassData({id:reader.readObject(Fr),artifactHash:reader.readObject(Fr),privateFunctionsRoot:reader.readObject(Fr),publicBytecodeCommitment:reader.readObject(Fr),privateFunctions:reader.readVector({fromBuffer:__name(r2=>({selector:r2.readObject(FunctionSelector),vkHash:r2.readObject(Fr)}),"fromBuffer")})})}},ContractStore=class{static{__name(this,"ContractStore")}#privateFunctionTrees=new Map;#contractArtifactCache=new Map;#store;#contractArtifacts;#contractClassData;#contractInstances;constructor(store){this.#store=store,this.#contractArtifacts=store.openMap("contract_artifacts"),this.#contractClassData=store.openMap("contract_classes"),this.#contractInstances=store.openMap("contracts_instances")}async addContractArtifact(contract,contractClassWithIdAndPreimage){let contractClass=contractClassWithIdAndPreimage??await getContractClassFromArtifact(contract),key=contractClass.id.toString();if(this.#contractArtifactCache.has(key))return contractClass.id;let privateFunctions=contract.functions.filter(functionArtifact=>functionArtifact.functionType===FunctionType.PRIVATE),privateSelectors=await Promise.all(privateFunctions.map(async fn=>(await FunctionSelector.fromNameAndParameters(fn.name,fn.parameters)).toString()));if(privateSelectors.length!==new Set(privateSelectors).size)throw new Error("Repeated function selectors of private functions");return this.#contractArtifactCache.set(key,contract),await this.#store.transactionAsync(async()=>{await this.#contractArtifacts.set(key,contractArtifactToBuffer(contract)),await this.#contractClassData.set(key,new SerializableContractClassData(contractClass).toBuffer())}),contractClass.id}async addContractInstance(contract){await this.#store.transactionAsync(async()=>{await this.#contractInstances.set(contract.address.toString(),new SerializableContractInstancePreimage(contract).toBuffer())})}async#getPrivateFunctionTreeForClassId(classId){if(!this.#privateFunctionTrees.has(classId.toString())){let artifact=await this.getContractArtifact(classId);if(!artifact)return;let tree=await PrivateFunctionsTree.create(artifact);this.#privateFunctionTrees.set(classId.toString(),tree)}return this.#privateFunctionTrees.get(classId.toString())}getContractsAddresses(){return this.#store.transactionAsync(async()=>(await toArray(this.#contractInstances.keysAsync())).map(AztecAddress.fromStringUnsafe))}getContractInstance(contractAddress){return this.#store.transactionAsync(async()=>{let contract=await this.#contractInstances.getAsync(contractAddress.toString());return contract&&SerializableContractInstancePreimage.fromBuffer(contract).withAddress(contractAddress)})}async getContractArtifact(contractClassId){let key=contractClassId.toString(),cached2=this.#contractArtifactCache.get(key);if(cached2)return cached2;let artifact=await this.#store.transactionAsync(async()=>{let buf=await this.#contractArtifacts.getAsync(key);return buf&&contractArtifactFromBuffer(buf)});return artifact&&this.#contractArtifactCache.set(key,artifact),artifact}async getContractClassWithPreimage(contractClassId){let key=contractClassId.toString(),buf=await this.#store.transactionAsync(()=>this.#contractClassData.getAsync(key));if(!buf)return;let classData=SerializableContractClassData.fromBuffer(buf),artifact=await this.getContractArtifact(contractClassId);if(!artifact)return;let packedBytecode=artifact.functions.find(f=>f.name==="public_dispatch")?.bytecode??Buffer.alloc(0);return{...classData,packedBytecode}}async getFunctionArtifact(contractClassId,selector){let artifact=await this.getContractArtifact(contractClassId);return artifact?{...assertSelectorInArtifact(artifact,await findFunctionArtifactBySelector(artifact,selector),{contractClassId,selector}),contractName:artifact.name}:void 0}async getFunctionArtifactWithDebugMetadata(contractClassId,selector){let artifact=await this.getContractArtifact(contractClassId);if(!artifact)return;let fn=assertSelectorInArtifact(artifact,await findFunctionArtifactBySelector(artifact,selector),{contractClassId,selector});return{...fn,contractName:artifact.name,debug:getFunctionDebugMetadata(artifact,fn)}}async getPublicFunctionArtifact(contractClassId){let artifact=await this.getContractArtifact(contractClassId),fn=artifact&&artifact.functions.find(f=>f.functionType===FunctionType.PUBLIC);return fn&&{...fn,contractName:artifact.name}}async getFunctionDebugMetadata(contractClassId,selector){let artifact=await this.getContractArtifact(contractClassId);if(!artifact)return;let fn=await findFunctionArtifactBySelector(artifact,selector);return fn&&getFunctionDebugMetadata(artifact,fn)}async getPublicFunctionDebugMetadata(contractClassId){let artifact=await this.getContractArtifact(contractClassId),fn=artifact&&artifact.functions.find(f=>f.functionType===FunctionType.PUBLIC);return fn&&getFunctionDebugMetadata(artifact,fn)}async getFunctionMembershipWitness(contractClassId,selector){return(await this.#getPrivateFunctionTreeForClassId(contractClassId))?.getFunctionMembershipWitness(selector)}async getDebugContractName(contractClassId){return(await this.getContractArtifact(contractClassId))?.name}async getDebugFunctionName(contractClassId,selector){let artifact=await this.getContractArtifact(contractClassId),fn=artifact&&await findFunctionAbiBySelector(artifact,selector);return`${artifact?.name??contractClassId}:${fn?.name??selector}`}async getFunctionCall(functionName,args,to,contractClassId){let artifact=await this.getContractArtifact(contractClassId);if(!artifact)throw new Error(`No artifact registered for contract class ${contractClassId} (contract ${to}): register it by calling wallet.registerContract(...).
|
|
212
|
+
See docs for context: https://docs.aztec.network/errors/14`);return completeAddress}async getContractInstance(address){let instance=await this.anchoredContractData.getContractInstance(address);if(!instance)throw new Error(`No contract instance found for address ${address.toString()}`);return instance}getAuthWitness(messageHash){let witness=this.authWitnesses.find(w=>w.requestHash.equals(messageHash))?.witness;if(!witness)throw new Error(`Unknown auth witness for message hash ${messageHash}`);return Promise.resolve(witness)}async getNotes(owner,storageSlot,numSelects,selectByIndexes,selectByOffsets,selectByLengths,selectValues,selectComparators,sortByIndexes,sortByOffsets,sortByLengths,sortOrder,limit,offset,status,maxNotes,packedHintedNoteLength){let dbNotes=await new NoteService(this.noteStore,this.aztecNode,this.anchorBlockHeader,this.jobId).getNotes(this.contractAddress,owner.value,storageSlot,status,this.scopes),picked=pickNotes(dbNotes,{selects:selectByIndexes.slice(0,numSelects).map((index,i)=>({selector:{index,offset:selectByOffsets[i],length:selectByLengths[i]},value:selectValues[i],comparator:selectComparators[i]})),sorts:sortByIndexes.map((index,i)=>({selector:{index,offset:sortByOffsets[i],length:sortByLengths[i]},order:sortOrder[i]})),limit,offset});return BoundedVec.from({data:picked,maxLength:maxNotes,elementSize:packedHintedNoteLength})}async doesNullifierExist(innerNullifier){let[nullifier,anchorBlockHash]=await Promise.all([siloNullifier(this.contractAddress,innerNullifier),this.anchorBlockHeader.hash()]),[leafIndex]=await this.aztecNode.findLeavesIndexes(anchorBlockHash,MerkleTreeId.NULLIFIER_TREE,[nullifier]);return leafIndex?.data!==void 0}async getL1ToL2MembershipWitness(contractAddress,messageHash,secret){let[messageIndex,siblingPath]=await getNonNullifiedL1ToL2MessageWitness(this.aztecNode,contractAddress,messageHash,secret,await this.anchorBlockHeader.hash());return{index:messageIndex,siblingPath}}getFromPublicStorage(blockHash,contractAddress,startStorageSlot,numberOfElements){return this.#queryWithBlockHashNotAfterAnchor(blockHash,async()=>{let slots=Array(numberOfElements).fill(0).map((_,i)=>new Fr(startStorageSlot.value+BigInt(i))),values=await Promise.all(slots.map(storageSlot=>this.aztecNode.getPublicStorageAt(blockHash,contractAddress,storageSlot)));return this.logger.debug(`Oracle storage read: slots=[${slots.map(slot=>slot.toString()).join(", ")}] address=${contractAddress.toString()} values=[${values.join(", ")}]`),values})}async#getContractLogger(){return this.contractLogger||(this.contractLogger=await createContractLogger(this.contractAddress,addr=>this.anchoredContractData.getDebugContractName(addr),"user",{instanceId:this.jobId})),this.contractLogger}async#getAztecnrLogger(){return this.aztecnrLogger||(this.aztecnrLogger=await createContractLogger(this.contractAddress,addr=>this.anchoredContractData.getDebugContractName(addr),"aztecnr",{instanceId:this.jobId})),this.aztecnrLogger}async log(level,message,_fieldsSize,fields){if(!LogLevels[level])throw new Error(`Invalid log level: ${level}`);let{kind,message:strippedMessage}=stripAztecnrLogPrefix(message),logger3=kind=="aztecnr"?await this.#getAztecnrLogger():await this.#getContractLogger();logContractMessage(logger3,LogLevels[level],strippedMessage,fields)}async getPendingTaggedLogsV2(scope,providedSecrets){let secrets=providedSecrets.readAll(this.ephemeralArrayService).map(ps=>new AppTaggingSecret(ps.secret,this.contractAddress,ps.mode)),logs=await this.#createLogService().fetchTaggedLogs(this.contractAddress,scope,secrets);return EphemeralArray.fromValues(this.ephemeralArrayService,logs)}#createLogService(){return new LogService(this.aztecNode,this.anchorBlockHeader,this.l2TipsStore,this.keyStore,this.recipientTaggingStore,this.taggingSecretSourcesStore,this.addressStore,this.jobId,this.logger.getBindings())}async validateAndStoreEnqueuedNotesAndEvents(noteValidationRequests,eventValidationRequests,scope){await this.#processValidationRequests(noteValidationRequests.readAll(this.ephemeralArrayService),eventValidationRequests.readAll(this.ephemeralArrayService),scope)}async#processValidationRequests(noteValidationRequests,eventValidationRequests,scope){let txEffects=await this.#fetchTxEffects([...noteValidationRequests.map(r2=>r2.txHash),...eventValidationRequests.map(r2=>r2.txHash)]),noteService=new NoteService(this.noteStore,this.aztecNode,this.anchorBlockHeader,this.jobId),eventService=new EventService(this.anchorBlockHeader,this.aztecNode,this.privateEventStore,this.jobId);await Promise.all([noteService.validateAndStoreNotes(noteValidationRequests,scope,txEffects),eventService.validateAndStoreEvents(eventValidationRequests,scope,txEffects)])}async getLogsByTagV2(requests){let logRetrievalRequests=requests.readAll(this.ephemeralArrayService),innerArrays=(await this.#createLogService().fetchLogsByTag(this.contractAddress,logRetrievalRequests)).map(responses=>EphemeralArray.fromValues(this.ephemeralArrayService,responses));return EphemeralArray.fromValues(this.ephemeralArrayService,innerArrays)}async getResolvedTxs(requests){let txHashes=requests.readAll(this.ephemeralArrayService),options=(await this.txResolver.resolveTxs(txHashes,this.anchorBlockHeader.getBlockNumber())).map(r2=>r2?Option.some(r2):Option.none());return EphemeralArray.fromValues(this.ephemeralArrayService,options)}async getTxEffect(txHash){if(txHash.hash.isZero())throw new Error("Invalid tx hash passed into aztec_utl_getTxEffect oracle handler");let receipt=await this.aztecNode.getTxReceipt(txHash,{includeTxEffect:!0});if(!receipt.isMined()||!receipt.txEffect||receipt.blockNumber>this.anchorBlockHeader.getBlockNumber())return Option.none();let txEffect=receipt.txEffect;return Option.some({...txEffect,publicLogs:FlatPublicLogs.fromLogs(txEffect.publicLogs),contractClassLogs:txEffect.contractClassLogs.map(log2=>({contractAddress:log2.contractAddress,fields:log2.fields.toFields(),emittedLength:log2.emittedLength}))})}setCapsule(contractAddress,slot,capsule,scope){this.#assertOwnContract(contractAddress),this.capsuleService.setCapsule(contractAddress,slot,capsule,this.jobId,scope)}async getCapsule(contractAddress,slot,tSize,scope){this.#assertOwnContract(contractAddress);let values=await this.capsuleService.getCapsule(contractAddress,slot,this.jobId,scope,this.capsules);return values?Option.some(values):Option.none({length:tSize})}deleteCapsule(contractAddress,slot,scope){this.#assertOwnContract(contractAddress),this.capsuleService.deleteCapsule(contractAddress,slot,this.jobId,scope)}copyCapsule(contractAddress,srcSlot,dstSlot,numEntries,scope){return this.#assertOwnContract(contractAddress),this.capsuleService.copyCapsule(contractAddress,srcSlot,dstSlot,numEntries,this.jobId,scope)}#assertOwnContract(contractAddress){if(!contractAddress.equals(this.contractAddress))throw new Error(`Contract ${contractAddress} is not allowed to access ${this.contractAddress}'s PXE DB`)}recordFact(contractAddress,scope,factCollectionTypeId,factCollectionId,factTypeId,payload,originBlock){return this.#assertOwnContract(contractAddress),this.factService.recordFact(new FactCollectionKey(contractAddress,scope,factCollectionTypeId,factCollectionId),factTypeId,payload.readAll(this.ephemeralArrayService),originBlock.isSome()?originBlock.value:void 0,this.jobId)}deleteFactCollection(contractAddress,scope,factCollectionTypeId,factCollectionId){return this.#assertOwnContract(contractAddress),this.factService.deleteFactCollection(new FactCollectionKey(contractAddress,scope,factCollectionTypeId,factCollectionId),this.jobId)}async getFactCollection(contractAddress,scope,factCollectionTypeId,factCollectionId){this.#assertOwnContract(contractAddress);let tips=anchoredTipBlockNumbers(await this.l2TipsStore.getL2Tips(),this.anchorBlockHeader.getBlockNumber()),collection=await this.factService.getFactCollection(new FactCollectionKey(contractAddress,scope,factCollectionTypeId,factCollectionId),tips,this.jobId);return collection?Option.some(toNoirFactCollection(this.ephemeralArrayService,contractAddress,scope,factCollectionTypeId,factCollectionId,collection.facts)):Option.none(emptyFactCollection(this.ephemeralArrayService))}async getFactCollectionsByType(contractAddress,scope,factCollectionTypeId){this.#assertOwnContract(contractAddress);let tips=anchoredTipBlockNumbers(await this.l2TipsStore.getL2Tips(),this.anchorBlockHeader.getBlockNumber()),collections=await this.factService.getFactCollectionsByType(new FactCollectionTypeKey(contractAddress,scope,factCollectionTypeId),tips,this.jobId);return EphemeralArray.fromValues(this.ephemeralArrayService,collections.map(collection=>toNoirFactCollection(this.ephemeralArrayService,collection.key.contractAddress,collection.key.scope,collection.key.factCollectionTypeId,collection.key.factCollectionId,collection.facts)))}setContractSyncCacheInvalid(contractAddress,scopes){if(!contractAddress.equals(this.contractAddress))throw new Error(`Contract ${this.contractAddress} cannot invalidate sync cache of ${contractAddress}`);this.contractSyncService.invalidateContractForScopes(contractAddress,scopes.data)}async decryptAes128(ciphertext,iv,symKey){let capacity=ciphertext.maxLength;try{let plaintext=await new Aes128().decryptBufferCBC(Buffer.from(ciphertext.data),iv,symKey);return Option.some(BoundedVec.from({data:[...plaintext],maxLength:capacity}))}catch{return Option.none({maxLength:capacity})}}async getSharedSecrets(address,ephPks,contractAddress){if(!contractAddress.equals(this.contractAddress))throw new Error(`getSharedSecrets called with contract address ${contractAddress}, expected ${this.contractAddress}`);let recipientCompleteAddress=await this.addressStore.getCompleteAddress(address);if(!recipientCompleteAddress)return this.logger.warn(`Computing shared secrets for address ${address} whose keys are not held - returning no secrets`,{address,contractAddress:this.contractAddress}),EphemeralArray.fromValues(this.ephemeralArrayService,[]);let ivpkMHash=await hashPublicKey(recipientCompleteAddress.publicKeys.ivpkM),ivskM=await this.keyStore.getMasterSecretKey(ivpkMHash),addressSecret=await computeAddressSecret(await recipientCompleteAddress.getPreaddress(),ivskM),ephPkPoints=ephPks.readAll(this.ephemeralArrayService),secrets=await Promise.all(ephPkPoints.map(({x,y})=>appSiloEcdhSharedSecret(addressSecret,new Point(x,y),this.contractAddress)));return EphemeralArray.fromValues(this.ephemeralArrayService,secrets)}pushEphemeral(slot,elements){return this.ephemeralArrayService.push(slot,elements)}popEphemeral(slot){return this.ephemeralArrayService.pop(slot)}getEphemeral(slot,index){return this.ephemeralArrayService.get(slot,index)}setEphemeral(slot,index,elements){this.ephemeralArrayService.set(slot,index,elements)}getEphemeralLen(slot){return this.ephemeralArrayService.len(slot)}removeEphemeral(slot,index){this.ephemeralArrayService.remove(slot,index)}clearEphemeral(slot){this.ephemeralArrayService.clear(slot)}pushTransient(slot,elements){return this.transientArrayService.push(this.contractAddress,slot,elements)}popTransient(slot){return this.transientArrayService.pop(this.contractAddress,slot)}getTransient(slot,index){return this.transientArrayService.get(this.contractAddress,slot,index)}setTransient(slot,index,elements){this.transientArrayService.set(this.contractAddress,slot,index,elements)}getTransientLen(slot){return this.transientArrayService.len(this.contractAddress,slot)}removeTransient(slot,index){this.transientArrayService.remove(this.contractAddress,slot,index)}clearTransient(slot){this.transientArrayService.clear(this.contractAddress,slot)}emitOffchainEffect(data){return this.offchainEffects.push({data,contractAddress:this.contractAddress}),Promise.resolve()}async callUtilityFunction(targetContractAddress,functionSelector,args){let targetArtifact=await this.anchoredContractData.getFunctionArtifactWithDebugMetadata(targetContractAddress,functionSelector);if(!targetArtifact)throw new Error(`Cannot call ${targetContractAddress}:${functionSelector}: the contract is not registered. Register it via wallet.registerContract(...).`);if(!targetContractAddress.equals(this.contractAddress)){if(!await isStandardHandshakeRegistryUtilityRead(targetContractAddress,functionSelector)){let[callerClassId,targetClassId]=await Promise.all([this.anchoredContractData.getCurrentClassId(this.contractAddress),this.anchoredContractData.getCurrentClassId(targetContractAddress)]);if(!callerClassId||!targetClassId)throw new Error(`Cannot authorize utility call from ${this.contractAddress} to ${targetContractAddress}: ${callerClassId?targetContractAddress:this.contractAddress} is not registered.`);let request={caller:this.contractAddress,callerClassId,target:targetContractAddress,targetClassId,functionSelector,functionName:targetArtifact.name,args,callerContext:this.callerContext},response=this.hooks?.authorizeUtilityCall?await this.hooks.authorizeUtilityCall(request):{authorized:!1,reason:"No authorizeUtilityCall hook configured"};if(!response.authorized){let reason=response.reason?`: ${response.reason}`:"";throw new Error(`Cross-contract utility call denied${reason}. ${this.contractAddress} attempted to call ${targetContractAddress}:${functionSelector} (${targetArtifact.name}). See https://docs.aztec.network/errors/11`)}}await this.contractSyncService.ensureContractSynced(targetContractAddress,functionSelector,this.utilityExecutor,this.anchorBlockHeader,this.jobId,this.scopes)}this.logger.debug(`Calling nested utility function ${targetContractAddress}:${functionSelector} from ${this.contractAddress}`);let nestedOracle=new _UtilityExecutionOracle({callContext:CallContext.from({msgSender:this.contractAddress,contractAddress:targetContractAddress,functionSelector,isStaticCall:!0}),authWitnesses:this.authWitnesses,capsules:this.capsules,anchorBlockHeader:this.anchorBlockHeader,anchoredContractData:this.anchoredContractData,noteStore:this.noteStore,keyStore:this.keyStore,addressStore:this.addressStore,aztecNode:this.aztecNode,recipientTaggingStore:this.recipientTaggingStore,taggingSecretSourcesStore:this.taggingSecretSourcesStore,capsuleService:this.capsuleService,factService:this.factService,privateEventStore:this.privateEventStore,txResolver:this.txResolver,contractSyncService:this.contractSyncService,l2TipsStore:this.l2TipsStore,jobId:this.jobId,scopes:this.scopes,simulator:this.simulator,hooks:this.hooks,utilityExecutor:this.utilityExecutor,log:this.logger,transientArrayService:this.transientArrayService}),initialWitness=toACVMWitness(0,args),acirExecutionResult=await this.simulator.executeUserCircuit(initialWitness,targetArtifact,buildACIRCallback(nestedOracle)).catch(err=>{throw err.message=resolveAssertionMessageFromError(err,targetArtifact),new ExecutionError(err.message,{contractAddress:targetContractAddress,functionSelector},extractCallStack(err,targetArtifact.debug),{cause:err})});return witnessMapToFields(acirExecutionResult.returnWitness)}getOffchainEffects(){return this.offchainEffects}async#fetchTxEffects(txHashes){let uniqueTxHashes=uniqueBy(txHashes,h=>h.toString()),fetched=await Promise.all(uniqueTxHashes.map(h=>this.aztecNode.getTxReceipt(h,{includeTxEffect:!0})));return new Map(uniqueTxHashes.map((h,i)=>{let receipt=fetched[i];return!receipt.isMined()||!receipt.txEffect?[h.toString(),void 0]:[h.toString(),{data:receipt.txEffect,l2BlockNumber:receipt.blockNumber,l2BlockHash:receipt.blockHash,txIndexInBlock:receipt.txIndexInBlock,slotNumber:receipt.slotNumber}]}).filter(entry=>entry[1]!==void 0))}async#queryWithBlockHashNotAfterAnchor(blockHash,query){let anchorHash=await this.anchorBlockHeader.hash();if(blockHash.equals(anchorHash))return query();let[response]=await Promise.all([query(),(async()=>{let header=(await this.aztecNode.getBlock(blockHash))?.header;if(!header)throw new Error(`Could not find block header for block hash ${blockHash}`);if(header.getBlockNumber()>this.anchorBlockHeader.getBlockNumber())throw new Error(`Made a node query with a reference block hash ${blockHash} with block number ${header.getBlockNumber()}, which is ahead of the anchor block number ${this.anchorBlockHeader.getBlockNumber()} (from anchor block hash ${anchorHash}).`)})()]);return response}get callerContext(){return"utility"}get contractAddress(){return this.callContext.contractAddress}},STANDARD_HANDSHAKE_REGISTRY_DEFAULT_AUTHORIZED_READ_SIGNATURES=["get_non_interactive_handshakes((Field),u32)","get_app_siloed_secrets((Field),(Field))"];async function doesSelectorHaveSignature(functionSelector,signature){return functionSelector.equals(await FunctionSelector.fromSignature(signature))}__name(doesSelectorHaveSignature,"doesSelectorHaveSignature");async function isStandardHandshakeRegistryUtilityRead(targetContractAddress,functionSelector){return targetContractAddress.equals(STANDARD_HANDSHAKE_REGISTRY_ADDRESS)?(await Promise.all(STANDARD_HANDSHAKE_REGISTRY_DEFAULT_AUTHORIZED_READ_SIGNATURES.map(signature=>doesSelectorHaveSignature(functionSelector,signature)))).some(Boolean):!1}__name(isStandardHandshakeRegistryUtilityRead,"isStandardHandshakeRegistryUtilityRead");var PrivateExecutionOracle=class _PrivateExecutionOracle extends UtilityExecutionOracle{static{__name(this,"PrivateExecutionOracle")}isPrivate=!0;newNotes=[];noteHashNullifierCounterMap=new Map;contractClassLogs=[];nestedExecutionResults=[];argsHash;txContext;executionCache;noteCache;taggingIndexCache;senderTaggingStore;totalPublicCalldataCount;initialSideEffectCounter;defaultSenderForTags;constructor(args){super({...args,log:args.log??createLogger("simulator:client_execution_context")}),this.argsHash=args.argsHash,this.txContext=args.txContext,this.executionCache=args.executionCache,this.noteCache=args.noteCache,this.taggingIndexCache=args.taggingIndexCache,this.senderTaggingStore=args.senderTaggingStore,this.totalPublicCalldataCount=args.totalPublicCalldataCount??0,this.initialSideEffectCounter=args.sideEffectCounter??0,this.defaultSenderForTags=args.senderForTags}getPrivateContextInputs(){return new PrivateContextInputs(this.callContext,this.anchorBlockHeader,this.txContext,this.initialSideEffectCounter)}getInitialWitness(abi){let argumentsSize=countArgumentsSize(abi),args=this.executionCache.getPreimage(this.argsHash);if(args?.length!==argumentsSize)throw new Error(`Invalid arguments size: expected ${argumentsSize}, got ${args?.length}`);let privateContextInputsAsFields=this.getPrivateContextInputs().toFields();if(privateContextInputsAsFields.length!==37)throw new Error("Invalid private context inputs size");let fields=[...privateContextInputsAsFields,...args];return toACVMWitness(0,fields)}getNewNotes(){return this.newNotes}getNoteHashNullifierCounterMap(){return this.noteHashNullifierCounterMap}getContractClassLogs(){return this.contractClassLogs}getUsedTaggingIndexRanges(){return this.taggingIndexCache.getUsedTaggingIndexRanges()}getNestedExecutionResults(){return this.nestedExecutionResults}getSenderForTags(){return Promise.resolve(this.defaultSenderForTags?Option.some(this.defaultSenderForTags):Option.none())}async resolveCustomRequest(kind,payload){let hook=this.hooks?.resolveCustomRequest;if(!hook)throw new Error("Cannot serve a request: no resolveCustomRequest hook is configured");let contractClassId=await this.#getCurrentContractClassId(this.contractAddress);return hook({contractAddress:this.contractAddress,contractClassId,kind,payload})}async resolveTaggingStrategy(sender,recipient,deliveryMode){let[isUnconstrainedSelfSend,chosenStrategy]=await Promise.all([this.#isUnconstrainedSelfSend(recipient,deliveryMode),this.#chooseTaggingSecretStrategy(sender,recipient,deliveryMode)]),strategy=isUnconstrainedSelfSend?{type:"address-derived"}:chosenStrategy;return this.#resolveTaggingSecretStrategy(strategy,sender,recipient)}async#chooseTaggingSecretStrategy(sender,recipient,deliveryMode){let hook=this.hooks?.resolveTaggingSecretStrategy;if(!hook)return{type:"non-interactive-handshake"};let contractClassId=await this.#getCurrentContractClassId(this.contractAddress);return hook({contractAddress:this.contractAddress,contractClassId,sender,recipient,deliveryMode})}async#getCurrentContractClassId(address){let classId=await this.anchoredContractData.getCurrentClassId(address);if(classId===void 0)throw new Error(`Cannot resolve the current contract class for ${address}`);return classId}#isUnconstrainedSelfSend(recipient,deliveryMode){return deliveryMode===AppTaggingSecretKind.UNCONSTRAINED?this.keyStore.hasAccount(recipient):Promise.resolve(!1)}async#resolveTaggingSecretStrategy(strategy,sender,recipient){switch(strategy.type){case"non-interactive-handshake":return{type:"non-interactive-handshake"};case"interactive-handshake":return{type:"interactive-handshake"};case"address-derived":return this.#addressDerivedSecret(sender,recipient);case"arbitrary-secret":return{type:"unconstrained-secret",secret:(await AppTaggingSecret.computeDirectional(strategy.secret,this.contractAddress,recipient)).secret}}}async#addressDerivedSecret(sender,recipient){let secret=await this.getAppTaggingSecret(sender,recipient);if(!secret.isSome())throw new Error(`Cannot derive an address-derived tagging secret for invalid recipient ${recipient}`);return{type:"unconstrained-secret",secret:secret.value}}async getAppTaggingSecret(sender,recipient){let extendedSecret=await this.#calculateAppTaggingSecret(this.contractAddress,sender,recipient);return extendedSecret?Option.some(extendedSecret.secret):(this.logger.warn(`Computing a tagging secret for invalid recipient ${recipient} - returning no secret`,{contractAddress:this.contractAddress}),Option.none())}async getNextTaggingIndex(secret,kind){let appTaggingSecret=new AppTaggingSecret(secret,this.contractAddress,kind),index=await this.#reserveNextIndexForSecret(appTaggingSecret);return this.logger.debug(`Incrementing ${kind} tagging index for secret in contract ${this.contractAddress} to ${index}`),index}async#reserveNextIndexForSecret(secret){let index=await this.#getIndexToUseForSecret(secret);return this.taggingIndexCache.setLastUsedIndex(secret,index),index}async#calculateAppTaggingSecret(contractAddress,sender,recipient){let senderCompleteAddress=await this.getCompleteAddressOrFail(sender),senderIvsk=await this.keyStore.getMasterIncomingViewingSecretKey(sender);return AppTaggingSecret.computeViaEcdh(senderCompleteAddress,senderIvsk,recipient,contractAddress,recipient)}async#getIndexToUseForSecret(secret){let lastUsedIndexInTx=this.taggingIndexCache.getLastUsedIndex(secret);if(lastUsedIndexInTx!==void 0)return lastUsedIndexInTx+1;{await syncSenderTaggingIndexes(secret,this.aztecNode,this.senderTaggingStore,await this.anchorBlockHeader.hash(),this.jobId);let lastUsedIndex=await this.senderTaggingStore.getLastUsedIndex(secret,this.jobId);return lastUsedIndex===void 0?0:lastUsedIndex+1}}setHashPreimage(values,hash5){return this.executionCache.store(values,hash5)}getHashPreimage(hash5){let preimage=this.executionCache.getPreimage(hash5);if(!preimage)throw new Error(`Preimage for hash ${hash5.toString()} not found in cache`);return Promise.resolve(preimage)}async doesNullifierExist(innerNullifier){this.logger.debug(`Checking existence of inner nullifier ${innerNullifier}`,{contractAddress:this.contractAddress});let nullifier=(await siloNullifier(this.contractAddress,innerNullifier)).toBigInt();return this.noteCache.getNullifiers(this.contractAddress).has(nullifier)||await super.doesNullifierExist(innerNullifier)}async getNotes(owner,storageSlot,numSelects,selectByIndexes,selectByOffsets,selectByLengths,selectValues,selectComparators,sortByIndexes,sortByOffsets,sortByLengths,sortOrder,limit,offset,status,maxNotes,packedHintedNoteLength){let pendingNotes=this.noteCache.getNotes(this.callContext.contractAddress,owner.value,storageSlot),pendingNullifiers=this.noteCache.getNullifiers(this.callContext.contractAddress),dbNotesFiltered=(await new NoteService(this.noteStore,this.aztecNode,this.anchorBlockHeader,this.jobId).getNotes(this.callContext.contractAddress,owner.value,storageSlot,status,this.scopes)).filter(n=>!pendingNullifiers.has(n.siloedNullifier.value)),notes=pickNotes([...dbNotesFiltered,...pendingNotes],{selects:selectByIndexes.slice(0,numSelects).map((index,i)=>({selector:{index,offset:selectByOffsets[i],length:selectByLengths[i]},value:selectValues[i],comparator:selectComparators[i]})),sorts:sortByIndexes.map((index,i)=>({selector:{index,offset:sortByOffsets[i],length:sortByLengths[i]},order:sortOrder[i]})),limit,offset});return this.logger.debug(`Returning ${notes.length} notes for ${this.callContext.contractAddress} at ${storageSlot}: ${notes.map(n=>`${n.noteNonce.toString()}:[${n.note.items.map(i=>i.toString()).join(",")}]`).join(", ")}`),BoundedVec.from({data:notes,maxLength:maxNotes,elementSize:packedHintedNoteLength})}notifyCreatedNote(owner,storageSlot,randomness,noteTypeId,noteItems,noteHash,counter){this.logger.debug(`Notified of new note with inner hash ${noteHash}`,{contractAddress:this.callContext.contractAddress,storageSlot,randomness,noteTypeId,counter});let note=new Note(noteItems);this.noteCache.addNewNote({contractAddress:this.callContext.contractAddress,owner,storageSlot,randomness,noteNonce:Fr.ZERO,note,siloedNullifier:void 0,noteHash,isPending:!0},counter),this.newNotes.push(NoteAndSlot.from({note,storageSlot,randomness,noteTypeId}))}async notifyNullifiedNote(innerNullifier,noteHash,counter){let nullifiedNoteHashCounter=await this.noteCache.nullifyNote(this.callContext.contractAddress,innerNullifier,noteHash);nullifiedNoteHashCounter!==void 0&&this.noteHashNullifierCounterMap.set(nullifiedNoteHashCounter,counter)}notifyCreatedNullifier(innerNullifier){return this.logger.debug(`Notified of new inner nullifier ${innerNullifier}`,{contractAddress:this.contractAddress}),this.noteCache.nullifierCreated(this.callContext.contractAddress,innerNullifier)}async isNullifierPending(innerNullifier,contractAddress){let siloedNullifier=await siloNullifier(contractAddress,innerNullifier),isNullifierPending=this.noteCache.getNullifiers(contractAddress).has(siloedNullifier.toBigInt());return Promise.resolve(isNullifierPending)}notifyCreatedContractClassLog(logData,counter){let log2=ContractClassLog.from({contractAddress:logData.contractAddress,fields:new ContractClassLogFields(logData.fields),emittedLength:logData.emittedLength});this.contractClassLogs.push(new CountedContractClassLog(log2,counter));let text=log2.toBuffer().toString("hex");this.logger.verbose(`Emitted log from ContractClassRegistry: "${text.length>100?text.slice(0,100)+"...":text}"`)}#checkValidStaticCall(childExecutionResult){if(childExecutionResult.publicInputs.noteHashes.claimedLength>0||childExecutionResult.publicInputs.nullifiers.claimedLength>0||childExecutionResult.publicInputs.l2ToL1Msgs.claimedLength>0||childExecutionResult.publicInputs.privateLogs.claimedLength>0||childExecutionResult.publicInputs.contractClassLogsHashes.claimedLength>0)throw new Error("Static call cannot update the state, emit L2->L1 messages or generate logs")}async callPrivateFunction(targetContractAddress,functionSelector,argsHash,sideEffectCounter,isStaticCall){if(!this.simulator)throw new Error("No simulator provided, cannot perform a nested private call");let simulatorSetupTimer=new Timer;this.logger.debug(`Calling private function ${targetContractAddress}:${functionSelector} from ${this.callContext.contractAddress}`),isStaticCall=isStaticCall||this.callContext.isStaticCall,await this.contractSyncService.ensureContractSynced(targetContractAddress,functionSelector,this.utilityExecutor,this.anchorBlockHeader,this.jobId,this.scopes);let targetArtifact=await this.anchoredContractData.getFunctionArtifactWithDebugMetadata(targetContractAddress,functionSelector);if(!targetArtifact)throw new Error(`Cannot call ${targetContractAddress}:${functionSelector}: the contract is not registered. Register it via wallet.registerContract(...).`);let derivedTxContext=this.txContext.clone(),derivedCallContext=await this.deriveCallContext(targetContractAddress,targetArtifact,isStaticCall),privateExecutionOracle=new _PrivateExecutionOracle({argsHash,txContext:derivedTxContext,callContext:derivedCallContext,anchorBlockHeader:this.anchorBlockHeader,utilityExecutor:this.utilityExecutor,authWitnesses:this.authWitnesses,capsules:this.capsules,executionCache:this.executionCache,noteCache:this.noteCache,taggingIndexCache:this.taggingIndexCache,anchoredContractData:this.anchoredContractData,noteStore:this.noteStore,keyStore:this.keyStore,addressStore:this.addressStore,aztecNode:this.aztecNode,senderTaggingStore:this.senderTaggingStore,recipientTaggingStore:this.recipientTaggingStore,taggingSecretSourcesStore:this.taggingSecretSourcesStore,capsuleService:this.capsuleService,factService:this.factService,privateEventStore:this.privateEventStore,txResolver:this.txResolver,contractSyncService:this.contractSyncService,jobId:this.jobId,totalPublicCalldataCount:this.totalPublicCalldataCount,sideEffectCounter,log:this.logger,scopes:this.scopes,senderForTags:this.defaultSenderForTags,simulator:this.simulator,hooks:this.hooks,l2TipsStore:this.l2TipsStore,transientArrayService:this.transientArrayService}),setupTime=simulatorSetupTimer.ms(),childExecutionResult=await executePrivateFunction(this.simulator,privateExecutionOracle,targetArtifact,targetContractAddress,functionSelector);this.totalPublicCalldataCount=privateExecutionOracle.getTotalPublicCalldataCount(),isStaticCall&&this.#checkValidStaticCall(childExecutionResult),this.nestedExecutionResults.push(childExecutionResult);let publicInputs=childExecutionResult.publicInputs;return childExecutionResult.profileResult&&(childExecutionResult.profileResult.timings.witgen+=setupTime),{endSideEffectCounter:publicInputs.endSideEffectCounter,returnsHash:publicInputs.returnsHash}}assertValidPublicCalldata(calldataHash){let calldata=this.executionCache.getPreimage(calldataHash);if(!calldata)throw new Error("Calldata for public call not found in cache");if(this.totalPublicCalldataCount+=calldata.length,this.totalPublicCalldataCount>16e3)throw new Error(`Too many total args to all enqueued public calls! (> ${16e3})`);return Promise.resolve()}getTotalPublicCalldataCount(){return this.totalPublicCalldataCount}notifyRevertiblePhaseStart(minRevertibleSideEffectCounter){return this.noteCache.setMinRevertibleSideEffectCounter(minRevertibleSideEffectCounter)}isExecutionInRevertiblePhase(sideEffectCounter){return Promise.resolve(this.noteCache.isSideEffectCounterRevertible(sideEffectCounter))}async deriveCallContext(targetContractAddress,targetArtifact,isStaticCall=!1){return new CallContext(this.contractAddress,targetContractAddress,await FunctionSelector.fromNameAndParameters(targetArtifact.name,targetArtifact.parameters),isStaticCall)}getDebugFunctionName(){return this.anchoredContractData.getDebugFunctionName(this.contractAddress,this.callContext.functionSelector)}get callerContext(){return this.callContext.isStaticCall?"private view":"private"}};var TransientArrayService=class{static{__name(this,"TransientArrayService")}#arrays=new Map;#key(contractAddress,slot){return`${contractAddress.toString()}:${slot.toString()}`}readArrayAt(contractAddress,slot){return this.#arrays.get(this.#key(contractAddress,slot))??[]}#setArray(contractAddress,slot,array2){this.#arrays.set(this.#key(contractAddress,slot),array2)}len(contractAddress,slot){return this.readArrayAt(contractAddress,slot).length}push(contractAddress,slot,elements){let array2=this.readArrayAt(contractAddress,slot);return array2.push(elements),this.#setArray(contractAddress,slot,array2),array2.length}pop(contractAddress,slot){let array2=this.readArrayAt(contractAddress,slot);if(array2.length===0)throw new Error(`Transient array at slot ${slot} is empty`);let element=array2.pop();return this.#setArray(contractAddress,slot,array2),element}get(contractAddress,slot,index){let array2=this.readArrayAt(contractAddress,slot);if(index<0||index>=array2.length)throw new Error(`Transient array index ${index} out of bounds for array of length ${array2.length} at slot ${slot}`);return array2[index]}set(contractAddress,slot,index,value){let array2=this.readArrayAt(contractAddress,slot);if(index<0||index>=array2.length)throw new Error(`Transient array index ${index} out of bounds for array of length ${array2.length} at slot ${slot}`);array2[index]=value}remove(contractAddress,slot,index){let array2=this.readArrayAt(contractAddress,slot);if(index<0||index>=array2.length)throw new Error(`Transient array index ${index} out of bounds for array of length ${array2.length} at slot ${slot}`);array2.splice(index,1)}clear(contractAddress,slot){this.#arrays.delete(this.#key(contractAddress,slot))}};var OrderedSideEffect=class{static{__name(this,"OrderedSideEffect")}sideEffect;counter;constructor(sideEffect,counter){this.sideEffect=sideEffect,this.counter=counter}};async function generateSimulatedProvingResult(privateExecutionResult,debugFunctionNameGetter,node,minRevertibleSideEffectCounterOverride){let taggedPrivateLogs=[],l2ToL1Messages=[],contractClassLogsHashes=[],publicCallRequests=[],executionSteps=[],scopedNoteHashes=[],scopedNullifiers=[],noteHashReadRequests=[],nullifierReadRequests=[],publicTeardownCallRequest,expirationTimestamp=privateExecutionResult.entrypoint.publicInputs.anchorBlockHeader.globalVariables.timestamp+BigInt(86400),feePayer=AztecAddress.zero(),executions=[privateExecutionResult.entrypoint];for(;executions.length!==0;){let execution=executions.shift();executions.unshift(...execution.nestedExecutionResults);let callExpirationTimestamp=execution.publicInputs.expirationTimestamp;callExpirationTimestamp!==0n&&callExpirationTimestamp<expirationTimestamp&&(expirationTimestamp=callExpirationTimestamp);let{contractAddress}=execution.publicInputs.callContext;if(execution.publicInputs.isFeePayer){if(!feePayer.isZero())throw new Error("Multiple fee payers found in private execution result");feePayer=contractAddress}if(scopedNoteHashes.push(...execution.publicInputs.noteHashes.getActiveItems().filter(nh=>!nh.isEmpty()).map(nh=>nh.scope(contractAddress))),scopedNullifiers.push(...execution.publicInputs.nullifiers.getActiveItems().map(n=>n.scope(contractAddress))),taggedPrivateLogs.push(...await Promise.all(execution.publicInputs.privateLogs.getActiveItems().map(async metadata=>(metadata.log.fields[0]=await computeSiloedPrivateLogFirstField(contractAddress,metadata.log.fields[0]),new OrderedSideEffect(metadata,metadata.counter))))),noteHashReadRequests.push(...execution.publicInputs.noteHashReadRequests.getActiveItems()),nullifierReadRequests.push(...execution.publicInputs.nullifierReadRequests.getActiveItems()),l2ToL1Messages.push(...execution.publicInputs.l2ToL1Msgs.getActiveItems().map(message=>new OrderedSideEffect(message.message.scope(contractAddress),message.counter))),contractClassLogsHashes.push(...execution.publicInputs.contractClassLogsHashes.getActiveItems().map(contractClassLogHash=>new OrderedSideEffect(contractClassLogHash.logHash.scope(contractAddress),contractClassLogHash.counter))),publicCallRequests.push(...execution.publicInputs.publicCallRequests.getActiveItems().map(callRequest=>new OrderedSideEffect(callRequest.inner,callRequest.counter))),publicTeardownCallRequest!==void 0&&!execution.publicInputs.publicTeardownCallRequest.isEmpty())throw new Error("Trying to set multiple teardown requests");publicTeardownCallRequest=execution.publicInputs.publicTeardownCallRequest.isEmpty()?publicTeardownCallRequest:execution.publicInputs.publicTeardownCallRequest,executionSteps.push({functionName:await debugFunctionNameGetter(execution.publicInputs.callContext.contractAddress,execution.publicInputs.callContext.functionSelector),timings:execution.profileResult?.timings??{witgen:0,oracles:{}},bytecode:execution.acir,vk:execution.vk,witness:execution.partialWitness})}let noteHashNullifierCounterMap=collectNoteHashNullifierCounterMap(privateExecutionResult),minRevertibleSideEffectCounter=minRevertibleSideEffectCounterOverride??getFinalMinRevertibleSideEffectCounter(privateExecutionResult),scopedNoteHashesCLA=new ClaimedLengthArray(padArrayEnd(scopedNoteHashes,ScopedNoteHash.empty(),64),scopedNoteHashes.length),scopedNullifiersCLA=new ClaimedLengthArray(padArrayEnd(scopedNullifiers,ScopedNullifier.empty(),64),scopedNullifiers.length),{filteredNoteHashes,filteredNullifiers,filteredPrivateLogs}=squashTransientSideEffects(taggedPrivateLogs,scopedNoteHashesCLA,scopedNullifiersCLA,noteHashNullifierCounterMap,minRevertibleSideEffectCounter);await verifyReadRequests(node,await privateExecutionResult.entrypoint.publicInputs.anchorBlockHeader.hash(),noteHashReadRequests,nullifierReadRequests,scopedNoteHashesCLA,scopedNullifiersCLA);let siloedNoteHashes=await Promise.all(filteredNoteHashes.sort((a,b)=>a.counter-b.counter).map(async nh=>new OrderedSideEffect(await siloNoteHash(nh.contractAddress,nh.value),nh.counter))),siloedNullifiers=await Promise.all(filteredNullifiers.sort((a,b)=>a.counter-b.counter).map(async n=>new OrderedSideEffect(await siloNullifier(n.contractAddress,n.value),n.counter))),constantData=new TxConstantData(privateExecutionResult.entrypoint.publicInputs.anchorBlockHeader,privateExecutionResult.entrypoint.publicInputs.txContext,getVKTreeRoot(),protocolContractsHash),hasPublicCalls=privateExecutionResult.publicFunctionCalldata.length!==0,inputsForRollup,inputsForPublic,gasUsed,sortByCounter2=__name((a,b)=>a.counter-b.counter,"sortByCounter"),getEffect=__name(orderedSideEffect=>orderedSideEffect.sideEffect,"getEffect"),isPrivateOnlyTx=privateExecutionResult.publicFunctionCalldata.length===0,[nonRevertibleNullifiers,revertibleNullifiers]=splitOrderedSideEffects(siloedNullifiers,minRevertibleSideEffectCounter),nonceGenerator=privateExecutionResult.firstNullifier;if(nonRevertibleNullifiers.length===0)nonRevertibleNullifiers.push(nonceGenerator);else if(!nonRevertibleNullifiers[0].equals(nonceGenerator))throw new Error("The first non revertible nullifier should be equal to the nonce generator. This is a bug!");if(isPrivateOnlyTx){let uniqueNoteHashes=await Promise.all(siloedNoteHashes.map(async(orderedSideEffect,i)=>{let siloedNoteHash=orderedSideEffect.sideEffect,nonce=await computeNoteHashNonce(nonceGenerator,i);return await computeUniqueNoteHash(nonce,siloedNoteHash)})),accumulatedDataForRollup=new PrivateToRollupAccumulatedData(padArrayEnd(uniqueNoteHashes,Fr.ZERO,64),padArrayEnd(nonRevertibleNullifiers.concat(revertibleNullifiers),Fr.ZERO,64),padArrayEnd(l2ToL1Messages.sort(sortByCounter2).map(getEffect),ScopedL2ToL1Message.empty(),8),padArrayEnd(filteredPrivateLogs.sort(sortByCounter2).map(getEffect),PrivateLog.empty(),64),padArrayEnd(contractClassLogsHashes.sort(sortByCounter2).map(getEffect),ScopedLogHash.empty(),1));gasUsed=meterGasUsed(accumulatedDataForRollup,isPrivateOnlyTx),inputsForRollup=new PartialPrivateTailPublicInputsForRollup(accumulatedDataForRollup)}else{let[nonRevertibleNoteHashes,revertibleNoteHashes]=splitOrderedSideEffects(siloedNoteHashes,minRevertibleSideEffectCounter),nonRevertibleUniqueNoteHashes=await Promise.all(nonRevertibleNoteHashes.map(async(noteHash,i)=>{let nonce=await computeNoteHashNonce(nonceGenerator,i);return await computeUniqueNoteHash(nonce,noteHash)})),[nonRevertibleL2ToL1Messages,revertibleL2ToL1Messages]=splitOrderedSideEffects(l2ToL1Messages.sort(sortByCounter2),minRevertibleSideEffectCounter),[nonRevertibleTaggedPrivateLogs,revertibleTaggedPrivateLogs]=splitOrderedSideEffects(filteredPrivateLogs,minRevertibleSideEffectCounter),[nonRevertibleContractClassLogHashes,revertibleContractClassLogHashes]=splitOrderedSideEffects(contractClassLogsHashes.sort(sortByCounter2),minRevertibleSideEffectCounter),[nonRevertiblePublicCallRequests,revertiblePublicCallRequests]=splitOrderedSideEffects(publicCallRequests.sort(sortByCounter2),minRevertibleSideEffectCounter),nonRevertibleData=new PrivateToPublicAccumulatedData(padArrayEnd(nonRevertibleUniqueNoteHashes,Fr.ZERO,64),padArrayEnd(nonRevertibleNullifiers,Fr.ZERO,64),padArrayEnd(nonRevertibleL2ToL1Messages,ScopedL2ToL1Message.empty(),8),padArrayEnd(nonRevertibleTaggedPrivateLogs,PrivateLog.empty(),64),padArrayEnd(nonRevertibleContractClassLogHashes,ScopedLogHash.empty(),1),padArrayEnd(nonRevertiblePublicCallRequests,PublicCallRequest.empty(),32)),revertibleData=new PrivateToPublicAccumulatedData(padArrayEnd(revertibleNoteHashes,Fr.ZERO,64),padArrayEnd(revertibleNullifiers,Fr.ZERO,64),padArrayEnd(revertibleL2ToL1Messages,ScopedL2ToL1Message.empty(),8),padArrayEnd(revertibleTaggedPrivateLogs,PrivateLog.empty(),64),padArrayEnd(revertibleContractClassLogHashes,ScopedLogHash.empty(),1),padArrayEnd(revertiblePublicCallRequests,PublicCallRequest.empty(),32));gasUsed=meterGasUsed(revertibleData,isPrivateOnlyTx).add(meterGasUsed(nonRevertibleData,isPrivateOnlyTx)),publicTeardownCallRequest&&(gasUsed=gasUsed.add(privateExecutionResult.entrypoint.publicInputs.txContext.gasSettings.teardownGasLimits)),inputsForPublic=new PartialPrivateTailPublicInputsForPublic(nonRevertibleData,revertibleData,publicTeardownCallRequest??PublicCallRequest.empty())}return{publicInputs:new PrivateKernelTailCircuitPublicInputs(constantData,gasUsed.add(Gas.from({l2Gas:isPrivateOnlyTx?44e4:54e4,daGas:96})),feePayer,expirationTimestamp,hasPublicCalls?inputsForPublic:void 0,hasPublicCalls?void 0:inputsForRollup),chonkProof:ChonkProof.empty(),executionSteps}}__name(generateSimulatedProvingResult,"generateSimulatedProvingResult");function squashTransientSideEffects(taggedPrivateLogs,scopedNoteHashesCLA,scopedNullifiersCLA,noteHashNullifierCounterMap,minRevertibleSideEffectCounter){let{numTransientData,hints:transientDataHints}=buildTransientDataHints(scopedNoteHashesCLA,scopedNullifiersCLA,[],[],[],noteHashNullifierCounterMap,minRevertibleSideEffectCounter),squashedNoteHashCounters=new Set,squashedNullifierCounters=new Set;for(let i=0;i<numTransientData;i++){let hint=transientDataHints[i];squashedNoteHashCounters.add(scopedNoteHashesCLA.array[hint.noteHashIndex].counter),squashedNullifierCounters.add(scopedNullifiersCLA.array[hint.nullifierIndex].counter)}return{filteredNoteHashes:scopedNoteHashesCLA.getActiveItems().filter(nh=>!squashedNoteHashCounters.has(nh.counter)),filteredNullifiers:scopedNullifiersCLA.getActiveItems().filter(n=>!squashedNullifierCounters.has(n.counter)),filteredPrivateLogs:taggedPrivateLogs.filter(item=>!squashedNoteHashCounters.has(item.sideEffect.noteHashCounter)).map(item=>new OrderedSideEffect(item.sideEffect.log,item.counter))}}__name(squashTransientSideEffects,"squashTransientSideEffects");async function verifyReadRequests(node,anchorBlockHash,noteHashReadRequests,nullifierReadRequests,scopedNoteHashesCLA,scopedNullifiersCLA){let noteHashReadRequestsCLA=new ClaimedLengthArray(padArrayEnd(noteHashReadRequests,ScopedReadRequest.empty(),64),noteHashReadRequests.length),nullifierReadRequestsCLA=new ClaimedLengthArray(padArrayEnd(nullifierReadRequests,ScopedReadRequest.empty(),64),nullifierReadRequests.length),noteHashResetActions=getNoteHashReadRequestResetActions(noteHashReadRequestsCLA,scopedNoteHashesCLA),nullifierResetActions=getNullifierReadRequestResetActions(nullifierReadRequestsCLA,scopedNullifiersCLA),settledNoteHashReads=[];for(let i=0;i<noteHashResetActions.actions.length;i++)noteHashResetActions.actions[i]===ReadRequestActionEnum.READ_AS_SETTLED&&settledNoteHashReads.push({index:i,value:noteHashReadRequests[i].value});let settledNullifierReads=[];for(let i=0;i<nullifierResetActions.actions.length;i++)nullifierResetActions.actions[i]===ReadRequestActionEnum.READ_AS_SETTLED&&settledNullifierReads.push({index:i,value:nullifierReadRequests[i].value});let[noteHashResults,nullifierResults]=await Promise.all([settledNoteHashReads.length>0?node.findLeavesIndexes(anchorBlockHash,MerkleTreeId.NOTE_HASH_TREE,settledNoteHashReads.map(({value})=>value)):[],settledNullifierReads.length>0?node.findLeavesIndexes(anchorBlockHash,MerkleTreeId.NULLIFIER_TREE,settledNullifierReads.map(({value})=>value)):[]]);for(let i=0;i<settledNoteHashReads.length;i++)if(!noteHashResults[i])throw new Error(`Note hash read request at index ${settledNoteHashReads[i].index} is reading an unknown note hash: ${settledNoteHashReads[i].value}`);for(let i=0;i<settledNullifierReads.length;i++)if(!nullifierResults[i])throw new Error(`Nullifier read request at index ${settledNullifierReads[i].index} is reading an unknown nullifier: ${settledNullifierReads[i].value}`)}__name(verifyReadRequests,"verifyReadRequests");function splitOrderedSideEffects(effects,minRevertibleSideEffectCounter){let revertibleSideEffects=[],nonRevertibleSideEffects=[];return effects.forEach(effect=>{minRevertibleSideEffectCounter===0||effect.counter<minRevertibleSideEffectCounter?nonRevertibleSideEffects.push(effect.sideEffect):revertibleSideEffects.push(effect.sideEffect)}),[nonRevertibleSideEffects,revertibleSideEffects]}__name(splitOrderedSideEffects,"splitOrderedSideEffects");function meterGasUsed(data,isPrivateOnlyTx){let meteredDAFields=0,meteredL2Gas=0,numNoteHashes=arrayNonEmptyLength(data.noteHashes,hash5=>hash5.isEmpty());meteredDAFields+=numNoteHashes,meteredL2Gas+=numNoteHashes*(isPrivateOnlyTx?9200:19275);let numNullifiers=arrayNonEmptyLength(data.nullifiers,nullifier=>nullifier.isEmpty());meteredDAFields+=numNullifiers,meteredL2Gas+=numNullifiers*(isPrivateOnlyTx?16e3:30800);let numL2toL1Messages=arrayNonEmptyLength(data.l2ToL1Msgs,msg=>msg.isEmpty());meteredDAFields+=numL2toL1Messages,meteredL2Gas+=numL2toL1Messages*(isPrivateOnlyTx?5200:5239);let numPrivatelogs=arrayNonEmptyLength(data.privateLogs,log2=>log2.isEmpty());meteredDAFields+=data.privateLogs.reduce((acc,log2)=>log2.isEmpty()?acc:acc+log2.emittedLength+1,0),meteredL2Gas+=numPrivatelogs*2500;let numContractClassLogs=arrayNonEmptyLength(data.contractClassLogsHashes,log2=>log2.isEmpty());meteredDAFields+=data.contractClassLogsHashes.reduce((acc,log2)=>log2.isEmpty()?acc:acc+log2.logHash.length+1,0),meteredL2Gas+=numContractClassLogs*73e3;let meteredDAGas=meteredDAFields*32;if(data.publicCallRequests){let numPublicCallRequests=arrayNonEmptyLength(data.publicCallRequests,req=>req.isEmpty());meteredL2Gas+=numPublicCallRequests*2e4}return Gas.from({l2Gas:meteredL2Gas,daGas:meteredDAGas})}__name(meterGasUsed,"meterGasUsed");async function enrichSimulationError(err,contractStore,contractClassService,anchorHeader,logger3){let mentionedFunctions=new Map;err.getCallStack().forEach(({contractAddress,functionSelector})=>{mentionedFunctions.has(contractAddress.toString())||mentionedFunctions.set(contractAddress.toString(),new Set),functionSelector&&mentionedFunctions.get(contractAddress.toString()).add(functionSelector)}),await Promise.all([...mentionedFunctions.entries()].map(async([contractAddress,fnSelectors])=>{let parsedContractAddress=AztecAddress.fromStringUnsafe(contractAddress),classId=await contractClassService.getCurrentClassId(parsedContractAddress,anchorHeader),artifact=classId&&await contractStore.getContractArtifact(classId);if(artifact){err.enrichWithContractName(parsedContractAddress,artifact.name);let selectorToNameMap=new Map;await Promise.all(artifact.functions.map(async fn=>{let selector=await FunctionSelector.fromNameAndParameters(fn);selectorToNameMap.set(selector.toString(),fn.name)}));for(let fnSelector of fnSelectors)selectorToNameMap.has(fnSelector.toString())?err.enrichWithFunctionName(parsedContractAddress,fnSelector,selectorToNameMap.get(fnSelector.toString())):logger3.warn(`Could not find function artifact in contract ${artifact.name} for function '${fnSelector}' when enriching error callstack`)}else logger3.warn(`Could not find contract in database for address: ${parsedContractAddress} when enriching error callstack`)}))}__name(enrichSimulationError,"enrichSimulationError");async function enrichPublicSimulationError(err,contractStore,contractClassService,anchorHeader,logger3){let callStack=err.getCallStack(),originalFailingFunction=callStack[callStack.length-1];if(!originalFailingFunction)throw new Error("Original failing function not found when enriching public simulation, missing callstack");let classId=await contractClassService.getCurrentClassId(originalFailingFunction.contractAddress,anchorHeader),artifact=classId&&await contractStore.getPublicFunctionArtifact(classId);if(!artifact)throw new Error(`Artifact not found when enriching public simulation error. Contract address: ${originalFailingFunction.contractAddress}.`);let assertionMessage=resolveAssertionMessageFromRevertData(err.revertData,artifact);assertionMessage&&err.setOriginalMessage(err.getOriginalMessage()+`${assertionMessage}`);let debugInfo=await contractStore.getPublicFunctionDebugMetadata(classId),noirCallStack=err.getNoirCallStack();if(debugInfo){if(isNoirCallStackUnresolved(noirCallStack))try{let parsedCallStack=resolveOpcodeLocations(noirCallStack,debugInfo.debugSymbols,debugInfo.files,0);err.setNoirCallStack(parsedCallStack)}catch(err2){logger3.warn(`Could not resolve noir call stack for ${originalFailingFunction.contractAddress.toString()}:${originalFailingFunction.functionName?.toString()??""}: ${err2}`)}await enrichSimulationError(err,contractStore,contractClassService,anchorHeader,logger3)}}__name(enrichPublicSimulationError,"enrichPublicSimulationError");var JobCoordinator=class{static{__name(this,"JobCoordinator")}log;kvStore;#currentJobId;#stores=new Map;constructor(kvStore,bindings){this.kvStore=kvStore,this.log=createLogger("pxe:job_coordinator",bindings)}registerStore(store){if(this.#stores.has(store.storeName))throw new Error(`Store "${store.storeName}" is already registered`);this.#stores.set(store.storeName,store),this.log.debug(`Registered staged store: ${store.storeName}`)}registerStores(stores){for(let store of stores)this.registerStore(store)}beginJob(){if(this.#currentJobId)throw new Error(`Cannot begin job: job ${this.#currentJobId} is already in progress. This should not happen - ensure jobs are properly committed or aborted.`);let jobId=randomBytes(8).toString("hex");return this.#currentJobId=jobId,this.log.debug(`Started job ${jobId}`),jobId}async commitJob(jobId){if(!this.#currentJobId||this.#currentJobId!==jobId)throw new Error(`Cannot commit job ${jobId}: no matching job in progress. Current job: ${this.#currentJobId??"none"}`);this.log.debug(`Committing job ${jobId}`),await this.kvStore.transactionAsync(async()=>{for(let store of this.#stores.values())await store.commit(jobId)}),this.#currentJobId=void 0,this.log.debug(`Job ${jobId} committed successfully`)}async abortJob(jobId){(!this.#currentJobId||this.#currentJobId!==jobId)&&this.log.warn(`Abort called for job ${jobId} but current job is ${this.#currentJobId??"none"}`),this.log.debug(`Aborting job ${jobId}`);for(let store of this.#stores.values())await store.discardStaged(jobId);this.#currentJobId=void 0,this.log.debug(`Job ${jobId} aborted`)}hasJobInProgress(){return this.#currentJobId!==void 0}};var TxResolverService=class{static{__name(this,"TxResolverService")}aztecNode;constructor(aztecNode){this.aztecNode=aztecNode}async resolveTxs(txHashes,anchorBlockNumber){let nonZeroTxHashes=txHashes.filter(h=>!h.isZero()).map(h=>TxHash.fromField(h)),uniqueTxHashes=uniqueBy(nonZeroTxHashes,h=>h.toString()),fetched=await Promise.all(uniqueTxHashes.map(h=>this.aztecNode.getTxReceipt(h,{includeTxEffect:!0}))),txEffects=new Map(uniqueTxHashes.map((h,i)=>{let receipt=fetched[i];return!receipt.isMined()||!receipt.txEffect?[h.toString(),void 0]:[h.toString(),{data:receipt.txEffect,l2BlockNumber:receipt.blockNumber,l2BlockHash:receipt.blockHash,txIndexInBlock:receipt.txIndexInBlock,slotNumber:receipt.slotNumber}]}).filter(entry=>entry[1]!==void 0));return txHashes.map(txHashField=>{let txHash=TxHash.fromField(txHashField),txEffect=txEffects.get(txHash.toString());if(!txEffect||txEffect.l2BlockNumber>anchorBlockNumber)return null;let data=txEffect.data;if(data.nullifiers.length===0)throw new Error(`Tx effect for ${txHash} has no nullifiers`);return new ResolvedTx(data.txHash,data.noteHashes,data.nullifiers[0],txEffect.l2BlockNumber,txEffect.l2BlockHash.toFr())})}};import{getVKTreeRoot as getVKTreeRoot2}from"@aztec/noir-protocol-circuits-types/vk-tree";import{privateKernelResetDimensionsConfig}from"@aztec/noir-protocol-circuits-types/client";var NULL_SIMULATE_OUTPUT={publicInputs:PrivateKernelCircuitPublicInputs.empty(),verificationKey:VerificationKeyData.empty(),outputWitness:new Map,bytecode:Buffer.from([])};import{getVKIndex,getVKSiblingPath}from"@aztec/noir-protocol-circuits-types/vk-tree";var DelayedPublicMutableValuesWithHash=class{static{__name(this,"DelayedPublicMutableValuesWithHash")}dpmv;constructor(svc,sdc){this.dpmv=new DelayedPublicMutableValues(svc,sdc)}async toFields(){return[...this.dpmv.toFields(),await this.dpmv.hash()]}async writeToTree(delayedPublicMutableSlot,storageWrite){let fields=await this.toFields();for(let i=0;i<fields.length;i++)await storageWrite(delayedPublicMutableSlot.add(new Fr(i)),fields[i])}static async getContractUpdateSlots(contractAddress){let delayedPublicMutableSlot=await deriveStorageSlotInMap(new Fr(1),contractAddress),delayedPublicMutableHashSlot=delayedPublicMutableSlot.add(new Fr(DELAYED_PUBLIC_MUTABLE_VALUES_LEN));return{delayedPublicMutableSlot,delayedPublicMutableHashSlot}}};async function toArray(iterator){let arr=[];for await(let i of iterator)arr.push(i);return arr}__name(toArray,"toArray");function secretKeyStorageSuffix(prefix){return prefix==="n"?"nhk_m":`${prefix}sk_m`}__name(secretKeyStorageSuffix,"secretKeyStorageSuffix");async function completeAccountKeys(keys){let{masterNullifierHidingSecretKey,masterIncomingViewingSecretKey,masterOutgoingViewingSecretKey,masterTaggingSecretKey,masterMessageSigningPublicKey,masterFallbackPublicKey}=keys,masterNullifierHidingPublicKey=await derivePublicKeyFromSecretKey(masterNullifierHidingSecretKey),masterIncomingViewingPublicKey=await derivePublicKeyFromSecretKey(masterIncomingViewingSecretKey),masterOutgoingViewingPublicKey=await derivePublicKeyFromSecretKey(masterOutgoingViewingSecretKey),masterTaggingPublicKey=await derivePublicKeyFromSecretKey(masterTaggingSecretKey);for(let[name,publicKey]of Object.entries({masterNullifierHidingPublicKey,masterIncomingViewingPublicKey,masterOutgoingViewingPublicKey,masterTaggingPublicKey,masterMessageSigningPublicKey,masterFallbackPublicKey}))if(publicKey.isInfinite)throw new Error(`Cannot register an account with an infinity ${name}.`);let publicKeys=new PublicKeys(await hashPublicKey(masterNullifierHidingPublicKey),masterIncomingViewingPublicKey,await hashPublicKey(masterOutgoingViewingPublicKey),await hashPublicKey(masterTaggingPublicKey),await hashPublicKey(masterMessageSigningPublicKey),await hashPublicKey(masterFallbackPublicKey));return{masterNullifierHidingSecretKey,masterIncomingViewingSecretKey,masterOutgoingViewingSecretKey,masterTaggingSecretKey,masterNullifierHidingPublicKey,masterOutgoingViewingPublicKey,masterTaggingPublicKey,publicKeys}}__name(completeAccountKeys,"completeAccountKeys");var KeyStore=class{static{__name(this,"KeyStore")}static SCHEMA_VERSION=1;#db;#keys;constructor(database){this.#db=database,this.#keys=database.openMap("key_store")}async addAccount(keys,partialAddress){let accountKeys=await completeAccountKeys(keys);return this.#storeAccountKeys(accountKeys,partialAddress)}async getAccounts(){return(await this.#db.transactionAsync(()=>toArray(this.#keys.keysAsync()))).filter(key=>key.endsWith("-ivsk_m")).map(key=>key.split("-")[0]).map(account=>AztecAddress.fromStringUnsafe(account))}async hasAccount(account){return!!await this.#db.transactionAsync(()=>this.#keys.getAsync(`${account.toString()}-ivsk_m`))}getKeyValidationRequest(pkMHash,contractAddress){return this.#db.transactionAsync(async()=>{let[keyPrefix,account]=await this.getKeyPrefixAndAccount(pkMHash),pkMBuffer=await this.#keys.getAsync(`${account.toString()}-${keyPrefix}pk_m`);if(!pkMBuffer)throw new Error(`Could not find ${keyPrefix}pk_m for account ${account.toString()} whose address was successfully obtained with ${keyPrefix}pk_m_hash ${pkMHash.toString()}.`);let pkM=Point.fromBuffer(pkMBuffer),skStorageSuffix=secretKeyStorageSuffix(keyPrefix),skMBuffer=await this.#keys.getAsync(`${account.toString()}-${skStorageSuffix}`);if(!skMBuffer)throw new Error(`Could not find ${skStorageSuffix} for account ${account.toString()} whose address was successfully obtained with ${keyPrefix}pk_m_hash ${pkMHash.toString()}.`);let skM=GrumpkinScalar.fromBuffer(skMBuffer);if(!(await hashPublicKey(pkM)).equals(pkMHash))throw new Error(`Could not find ${keyPrefix}pkM for ${keyPrefix}pk_m_hash ${pkMHash.toString()}.`);if(!(await derivePublicKeyFromSecretKey(skM)).equals(pkM))throw new Error(`Could not derive ${keyPrefix}pkM from ${keyPrefix}skM.`);let skApp=await computeAppSecretKey(skM,contractAddress,keyPrefix);return new KeyValidationRequest(pkMHash,skApp)})}async getMasterNullifierHidingPublicKey(account){return Point.fromBuffer(await this.#getMasterKeyBuffer(account,"npk_m"))}async getMasterIncomingViewingPublicKey(account){return Point.fromBuffer(await this.#getMasterKeyBuffer(account,"ivpk_m"))}async getMasterOutgoingViewingPublicKey(account){return Point.fromBuffer(await this.#getMasterKeyBuffer(account,"ovpk_m"))}async getMasterTaggingPublicKey(account){return Point.fromBuffer(await this.#getMasterKeyBuffer(account,"tpk_m"))}async getMasterIncomingViewingSecretKey(account){return GrumpkinScalar.fromBuffer(await this.#getMasterKeyBuffer(account,"ivsk_m"))}async getAccountSecretKeys(account){let[nhkM,ivskM,ovskM,tskM]=await this.#getMasterKeyBuffers(account,["nhk_m","ivsk_m","ovsk_m","tsk_m"]);return{masterNullifierHidingSecretKey:GrumpkinScalar.fromBuffer(nhkM),masterIncomingViewingSecretKey:GrumpkinScalar.fromBuffer(ivskM),masterOutgoingViewingSecretKey:GrumpkinScalar.fromBuffer(ovskM),masterTaggingSecretKey:GrumpkinScalar.fromBuffer(tskM)}}async getAppOutgoingViewingSecretKey(account,app){let masterOutgoingViewingSecretKey=GrumpkinScalar.fromBuffer(await this.#getMasterKeyBuffer(account,"ovsk_m"));return poseidon2HashWithSeparator([masterOutgoingViewingSecretKey.hi,masterOutgoingViewingSecretKey.lo,app],DomainSeparator.OVSK_M)}getMasterSecretKey(pkMHash){return this.#db.transactionAsync(async()=>{let[keyPrefix,account]=await this.getKeyPrefixAndAccount(pkMHash),skStorageSuffix=secretKeyStorageSuffix(keyPrefix),secretKeyBuffer=await this.#keys.getAsync(`${account.toString()}-${skStorageSuffix}`);if(!secretKeyBuffer)throw new Error(`Could not find ${skStorageSuffix} for ${keyPrefix}pk_m_hash ${pkMHash.toString()}. This should not happen.`);let skM=GrumpkinScalar.fromBuffer(secretKeyBuffer),derivedPkM=await derivePublicKeyFromSecretKey(skM);if(!(await hashPublicKey(derivedPkM)).equals(pkMHash))throw new Error(`Could not find ${skStorageSuffix} for ${keyPrefix}pk_m_hash ${pkMHash.toString()} in secret keys buffer.`);return skM})}accountHasKey(account,pkMHash){return this.#db.transactionAsync(async()=>{let pkMHashBuffer=serializeToBuffer(pkMHash);for(let prefix of KEY_PREFIXES){let stored=await this.#keys.getAsync(`${account.toString()}-${prefix}pk_m_hash`);if(stored&&Buffer.from(stored).equals(pkMHashBuffer))return!0}return!1})}async getKeyPrefixAndAccount(value){let valueBuffer=serializeToBuffer(value);for await(let[key,val]of this.#keys.entriesAsync())if(Buffer.from(val).equals(valueBuffer)){for(let prefix of KEY_PREFIXES)if(key.includes(`-${prefix}`)){let account=AztecAddress.fromStringUnsafe(key.split("-")[0]);return[prefix,account]}}throw new Error("Could not find key prefix.")}async#storeAccountKeys(accountKeys,partialAddress){let{masterNullifierHidingSecretKey,masterIncomingViewingSecretKey,masterOutgoingViewingSecretKey,masterTaggingSecretKey,masterNullifierHidingPublicKey,masterOutgoingViewingPublicKey,masterTaggingPublicKey,publicKeys}=accountKeys,completeAddress=await CompleteAddress.fromPublicKeysAndPartialAddress(publicKeys,partialAddress),{address:account}=completeAddress,masterIncomingViewingPublicKeyHash=await hashPublicKey(publicKeys.ivpkM);return await this.#db.transactionAsync(async()=>{await this.#keys.set(`${account.toString()}-ivsk_m`,masterIncomingViewingSecretKey.toBuffer()),await this.#keys.set(`${account.toString()}-ovsk_m`,masterOutgoingViewingSecretKey.toBuffer()),await this.#keys.set(`${account.toString()}-tsk_m`,masterTaggingSecretKey.toBuffer()),await this.#keys.set(`${account.toString()}-nhk_m`,masterNullifierHidingSecretKey.toBuffer()),await this.#keys.set(`${account.toString()}-npk_m`,masterNullifierHidingPublicKey.toBuffer()),await this.#keys.set(`${account.toString()}-ivpk_m`,publicKeys.ivpkM.toBuffer()),await this.#keys.set(`${account.toString()}-ovpk_m`,masterOutgoingViewingPublicKey.toBuffer()),await this.#keys.set(`${account.toString()}-tpk_m`,masterTaggingPublicKey.toBuffer()),await this.#keys.set(`${account.toString()}-npk_m_hash`,publicKeys.npkMHash.toBuffer()),await this.#keys.set(`${account.toString()}-ivpk_m_hash`,masterIncomingViewingPublicKeyHash.toBuffer()),await this.#keys.set(`${account.toString()}-ovpk_m_hash`,publicKeys.ovpkMHash.toBuffer()),await this.#keys.set(`${account.toString()}-tpk_m_hash`,publicKeys.tpkMHash.toBuffer())}),completeAddress}async#getMasterKeyBuffer(account,suffix){let[buffer]=await this.#getMasterKeyBuffers(account,[suffix]);return buffer}async#getMasterKeyBuffers(account,suffixes){let buffers=await this.#db.transactionAsync(()=>Promise.all(suffixes.map(suffix=>this.#keys.getAsync(`${account.toString()}-${suffix}`))));if(!buffers.every(buffer=>buffer!==void 0))throw new Error(`Account ${account.toString()} does not exist. Registered accounts: ${await this.getAccounts()}.`);return buffers}};var AddressStore=class{static{__name(this,"AddressStore")}#store;#completeAddresses;#completeAddressIndex;constructor(store){this.#store=store,this.#completeAddresses=this.#store.openArray("complete_addresses"),this.#completeAddressIndex=this.#store.openMap("complete_address_index")}addCompleteAddress(completeAddress){return this.#store.transactionAsync(async()=>{let addressString=completeAddress.address.toString(),buffer=completeAddress.toBuffer(),existing=await this.#completeAddressIndex.getAsync(addressString);if(existing===void 0){let index=await this.#completeAddresses.lengthAsync();return await this.#completeAddresses.push(buffer),await this.#completeAddressIndex.set(addressString,index),!0}else{let existingBuffer=await this.#completeAddresses.atAsync(existing);if(existingBuffer&&Buffer.from(existingBuffer).equals(buffer))return!1;throw new Error(`Complete address with aztec address ${addressString} but different public key or partial key already exists in memory database`)}})}getCompleteAddress(account){return this.#store.transactionAsync(async()=>{let index=await this.#completeAddressIndex.getAsync(account.toString());if(index===void 0)return;let value=await this.#completeAddresses.atAsync(index);return value?await CompleteAddress.fromBuffer(value):void 0})}getCompleteAddresses(){return this.#store.transactionAsync(async()=>await Promise.all((await toArray(this.#completeAddresses.valuesAsync())).map(v=>CompleteAddress.fromBuffer(v))))}};var AnchorBlockStore=class{static{__name(this,"AnchorBlockStore")}#store;#synchronizedHeader;constructor(store){this.#store=store,this.#synchronizedHeader=this.#store.openSingleton("header")}async setHeader(header){await this.#synchronizedHeader.set(header.toBuffer())}async getBlockHeader(){let headerBuffer=await this.#store.transactionAsync(()=>this.#synchronizedHeader.getAsync());if(!headerBuffer)throw new Error("Trying to get block header with a not-yet-synchronized PXE - this should never happen");return BlockHeader.fromBuffer(headerBuffer)}};var CapsuleStore=class{static{__name(this,"CapsuleStore")}storeName="capsule";#store;#capsules;#stagedCapsules;logger;constructor(store){this.#store=store,this.#capsules=this.#store.openMap("capsules"),this.#stagedCapsules=new Map,this.logger=createLogger("pxe:capsule-data-provider")}#getJobStagedCapsules(jobId){let jobStagedCapsules=this.#stagedCapsules.get(jobId);return jobStagedCapsules||(jobStagedCapsules=new Map,this.#stagedCapsules.set(jobId,jobStagedCapsules)),jobStagedCapsules}async#getFromStage(jobId,dbSlotKey){let staged=this.#getJobStagedCapsules(jobId).get(dbSlotKey),dbValue=await this.#loadCapsuleFromDb(dbSlotKey);return staged!==void 0?staged:dbValue}#setOnStage(jobId,dbSlotKey,capsuleData){this.#getJobStagedCapsules(jobId).set(dbSlotKey,capsuleData)}#deleteOnStage(jobId,dbSlotKey){this.#getJobStagedCapsules(jobId).set(dbSlotKey,null)}async#loadCapsuleFromDb(dbSlotKey){let dataBuffer=await this.#capsules.getAsync(dbSlotKey);return dataBuffer||null}async commit(jobId){let jobStagedCapsules=this.#getJobStagedCapsules(jobId);for(let[key,value]of jobStagedCapsules)value===null?await this.#capsules.delete(key):await this.#capsules.set(key,value);this.#stagedCapsules.delete(jobId)}discardStaged(jobId){return this.#stagedCapsules.delete(jobId),Promise.resolve()}setCapsule(contractAddress,slot,capsule,jobId,scope){let dbSlotKey=dbSlotToKey(contractAddress,slot,scope);this.#setOnStage(jobId,dbSlotKey,Buffer.concat(capsule.map(value=>value.toBuffer())))}getCapsule(contractAddress,slot,jobId,scope){return this.#store.transactionAsync(()=>this.#getCapsuleInternal(contractAddress,slot,jobId,scope))}async#getCapsuleInternal(contractAddress,slot,jobId,scope){let dataBuffer=await this.#getFromStage(jobId,dbSlotToKey(contractAddress,slot,scope));if(!dataBuffer)return this.logger.trace(`Data not found for contract ${contractAddress.toString()} and slot ${slot.toString()}`),null;let capsule=[];for(let i=0;i<dataBuffer.length;i+=Fr.SIZE_IN_BYTES)capsule.push(Fr.fromBuffer(dataBuffer.subarray(i,i+Fr.SIZE_IN_BYTES)));return capsule}deleteCapsule(contractAddress,slot,jobId,scope){this.#deleteOnStage(jobId,dbSlotToKey(contractAddress,slot,scope))}copyCapsule(contractAddress,srcSlot,dstSlot,numEntries,jobId,scope){return this.#store.transactionAsync(async()=>{let indexes=Array.from(Array(numEntries).keys());srcSlot.lt(dstSlot)&&indexes.reverse();for(let i of indexes){let currentSrcSlot=dbSlotToKey(contractAddress,srcSlot.add(new Fr(i)),scope),currentDstSlot=dbSlotToKey(contractAddress,dstSlot.add(new Fr(i)),scope),toCopy=await this.#getFromStage(jobId,currentSrcSlot);if(!toCopy)throw new Error(`Attempted to copy empty slot ${currentSrcSlot} for contract ${contractAddress.toString()}`);this.#setOnStage(jobId,currentDstSlot,toCopy)}})}appendToCapsuleArray(contractAddress,baseSlot,content,jobId,scope){return this.#store.transactionAsync(async()=>{let lengthData=await this.#getCapsuleInternal(contractAddress,baseSlot,jobId,scope),currentLength=lengthData?lengthData[0].toNumber():0;for(let i=0;i<content.length;i++){let nextSlot=arraySlot(baseSlot,currentLength+i);this.setCapsule(contractAddress,nextSlot,content[i],jobId,scope)}let newLength=currentLength+content.length;this.setCapsule(contractAddress,baseSlot,[new Fr(newLength)],jobId,scope)})}readCapsuleArray(contractAddress,baseSlot,jobId,scope){return this.#store.transactionAsync(async()=>{let maybeLength=await this.#getCapsuleInternal(contractAddress,baseSlot,jobId,scope),length=maybeLength?maybeLength[0].toBigInt():0n,values=[];for(let i=0;i<length;i++){let currentValue=await this.#getCapsuleInternal(contractAddress,arraySlot(baseSlot,i),jobId,scope);if(currentValue==null)throw new Error(`Expected non-empty value at capsule array in base slot ${baseSlot} at index ${i} for contract ${contractAddress}`);values.push(currentValue)}return values})}setCapsuleArray(contractAddress,baseSlot,content,jobId,scope){return this.#store.transactionAsync(async()=>{let maybeLength=await this.#getCapsuleInternal(contractAddress,baseSlot,jobId,scope),originalLength=maybeLength?maybeLength[0].toNumber():0;this.setCapsule(contractAddress,baseSlot,[new Fr(content.length)],jobId,scope);for(let i=0;i<content.length;i++)this.setCapsule(contractAddress,arraySlot(baseSlot,i),content[i],jobId,scope);for(let i=content.length;i<originalLength;i++)this.deleteCapsule(contractAddress,arraySlot(baseSlot,i),jobId,scope)})}};function dbSlotToKey(contractAddress,slot,scope){return[contractAddress.toString(),scope.toString(),slot.toString()].join(":")}__name(dbSlotToKey,"dbSlotToKey");function arraySlot(baseSlot,index){return baseSlot.add(new Fr(1)).add(new Fr(index))}__name(arraySlot,"arraySlot");var PrivateFunctionsTree=class _PrivateFunctionsTree{static{__name(this,"PrivateFunctionsTree")}privateFunctions;tree;constructor(privateFunctions){this.privateFunctions=privateFunctions}static async create(artifact){let privateFunctions=await Promise.all(artifact.functions.filter(fn=>fn.functionType===FunctionType.PRIVATE).map(getContractClassPrivateFunctionFromArtifact));return new _PrivateFunctionsTree(privateFunctions)}async getFunctionMembershipWitness(selector){let fn=this.privateFunctions.find(f=>f.selector.equals(selector));if(!fn)throw new Error(`Private function with selector ${selector.toString()} not found in contract class.`);let leaf=await computePrivateFunctionLeaf(fn),tree=await this.getTree(),index=tree.getIndex(leaf),path=tree.getSiblingPath(index);return new MembershipWitness(7,BigInt(index),assertLength(path.map(Fr.fromBuffer),7))}async getTree(){return this.tree||(this.tree=await computePrivateFunctionsTree(this.privateFunctions)),this.tree}};var VERSION5=1,SerializableContractClassData=class _SerializableContractClassData{static{__name(this,"SerializableContractClassData")}version=VERSION5;id;artifactHash;privateFunctionsRoot;publicBytecodeCommitment;privateFunctions;constructor(data){this.id=data.id,this.artifactHash=data.artifactHash,this.privateFunctionsRoot=data.privateFunctionsRoot,this.publicBytecodeCommitment=data.publicBytecodeCommitment,this.privateFunctions=data.privateFunctions}toBuffer(){return serializeToBuffer(numToUInt8(this.version),this.id,this.artifactHash,this.privateFunctionsRoot,this.publicBytecodeCommitment,this.privateFunctions.length,...this.privateFunctions.map(fn=>serializeToBuffer(fn.selector,fn.vkHash)))}static fromBuffer(bufferOrReader){let reader=BufferReader.asReader(bufferOrReader),version2=reader.readUInt8();if(version2!==VERSION5)throw new Error(`Unexpected contract class data version ${version2}`);return new _SerializableContractClassData({id:reader.readObject(Fr),artifactHash:reader.readObject(Fr),privateFunctionsRoot:reader.readObject(Fr),publicBytecodeCommitment:reader.readObject(Fr),privateFunctions:reader.readVector({fromBuffer:__name(r2=>({selector:r2.readObject(FunctionSelector),vkHash:r2.readObject(Fr)}),"fromBuffer")})})}},ContractStore=class{static{__name(this,"ContractStore")}#privateFunctionTrees=new Map;#contractArtifactCache=new Map;#store;#contractArtifacts;#contractClassData;#contractInstances;constructor(store){this.#store=store,this.#contractArtifacts=store.openMap("contract_artifacts"),this.#contractClassData=store.openMap("contract_classes"),this.#contractInstances=store.openMap("contracts_instances")}async addContractArtifact(contract,contractClassWithIdAndPreimage){let contractClass=contractClassWithIdAndPreimage??await getContractClassFromArtifact(contract),key=contractClass.id.toString();if(this.#contractArtifactCache.has(key))return contractClass.id;let privateFunctions=contract.functions.filter(functionArtifact=>functionArtifact.functionType===FunctionType.PRIVATE),privateSelectors=await Promise.all(privateFunctions.map(async fn=>(await FunctionSelector.fromNameAndParameters(fn.name,fn.parameters)).toString()));if(privateSelectors.length!==new Set(privateSelectors).size)throw new Error("Repeated function selectors of private functions");return this.#contractArtifactCache.set(key,contract),await this.#store.transactionAsync(async()=>{await this.#contractArtifacts.set(key,contractArtifactToBuffer(contract)),await this.#contractClassData.set(key,new SerializableContractClassData(contractClass).toBuffer())}),contractClass.id}async addContractInstance(contract){await this.#store.transactionAsync(async()=>{await this.#contractInstances.set(contract.address.toString(),new SerializableContractInstancePreimage(contract).toBuffer())})}async#getPrivateFunctionTreeForClassId(classId){if(!this.#privateFunctionTrees.has(classId.toString())){let artifact=await this.getContractArtifact(classId);if(!artifact)return;let tree=await PrivateFunctionsTree.create(artifact);this.#privateFunctionTrees.set(classId.toString(),tree)}return this.#privateFunctionTrees.get(classId.toString())}getContractsAddresses(){return this.#store.transactionAsync(async()=>(await toArray(this.#contractInstances.keysAsync())).map(AztecAddress.fromStringUnsafe))}getContractInstance(contractAddress){return this.#store.transactionAsync(async()=>{let contract=await this.#contractInstances.getAsync(contractAddress.toString());return contract&&SerializableContractInstancePreimage.fromBuffer(contract).withAddress(contractAddress)})}async getContractArtifact(contractClassId){let key=contractClassId.toString(),cached2=this.#contractArtifactCache.get(key);if(cached2)return cached2;let artifact=await this.#store.transactionAsync(async()=>{let buf=await this.#contractArtifacts.getAsync(key);return buf&&contractArtifactFromBuffer(buf)});return artifact&&this.#contractArtifactCache.set(key,artifact),artifact}async getContractClassWithPreimage(contractClassId){let key=contractClassId.toString(),buf=await this.#store.transactionAsync(()=>this.#contractClassData.getAsync(key));if(!buf)return;let classData=SerializableContractClassData.fromBuffer(buf),artifact=await this.getContractArtifact(contractClassId);if(!artifact)return;let packedBytecode=artifact.functions.find(f=>f.name==="public_dispatch")?.bytecode??Buffer.alloc(0);return{...classData,packedBytecode}}async getFunctionArtifact(contractClassId,selector){let artifact=await this.getContractArtifact(contractClassId);return artifact?{...assertSelectorInArtifact(artifact,await findFunctionArtifactBySelector(artifact,selector),{contractClassId,selector}),contractName:artifact.name}:void 0}async getFunctionArtifactWithDebugMetadata(contractClassId,selector){let artifact=await this.getContractArtifact(contractClassId);if(!artifact)return;let fn=assertSelectorInArtifact(artifact,await findFunctionArtifactBySelector(artifact,selector),{contractClassId,selector});return{...fn,contractName:artifact.name,debug:getFunctionDebugMetadata(artifact,fn)}}async getPublicFunctionArtifact(contractClassId){let artifact=await this.getContractArtifact(contractClassId),fn=artifact&&artifact.functions.find(f=>f.functionType===FunctionType.PUBLIC);return fn&&{...fn,contractName:artifact.name}}async getFunctionDebugMetadata(contractClassId,selector){let artifact=await this.getContractArtifact(contractClassId);if(!artifact)return;let fn=await findFunctionArtifactBySelector(artifact,selector);return fn&&getFunctionDebugMetadata(artifact,fn)}async getPublicFunctionDebugMetadata(contractClassId){let artifact=await this.getContractArtifact(contractClassId),fn=artifact&&artifact.functions.find(f=>f.functionType===FunctionType.PUBLIC);return fn&&getFunctionDebugMetadata(artifact,fn)}async getFunctionMembershipWitness(contractClassId,selector){return(await this.#getPrivateFunctionTreeForClassId(contractClassId))?.getFunctionMembershipWitness(selector)}async getDebugContractName(contractClassId){return(await this.getContractArtifact(contractClassId))?.name}async getDebugFunctionName(contractClassId,selector){let artifact=await this.getContractArtifact(contractClassId),fn=artifact&&await findFunctionAbiBySelector(artifact,selector);return`${artifact?.name??contractClassId}:${fn?.name??selector}`}async getFunctionCall(functionName,args,to,contractClassId){let artifact=await this.getContractArtifact(contractClassId);if(!artifact)throw new Error(`No artifact registered for contract class ${contractClassId} (contract ${to}): register it by calling wallet.registerContract(...).
|
|
213
213
|
See docs for context: https://docs.aztec.network/errors/14`);let functionDao=artifact.functions.find(f=>f.name===functionName);if(!functionDao)throw new Error(`Unknown function ${functionName} in contract ${artifact.name}.`);let selector=await FunctionSelector.fromNameAndParameters(functionDao.name,functionDao.parameters);return FunctionCall.from({name:functionDao.name,to,selector,type:functionDao.functionType,hideMsgSender:!1,isStatic:functionDao.isStatic,args:encodeArguments(functionDao,args),returnTypes:functionDao.returnTypes})}};function assertSelectorInArtifact(artifact,fn,context2){if(!fn)throw new Error(`Function with selector ${context2.selector} not found in the registered artifact for contract class ${context2.contractClassId} (${artifact.name}). Either no function with this selector exists in the contract, or the registered artifact does not match the class id (re-register it via wallet.registerContract(...)).`);return fn}__name(assertSelectorInArtifact,"assertSelectorInArtifact");var StoredNote=class _StoredNote{static{__name(this,"StoredNote")}noteDao;scopes;constructor(noteDao,scopes){this.noteDao=noteDao,this.scopes=scopes}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer),noteDao=NoteDao.fromBuffer(reader),scopes=reader.readVector({fromBuffer:__name(r2=>r2.readString(),"fromBuffer")});return new _StoredNote(noteDao,new Set(scopes))}toBuffer(){let scopesArray=[...this.scopes];return serializeToBuffer(this.noteDao,scopesArray.length,...scopesArray)}addScope(scope){this.scopes.add(scope)}};var NoteStore=class{static{__name(this,"NoteStore")}storeName="note";logger=createLogger("note_store");#store;#notes;#notesByContractAddress;#notesByBlockNumber;#nullifierEmissions;#nullifierEmissionsByBlockNumber;#notesForJob;#nullifierEmissionsForJob;#jobLocks;constructor(store){this.#store=store,this.#notes=store.openMap("notes"),this.#notesByContractAddress=store.openMultiMap("note_nullifiers_by_contract"),this.#notesByBlockNumber=store.openMultiMap("note_nullifiers_by_block"),this.#nullifierEmissions=store.openMap("note_nullifications_by_nullifier"),this.#nullifierEmissionsByBlockNumber=store.openMultiMap("note_nullifications_by_block"),this.#jobLocks=new Map,this.#notesForJob=new Map,this.#nullifierEmissionsForJob=new Map}addNotes(notes,scope,jobId){return this.#withJobLock(jobId,()=>this.#store.transactionAsync(()=>Promise.all(notes.map(async note=>{let noteForJob=await this.#readNote(note.siloedNullifier.toString(),jobId)??new StoredNote(note,new Set);noteForJob.addScope(scope.toString()),this.#writeNote(noteForJob,jobId)}))))}async#readNote(nullifier,jobId){let noteBuffer=await this.#notes.getAsync(nullifier);return this.#getNotesForJob(jobId).get(nullifier)??(noteBuffer?StoredNote.fromBuffer(noteBuffer):void 0)}#writeNote(note,jobId){this.#getNotesForJob(jobId).set(note.noteDao.siloedNullifier.toString(),note)}async#readNullifierEmission(nullifier,jobId){let committed=await this.#nullifierEmissions.getAsync(nullifier);return this.#getNullifierEmissionsForJob(jobId).get(nullifier)??committed}#writeNullifierEmission(nullifier,blockNumber,jobId){this.#getNullifierEmissionsForJob(jobId).set(nullifier,blockNumber)}getNotes(filter,jobId){return filter.scopes.length===0?Promise.resolve([]):this.#store.transactionAsync(async()=>{let targetStatus=filter.status??NoteStatus.ACTIVE,candidates=new Map;for await(let nullifier of this.#notesByContractAddress.getValuesAsync(filter.contractAddress.toString()))candidates.set(nullifier,{notePromise:this.#readNote(nullifier,jobId),nullificationPromise:this.#readNullifierEmission(nullifier,jobId)});for(let storedNote of this.#getNotesForJob(jobId).values())if(storedNote.noteDao.contractAddress.equals(filter.contractAddress)){let nullifier=storedNote.noteDao.siloedNullifier.toString();candidates.has(nullifier)||candidates.set(nullifier,{notePromise:Promise.resolve(storedNote),nullificationPromise:this.#readNullifierEmission(nullifier,jobId)})}let entries=[...candidates.entries()],notes=await Promise.all(entries.map(([,{notePromise}])=>notePromise)),nullifierEmissions=await Promise.all(entries.map(([,{nullificationPromise}])=>nullificationPromise)),emissionByNullifier=new Map;for(let i=0;i<entries.length;i++)emissionByNullifier.set(entries[i][0],nullifierEmissions[i]);let foundNotes=new Map;for(let note of notes){if(!note)throw new Error("PXE note database is corrupted.");let nullified=emissionByNullifier.get(note.noteDao.siloedNullifier.toString())!==void 0;targetStatus===NoteStatus.ACTIVE&&nullified||filter.owner&&!note.noteDao.owner.equals(filter.owner)||filter.storageSlot&&!note.noteDao.storageSlot.equals(filter.storageSlot)||filter.siloedNullifier&&!note.noteDao.siloedNullifier.equals(filter.siloedNullifier)||note.scopes.intersection(new Set(filter.scopes.map(s2=>s2.toString()))).size!==0&&foundNotes.set(note.noteDao.siloedNullifier.toString(),note.noteDao)}return[...foundNotes.values()].sort((a,b)=>a.l2BlockNumber!==b.l2BlockNumber?a.l2BlockNumber-b.l2BlockNumber:a.txIndexInBlock!==b.txIndexInBlock?a.txIndexInBlock-b.txIndexInBlock:a.noteIndexInTx-b.noteIndexInTx)})}applyNullifiers(siloedNullifiers,jobId){return siloedNullifiers.length===0?Promise.resolve([]):siloedNullifiers.some(n=>n.l2BlockNumber===0)?Promise.reject(new Error("applyNullifiers: nullifiers cannot have been emitted at block 0")):this.#withJobLock(jobId,()=>this.#store.transactionAsync(async()=>{let resolved=await Promise.all(siloedNullifiers.map(async nullifier=>{let key=nullifier.data.toString(),[storedNote,existingEmission]=await Promise.all([this.#readNote(key,jobId),this.#readNullifierEmission(key,jobId)]);if(!storedNote)throw new Error(`Attempted to mark a note as nullified which does not exist in PXE DB: ${key}`);return{nullifier,storedNote,alreadyEmitted:existingEmission!==void 0}})),affected=[];for(let{nullifier,storedNote,alreadyEmitted}of resolved)alreadyEmitted||(this.#writeNullifierEmission(nullifier.data.toString(),nullifier.l2BlockNumber,jobId),affected.push(storedNote.noteDao));return affected}))}async commit(jobId){for(let[nullifier,storedNote]of this.#getNotesForJob(jobId))await this.#notes.set(nullifier,storedNote.toBuffer()),await this.#notesByContractAddress.set(storedNote.noteDao.contractAddress.toString(),nullifier),await this.#notesByBlockNumber.set(storedNote.noteDao.l2BlockNumber,nullifier);for(let[nullifier,blockNumber]of this.#getNullifierEmissionsForJob(jobId))await this.#nullifierEmissions.set(nullifier,blockNumber),await this.#nullifierEmissionsByBlockNumber.set(blockNumber,nullifier);this.#clearJobData(jobId)}discardStaged(jobId){return this.#clearJobData(jobId),Promise.resolve()}#clearJobData(jobId){this.#notesForJob.delete(jobId),this.#nullifierEmissionsForJob.delete(jobId),this.#jobLocks.delete(jobId)}async#withJobLock(jobId,fn){let lock=this.#jobLocks.get(jobId);lock||(lock=new Semaphore(1),this.#jobLocks.set(jobId,lock)),await lock.acquire();try{return await fn()}finally{lock.release()}}#getNotesForJob(jobId){let notesForJob=this.#notesForJob.get(jobId);return notesForJob||(notesForJob=new Map,this.#notesForJob.set(jobId,notesForJob)),notesForJob}#getNullifierEmissionsForJob(jobId){let nullificationsForJob=this.#nullifierEmissionsForJob.get(jobId);return nullificationsForJob||(nullificationsForJob=new Map,this.#nullifierEmissionsForJob.set(jobId,nullificationsForJob)),nullificationsForJob}async nullifiersOfNotesAtBlock(blockNumber){let nullifiers=[];for await(let nullifier of this.#notesByBlockNumber.getValuesAsync(blockNumber))nullifiers.push(nullifier);return nullifiers}async rollback(toBlock){if(this.#notesForJob.size>0||this.#nullifierEmissionsForJob.size>0)throw new Error("PXE note store rollback is not allowed while jobs are running");let orphanedNotes=[];for await(let[block,siloedNullifier]of this.#notesByBlockNumber.entriesAsync({start:toBlock+1}))orphanedNotes.push({block,siloedNullifier});let removedNotes=0;await Promise.all(orphanedNotes.map(async({block,siloedNullifier})=>{let buf=await this.#notes.getAsync(siloedNullifier);if(!buf)throw new Error(`Note not found for siloedNullifier ${siloedNullifier}`);let stored=StoredNote.fromBuffer(buf);await this.#notes.delete(siloedNullifier),await this.#notesByContractAddress.deleteValue(stored.noteDao.contractAddress.toString(),siloedNullifier),await this.#notesByBlockNumber.deleteValue(block,siloedNullifier),removedNotes++}));let orphanedEmissions=[];for await(let[block,siloedNullifier]of this.#nullifierEmissionsByBlockNumber.entriesAsync({start:toBlock+1}))orphanedEmissions.push({block,siloedNullifier});await Promise.all(orphanedEmissions.map(async({block,siloedNullifier})=>{await this.#nullifierEmissions.delete(siloedNullifier),await this.#nullifierEmissionsByBlockNumber.deleteValue(block,siloedNullifier)})),this.logger.verbose("rolled back notes and nullifier emissions",{removedNotes,removedNullifierEmissions:orphanedEmissions.length,toBlock})}};var StoredPrivateEvent=class _StoredPrivateEvent{static{__name(this,"StoredPrivateEvent")}randomness;msgContent;l2BlockNumber;l2BlockHash;txHash;txIndexInBlock;eventIndexInTx;contractAddress;eventSelector;scopes;constructor(randomness,msgContent,l2BlockNumber,l2BlockHash,txHash,txIndexInBlock,eventIndexInTx,contractAddress,eventSelector,scopes){this.randomness=randomness,this.msgContent=msgContent,this.l2BlockNumber=l2BlockNumber,this.l2BlockHash=l2BlockHash,this.txHash=txHash,this.txIndexInBlock=txIndexInBlock,this.eventIndexInTx=eventIndexInTx,this.contractAddress=contractAddress,this.eventSelector=eventSelector,this.scopes=scopes}addScope(scope){this.scopes.add(scope)}toBuffer(){let scopesArray=[...this.scopes];return serializeToBuffer(this.randomness,this.msgContent.length,...this.msgContent,this.l2BlockNumber,this.l2BlockHash,this.txHash,this.txIndexInBlock,this.eventIndexInTx,this.contractAddress,this.eventSelector.toBuffer(),scopesArray.length,...scopesArray)}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer),randomness=Fr.fromBuffer(reader),msgContentLength=reader.readNumber(),msgContent=reader.readArray(msgContentLength,Fr),l2BlockNumber=reader.readNumber(),l2BlockHash=BlockHash.fromBuffer(reader),txHash=TxHash.fromBuffer(reader),txIndexInBlock=reader.readNumber(),eventIndexInTx=reader.readNumber(),contractAddress=AztecAddress.fromBuffer(reader),eventSelector=EventSelector.fromBuffer(reader),scopes=reader.readVector({fromBuffer:__name(r2=>r2.readString(),"fromBuffer")});return new _StoredPrivateEvent(randomness,msgContent,l2BlockNumber,l2BlockHash,txHash,txIndexInBlock,eventIndexInTx,contractAddress,eventSelector,new Set(scopes))}};var PrivateEventStore=class{static{__name(this,"PrivateEventStore")}storeName="private_event";#store;#events;#eventsByContractAndEventSelector;#eventsByBlockNumber;#eventsForJob;#jobLocks;logger=createLogger("private_event_store");constructor(store){this.#store=store,this.#events=this.#store.openMap("private_event_logs"),this.#eventsByContractAndEventSelector=this.#store.openMultiMap("events_by_contract_selector"),this.#eventsByBlockNumber=this.#store.openMultiMap("events_by_block_number"),this.#eventsForJob=new Map,this.#jobLocks=new Map}storePrivateEventLog(eventSelector,randomness,msgContent,siloedEventCommitment,metadata,jobId){return this.#withJobLock(jobId,()=>this.#store.transactionAsync(async()=>{let{contractAddress,scope,txHash,l2BlockNumber,l2BlockHash,txIndexInBlock,eventIndexInTx}=metadata,eventId=siloedEventCommitment.toString();this.logger.verbose("storing private event log (job stage)",{eventId,contractAddress,scope,msgContent,l2BlockNumber});let existing=await this.#readEvent(eventId,jobId);existing?(existing.addScope(scope.toString()),this.#writeEvent(eventId,existing,jobId)):this.#writeEvent(eventId,new StoredPrivateEvent(randomness,msgContent,l2BlockNumber,l2BlockHash,txHash,txIndexInBlock,eventIndexInTx,contractAddress,eventSelector,new Set([scope.toString()])),jobId)}))}getPrivateEvents(eventSelector,filter){return this.#store.transactionAsync(async()=>{let key=this.#keyFor(filter.contractAddress,eventSelector),targetScopes=new Set(filter.scopes.map(s2=>s2.toString())),eventReadPromises=new Map;for await(let eventId of this.#eventsByContractAndEventSelector.getValuesAsync(key))eventReadPromises.set(eventId,this.#events.getAsync(eventId));let eventIds=[...eventReadPromises.keys()],eventBuffers=await Promise.all(eventReadPromises.values()),events=[];for(let i=0;i<eventIds.length;i++){let eventId=eventIds[i],eventBuffer=eventBuffers[i];if(!eventBuffer){this.logger.verbose(`EventId ${eventId} does not exist in main index but it is referenced from contract event selector index`);continue}let storedPrivateEvent=StoredPrivateEvent.fromBuffer(eventBuffer);storedPrivateEvent.l2BlockNumber<filter.fromBlock||storedPrivateEvent.l2BlockNumber>=filter.toBlock||storedPrivateEvent.scopes.intersection(targetScopes).size!==0&&(filter.txHash&&!storedPrivateEvent.txHash.equals(filter.txHash)||events.push({l2BlockNumber:storedPrivateEvent.l2BlockNumber,txIndexInBlock:storedPrivateEvent.txIndexInBlock,eventIndexInTx:storedPrivateEvent.eventIndexInTx,event:{packedEvent:storedPrivateEvent.msgContent,l2BlockNumber:BlockNumber(storedPrivateEvent.l2BlockNumber),txHash:storedPrivateEvent.txHash,l2BlockHash:storedPrivateEvent.l2BlockHash,eventSelector}}))}return events.sort((a,b)=>a.l2BlockNumber!==b.l2BlockNumber?a.l2BlockNumber-b.l2BlockNumber:a.txIndexInBlock!==b.txIndexInBlock?a.txIndexInBlock-b.txIndexInBlock:a.eventIndexInTx-b.eventIndexInTx),events.map(ev=>ev.event)})}async eventIdsAtBlock(blockNumber){let eventIds=[];for await(let eventId of this.#eventsByBlockNumber.getValuesAsync(blockNumber))eventIds.push(eventId);return eventIds}async rollback(toBlock){if(this.#eventsForJob.size>0)throw new Error("PXE private event store rollback is not allowed while jobs are running");let orphaned=[];for await(let[block,eventId]of this.#eventsByBlockNumber.entriesAsync({start:toBlock+1}))orphaned.push({block,eventId});let removedCount=0;for(let{block,eventId}of orphaned){let buf=await this.#events.getAsync(eventId);if(!buf)throw new Error(`Event not found for eventId ${eventId}`);let stored=StoredPrivateEvent.fromBuffer(buf);await this.#events.delete(eventId),await this.#eventsByContractAndEventSelector.deleteValue(this.#keyFor(stored.contractAddress,stored.eventSelector),eventId),await this.#eventsByBlockNumber.deleteValue(block,eventId),removedCount++}this.logger.verbose("rolled back private events",{removedCount,toBlock})}async commit(jobId){for(let[eventId,entry]of this.#getEventsForJob(jobId).entries()){let lookupKey=this.#keyFor(entry.contractAddress,entry.eventSelector);this.logger.verbose("storing private event log",{eventId,lookupKey}),await Promise.all([this.#events.set(eventId,entry.toBuffer()),this.#eventsByContractAndEventSelector.set(lookupKey,eventId),this.#eventsByBlockNumber.set(entry.l2BlockNumber,eventId)])}this.#clearJobData(jobId)}discardStaged(jobId){return this.#clearJobData(jobId),Promise.resolve()}async#readEvent(eventId,jobId){let buffer=await this.#events.getAsync(eventId);return this.#getEventsForJob(jobId).get(eventId)??(buffer?StoredPrivateEvent.fromBuffer(buffer):void 0)}#writeEvent(eventId,entry,jobId){this.#getEventsForJob(jobId).set(eventId,entry)}#getEventsForJob(jobId){let eventsForJob=this.#eventsForJob.get(jobId);return eventsForJob===void 0&&(eventsForJob=new Map,this.#eventsForJob.set(jobId,eventsForJob)),eventsForJob}#clearJobData(jobId){this.#eventsForJob.delete(jobId),this.#jobLocks.delete(jobId)}async#withJobLock(jobId,fn){let lock=this.#jobLocks.get(jobId);lock||(lock=new Semaphore(1),this.#jobLocks.set(jobId,lock)),await lock.acquire();try{return await fn()}finally{lock.release()}}#keyFor(contractAddress,eventSelector){return`${contractAddress.toString()}_${eventSelector.toString()}`}};var SenderTaggingStore=class{static{__name(this,"SenderTaggingStore")}storeName="sender_tagging";#store;#pendingIndexes;#pendingIndexesForJob;#lastFinalizedIndexes;#lastFinalizedIndexesForJob;constructor(store){this.#store=store,this.#pendingIndexes=this.#store.openMap("pending_indexes"),this.#lastFinalizedIndexes=this.#store.openMap("last_finalized_indexes"),this.#pendingIndexesForJob=new Map,this.#lastFinalizedIndexesForJob=new Map}#getPendingIndexesForJob(jobId){let pendingIndexesForJob=this.#pendingIndexesForJob.get(jobId);return pendingIndexesForJob||(pendingIndexesForJob=new Map,this.#pendingIndexesForJob.set(jobId,pendingIndexesForJob)),pendingIndexesForJob}#getLastFinalizedIndexesForJob(jobId){let jobStagedLastFinalizedIndexes=this.#lastFinalizedIndexesForJob.get(jobId);return jobStagedLastFinalizedIndexes||(jobStagedLastFinalizedIndexes=new Map,this.#lastFinalizedIndexesForJob.set(jobId,jobStagedLastFinalizedIndexes)),jobStagedLastFinalizedIndexes}async#readPendingIndexes(jobId,secret){let dbValue=await this.#pendingIndexes.getAsync(secret),staged=this.#getPendingIndexesForJob(jobId).get(secret);return staged!==void 0?staged:dbValue??[]}#writePendingIndexes(jobId,secret,pendingIndexes){this.#getPendingIndexesForJob(jobId).set(secret,pendingIndexes)}async#readLastFinalizedIndex(jobId,secret){let dbValue=await this.#lastFinalizedIndexes.getAsync(secret);return this.#getLastFinalizedIndexesForJob(jobId).get(secret)??dbValue}#writeLastFinalizedIndex(jobId,secret,lastFinalizedIndex){this.#getLastFinalizedIndexesForJob(jobId).set(secret,lastFinalizedIndex)}async commit(jobId){let pendingIndexesForJob=this.#pendingIndexesForJob.get(jobId);if(pendingIndexesForJob)for(let[secret,pendingIndexes]of pendingIndexesForJob.entries())pendingIndexes.length===0?await this.#pendingIndexes.delete(secret):await this.#pendingIndexes.set(secret,pendingIndexes);let lastFinalizedIndexesForJob=this.#lastFinalizedIndexesForJob.get(jobId);if(lastFinalizedIndexesForJob)for(let[secret,lastFinalizedIndex]of lastFinalizedIndexesForJob.entries())await this.#lastFinalizedIndexes.set(secret,lastFinalizedIndex);return this.discardStaged(jobId)}discardStaged(jobId){return this.#pendingIndexesForJob.delete(jobId),this.#lastFinalizedIndexesForJob.delete(jobId),Promise.resolve()}storePendingIndexes(ranges,txHash,jobId){if(ranges.length===0)return Promise.resolve();let txHashStr=txHash.toString();return this.#store.transactionAsync(async()=>{let rangeReadPromises=ranges.map(range=>({range,secretStr:range.extendedSecret.toString(),pending:this.#readPendingIndexes(jobId,range.extendedSecret.toString()),finalized:this.#readLastFinalizedIndex(jobId,range.extendedSecret.toString())})),rangeData=await Promise.all(rangeReadPromises.map(async item=>({...item,pendingData:await item.pending,finalizedIndex:await item.finalized})));for(let{range,secretStr,pendingData,finalizedIndex}of rangeData){if(range.highestIndex>(finalizedIndex??0)+UNFINALIZED_TAGGING_INDEXES_WINDOW_LEN)throw new Error(`Highest used index ${range.highestIndex} is further than window length from the highest finalized index ${finalizedIndex??0}.
|
|
214
214
|
Tagging window length ${UNFINALIZED_TAGGING_INDEXES_WINDOW_LEN} is configured too low. Contact the Aztec team
|
|
215
|
-
to increase it!`);if(finalizedIndex!==void 0&&range.lowestIndex<=finalizedIndex)throw new Error(`Cannot store pending index range [${range.lowestIndex}, ${range.highestIndex}] for secret ${secretStr}: lowestIndex is lower than or equal to the last finalized index ${finalizedIndex}`);let existingEntry=pendingData.find(entry=>entry.txHash===txHashStr);if(existingEntry){if(existingEntry.lowestIndex!==range.lowestIndex||existingEntry.highestIndex!==range.highestIndex)throw new Error(`Conflicting range for secret ${secretStr} and txHash ${txHashStr}: existing [${existingEntry.lowestIndex}, ${existingEntry.highestIndex}] vs new [${range.lowestIndex}, ${range.highestIndex}]`)}else this.#writePendingIndexes(jobId,secretStr,[...pendingData,{lowestIndex:range.lowestIndex,highestIndex:range.highestIndex,txHash:txHashStr}])}})}getTxHashesOfPendingIndexes(secret,startIndex,endIndex,jobId){return this.#store.transactionAsync(async()=>{let txHashes=(await this.#readPendingIndexes(jobId,secret.toString())).filter(entry=>entry.highestIndex>=startIndex&&entry.highestIndex<endIndex).map(entry=>entry.txHash);return Array.from(new Set(txHashes)).map(TxHash.fromString)})}getLastFinalizedIndex(secret,jobId){return this.#store.transactionAsync(()=>this.#readLastFinalizedIndex(jobId,secret.toString()))}getLastUsedIndex(secret,jobId){let secretStr=secret.toString();return this.#store.transactionAsync(async()=>{let pendingPromise=this.#readPendingIndexes(jobId,secretStr),finalizedPromise=this.#readLastFinalizedIndex(jobId,secretStr),[pendingEntries,lastFinalized]=await Promise.all([pendingPromise,finalizedPromise]);return pendingEntries.length===0?lastFinalized:Math.max(...pendingEntries.map(entry=>entry.highestIndex))})}dropPendingIndexes(txHashes,jobId){if(txHashes.length===0)return Promise.resolve();let txHashStrings=new Set(txHashes.map(txHash=>txHash.toString()));return this.#store.transactionAsync(async()=>{let secretReadPromises=new Map;for await(let secret of this.#pendingIndexes.keysAsync())secretReadPromises.set(secret,this.#readPendingIndexes(jobId,secret));for(let secret of this.#getPendingIndexesForJob(jobId).keys())secretReadPromises.has(secret)||secretReadPromises.set(secret,Promise.resolve(this.#getPendingIndexesForJob(jobId).get(secret)??[]));let secrets=[...secretReadPromises.keys()],pendingDataResults=await Promise.all(secretReadPromises.values());for(let i=0;i<secrets.length;i++){let secret=secrets[i],pendingData=pendingDataResults[i];if(pendingData&&pendingData.length>0){let filtered=pendingData.filter(item=>!txHashStrings.has(item.txHash));filtered.length===0?this.#writePendingIndexes(jobId,secret,[]):filtered.length!==pendingData.length&&this.#writePendingIndexes(jobId,secret,filtered)}}})}#getSecretsWithPendingData(jobId){return this.#store.transactionAsync(async()=>{let secretDataPromises=new Map;for await(let secret of this.#pendingIndexes.keysAsync())secretDataPromises.set(secret,{pending:this.#readPendingIndexes(jobId,secret),finalized:this.#readLastFinalizedIndex(jobId,secret)});for(let secret of this.#getPendingIndexesForJob(jobId).keys())secretDataPromises.has(secret)||secretDataPromises.set(secret,{pending:Promise.resolve(this.#getPendingIndexesForJob(jobId).get(secret)??[]),finalized:Promise.resolve(this.#getLastFinalizedIndexesForJob(jobId).get(secret))});let secrets=[...secretDataPromises.keys()];return(await Promise.all(secrets.map(async secret=>({secret,pendingData:await secretDataPromises.get(secret).pending,lastFinalized:await secretDataPromises.get(secret).finalized})))).filter(r2=>r2.pendingData.length>0)})}async finalizePendingIndexes(txHashes,jobId){if(txHashes.length===0)return;let txHashStrings=new Set(txHashes.map(tx=>tx.toString())),secretsWithData=await this.#getSecretsWithPendingData(jobId);for(let{secret,pendingData,lastFinalized}of secretsWithData){let currentPending=pendingData,currentFinalized=lastFinalized;for(let txHashStr of txHashStrings){let matchingEntries=currentPending.filter(item=>item.txHash===txHashStr);if(matchingEntries.length===0)continue;if(matchingEntries.length>1)throw new Error(`Multiple pending entries found for tx hash ${txHashStr} and secret ${secret}`);let newFinalized=matchingEntries[0].highestIndex;if(newFinalized<(currentFinalized??0))throw new Error(`New finalized index ${newFinalized} is smaller than the current last finalized index ${currentFinalized}`);currentFinalized=newFinalized,currentPending=currentPending.filter(item=>item.highestIndex>currentFinalized)}currentFinalized!==lastFinalized&&this.#writeLastFinalizedIndex(jobId,secret,currentFinalized),currentPending!==pendingData&&this.#writePendingIndexes(jobId,secret,currentPending)}}async finalizePendingIndexesOfAPartiallyRevertedTx(txEffect,jobId){let txHashStr=txEffect.txHash.toString(),onChainTags=new Set(txEffect.privateLogs.map(log2=>log2.fields[0].toString())),secretsWithData=await this.#getSecretsWithPendingData(jobId);for(let{secret,pendingData,lastFinalized}of secretsWithData){let matchingEntries=pendingData.filter(item=>item.txHash===txHashStr);if(matchingEntries.length===0)continue;if(matchingEntries.length>1)throw new Error(`Multiple pending entries found for tx hash ${txHashStr} and secret ${secret}`);let pendingEntry=matchingEntries[0],appTaggingSecret=AppTaggingSecret.fromString(secret),highestSurvivingIndex;for(let index=pendingEntry.lowestIndex;index<=pendingEntry.highestIndex;index++){let siloedTag=await SiloedTag.compute({extendedSecret:appTaggingSecret,index});onChainTags.has(siloedTag.value.toString())&&(highestSurvivingIndex=highestSurvivingIndex!==void 0?Math.max(highestSurvivingIndex,index):index)}let currentPending=pendingData.filter(item=>item.txHash!==txHashStr);if(highestSurvivingIndex!==void 0){let newFinalized=Math.max(lastFinalized??0,highestSurvivingIndex);this.#writeLastFinalizedIndex(jobId,secret,newFinalized),currentPending=currentPending.filter(item=>item.highestIndex>newFinalized)}this.#writePendingIndexes(jobId,secret,currentPending)}}};var TaggingSecretSourcesStore=class{static{__name(this,"TaggingSecretSourcesStore")}#store;#senders;#sharedSecretsByRecipient;constructor(store){this.#store=store,this.#senders=this.#store.openMap("senders"),this.#sharedSecretsByRecipient=this.#store.openMultiMap("recipient_shared_secrets")}addSender(address){return this.#store.transactionAsync(async()=>await this.#senders.hasAsync(address.toString())?!1:(await this.#senders.set(address.toString(),!0),!0))}getSenders(){return this.#store.transactionAsync(async()=>(await toArray(this.#senders.keysAsync())).map(AztecAddress.fromStringUnsafe))}removeSender(address){return this.#store.transactionAsync(async()=>await this.#senders.hasAsync(address.toString())?(await this.#senders.delete(address.toString()),!0):!1)}addSharedSecret(recipient,secret){return this.#store.transactionAsync(async()=>{let secretStr=secret.toString();for await(let existing of this.#sharedSecretsByRecipient.getValuesAsync(recipient.toString()))if(existing===secretStr)return!1;return await this.#sharedSecretsByRecipient.set(recipient.toString(),secretStr),!0})}getSharedSecretsForRecipient(recipient){return this.#store.transactionAsync(async()=>(await toArray(this.#sharedSecretsByRecipient.getValuesAsync(recipient.toString()))).map(secret=>Point.fromString(secret)))}getAllSharedSecrets(){return this.#store.transactionAsync(async()=>(await toArray(this.#sharedSecretsByRecipient.entriesAsync())).map(([recipient,secret])=>({recipient:AztecAddress.fromStringUnsafe(recipient),secret:Point.fromString(secret)})))}removeSharedSecret(recipient,secret){return this.#store.transactionAsync(async()=>{let secretStr=secret.toString();for await(let existing of this.#sharedSecretsByRecipient.getValuesAsync(recipient.toString()))if(existing===secretStr)return await this.#sharedSecretsByRecipient.deleteValue(recipient.toString(),secretStr),!0;return!1})}};var RecipientTaggingStore=class{static{__name(this,"RecipientTaggingStore")}storeName="recipient_tagging";#store;#highestAgedIndex;#highestFinalizedIndex;#highestAgedIndexForJob;#highestFinalizedIndexForJob;constructor(store){this.#store=store,this.#highestAgedIndex=this.#store.openMap("highest_aged_index"),this.#highestFinalizedIndex=this.#store.openMap("highest_finalized_index"),this.#highestAgedIndexForJob=new Map,this.#highestFinalizedIndexForJob=new Map}#getHighestAgedIndexForJob(jobId){let highestAgedIndexForJob=this.#highestAgedIndexForJob.get(jobId);return highestAgedIndexForJob||(highestAgedIndexForJob=new Map,this.#highestAgedIndexForJob.set(jobId,highestAgedIndexForJob)),highestAgedIndexForJob}async#readHighestAgedIndex(jobId,secret){let dbValue=await this.#highestAgedIndex.getAsync(secret);return this.#getHighestAgedIndexForJob(jobId).get(secret)??dbValue}#writeHighestAgedIndex(jobId,secret,index){this.#getHighestAgedIndexForJob(jobId).set(secret,index)}#getHighestFinalizedIndexForJob(jobId){let jobStagedHighestFinalizedIndex=this.#highestFinalizedIndexForJob.get(jobId);return jobStagedHighestFinalizedIndex||(jobStagedHighestFinalizedIndex=new Map,this.#highestFinalizedIndexForJob.set(jobId,jobStagedHighestFinalizedIndex)),jobStagedHighestFinalizedIndex}async#readHighestFinalizedIndex(jobId,secret){let dbValue=await this.#highestFinalizedIndex.getAsync(secret);return this.#getHighestFinalizedIndexForJob(jobId).get(secret)??dbValue}#writeHighestFinalizedIndex(jobId,secret,index){this.#getHighestFinalizedIndexForJob(jobId).set(secret,index)}async commit(jobId){let highestAgedIndexForJob=this.#highestAgedIndexForJob.get(jobId);if(highestAgedIndexForJob)for(let[secret,index]of highestAgedIndexForJob.entries())await this.#highestAgedIndex.set(secret,index);let highestFinalizedIndexForJob=this.#highestFinalizedIndexForJob.get(jobId);if(highestFinalizedIndexForJob)for(let[secret,index]of highestFinalizedIndexForJob.entries())await this.#highestFinalizedIndex.set(secret,index);return this.discardStaged(jobId)}discardStaged(jobId){return this.#highestAgedIndexForJob.delete(jobId),this.#highestFinalizedIndexForJob.delete(jobId),Promise.resolve()}getHighestAgedIndex(secret,jobId){return this.#store.transactionAsync(()=>this.#readHighestAgedIndex(jobId,secret.toString()))}updateHighestAgedIndex(secret,index,jobId){return this.#store.transactionAsync(async()=>{let currentIndex=await this.#readHighestAgedIndex(jobId,secret.toString());if(currentIndex!==void 0&&index<=currentIndex)throw new Error(`New highest aged index (${index}) must be higher than the current one (${currentIndex})`);this.#writeHighestAgedIndex(jobId,secret.toString(),index)})}getHighestFinalizedIndex(secret,jobId){return this.#store.transactionAsync(()=>this.#readHighestFinalizedIndex(jobId,secret.toString()))}updateHighestFinalizedIndex(secret,index,jobId){return this.#store.transactionAsync(async()=>{let currentIndex=await this.#readHighestFinalizedIndex(jobId,secret.toString());if(currentIndex!==void 0&&index<currentIndex)throw new Error(`New highest finalized index (${index}) must be higher than the current one (${currentIndex})`);this.#writeHighestFinalizedIndex(jobId,secret.toString(),index)})}};import{pickL1ContractAddressMappings as pickL1ContractAddressMappings3}from"@aztec/ethereum/l1-contract-addresses";var emptyChainConfig={l1ChainId:0,rollupVersion:0,rollupAddress:EthAddress.ZERO},chainConfigMappings={l1ChainId:{env:"L1_CHAIN_ID",...numberConfigHelper(31337),description:"The chain ID of the ethereum host."},rollupVersion:{env:"ROLLUP_VERSION",description:"The version of the rollup.",parseEnv:__name(val=>{let parsed=parseInt(val,10);if(!Number.isSafeInteger(parsed))throw new Error(`Invalid rollup version: ${val}`);return parsed},"parseEnv")},...pickL1ContractAddressMappings3("rollupAddress")};import{l1ContractsConfigMappings}from"@aztec/ethereum/config";var DEFAULT_BLOCK_DURATION_MS=3*1e3;var DEFAULT_MAX_BLOCKS_PER_CHECKPOINT=24,sharedSequencerConfigMappings={blockDurationMs:{env:"SEQ_BLOCK_DURATION_MS",description:"Duration per block in milliseconds, used to derive how many blocks fit in a slot.",...numberConfigHelper(DEFAULT_BLOCK_DURATION_MS)},expectedBlockProposalsPerSlot:{env:"SEQ_EXPECTED_BLOCK_PROPOSALS_PER_SLOT",description:"Expected number of block proposals per slot for P2P peer scoring. 0 (default) disables block proposal scoring. Set to a positive value to enable.",...numberConfigHelper(0)},checkpointProposalSyncGraceSeconds:{env:"CHECKPOINT_PROPOSAL_SYNC_GRACE_SECONDS",description:"Consensus grace in seconds for a received checkpoint proposal to materialize into local proposed state. Defaults to twice the block duration.",defaultValue:getDefaultCheckpointProposalSyncGrace(DEFAULT_BLOCK_DURATION_MS/1e3),...optionalNumberConfigHelper()},maxTxsPerBlock:{env:"SEQ_MAX_TX_PER_BLOCK",description:"The maximum number of txs to include in a block.",...optionalNumberConfigHelper()},attestationPropagationTime:{env:"SEQ_ATTESTATION_PROPAGATION_TIME",description:"How many seconds it takes for proposals and attestations to travel across the p2p layer (one-way).",defaultValue:2,...floatConfigHelper(2)},checkpointProposalPrepareTime:{env:"SEQ_CHECKPOINT_PROPOSAL_PREPARE_TIME",description:"Local time in seconds between the last block build finishing and the checkpoint proposal being ready for p2p send.",defaultValue:1,...floatConfigHelper(1)},minBlockDuration:{env:"SEQ_MIN_BLOCK_DURATION",description:"Minimum block-building time in seconds still worth allocating if the proposer starts late.",defaultValue:2,...floatConfigHelper(2)},maxBlocksPerCheckpoint:{env:"MAX_BLOCKS_PER_CHECKPOINT",description:"Maximum number of blocks the sequencer packs into a single checkpoint, and the maximum indexWithinCheckpoint accepted on inbound block proposals.",parseEnv:__name(val=>parseInt(val,10),"parseEnv"),defaultValue:DEFAULT_MAX_BLOCKS_PER_CHECKPOINT}};var networkConsensusConfigMappings={...pickConfigMappings(l1ContractsConfigMappings,["aztecSlotDuration","ethereumSlotDuration"]),...pickConfigMappings(sharedSequencerConfigMappings,["blockDurationMs","maxBlocksPerCheckpoint","checkpointProposalSyncGraceSeconds"])};var nodeRpcConfigMappings={rpcSimulatePublicMaxGasLimit:{env:"RPC_SIMULATE_PUBLIC_MAX_GAS_LIMIT",description:"Maximum gas limit for public tx simulation in the node on `simulatePublicCalls`.",...numberConfigHelper(1e10)},rpcSimulatePublicMaxDebugLogMemoryReads:{env:"RPC_SIMULATE_PUBLIC_MAX_DEBUG_LOG_MEMORY_READS",description:"Maximum memory reads for debug logs performed for public tx simulation in the node on `simulatePublicCalls`. ",...numberConfigHelper(125e3)},rpcMaxBatchSize:{env:"RPC_MAX_BATCH_SIZE",description:"Maximum allowed batch size for JSON RPC batch requests.",...numberConfigHelper(100)},rpcMaxBodySize:{env:"RPC_MAX_BODY_SIZE",description:"Maximum allowed batch size for JSON RPC batch requests.",defaultValue:"1mb"}};function composeHooks(hooks){if(!Object.values(hooks).every(v=>v===void 0))return hooks}__name(composeHooks,"composeHooks");var pxeConfigMappings={...dataConfigMappings,...chainConfigMappings,l2BlockBatchSize:{env:"PXE_L2_BLOCK_BATCH_SIZE",...numberConfigHelper(50),description:"Maximum amount of blocks to pull from the stream in one request when synchronizing"},proverEnabled:{env:"PXE_PROVER_ENABLED",description:"Enable real proofs",...booleanConfigHelper(!0)},syncChainTip:{env:"PXE_SYNC_CHAIN_TIP",description:"Which chain tip to sync to (proposed, checkpointed, proven, finalized)",...enumConfigHelper(["proposed","checkpointed","proven","finalized"],"proposed")},autoSync:{env:"PXE_AUTO_SYNC",description:"Whether PXE syncs with the node automatically before each operation. Disable to let the caller (e.g. a wallet) drive syncs explicitly via pxe.sync().",...booleanConfigHelper(!0)}};var pxeCliConfigMappings={nodeUrl:{env:"AZTEC_NODE_URL",description:"Custom Aztec Node URL to connect to"}},allPxeConfigMappings={...pxeConfigMappings,...pxeCliConfigMappings,...dataConfigMappings,proverEnabled:{env:"PXE_PROVER_ENABLED",parseEnv:__name(val=>parseBooleanEnv(val)||!!process.env.NETWORK,"parseEnv"),description:"Enable real proofs",isBoolean:!0,defaultValue:!0}};import{LazyArtifactProvider}from"@aztec/noir-protocol-circuits-types/client/lazy";import{AztecClientBackend,Barretenberg as Barretenberg2}from"@aztec/bb.js";import{serializeWitness as serializeWitness2}from"@aztec/noir-noirc_abi";import{convertHidingKernelPublicInputsToWitnessMapWithAbi,convertHidingKernelToRollupInputsToWitnessMapWithAbi,convertPrivateKernelInit2InputsToWitnessMapWithAbi,convertPrivateKernelInit2OutputsFromWitnessMapWithAbi,convertPrivateKernelInit3InputsToWitnessMapWithAbi,convertPrivateKernelInit3OutputsFromWitnessMapWithAbi,convertPrivateKernelInitInputsToWitnessMapWithAbi,convertPrivateKernelInitOutputsFromWitnessMapWithAbi,convertPrivateKernelInner2InputsToWitnessMapWithAbi,convertPrivateKernelInner2OutputsFromWitnessMapWithAbi,convertPrivateKernelInner3InputsToWitnessMapWithAbi,convertPrivateKernelInner3OutputsFromWitnessMapWithAbi,convertPrivateKernelInnerInputsToWitnessMapWithAbi,convertPrivateKernelInnerOutputsFromWitnessMapWithAbi,convertPrivateKernelResetInputsToWitnessMapWithAbi,convertPrivateKernelResetOutputsFromWitnessMapWithAbi,convertPrivateKernelTailForPublicOutputsFromWitnessMapWithAbi,convertPrivateKernelTailInputsToWitnessMapWithAbi,convertPrivateKernelTailOutputsFromWitnessMapWithAbi,convertPrivateKernelTailToPublicInputsToWitnessMapWithAbi,foreignCallHandler,getPrivateKernelResetArtifactName,updateResetCircuitSampleInputs}from"@aztec/noir-protocol-circuits-types/client";import{mapProtocolArtifactNameToCircuitName}from"@aztec/noir-protocol-circuits-types/types";import{ungzip}from"pako";var decoder;try{decoder=new TextDecoder}catch{}var src,srcEnd,position2=0;var EMPTY_ARRAY=[],strings=EMPTY_ARRAY,stringPosition=0,currentUnpackr={},currentStructures,srcString,srcStringStart=0,srcStringEnd=0,bundledStrings,referenceMap,currentExtensions=[],dataView,defaultOptions={useRecords:!1,mapsAsObjects:!0},C1Type=class{static{__name(this,"C1Type")}},C1=new C1Type;C1.name="MessagePack 0xC1";var sequentialMode=!1,inlineObjectReadThreshold=2,readStruct,onLoadedStructures,onSaveState;try{new Function("")}catch{inlineObjectReadThreshold=1/0}var Unpackr=class _Unpackr{static{__name(this,"Unpackr")}constructor(options){options&&(options.useRecords===!1&&options.mapsAsObjects===void 0&&(options.mapsAsObjects=!0),options.sequential&&options.trusted!==!1&&(options.trusted=!0,!options.structures&&options.useRecords!=!1&&(options.structures=[],options.maxSharedStructures||(options.maxSharedStructures=0))),options.structures?options.structures.sharedLength=options.structures.length:options.getStructures&&((options.structures=[]).uninitialized=!0,options.structures.sharedLength=0),options.int64AsNumber&&(options.int64AsType="number")),Object.assign(this,options)}unpack(source,options){if(src)return saveState(()=>(clearSource(),this?this.unpack(source,options):_Unpackr.prototype.unpack.call(defaultOptions,source,options)));!source.buffer&&source.constructor===ArrayBuffer&&(source=typeof Buffer<"u"?Buffer.from(source):new Uint8Array(source)),typeof options=="object"?(srcEnd=options.end||source.length,position2=options.start||0):(position2=0,srcEnd=options>-1?options:source.length),stringPosition=0,srcStringEnd=0,srcString=null,strings=EMPTY_ARRAY,bundledStrings=null,src=source;try{dataView=source.dataView||(source.dataView=new DataView(source.buffer,source.byteOffset,source.byteLength))}catch(error2){throw src=null,source instanceof Uint8Array?error2:new Error("Source must be a Uint8Array or Buffer but was a "+(source&&typeof source=="object"?source.constructor.name:typeof source))}if(this instanceof _Unpackr){if(currentUnpackr=this,this.structures)return currentStructures=this.structures,checkedRead(options);(!currentStructures||currentStructures.length>0)&&(currentStructures=[])}else currentUnpackr=defaultOptions,(!currentStructures||currentStructures.length>0)&&(currentStructures=[]);return checkedRead(options)}unpackMultiple(source,forEach){let values,lastPosition=0;try{sequentialMode=!0;let size=source.length,value=this?this.unpack(source,size):defaultUnpackr.unpack(source,size);if(forEach){if(forEach(value,lastPosition,position2)===!1)return;for(;position2<size;)if(lastPosition=position2,forEach(checkedRead(),lastPosition,position2)===!1)return}else{for(values=[value];position2<size;)lastPosition=position2,values.push(checkedRead());return values}}catch(error2){throw error2.lastPosition=lastPosition,error2.values=values,error2}finally{sequentialMode=!1,clearSource()}}_mergeStructures(loadedStructures,existingStructures){onLoadedStructures&&(loadedStructures=onLoadedStructures.call(this,loadedStructures)),loadedStructures=loadedStructures||[],Object.isFrozen(loadedStructures)&&(loadedStructures=loadedStructures.map(structure=>structure.slice(0)));for(let i=0,l=loadedStructures.length;i<l;i++){let structure=loadedStructures[i];structure&&(structure.isShared=!0,i>=32&&(structure.highByte=i-32>>5))}loadedStructures.sharedLength=loadedStructures.length;for(let id in existingStructures||[])if(id>=0){let structure=loadedStructures[id],existing=existingStructures[id];existing&&(structure&&((loadedStructures.restoreStructures||(loadedStructures.restoreStructures=[]))[id]=structure),loadedStructures[id]=existing)}return this.structures=loadedStructures}decode(source,options){return this.unpack(source,options)}};function checkedRead(options){try{if(!currentUnpackr.trusted&&!sequentialMode){let sharedLength=currentStructures.sharedLength||0;sharedLength<currentStructures.length&&(currentStructures.length=sharedLength)}let result;if(currentUnpackr.randomAccessStructure&&src[position2]<64&&src[position2]>=32&&readStruct?(result=readStruct(src,position2,srcEnd,currentUnpackr),src=null,!(options&&options.lazy)&&result&&(result=result.toJSON()),position2=srcEnd):result=read(),bundledStrings&&(position2=bundledStrings.postBundlePosition,bundledStrings=null),sequentialMode&&(currentStructures.restoreStructures=null),position2==srcEnd)currentStructures&¤tStructures.restoreStructures&&restoreStructures(),currentStructures=null,src=null,referenceMap&&(referenceMap=null);else{if(position2>srcEnd)throw new Error("Unexpected end of MessagePack data");if(!sequentialMode){let jsonView;try{jsonView=JSON.stringify(result,(_,value)=>typeof value=="bigint"?`${value}n`:value).slice(0,100)}catch(error2){jsonView="(JSON view not available "+error2+")"}throw new Error("Data read, but end of buffer not reached "+jsonView)}}return result}catch(error2){throw currentStructures&¤tStructures.restoreStructures&&restoreStructures(),clearSource(),(error2 instanceof RangeError||error2.message.startsWith("Unexpected end of buffer")||position2>srcEnd)&&(error2.incomplete=!0),error2}}__name(checkedRead,"checkedRead");function restoreStructures(){for(let id in currentStructures.restoreStructures)currentStructures[id]=currentStructures.restoreStructures[id];currentStructures.restoreStructures=null}__name(restoreStructures,"restoreStructures");function read(){let token=src[position2++];if(token<160)if(token<128){if(token<64)return token;{let structure=currentStructures[token&63]||currentUnpackr.getStructures&&loadStructures()[token&63];return structure?(structure.read||(structure.read=createStructureReader(structure,token&63)),structure.read()):token}}else if(token<144)if(token-=128,currentUnpackr.mapsAsObjects){let object2={};for(let i=0;i<token;i++){let key=readKey2();key==="__proto__"&&(key="__proto_"),object2[key]=read()}return object2}else{let map2=new Map;for(let i=0;i<token;i++)map2.set(read(),read());return map2}else{token-=144;let array2=new Array(token);for(let i=0;i<token;i++)array2[i]=read();return currentUnpackr.freezeData?Object.freeze(array2):array2}else if(token<192){let length=token-160;if(srcStringEnd>=position2)return srcString.slice(position2-srcStringStart,(position2+=length)-srcStringStart);if(srcStringEnd==0&&srcEnd<140){let string4=length<16?shortStringInJS(length):longStringInJS(length);if(string4!=null)return string4}return readFixedString(length)}else{let value;switch(token){case 192:return null;case 193:return bundledStrings?(value=read(),value>0?bundledStrings[1].slice(bundledStrings.position1,bundledStrings.position1+=value):bundledStrings[0].slice(bundledStrings.position0,bundledStrings.position0-=value)):C1;case 194:return!1;case 195:return!0;case 196:if(value=src[position2++],value===void 0)throw new Error("Unexpected end of buffer");return readBin(value);case 197:return value=dataView.getUint16(position2),position2+=2,readBin(value);case 198:return value=dataView.getUint32(position2),position2+=4,readBin(value);case 199:return readExt(src[position2++]);case 200:return value=dataView.getUint16(position2),position2+=2,readExt(value);case 201:return value=dataView.getUint32(position2),position2+=4,readExt(value);case 202:if(value=dataView.getFloat32(position2),currentUnpackr.useFloat32>2){let multiplier=mult10[(src[position2]&127)<<1|src[position2+1]>>7];return position2+=4,(multiplier*value+(value>0?.5:-.5)>>0)/multiplier}return position2+=4,value;case 203:return value=dataView.getFloat64(position2),position2+=8,value;case 204:return src[position2++];case 205:return value=dataView.getUint16(position2),position2+=2,value;case 206:return value=dataView.getUint32(position2),position2+=4,value;case 207:return currentUnpackr.int64AsType==="number"?(value=dataView.getUint32(position2)*4294967296,value+=dataView.getUint32(position2+4)):currentUnpackr.int64AsType==="string"?value=dataView.getBigUint64(position2).toString():currentUnpackr.int64AsType==="auto"?(value=dataView.getBigUint64(position2),value<=BigInt(2)<<BigInt(52)&&(value=Number(value))):value=dataView.getBigUint64(position2),position2+=8,value;case 208:return dataView.getInt8(position2++);case 209:return value=dataView.getInt16(position2),position2+=2,value;case 210:return value=dataView.getInt32(position2),position2+=4,value;case 211:return currentUnpackr.int64AsType==="number"?(value=dataView.getInt32(position2)*4294967296,value+=dataView.getUint32(position2+4)):currentUnpackr.int64AsType==="string"?value=dataView.getBigInt64(position2).toString():currentUnpackr.int64AsType==="auto"?(value=dataView.getBigInt64(position2),value>=BigInt(-2)<<BigInt(52)&&value<=BigInt(2)<<BigInt(52)&&(value=Number(value))):value=dataView.getBigInt64(position2),position2+=8,value;case 212:if(value=src[position2++],value==114)return recordDefinition(src[position2++]&63);{let extension=currentExtensions[value];if(extension)return extension.read?(position2++,extension.read(read())):extension.noBuffer?(position2++,extension()):extension(src.subarray(position2,++position2));throw new Error("Unknown extension "+value)}case 213:return value=src[position2],value==114?(position2++,recordDefinition(src[position2++]&63,src[position2++])):readExt(2);case 214:return readExt(4);case 215:return readExt(8);case 216:return readExt(16);case 217:return value=src[position2++],srcStringEnd>=position2?srcString.slice(position2-srcStringStart,(position2+=value)-srcStringStart):readString8(value);case 218:return value=dataView.getUint16(position2),position2+=2,srcStringEnd>=position2?srcString.slice(position2-srcStringStart,(position2+=value)-srcStringStart):readString16(value);case 219:return value=dataView.getUint32(position2),position2+=4,srcStringEnd>=position2?srcString.slice(position2-srcStringStart,(position2+=value)-srcStringStart):readString32(value);case 220:return value=dataView.getUint16(position2),position2+=2,readArray(value);case 221:return value=dataView.getUint32(position2),position2+=4,readArray(value);case 222:return value=dataView.getUint16(position2),position2+=2,readMap(value);case 223:return value=dataView.getUint32(position2),position2+=4,readMap(value);default:if(token>=224)return token-256;if(token===void 0){let error2=new Error("Unexpected end of MessagePack data");throw error2.incomplete=!0,error2}throw new Error("Unknown MessagePack token "+token)}}}__name(read,"read");var validName=/^[a-zA-Z_$][a-zA-Z\d_$]*$/;function createStructureReader(structure,firstId){function readObject(){if(readObject.count++>inlineObjectReadThreshold){let readObject2=structure.read=new Function("r","return function(){return "+(currentUnpackr.freezeData?"Object.freeze":"")+"({"+structure.map(key=>key==="__proto__"?"__proto_:r()":validName.test(key)?key+":r()":"["+JSON.stringify(key)+"]:r()").join(",")+"})}")(read);return structure.highByte===0&&(structure.read=createSecondByteReader(firstId,structure.read)),readObject2()}let object2={};for(let i=0,l=structure.length;i<l;i++){let key=structure[i];key==="__proto__"&&(key="__proto_"),object2[key]=read()}return currentUnpackr.freezeData?Object.freeze(object2):object2}return __name(readObject,"readObject"),readObject.count=0,structure.highByte===0?createSecondByteReader(firstId,readObject):readObject}__name(createStructureReader,"createStructureReader");var createSecondByteReader=__name((firstId,read0)=>function(){let highByte=src[position2++];if(highByte===0)return read0();let id=firstId<32?-(firstId+(highByte<<5)):firstId+(highByte<<5),structure=currentStructures[id]||loadStructures()[id];if(!structure)throw new Error("Record id is not defined for "+id);return structure.read||(structure.read=createStructureReader(structure,firstId)),structure.read()},"createSecondByteReader");function loadStructures(){let loadedStructures=saveState(()=>(src=null,currentUnpackr.getStructures()));return currentStructures=currentUnpackr._mergeStructures(loadedStructures,currentStructures)}__name(loadStructures,"loadStructures");var readFixedString=readStringJS,readString8=readStringJS,readString16=readStringJS,readString32=readStringJS,isNativeAccelerationEnabled=!1;function setExtractor(extractStrings){isNativeAccelerationEnabled=!0,readFixedString=readString3(1),readString8=readString3(2),readString16=readString3(3),readString32=readString3(5);function readString3(headerLength){return __name(function(length){let string4=strings[stringPosition++];if(string4==null){if(bundledStrings)return readStringJS(length);let byteOffset=src.byteOffset,extraction=extractStrings(position2-headerLength+byteOffset,srcEnd+byteOffset,src.buffer);if(typeof extraction=="string")string4=extraction,strings=EMPTY_ARRAY;else if(strings=extraction,stringPosition=1,srcStringEnd=1,string4=strings[0],string4===void 0)throw new Error("Unexpected end of buffer")}let srcStringLength=string4.length;return srcStringLength<=length?(position2+=length,string4):(srcString=string4,srcStringStart=position2,srcStringEnd=position2+srcStringLength,position2+=length,string4.slice(0,length))},"readString")}__name(readString3,"readString")}__name(setExtractor,"setExtractor");function readStringJS(length){let result;if(length<16&&(result=shortStringInJS(length)))return result;if(length>64&&decoder)return decoder.decode(src.subarray(position2,position2+=length));let end=position2+length,units=[];for(result="";position2<end;){let byte1=src[position2++];if((byte1&128)===0)units.push(byte1);else if((byte1&224)===192){let byte2=src[position2++]&63;units.push((byte1&31)<<6|byte2)}else if((byte1&240)===224){let byte2=src[position2++]&63,byte3=src[position2++]&63;units.push((byte1&31)<<12|byte2<<6|byte3)}else if((byte1&248)===240){let byte2=src[position2++]&63,byte3=src[position2++]&63,byte4=src[position2++]&63,unit=(byte1&7)<<18|byte2<<12|byte3<<6|byte4;unit>65535&&(unit-=65536,units.push(unit>>>10&1023|55296),unit=56320|unit&1023),units.push(unit)}else units.push(byte1);units.length>=4096&&(result+=fromCharCode2.apply(String,units),units.length=0)}return units.length>0&&(result+=fromCharCode2.apply(String,units)),result}__name(readStringJS,"readStringJS");function readString2(source,start,length){let existingSrc=src;src=source,position2=start;try{return readStringJS(length)}finally{src=existingSrc}}__name(readString2,"readString");function readArray(length){let array2=new Array(length);for(let i=0;i<length;i++)array2[i]=read();return currentUnpackr.freezeData?Object.freeze(array2):array2}__name(readArray,"readArray");function readMap(length){if(currentUnpackr.mapsAsObjects){let object2={};for(let i=0;i<length;i++){let key=readKey2();key==="__proto__"&&(key="__proto_"),object2[key]=read()}return object2}else{let map2=new Map;for(let i=0;i<length;i++)map2.set(read(),read());return map2}}__name(readMap,"readMap");var fromCharCode2=String.fromCharCode;function longStringInJS(length){let start=position2,bytes=new Array(length);for(let i=0;i<length;i++){let byte=src[position2++];if((byte&128)>0){position2=start;return}bytes[i]=byte}return fromCharCode2.apply(String,bytes)}__name(longStringInJS,"longStringInJS");function shortStringInJS(length){if(length<4)if(length<2){if(length===0)return"";{let a=src[position2++];if((a&128)>1){position2-=1;return}return fromCharCode2(a)}}else{let a=src[position2++],b=src[position2++];if((a&128)>0||(b&128)>0){position2-=2;return}if(length<3)return fromCharCode2(a,b);let c2=src[position2++];if((c2&128)>0){position2-=3;return}return fromCharCode2(a,b,c2)}else{let a=src[position2++],b=src[position2++],c2=src[position2++],d=src[position2++];if((a&128)>0||(b&128)>0||(c2&128)>0||(d&128)>0){position2-=4;return}if(length<6){if(length===4)return fromCharCode2(a,b,c2,d);{let e2=src[position2++];if((e2&128)>0){position2-=5;return}return fromCharCode2(a,b,c2,d,e2)}}else if(length<8){let e2=src[position2++],f=src[position2++];if((e2&128)>0||(f&128)>0){position2-=6;return}if(length<7)return fromCharCode2(a,b,c2,d,e2,f);let g=src[position2++];if((g&128)>0){position2-=7;return}return fromCharCode2(a,b,c2,d,e2,f,g)}else{let e2=src[position2++],f=src[position2++],g=src[position2++],h=src[position2++];if((e2&128)>0||(f&128)>0||(g&128)>0||(h&128)>0){position2-=8;return}if(length<10){if(length===8)return fromCharCode2(a,b,c2,d,e2,f,g,h);{let i=src[position2++];if((i&128)>0){position2-=9;return}return fromCharCode2(a,b,c2,d,e2,f,g,h,i)}}else if(length<12){let i=src[position2++],j=src[position2++];if((i&128)>0||(j&128)>0){position2-=10;return}if(length<11)return fromCharCode2(a,b,c2,d,e2,f,g,h,i,j);let k=src[position2++];if((k&128)>0){position2-=11;return}return fromCharCode2(a,b,c2,d,e2,f,g,h,i,j,k)}else{let i=src[position2++],j=src[position2++],k=src[position2++],l=src[position2++];if((i&128)>0||(j&128)>0||(k&128)>0||(l&128)>0){position2-=12;return}if(length<14){if(length===12)return fromCharCode2(a,b,c2,d,e2,f,g,h,i,j,k,l);{let m=src[position2++];if((m&128)>0){position2-=13;return}return fromCharCode2(a,b,c2,d,e2,f,g,h,i,j,k,l,m)}}else{let m=src[position2++],n=src[position2++];if((m&128)>0||(n&128)>0){position2-=14;return}if(length<15)return fromCharCode2(a,b,c2,d,e2,f,g,h,i,j,k,l,m,n);let o=src[position2++];if((o&128)>0){position2-=15;return}return fromCharCode2(a,b,c2,d,e2,f,g,h,i,j,k,l,m,n,o)}}}}}__name(shortStringInJS,"shortStringInJS");function readOnlyJSString(){let token=src[position2++],length;if(token<192)length=token-160;else switch(token){case 217:length=src[position2++];break;case 218:length=dataView.getUint16(position2),position2+=2;break;case 219:length=dataView.getUint32(position2),position2+=4;break;default:throw new Error("Expected string")}return readStringJS(length)}__name(readOnlyJSString,"readOnlyJSString");function readBin(length){return currentUnpackr.copyBuffers?Uint8Array.prototype.slice.call(src,position2,position2+=length):src.subarray(position2,position2+=length)}__name(readBin,"readBin");function readExt(length){let type=src[position2++];if(currentExtensions[type]){let end;return currentExtensions[type](src.subarray(position2,end=position2+=length),readPosition=>{position2=readPosition;try{return read()}finally{position2=end}})}else throw new Error("Unknown extension type "+type)}__name(readExt,"readExt");var keyCache=new Array(4096);function readKey2(){let length=src[position2++];if(length>=160&&length<192){if(length=length-160,srcStringEnd>=position2)return srcString.slice(position2-srcStringStart,(position2+=length)-srcStringStart);if(!(srcStringEnd==0&&srcEnd<180))return readFixedString(length)}else return position2--,asSafeString(read());let key=(length<<5^(length>1?dataView.getUint16(position2):length>0?src[position2]:0))&4095,entry=keyCache[key],checkPosition=position2,end=position2+length-3,chunk3,i=0;if(entry&&entry.bytes==length){for(;checkPosition<end;){if(chunk3=dataView.getUint32(checkPosition),chunk3!=entry[i++]){checkPosition=1879048192;break}checkPosition+=4}for(end+=3;checkPosition<end;)if(chunk3=src[checkPosition++],chunk3!=entry[i++]){checkPosition=1879048192;break}if(checkPosition===end)return position2=checkPosition,entry.string;end-=3,checkPosition=position2}for(entry=[],keyCache[key]=entry,entry.bytes=length;checkPosition<end;)chunk3=dataView.getUint32(checkPosition),entry.push(chunk3),checkPosition+=4;for(end+=3;checkPosition<end;)chunk3=src[checkPosition++],entry.push(chunk3);let string4=length<16?shortStringInJS(length):longStringInJS(length);return string4!=null?entry.string=string4:entry.string=readFixedString(length)}__name(readKey2,"readKey");function asSafeString(property){if(typeof property=="string")return property;if(typeof property=="number"||typeof property=="boolean"||typeof property=="bigint")return property.toString();if(property==null)return property+"";throw new Error("Invalid property type for record",typeof property)}__name(asSafeString,"asSafeString");var recordDefinition=__name((id,highByte)=>{let structure=read().map(asSafeString),firstByte=id;highByte!==void 0&&(id=id<32?-((highByte<<5)+id):(highByte<<5)+id,structure.highByte=highByte);let existingStructure=currentStructures[id];return existingStructure&&(existingStructure.isShared||sequentialMode)&&((currentStructures.restoreStructures||(currentStructures.restoreStructures=[]))[id]=existingStructure),currentStructures[id]=structure,structure.read=createStructureReader(structure,firstByte),structure.read()},"recordDefinition");currentExtensions[0]=()=>{};currentExtensions[0].noBuffer=!0;currentExtensions[66]=data=>{let length=data.length,value=BigInt(data[0]&128?data[0]-256:data[0]);for(let i=1;i<length;i++)value<<=BigInt(8),value+=BigInt(data[i]);return value};var errors={Error,TypeError,ReferenceError};currentExtensions[101]=()=>{let data=read();return(errors[data[0]]||Error)(data[1],{cause:data[2]})};currentExtensions[105]=data=>{if(currentUnpackr.structuredClone===!1)throw new Error("Structured clone extension is disabled");let id=dataView.getUint32(position2-4);referenceMap||(referenceMap=new Map);let token=src[position2],target2;token>=144&&token<160||token==220||token==221?target2=[]:target2={};let refEntry={target:target2};referenceMap.set(id,refEntry);let targetProperties=read();return refEntry.used?Object.assign(target2,targetProperties):(refEntry.target=targetProperties,targetProperties)};currentExtensions[112]=data=>{if(currentUnpackr.structuredClone===!1)throw new Error("Structured clone extension is disabled");let id=dataView.getUint32(position2-4),refEntry=referenceMap.get(id);return refEntry.used=!0,refEntry.target};currentExtensions[115]=()=>new Set(read());var typedArrays=["Int8","Uint8","Uint8Clamped","Int16","Uint16","Int32","Uint32","Float32","Float64","BigInt64","BigUint64"].map(type=>type+"Array"),glbl=typeof globalThis=="object"?globalThis:window;currentExtensions[116]=data=>{let typeCode=data[0],typedArrayName=typedArrays[typeCode];if(!typedArrayName){if(typeCode===16){let ab=new ArrayBuffer(data.length-1);return new Uint8Array(ab).set(data.subarray(1)),ab}throw new Error("Could not find typed array for code "+typeCode)}return new glbl[typedArrayName](Uint8Array.prototype.slice.call(data,1).buffer)};currentExtensions[120]=()=>{let data=read();return new RegExp(data[0],data[1])};var TEMP_BUNDLE=[];currentExtensions[98]=data=>{let dataSize=(data[0]<<24)+(data[1]<<16)+(data[2]<<8)+data[3],dataPosition=position2;return position2+=dataSize-data.length,bundledStrings=TEMP_BUNDLE,bundledStrings=[readOnlyJSString(),readOnlyJSString()],bundledStrings.position0=0,bundledStrings.position1=0,bundledStrings.postBundlePosition=position2,position2=dataPosition,read()};currentExtensions[255]=data=>data.length==4?new Date((data[0]*16777216+(data[1]<<16)+(data[2]<<8)+data[3])*1e3):data.length==8?new Date(((data[0]<<22)+(data[1]<<14)+(data[2]<<6)+(data[3]>>2))/1e6+((data[3]&3)*4294967296+data[4]*16777216+(data[5]<<16)+(data[6]<<8)+data[7])*1e3):data.length==12?new Date(((data[0]<<24)+(data[1]<<16)+(data[2]<<8)+data[3])/1e6+((data[4]&128?-281474976710656:0)+data[6]*1099511627776+data[7]*4294967296+data[8]*16777216+(data[9]<<16)+(data[10]<<8)+data[11])*1e3):new Date("invalid");function saveState(callback){onSaveState&&onSaveState();let savedSrcEnd=srcEnd,savedPosition=position2,savedStringPosition=stringPosition,savedSrcStringStart=srcStringStart,savedSrcStringEnd=srcStringEnd,savedSrcString=srcString,savedStrings=strings,savedReferenceMap=referenceMap,savedBundledStrings=bundledStrings,savedSrc=new Uint8Array(src.slice(0,srcEnd)),savedStructures=currentStructures,savedStructuresContents=currentStructures.slice(0,currentStructures.length),savedPackr=currentUnpackr,savedSequentialMode=sequentialMode,value=callback();return srcEnd=savedSrcEnd,position2=savedPosition,stringPosition=savedStringPosition,srcStringStart=savedSrcStringStart,srcStringEnd=savedSrcStringEnd,srcString=savedSrcString,strings=savedStrings,referenceMap=savedReferenceMap,bundledStrings=savedBundledStrings,src=savedSrc,sequentialMode=savedSequentialMode,currentStructures=savedStructures,currentStructures.splice(0,currentStructures.length,...savedStructuresContents),currentUnpackr=savedPackr,dataView=new DataView(src.buffer,src.byteOffset,src.byteLength),value}__name(saveState,"saveState");function clearSource(){src=null,referenceMap=null,currentStructures=null}__name(clearSource,"clearSource");var mult10=new Array(147);for(let i=0;i<256;i++)mult10[i]=+("1e"+Math.floor(45.15-i*.30103));var defaultUnpackr=new Unpackr({useRecords:!1}),unpack=defaultUnpackr.unpack,unpackMultiple=defaultUnpackr.unpackMultiple,decode3=defaultUnpackr.unpack,FLOAT32_OPTIONS={NEVER:0,ALWAYS:1,DECIMAL_ROUND:3,DECIMAL_FIT:4},f32Array=new Float32Array(1),u8Array=new Uint8Array(f32Array.buffer,0,4);function setReadStruct(updatedReadStruct,loadedStructs,saveState3){readStruct=updatedReadStruct,onLoadedStructures=loadedStructs,onSaveState=saveState3}__name(setReadStruct,"setReadStruct");var textEncoder2;try{textEncoder2=new TextEncoder}catch{}var extensions,extensionClasses,hasNodeBuffer2=typeof Buffer<"u",ByteArrayAllocate2=hasNodeBuffer2?function(length){return Buffer.allocUnsafeSlow(length)}:Uint8Array,ByteArray=hasNodeBuffer2?Buffer:Uint8Array,MAX_BUFFER_SIZE=hasNodeBuffer2?4294967296:2144337920,target,keysTarget,targetView,position3=0,safeEnd,bundledStrings2=null,writeStructSlots,MAX_BUNDLE_SIZE=21760,hasNonLatin=/[\u0080-\uFFFF]/,RECORD_SYMBOL=Symbol("record-id"),Packr=class extends Unpackr{static{__name(this,"Packr")}constructor(options){super(options),this.offset=0;let typeBuffer,start,hasSharedUpdate,structures,referenceMap2,encodeUtf82=ByteArray.prototype.utf8Write?function(string4,position4){return target.utf8Write(string4,position4,target.byteLength-position4)}:textEncoder2&&textEncoder2.encodeInto?function(string4,position4){return textEncoder2.encodeInto(string4,target.subarray(position4)).written}:!1,packr=this;options||(options={});let isSequential=options&&options.sequential,hasSharedStructures=options.structures||options.saveStructures,maxSharedStructures=options.maxSharedStructures;if(maxSharedStructures==null&&(maxSharedStructures=hasSharedStructures?32:0),maxSharedStructures>8160)throw new Error("Maximum maxSharedStructure is 8160");options.structuredClone&&options.moreTypes==null&&(this.moreTypes=!0);let maxOwnStructures=options.maxOwnStructures;maxOwnStructures==null&&(maxOwnStructures=hasSharedStructures?32:64),!this.structures&&options.useRecords!=!1&&(this.structures=[]);let useTwoByteRecords=maxSharedStructures>32||maxOwnStructures+maxSharedStructures>64,sharedLimitId=maxSharedStructures+64,maxStructureId=maxSharedStructures+maxOwnStructures+64;if(maxStructureId>8256)throw new Error("Maximum maxSharedStructure + maxOwnStructure is 8192");let recordIdsToRemove=[],transitionsCount=0,serializationsSinceTransitionRebuild=0;this.pack=this.encode=function(value,encodeOptions){if(target||(target=new ByteArrayAllocate2(8192),targetView=target.dataView||(target.dataView=new DataView(target.buffer,0,8192)),position3=0),safeEnd=target.length-10,safeEnd-position3<2048?(target=new ByteArrayAllocate2(target.length),targetView=target.dataView||(target.dataView=new DataView(target.buffer,0,target.length)),safeEnd=target.length-10,position3=0):position3=position3+7&2147483640,start=position3,encodeOptions&RESERVE_START_SPACE&&(position3+=encodeOptions&255),referenceMap2=packr.structuredClone?new Map:null,packr.bundleStrings&&typeof value!="string"?(bundledStrings2=[],bundledStrings2.size=1/0):bundledStrings2=null,structures=packr.structures,structures){structures.uninitialized&&(structures=packr._mergeStructures(packr.getStructures()));let sharedLength=structures.sharedLength||0;if(sharedLength>maxSharedStructures)throw new Error("Shared structures is larger than maximum shared structures, try increasing maxSharedStructures to "+structures.sharedLength);if(!structures.transitions){structures.transitions=Object.create(null);for(let i=0;i<sharedLength;i++){let keys=structures[i];if(!keys)continue;let nextTransition,transition=structures.transitions;for(let j=0,l=keys.length;j<l;j++){let key=keys[j];nextTransition=transition[key],nextTransition||(nextTransition=transition[key]=Object.create(null)),transition=nextTransition}transition[RECORD_SYMBOL]=i+64}this.lastNamedStructuresLength=sharedLength}isSequential||(structures.nextId=sharedLength+64)}hasSharedUpdate&&(hasSharedUpdate=!1);let encodingError;try{packr.randomAccessStructure&&value&&value.constructor&&value.constructor===Object?writeStruct2(value):pack2(value);let lastBundle=bundledStrings2;if(bundledStrings2&&writeBundles(start,pack2,0),referenceMap2&&referenceMap2.idsToInsert){let idsToInsert=referenceMap2.idsToInsert.sort((a,b)=>a.offset>b.offset?1:-1),i=idsToInsert.length,incrementPosition=-1;for(;lastBundle&&i>0;){let insertionPoint=idsToInsert[--i].offset+start;insertionPoint<lastBundle.stringsPosition+start&&incrementPosition===-1&&(incrementPosition=0),insertionPoint>lastBundle.position+start?incrementPosition>=0&&(incrementPosition+=6):(incrementPosition>=0&&(targetView.setUint32(lastBundle.position+start,targetView.getUint32(lastBundle.position+start)+incrementPosition),incrementPosition=-1),lastBundle=lastBundle.previous,i++)}incrementPosition>=0&&lastBundle&&targetView.setUint32(lastBundle.position+start,targetView.getUint32(lastBundle.position+start)+incrementPosition),position3+=idsToInsert.length*6,position3>safeEnd&&makeRoom(position3),packr.offset=position3;let serialized=insertIds(target.subarray(start,position3),idsToInsert);return referenceMap2=null,serialized}return packr.offset=position3,encodeOptions&REUSE_BUFFER_MODE?(target.start=start,target.end=position3,target):target.subarray(start,position3)}catch(error2){throw encodingError=error2,error2}finally{if(structures&&(resetStructures(),hasSharedUpdate&&packr.saveStructures)){let sharedLength=structures.sharedLength||0,returnBuffer=target.subarray(start,position3),newSharedData=prepareStructures(structures,packr);if(!encodingError)return packr.saveStructures(newSharedData,newSharedData.isCompatible)===!1?packr.pack(value,encodeOptions):(packr.lastNamedStructuresLength=sharedLength,target.length>1073741824&&(target=null),returnBuffer)}target.length>1073741824&&(target=null),encodeOptions&RESET_BUFFER_MODE&&(position3=start)}};let resetStructures=__name(()=>{serializationsSinceTransitionRebuild<10&&serializationsSinceTransitionRebuild++;let sharedLength=structures.sharedLength||0;if(structures.length>sharedLength&&!isSequential&&(structures.length=sharedLength),transitionsCount>1e4)structures.transitions=null,serializationsSinceTransitionRebuild=0,transitionsCount=0,recordIdsToRemove.length>0&&(recordIdsToRemove=[]);else if(recordIdsToRemove.length>0&&!isSequential){for(let i=0,l=recordIdsToRemove.length;i<l;i++)recordIdsToRemove[i][RECORD_SYMBOL]=0;recordIdsToRemove=[]}},"resetStructures"),packArray=__name(value=>{var length=value.length;length<16?target[position3++]=144|length:length<65536?(target[position3++]=220,target[position3++]=length>>8,target[position3++]=length&255):(target[position3++]=221,targetView.setUint32(position3,length),position3+=4);for(let i=0;i<length;i++)pack2(value[i])},"packArray"),pack2=__name(value=>{position3>safeEnd&&(target=makeRoom(position3));var type=typeof value,length;if(type==="string"){let strLength=value.length;if(bundledStrings2&&strLength>=4&&strLength<4096){if((bundledStrings2.size+=strLength)>MAX_BUNDLE_SIZE){let extStart,maxBytes2=(bundledStrings2[0]?bundledStrings2[0].length*3+bundledStrings2[1].length:0)+10;position3+maxBytes2>safeEnd&&(target=makeRoom(position3+maxBytes2));let lastBundle;bundledStrings2.position?(lastBundle=bundledStrings2,target[position3]=200,position3+=3,target[position3++]=98,extStart=position3-start,position3+=4,writeBundles(start,pack2,0),targetView.setUint16(extStart+start-3,position3-start-extStart)):(target[position3++]=214,target[position3++]=98,extStart=position3-start,position3+=4),bundledStrings2=["",""],bundledStrings2.previous=lastBundle,bundledStrings2.size=0,bundledStrings2.position=extStart}let twoByte=hasNonLatin.test(value);bundledStrings2[twoByte?0:1]+=value,target[position3++]=193,pack2(twoByte?-strLength:strLength);return}let headerSize;strLength<32?headerSize=1:strLength<256?headerSize=2:strLength<65536?headerSize=3:headerSize=5;let maxBytes=strLength*3;if(position3+maxBytes>safeEnd&&(target=makeRoom(position3+maxBytes)),strLength<64||!encodeUtf82){let i,c1,c2,strPosition=position3+headerSize;for(i=0;i<strLength;i++)c1=value.charCodeAt(i),c1<128?target[strPosition++]=c1:c1<2048?(target[strPosition++]=c1>>6|192,target[strPosition++]=c1&63|128):(c1&64512)===55296&&((c2=value.charCodeAt(i+1))&64512)===56320?(c1=65536+((c1&1023)<<10)+(c2&1023),i++,target[strPosition++]=c1>>18|240,target[strPosition++]=c1>>12&63|128,target[strPosition++]=c1>>6&63|128,target[strPosition++]=c1&63|128):(target[strPosition++]=c1>>12|224,target[strPosition++]=c1>>6&63|128,target[strPosition++]=c1&63|128);length=strPosition-position3-headerSize}else length=encodeUtf82(value,position3+headerSize);length<32?target[position3++]=160|length:length<256?(headerSize<2&&target.copyWithin(position3+2,position3+1,position3+1+length),target[position3++]=217,target[position3++]=length):length<65536?(headerSize<3&&target.copyWithin(position3+3,position3+2,position3+2+length),target[position3++]=218,target[position3++]=length>>8,target[position3++]=length&255):(headerSize<5&&target.copyWithin(position3+5,position3+3,position3+3+length),target[position3++]=219,targetView.setUint32(position3,length),position3+=4),position3+=length}else if(type==="number")if(value>>>0===value)value<32||value<128&&this.useRecords===!1||value<64&&!this.randomAccessStructure?target[position3++]=value:value<256?(target[position3++]=204,target[position3++]=value):value<65536?(target[position3++]=205,target[position3++]=value>>8,target[position3++]=value&255):(target[position3++]=206,targetView.setUint32(position3,value),position3+=4);else if(value>>0===value)value>=-32?target[position3++]=256+value:value>=-128?(target[position3++]=208,target[position3++]=value+256):value>=-32768?(target[position3++]=209,targetView.setInt16(position3,value),position3+=2):(target[position3++]=210,targetView.setInt32(position3,value),position3+=4);else{let useFloat32;if((useFloat32=this.useFloat32)>0&&value<4294967296&&value>=-2147483648){target[position3++]=202,targetView.setFloat32(position3,value);let xShifted;if(useFloat32<4||(xShifted=value*mult10[(target[position3]&127)<<1|target[position3+1]>>7])>>0===xShifted){position3+=4;return}else position3--}target[position3++]=203,targetView.setFloat64(position3,value),position3+=8}else if(type==="object"||type==="function")if(!value)target[position3++]=192;else{if(referenceMap2){let referee=referenceMap2.get(value);if(referee){if(!referee.id){let idsToInsert=referenceMap2.idsToInsert||(referenceMap2.idsToInsert=[]);referee.id=idsToInsert.push(referee)}target[position3++]=214,target[position3++]=112,targetView.setUint32(position3,referee.id),position3+=4;return}else referenceMap2.set(value,{offset:position3-start})}let constructor=value.constructor;if(constructor===Object)writeObject(value);else if(constructor===Array)packArray(value);else if(constructor===Map)if(this.mapAsEmptyObject)target[position3++]=128;else{length=value.size,length<16?target[position3++]=128|length:length<65536?(target[position3++]=222,target[position3++]=length>>8,target[position3++]=length&255):(target[position3++]=223,targetView.setUint32(position3,length),position3+=4);for(let[key,entryValue]of value)pack2(key),pack2(entryValue)}else{for(let i=0,l=extensions.length;i<l;i++){let extensionClass=extensionClasses[i];if(value instanceof extensionClass){let extension=extensions[i];if(extension.write){extension.type&&(target[position3++]=212,target[position3++]=extension.type,target[position3++]=0);let writeResult=extension.write.call(this,value);writeResult===value?Array.isArray(value)?packArray(value):writeObject(value):pack2(writeResult);return}let currentTarget=target,currentTargetView=targetView,currentPosition=position3;target=null;let result;try{result=extension.pack.call(this,value,size=>(target=currentTarget,currentTarget=null,position3+=size,position3>safeEnd&&makeRoom(position3),{target,targetView,position:position3-size}),pack2)}finally{currentTarget&&(target=currentTarget,targetView=currentTargetView,position3=currentPosition,safeEnd=target.length-10)}result&&(result.length+position3>safeEnd&&makeRoom(result.length+position3),position3=writeExtensionData(result,target,position3,extension.type));return}}if(Array.isArray(value))packArray(value);else{if(value.toJSON){let json2=value.toJSON();if(json2!==value)return pack2(json2)}if(type==="function")return pack2(this.writeFunction&&this.writeFunction(value));writeObject(value)}}}else if(type==="boolean")target[position3++]=value?195:194;else if(type==="bigint"){if(value<BigInt(1)<<BigInt(63)&&value>=-(BigInt(1)<<BigInt(63)))target[position3++]=211,targetView.setBigInt64(position3,value);else if(value<BigInt(1)<<BigInt(64)&&value>0)target[position3++]=207,targetView.setBigUint64(position3,value);else if(this.largeBigIntToFloat)target[position3++]=203,targetView.setFloat64(position3,Number(value));else{if(this.largeBigIntToString)return pack2(value.toString());if(this.useBigIntExtension&&value<BigInt(2)**BigInt(1023)&&value>-(BigInt(2)**BigInt(1023))){target[position3++]=199,position3++,target[position3++]=66;let bytes=[],alignedSign;do{let byte=value&BigInt(255);alignedSign=(byte&BigInt(128))===(value<BigInt(0)?BigInt(128):BigInt(0)),bytes.push(byte),value>>=BigInt(8)}while(!((value===BigInt(0)||value===BigInt(-1))&&alignedSign));target[position3-2]=bytes.length;for(let i=bytes.length;i>0;)target[position3++]=Number(bytes[--i]);return}else throw new RangeError(value+" was too large to fit in MessagePack 64-bit integer format, use useBigIntExtension, or set largeBigIntToFloat to convert to float-64, or set largeBigIntToString to convert to string")}position3+=8}else if(type==="undefined")this.encodeUndefinedAsNil?target[position3++]=192:(target[position3++]=212,target[position3++]=0,target[position3++]=0);else throw new Error("Unknown type: "+type)},"pack"),writePlainObject=this.variableMapSize||this.coercibleKeyAsNumber||this.skipValues?object2=>{let keys;if(this.skipValues){keys=[];for(let key2 in object2)(typeof object2.hasOwnProperty!="function"||object2.hasOwnProperty(key2))&&!this.skipValues.includes(object2[key2])&&keys.push(key2)}else keys=Object.keys(object2);let length=keys.length;length<16?target[position3++]=128|length:length<65536?(target[position3++]=222,target[position3++]=length>>8,target[position3++]=length&255):(target[position3++]=223,targetView.setUint32(position3,length),position3+=4);let key;if(this.coercibleKeyAsNumber)for(let i=0;i<length;i++){key=keys[i];let num=Number(key);pack2(isNaN(num)?key:num),pack2(object2[key])}else for(let i=0;i<length;i++)pack2(key=keys[i]),pack2(object2[key])}:object2=>{target[position3++]=222;let objectOffset=position3-start;position3+=2;let size=0;for(let key in object2)(typeof object2.hasOwnProperty!="function"||object2.hasOwnProperty(key))&&(pack2(key),pack2(object2[key]),size++);if(size>65535)throw new Error('Object is too large to serialize with fast 16-bit map size, use the "variableMapSize" option to serialize this object');target[objectOffset+++start]=size>>8,target[objectOffset+start]=size&255},writeRecord=this.useRecords===!1?writePlainObject:options.progressiveRecords&&!useTwoByteRecords?object2=>{let nextTransition,transition=structures.transitions||(structures.transitions=Object.create(null)),objectOffset=position3++-start,wroteKeys;for(let key in object2)if(typeof object2.hasOwnProperty!="function"||object2.hasOwnProperty(key)){if(nextTransition=transition[key],nextTransition)transition=nextTransition;else{let keys=Object.keys(object2),lastTransition=transition;transition=structures.transitions;let newTransitions=0;for(let i=0,l=keys.length;i<l;i++){let key2=keys[i];nextTransition=transition[key2],nextTransition||(nextTransition=transition[key2]=Object.create(null),newTransitions++),transition=nextTransition}objectOffset+start+1==position3?(position3--,newRecord(transition,keys,newTransitions)):insertNewRecord(transition,keys,objectOffset,newTransitions),wroteKeys=!0,transition=lastTransition[key]}pack2(object2[key])}if(!wroteKeys){let recordId=transition[RECORD_SYMBOL];recordId?target[objectOffset+start]=recordId:insertNewRecord(transition,Object.keys(object2),objectOffset,0)}}:object2=>{let nextTransition,transition=structures.transitions||(structures.transitions=Object.create(null)),newTransitions=0;for(let key in object2)(typeof object2.hasOwnProperty!="function"||object2.hasOwnProperty(key))&&(nextTransition=transition[key],nextTransition||(nextTransition=transition[key]=Object.create(null),newTransitions++),transition=nextTransition);let recordId=transition[RECORD_SYMBOL];recordId?recordId>=96&&useTwoByteRecords?(target[position3++]=((recordId-=96)&31)+96,target[position3++]=recordId>>5):target[position3++]=recordId:newRecord(transition,transition.__keys__||Object.keys(object2),newTransitions);for(let key in object2)(typeof object2.hasOwnProperty!="function"||object2.hasOwnProperty(key))&&pack2(object2[key])},checkUseRecords=typeof this.useRecords=="function"&&this.useRecords,writeObject=checkUseRecords?object2=>{checkUseRecords(object2)?writeRecord(object2):writePlainObject(object2)}:writeRecord,makeRoom=__name(end=>{let newSize;if(end>16777216){if(end-start>MAX_BUFFER_SIZE)throw new Error("Packed buffer would be larger than maximum buffer size");newSize=Math.min(MAX_BUFFER_SIZE,Math.round(Math.max((end-start)*(end>67108864?1.25:2),4194304)/4096)*4096)}else newSize=(Math.max(end-start<<2,target.length-1)>>12)+1<<12;let newBuffer=new ByteArrayAllocate2(newSize);return targetView=newBuffer.dataView||(newBuffer.dataView=new DataView(newBuffer.buffer,0,newSize)),end=Math.min(end,target.length),target.copy?target.copy(newBuffer,0,start,end):newBuffer.set(target.slice(start,end)),position3-=start,start=0,safeEnd=newBuffer.length-10,target=newBuffer},"makeRoom"),newRecord=__name((transition,keys,newTransitions)=>{let recordId=structures.nextId;recordId||(recordId=64),recordId<sharedLimitId&&this.shouldShareStructure&&!this.shouldShareStructure(keys)?(recordId=structures.nextOwnId,recordId<maxStructureId||(recordId=sharedLimitId),structures.nextOwnId=recordId+1):(recordId>=maxStructureId&&(recordId=sharedLimitId),structures.nextId=recordId+1);let highByte=keys.highByte=recordId>=96&&useTwoByteRecords?recordId-96>>5:-1;transition[RECORD_SYMBOL]=recordId,transition.__keys__=keys,structures[recordId-64]=keys,recordId<sharedLimitId?(keys.isShared=!0,structures.sharedLength=recordId-63,hasSharedUpdate=!0,highByte>=0?(target[position3++]=(recordId&31)+96,target[position3++]=highByte):target[position3++]=recordId):(highByte>=0?(target[position3++]=213,target[position3++]=114,target[position3++]=(recordId&31)+96,target[position3++]=highByte):(target[position3++]=212,target[position3++]=114,target[position3++]=recordId),newTransitions&&(transitionsCount+=serializationsSinceTransitionRebuild*newTransitions),recordIdsToRemove.length>=maxOwnStructures&&(recordIdsToRemove.shift()[RECORD_SYMBOL]=0),recordIdsToRemove.push(transition),pack2(keys))},"newRecord"),insertNewRecord=__name((transition,keys,insertionOffset,newTransitions)=>{let mainTarget=target,mainPosition=position3,mainSafeEnd=safeEnd,mainStart=start;target=keysTarget,position3=0,start=0,target||(keysTarget=target=new ByteArrayAllocate2(8192)),safeEnd=target.length-10,newRecord(transition,keys,newTransitions),keysTarget=target;let keysPosition=position3;if(target=mainTarget,position3=mainPosition,safeEnd=mainSafeEnd,start=mainStart,keysPosition>1){let newEnd=position3+keysPosition-1;newEnd>safeEnd&&makeRoom(newEnd);let insertionPosition=insertionOffset+start;target.copyWithin(insertionPosition+keysPosition,insertionPosition+1,position3),target.set(keysTarget.slice(0,keysPosition),insertionPosition),position3=newEnd}else target[insertionOffset+start]=keysTarget[0]},"insertNewRecord"),writeStruct2=__name(object2=>{let newPosition=writeStructSlots(object2,target,start,position3,structures,makeRoom,(value,newPosition2,notifySharedUpdate)=>{if(notifySharedUpdate)return hasSharedUpdate=!0;position3=newPosition2;let startTarget=target;return pack2(value),resetStructures(),startTarget!==target?{position:position3,targetView,target}:position3},this);if(newPosition===0)return writeObject(object2);position3=newPosition},"writeStruct")}useBuffer(buffer){target=buffer,target.dataView||(target.dataView=new DataView(target.buffer,target.byteOffset,target.byteLength)),position3=0}set position(value){position3=value}get position(){return position3}clearSharedData(){this.structures&&(this.structures=[]),this.typedStructs&&(this.typedStructs=[])}};extensionClasses=[Date,Set,Error,RegExp,ArrayBuffer,Object.getPrototypeOf(Uint8Array.prototype).constructor,C1Type];extensions=[{pack(date5,allocateForWrite,pack2){let seconds=date5.getTime()/1e3;if((this.useTimestamp32||date5.getMilliseconds()===0)&&seconds>=0&&seconds<4294967296){let{target:target2,targetView:targetView2,position:position4}=allocateForWrite(6);target2[position4++]=214,target2[position4++]=255,targetView2.setUint32(position4,seconds)}else if(seconds>0&&seconds<4294967296){let{target:target2,targetView:targetView2,position:position4}=allocateForWrite(10);target2[position4++]=215,target2[position4++]=255,targetView2.setUint32(position4,date5.getMilliseconds()*4e6+(seconds/1e3/4294967296>>0)),targetView2.setUint32(position4+4,seconds)}else if(isNaN(seconds)){if(this.onInvalidDate)return allocateForWrite(0),pack2(this.onInvalidDate());let{target:target2,targetView:targetView2,position:position4}=allocateForWrite(3);target2[position4++]=212,target2[position4++]=255,target2[position4++]=255}else{let{target:target2,targetView:targetView2,position:position4}=allocateForWrite(15);target2[position4++]=199,target2[position4++]=12,target2[position4++]=255,targetView2.setUint32(position4,date5.getMilliseconds()*1e6),targetView2.setBigInt64(position4+4,BigInt(Math.floor(seconds)))}}},{pack(set2,allocateForWrite,pack2){if(this.setAsEmptyObject)return allocateForWrite(0),pack2({});let array2=Array.from(set2),{target:target2,position:position4}=allocateForWrite(this.moreTypes?3:0);this.moreTypes&&(target2[position4++]=212,target2[position4++]=115,target2[position4++]=0),pack2(array2)}},{pack(error2,allocateForWrite,pack2){let{target:target2,position:position4}=allocateForWrite(this.moreTypes?3:0);this.moreTypes&&(target2[position4++]=212,target2[position4++]=101,target2[position4++]=0),pack2([error2.name,error2.message,error2.cause])}},{pack(regex,allocateForWrite,pack2){let{target:target2,position:position4}=allocateForWrite(this.moreTypes?3:0);this.moreTypes&&(target2[position4++]=212,target2[position4++]=120,target2[position4++]=0),pack2([regex.source,regex.flags])}},{pack(arrayBuffer,allocateForWrite){this.moreTypes?writeExtBuffer(arrayBuffer,16,allocateForWrite):writeBuffer(hasNodeBuffer2?Buffer.from(arrayBuffer):new Uint8Array(arrayBuffer),allocateForWrite)}},{pack(typedArray,allocateForWrite){let constructor=typedArray.constructor;constructor!==ByteArray&&this.moreTypes?writeExtBuffer(typedArray,typedArrays.indexOf(constructor.name),allocateForWrite):writeBuffer(typedArray,allocateForWrite)}},{pack(c1,allocateForWrite){let{target:target2,position:position4}=allocateForWrite(1);target2[position4]=193}}];function writeExtBuffer(typedArray,type,allocateForWrite,encode4){let length=typedArray.byteLength;if(length+1<256){var{target:target2,position:position4}=allocateForWrite(4+length);target2[position4++]=199,target2[position4++]=length+1}else if(length+1<65536){var{target:target2,position:position4}=allocateForWrite(5+length);target2[position4++]=200,target2[position4++]=length+1>>8,target2[position4++]=length+1&255}else{var{target:target2,position:position4,targetView:targetView2}=allocateForWrite(7+length);target2[position4++]=201,targetView2.setUint32(position4,length+1),position4+=4}target2[position4++]=116,target2[position4++]=type,typedArray.buffer||(typedArray=new Uint8Array(typedArray)),target2.set(new Uint8Array(typedArray.buffer,typedArray.byteOffset,typedArray.byteLength),position4)}__name(writeExtBuffer,"writeExtBuffer");function writeBuffer(buffer,allocateForWrite){let length=buffer.byteLength;var target2,position4;if(length<256){var{target:target2,position:position4}=allocateForWrite(length+2);target2[position4++]=196,target2[position4++]=length}else if(length<65536){var{target:target2,position:position4}=allocateForWrite(length+3);target2[position4++]=197,target2[position4++]=length>>8,target2[position4++]=length&255}else{var{target:target2,position:position4,targetView:targetView2}=allocateForWrite(length+5);target2[position4++]=198,targetView2.setUint32(position4,length),position4+=4}target2.set(buffer,position4)}__name(writeBuffer,"writeBuffer");function writeExtensionData(result,target2,position4,type){let length=result.length;switch(length){case 1:target2[position4++]=212;break;case 2:target2[position4++]=213;break;case 4:target2[position4++]=214;break;case 8:target2[position4++]=215;break;case 16:target2[position4++]=216;break;default:length<256?(target2[position4++]=199,target2[position4++]=length):length<65536?(target2[position4++]=200,target2[position4++]=length>>8,target2[position4++]=length&255):(target2[position4++]=201,target2[position4++]=length>>24,target2[position4++]=length>>16&255,target2[position4++]=length>>8&255,target2[position4++]=length&255)}return target2[position4++]=type,target2.set(result,position4),position4+=length,position4}__name(writeExtensionData,"writeExtensionData");function insertIds(serialized,idsToInsert){let nextId,distanceToMove=idsToInsert.length*6,lastEnd=serialized.length-distanceToMove;for(;nextId=idsToInsert.pop();){let offset=nextId.offset,id=nextId.id;serialized.copyWithin(offset+distanceToMove,offset,lastEnd),distanceToMove-=6;let position4=offset+distanceToMove;serialized[position4++]=214,serialized[position4++]=105,serialized[position4++]=id>>24,serialized[position4++]=id>>16&255,serialized[position4++]=id>>8&255,serialized[position4++]=id&255,lastEnd=offset}return serialized}__name(insertIds,"insertIds");function writeBundles(start,pack2,incrementPosition){if(bundledStrings2.length>0){targetView.setUint32(bundledStrings2.position+start,position3+incrementPosition-bundledStrings2.position-start),bundledStrings2.stringsPosition=position3-start;let writeStrings=bundledStrings2;bundledStrings2=null,pack2(writeStrings[0]),pack2(writeStrings[1])}}__name(writeBundles,"writeBundles");function prepareStructures(structures,packr){return structures.isCompatible=existingStructures=>{let compatible=!existingStructures||(packr.lastNamedStructuresLength||0)===existingStructures.length;return compatible||packr._mergeStructures(existingStructures),compatible},structures}__name(prepareStructures,"prepareStructures");function setWriteStructSlots(writeSlots,makeStructures){writeStructSlots=writeSlots,prepareStructures=makeStructures}__name(setWriteStructSlots,"setWriteStructSlots");var defaultPackr=new Packr({useRecords:!1}),pack=defaultPackr.pack,encode3=defaultPackr.pack,Encoder6=Packr,{NEVER:NEVER2,ALWAYS,DECIMAL_ROUND,DECIMAL_FIT}=FLOAT32_OPTIONS,REUSE_BUFFER_MODE=512,RESET_BUFFER_MODE=1024,RESERVE_START_SPACE=2048;var ASCII=3,NUMBER=0,UTF8=2,OBJECT_DATA=1,DATE=16,TYPE_NAMES=["num","object","string","ascii"];TYPE_NAMES[DATE]="date";var float32Headers=[!1,!0,!0,!1,!1,!0,!0,!1],evalSupported;try{new Function(""),evalSupported=!0}catch{}var updatedPosition,hasNodeBuffer3=typeof Buffer<"u",textEncoder3,currentSource;try{textEncoder3=new TextEncoder}catch{}var encodeUtf8=hasNodeBuffer3?function(target2,string4,position4){return target2.utf8Write(string4,position4,target2.byteLength-position4)}:textEncoder3&&textEncoder3.encodeInto?function(target2,string4,position4){return textEncoder3.encodeInto(string4,target2.subarray(position4)).written}:!1;setWriteStructSlots(writeStruct,prepareStructures2);function writeStruct(object2,target2,encodingStart,position4,structures,makeRoom,pack2,packr){let typedStructs=packr.typedStructs||(packr.typedStructs=[]),targetView2=target2.dataView,refsStartPosition=(typedStructs.lastStringStart||100)+position4,safeEnd2=target2.length-10,start=position4;position4>safeEnd2&&(target2=makeRoom(position4),targetView2=target2.dataView,position4-=encodingStart,start-=encodingStart,refsStartPosition-=encodingStart,encodingStart=0,safeEnd2=target2.length-10);let refOffset,refPosition=refsStartPosition,transition=typedStructs.transitions||(typedStructs.transitions=Object.create(null)),nextId=typedStructs.nextId||typedStructs.length,headerSize=nextId<15?1:nextId<240?2:nextId<61440?3:nextId<15728640?4:0;if(headerSize===0)return 0;position4+=headerSize;let queuedReferences=[],usedAscii0,keyIndex=0;for(let key in object2){let value=object2[key],nextTransition=transition[key];switch(nextTransition||(transition[key]=nextTransition={key,parent:transition,enumerationOffset:0,ascii0:null,ascii8:null,num8:null,string16:null,object16:null,num32:null,float64:null,date64:null}),position4>safeEnd2&&(target2=makeRoom(position4),targetView2=target2.dataView,position4-=encodingStart,start-=encodingStart,refsStartPosition-=encodingStart,refPosition-=encodingStart,encodingStart=0,safeEnd2=target2.length-10),typeof value){case"number":let number4=value;if(nextId<200||!nextTransition.num64){if(number4>>0===number4&&number4<536870912&&number4>-520093696){number4<246&&number4>=0&&(nextTransition.num8&&!(nextId>200&&nextTransition.num32)||number4<32&&!nextTransition.num32)?(transition=nextTransition.num8||createTypeTransition(nextTransition,NUMBER,1),target2[position4++]=number4):(transition=nextTransition.num32||createTypeTransition(nextTransition,NUMBER,4),targetView2.setUint32(position4,number4,!0),position4+=4);break}else if(number4<4294967296&&number4>=-2147483648&&(targetView2.setFloat32(position4,number4,!0),float32Headers[target2[position4+3]>>>5])){let xShifted;if((xShifted=number4*mult10[(target2[position4+3]&127)<<1|target2[position4+2]>>7])>>0===xShifted){transition=nextTransition.num32||createTypeTransition(nextTransition,NUMBER,4),position4+=4;break}}}transition=nextTransition.num64||createTypeTransition(nextTransition,NUMBER,8),targetView2.setFloat64(position4,number4,!0),position4+=8;break;case"string":let strLength=value.length;if(refOffset=refPosition-refsStartPosition,(strLength<<2)+refPosition>safeEnd2&&(target2=makeRoom((strLength<<2)+refPosition),targetView2=target2.dataView,position4-=encodingStart,start-=encodingStart,refsStartPosition-=encodingStart,refPosition-=encodingStart,encodingStart=0,safeEnd2=target2.length-10),strLength>65280+refOffset>>2){queuedReferences.push(key,value,position4-start);break}let isNotAscii,strStart=refPosition;if(strLength<64){let i,c1,c2;for(i=0;i<strLength;i++)c1=value.charCodeAt(i),c1<128?target2[refPosition++]=c1:c1<2048?(isNotAscii=!0,target2[refPosition++]=c1>>6|192,target2[refPosition++]=c1&63|128):(c1&64512)===55296&&((c2=value.charCodeAt(i+1))&64512)===56320?(isNotAscii=!0,c1=65536+((c1&1023)<<10)+(c2&1023),i++,target2[refPosition++]=c1>>18|240,target2[refPosition++]=c1>>12&63|128,target2[refPosition++]=c1>>6&63|128,target2[refPosition++]=c1&63|128):(isNotAscii=!0,target2[refPosition++]=c1>>12|224,target2[refPosition++]=c1>>6&63|128,target2[refPosition++]=c1&63|128)}else refPosition+=encodeUtf8(target2,value,refPosition),isNotAscii=refPosition-strStart>strLength;if(refOffset<160||refOffset<246&&(nextTransition.ascii8||nextTransition.string8)){if(isNotAscii)(transition=nextTransition.string8)||(typedStructs.length>10&&(transition=nextTransition.ascii8)?(transition.__type=UTF8,nextTransition.ascii8=null,nextTransition.string8=transition,pack2(null,0,!0)):transition=createTypeTransition(nextTransition,UTF8,1));else if(refOffset===0&&!usedAscii0){usedAscii0=!0,transition=nextTransition.ascii0||createTypeTransition(nextTransition,ASCII,0);break}else!(transition=nextTransition.ascii8)&&!(typedStructs.length>10&&(transition=nextTransition.string8))&&(transition=createTypeTransition(nextTransition,ASCII,1));target2[position4++]=refOffset}else transition=nextTransition.string16||createTypeTransition(nextTransition,UTF8,2),targetView2.setUint16(position4,refOffset,!0),position4+=2;break;case"object":if(value){value.constructor===Date?(transition=nextTransition.date64||createTypeTransition(nextTransition,DATE,8),targetView2.setFloat64(position4,value.getTime(),!0),position4+=8):queuedReferences.push(key,value,keyIndex);break}else nextTransition=anyType(nextTransition,position4,targetView2,-10),nextTransition?(transition=nextTransition,position4=updatedPosition):queuedReferences.push(key,value,keyIndex);break;case"boolean":transition=nextTransition.num8||nextTransition.ascii8||createTypeTransition(nextTransition,NUMBER,1),target2[position4++]=value?249:248;break;case"undefined":nextTransition=anyType(nextTransition,position4,targetView2,-9),nextTransition?(transition=nextTransition,position4=updatedPosition):queuedReferences.push(key,value,keyIndex);break;default:queuedReferences.push(key,value,keyIndex)}keyIndex++}for(let i=0,l=queuedReferences.length;i<l;){let key=queuedReferences[i++],value=queuedReferences[i++],propertyIndex=queuedReferences[i++],nextTransition=transition[key];nextTransition||(transition[key]=nextTransition={key,parent:transition,enumerationOffset:propertyIndex-keyIndex,ascii0:null,ascii8:null,num8:null,string16:null,object16:null,num32:null,float64:null});let newPosition;if(value){let size;refOffset=refPosition-refsStartPosition,refOffset<65280?(transition=nextTransition.object16,transition?size=2:(transition=nextTransition.object32)?size=4:(transition=createTypeTransition(nextTransition,OBJECT_DATA,2),size=2)):(transition=nextTransition.object32||createTypeTransition(nextTransition,OBJECT_DATA,4),size=4),newPosition=pack2(value,refPosition),typeof newPosition=="object"?(refPosition=newPosition.position,targetView2=newPosition.targetView,target2=newPosition.target,refsStartPosition-=encodingStart,position4-=encodingStart,start-=encodingStart,encodingStart=0):refPosition=newPosition,size===2?(targetView2.setUint16(position4,refOffset,!0),position4+=2):(targetView2.setUint32(position4,refOffset,!0),position4+=4)}else transition=nextTransition.object16||createTypeTransition(nextTransition,OBJECT_DATA,2),targetView2.setInt16(position4,value===null?-10:-9,!0),position4+=2;keyIndex++}let recordId=transition[RECORD_SYMBOL];if(recordId==null){recordId=packr.typedStructs.length;let structure=[],nextTransition=transition,key,type;for(;(type=nextTransition.__type)!==void 0;){let size=nextTransition.__size;nextTransition=nextTransition.__parent,key=nextTransition.key;let property=[type,size,key];nextTransition.enumerationOffset&&property.push(nextTransition.enumerationOffset),structure.push(property),nextTransition=nextTransition.parent}structure.reverse(),transition[RECORD_SYMBOL]=recordId,packr.typedStructs[recordId]=structure,pack2(null,0,!0)}switch(headerSize){case 1:if(recordId>=16)return 0;target2[start]=recordId+32;break;case 2:if(recordId>=256)return 0;target2[start]=56,target2[start+1]=recordId;break;case 3:if(recordId>=65536)return 0;target2[start]=57,targetView2.setUint16(start+1,recordId,!0);break;case 4:if(recordId>=16777216)return 0;targetView2.setUint32(start,(recordId<<8)+58,!0);break}if(position4<refsStartPosition){if(refsStartPosition===refPosition)return position4;target2.copyWithin(position4,refsStartPosition,refPosition),refPosition+=position4-refsStartPosition,typedStructs.lastStringStart=position4-start}else if(position4>refsStartPosition)return refsStartPosition===refPosition?position4:(typedStructs.lastStringStart=position4-start,writeStruct(object2,target2,encodingStart,start,structures,makeRoom,pack2,packr));return refPosition}__name(writeStruct,"writeStruct");function anyType(transition,position4,targetView2,value){let nextTransition;if(nextTransition=transition.ascii8||transition.num8)return targetView2.setInt8(position4,value,!0),updatedPosition=position4+1,nextTransition;if(nextTransition=transition.string16||transition.object16)return targetView2.setInt16(position4,value,!0),updatedPosition=position4+2,nextTransition;if(nextTransition=transition.num32)return targetView2.setUint32(position4,3758096640+value,!0),updatedPosition=position4+4,nextTransition;if(nextTransition=transition.num64)return targetView2.setFloat64(position4,NaN,!0),targetView2.setInt8(position4,value),updatedPosition=position4+8,nextTransition;updatedPosition=position4}__name(anyType,"anyType");function createTypeTransition(transition,type,size){let typeName=TYPE_NAMES[type]+(size<<3),newTransition=transition[typeName]||(transition[typeName]=Object.create(null));return newTransition.__type=type,newTransition.__size=size,newTransition.__parent=transition,newTransition}__name(createTypeTransition,"createTypeTransition");function onLoadedStructures2(sharedData){if(!(sharedData instanceof Map))return sharedData;let typed=sharedData.get("typed")||[];Object.isFrozen(typed)&&(typed=typed.map(structure=>structure.slice(0)));let named=sharedData.get("named"),transitions=Object.create(null);for(let i=0,l=typed.length;i<l;i++){let structure=typed[i],transition=transitions;for(let[type,size,key]of structure){let nextTransition=transition[key];nextTransition||(transition[key]=nextTransition={key,parent:transition,enumerationOffset:0,ascii0:null,ascii8:null,num8:null,string16:null,object16:null,num32:null,float64:null,date64:null}),transition=createTypeTransition(nextTransition,type,size)}transition[RECORD_SYMBOL]=i}return typed.transitions=transitions,this.typedStructs=typed,this.lastTypedStructuresLength=typed.length,named}__name(onLoadedStructures2,"onLoadedStructures");var sourceSymbol=Symbol.for("source");function readStruct2(src2,position4,srcEnd2,unpackr){let recordId=src2[position4++]-32;if(recordId>=24)switch(recordId){case 24:recordId=src2[position4++];break;case 25:recordId=src2[position4++]+(src2[position4++]<<8);break;case 26:recordId=src2[position4++]+(src2[position4++]<<8)+(src2[position4++]<<16);break;case 27:recordId=src2[position4++]+(src2[position4++]<<8)+(src2[position4++]<<16)+(src2[position4++]<<24);break}let structure=unpackr.typedStructs&&unpackr.typedStructs[recordId];if(!structure){if(src2=Uint8Array.prototype.slice.call(src2,position4,srcEnd2),srcEnd2-=position4,position4=0,!unpackr.getStructures)throw new Error(`Reference to shared structure ${recordId} without getStructures method`);if(unpackr._mergeStructures(unpackr.getStructures()),!unpackr.typedStructs)throw new Error("Could not find any shared typed structures");if(unpackr.lastTypedStructuresLength=unpackr.typedStructs.length,structure=unpackr.typedStructs[recordId],!structure)throw new Error("Could not find typed structure "+recordId)}var construct=structure.construct;if(!construct){construct=structure.construct=__name(function(){},"LazyObject");var prototype=construct.prototype;let properties=[],currentOffset=0,lastRefProperty;for(let i=0,l=structure.length;i<l;i++){let definition=structure[i],[type,size,key,enumerationOffset]=definition;key==="__proto__"&&(key="__proto_");let property={key,offset:currentOffset};enumerationOffset?properties.splice(i+enumerationOffset,0,property):properties.push(property);let getRef;switch(size){case 0:getRef=__name(()=>0,"getRef");break;case 1:getRef=__name((source,position5)=>{let ref=source.bytes[position5+property.offset];return ref>=246?toConstant(ref):ref},"getRef");break;case 2:getRef=__name((source,position5)=>{let src3=source.bytes,ref=(src3.dataView||(src3.dataView=new DataView(src3.buffer,src3.byteOffset,src3.byteLength))).getUint16(position5+property.offset,!0);return ref>=65280?toConstant(ref&255):ref},"getRef");break;case 4:getRef=__name((source,position5)=>{let src3=source.bytes,ref=(src3.dataView||(src3.dataView=new DataView(src3.buffer,src3.byteOffset,src3.byteLength))).getUint32(position5+property.offset,!0);return ref>=4294967040?toConstant(ref&255):ref},"getRef");break}property.getRef=getRef,currentOffset+=size;let get;switch(type){case ASCII:lastRefProperty&&!lastRefProperty.next&&(lastRefProperty.next=property),lastRefProperty=property,property.multiGetCount=0,get=__name(function(source){let src3=source.bytes,position5=source.position,refStart=currentOffset+position5,ref=getRef(source,position5);if(typeof ref!="number")return ref;let end,next=property.next;for(;next&&(end=next.getRef(source,position5),typeof end!="number");)end=null,next=next.next;return end==null&&(end=source.bytesEnd-refStart),source.srcString?source.srcString.slice(ref,end):readString2(src3,ref+refStart,end-ref)},"get");break;case UTF8:case OBJECT_DATA:lastRefProperty&&!lastRefProperty.next&&(lastRefProperty.next=property),lastRefProperty=property,get=__name(function(source){let position5=source.position,refStart=currentOffset+position5,ref=getRef(source,position5);if(typeof ref!="number")return ref;let src3=source.bytes,end,next=property.next;for(;next&&(end=next.getRef(source,position5),typeof end!="number");)end=null,next=next.next;if(end==null&&(end=source.bytesEnd-refStart),type===UTF8)return src3.toString("utf8",ref+refStart,end+refStart);currentSource=source;try{return unpackr.unpack(src3,{start:ref+refStart,end:end+refStart})}finally{currentSource=null}},"get");break;case NUMBER:switch(size){case 4:get=__name(function(source){let src3=source.bytes,dataView2=src3.dataView||(src3.dataView=new DataView(src3.buffer,src3.byteOffset,src3.byteLength)),position5=source.position+property.offset,value=dataView2.getInt32(position5,!0);if(value<536870912){if(value>-520093696)return value;if(value>-536870912)return toConstant(value&255)}let fValue=dataView2.getFloat32(position5,!0),multiplier=mult10[(src3[position5+3]&127)<<1|src3[position5+2]>>7];return(multiplier*fValue+(fValue>0?.5:-.5)>>0)/multiplier},"get");break;case 8:get=__name(function(source){let src3=source.bytes,value=(src3.dataView||(src3.dataView=new DataView(src3.buffer,src3.byteOffset,src3.byteLength))).getFloat64(source.position+property.offset,!0);if(isNaN(value)){let byte=src3[source.position+property.offset];if(byte>=246)return toConstant(byte)}return value},"get");break;case 1:get=__name(function(source){let value=source.bytes[source.position+property.offset];return value<246?value:toConstant(value)},"get");break}break;case DATE:get=__name(function(source){let src3=source.bytes,dataView2=src3.dataView||(src3.dataView=new DataView(src3.buffer,src3.byteOffset,src3.byteLength));return new Date(dataView2.getFloat64(source.position+property.offset,!0))},"get");break}property.get=get}if(evalSupported){let objectLiteralProperties=[],args=[],i=0,hasInheritedProperties;for(let property of properties){if(unpackr.alwaysLazyProperty&&unpackr.alwaysLazyProperty(property.key)){hasInheritedProperties=!0;continue}Object.defineProperty(prototype,property.key,{get:withSource(property.get),enumerable:!0});let valueFunction="v"+i++;args.push(valueFunction),objectLiteralProperties.push("["+JSON.stringify(property.key)+"]:"+valueFunction+"(s)")}hasInheritedProperties&&objectLiteralProperties.push("__proto__:this");let toObject=new Function(...args,"return function(s){return{"+objectLiteralProperties.join(",")+"}}").apply(null,properties.map(prop=>prop.get));Object.defineProperty(prototype,"toJSON",{value(omitUnderscoredProperties){return toObject.call(this,this[sourceSymbol])}})}else Object.defineProperty(prototype,"toJSON",{value(omitUnderscoredProperties){let resolved={};for(let i=0,l=properties.length;i<l;i++){let key=properties[i].key;resolved[key]=this[key]}return resolved}})}var instance=new construct;return instance[sourceSymbol]={bytes:src2,position:position4,srcString:"",bytesEnd:srcEnd2},instance}__name(readStruct2,"readStruct");function toConstant(code){switch(code){case 246:return null;case 247:return;case 248:return!1;case 249:return!0}throw new Error("Unknown constant")}__name(toConstant,"toConstant");function withSource(get){return function(){return get(this[sourceSymbol])}}__name(withSource,"withSource");function saveState2(){currentSource&&(currentSource.bytes=Uint8Array.prototype.slice.call(currentSource.bytes,currentSource.position,currentSource.bytesEnd),currentSource.position=0,currentSource.bytesEnd=currentSource.bytes.length)}__name(saveState2,"saveState");function prepareStructures2(structures,packr){if(packr.typedStructs){let structMap=new Map;structMap.set("named",structures),structMap.set("typed",packr.typedStructs),structures=structMap}let lastTypedStructuresLength=packr.lastTypedStructuresLength||0;return structures.isCompatible=existing=>{let compatible=!0;return existing instanceof Map?((existing.get("named")||[]).length!==(packr.lastNamedStructuresLength||0)&&(compatible=!1),(existing.get("typed")||[]).length!==lastTypedStructuresLength&&(compatible=!1)):(existing instanceof Array||Array.isArray(existing))&&existing.length!==(packr.lastNamedStructuresLength||0)&&(compatible=!1),compatible||packr._mergeStructures(existing),compatible},packr.lastTypedStructuresLength=packr.typedStructs&&packr.typedStructs.length,structures}__name(prepareStructures2,"prepareStructures");setReadStruct(readStruct2,onLoadedStructures2,saveState2);import{createRequire}from"module";var nativeAccelerationDisabled=process.env.MSGPACKR_NATIVE_ACCELERATION_DISABLED!==void 0&&process.env.MSGPACKR_NATIVE_ACCELERATION_DISABLED.toLowerCase()==="true";if(!nativeAccelerationDisabled){let extractor;try{typeof __require=="function"?extractor=__require("msgpackr-extract"):extractor=createRequire(import.meta.url)("msgpackr-extract"),extractor&&setExtractor(extractor.extractStrings)}catch{}}function serialize(o){return typeof o=="string"?`'${o}'`:new c().serialize(o)}__name(serialize,"serialize");var c=(function(){class o{static{__name(this,"o")}#t=new Map;compare(t,r2){let e2=typeof t,n=typeof r2;return e2==="string"&&n==="string"?t.localeCompare(r2):e2==="number"&&n==="number"?t-r2:String.prototype.localeCompare.call(this.serialize(t,!0),this.serialize(r2,!0))}serialize(t,r2){if(t===null)return"null";switch(typeof t){case"string":return r2?t:`'${t}'`;case"bigint":return`${t}n`;case"object":return this.$object(t);case"function":return this.$function(t)}return String(t)}serializeObject(t){let r2=Object.prototype.toString.call(t);if(r2!=="[object Object]")return this.serializeBuiltInType(r2.length<10?`unknown:${r2}`:r2.slice(8,-1),t);let e2=t.constructor,n=e2===Object||e2===void 0?"":e2.name;if(n!==""&&globalThis[n]===e2)return this.serializeBuiltInType(n,t);if(typeof t.toJSON=="function"){let i=t.toJSON();return n+(i!==null&&typeof i=="object"?this.$object(i):`(${this.serialize(i)})`)}return this.serializeObjectEntries(n,Object.entries(t))}serializeBuiltInType(t,r2){let e2=this["$"+t];if(e2)return e2.call(this,r2);if(typeof r2?.entries=="function")return this.serializeObjectEntries(t,r2.entries());throw new Error(`Cannot serialize ${t}`)}serializeObjectEntries(t,r2){let e2=Array.from(r2).sort((i,a)=>this.compare(i[0],a[0])),n=`${t}{`;for(let i=0;i<e2.length;i++){let[a,l]=e2[i];n+=`${this.serialize(a,!0)}:${this.serialize(l)}`,i<e2.length-1&&(n+=",")}return n+"}"}$object(t){let r2=this.#t.get(t);return r2===void 0&&(this.#t.set(t,`#${this.#t.size}`),r2=this.serializeObject(t),this.#t.set(t,r2)),r2}$function(t){let r2=Function.prototype.toString.call(t);return r2.slice(-15)==="[native code] }"?`${t.name||""}()[native]`:`${t.name}(${t.length})${r2.replace(/\s*\n\s*/g,"")}`}$Array(t){let r2="[";for(let e2=0;e2<t.length;e2++)r2+=this.serialize(t[e2]),e2<t.length-1&&(r2+=",");return r2+"]"}$Date(t){try{return`Date(${t.toISOString()})`}catch{return"Date(null)"}}$ArrayBuffer(t){return`ArrayBuffer[${new Uint8Array(t).join(",")}]`}$Set(t){return`Set${this.$Array(Array.from(t).sort((r2,e2)=>this.compare(r2,e2)))}`}$Map(t){return this.serializeObjectEntries("Map",t.entries())}}for(let s2 of["Error","RegExp","URL"])o.prototype["$"+s2]=function(t){return`${s2}(${t})`};for(let s2 of["Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array"])o.prototype["$"+s2]=function(t){return`${s2}[${t.join(",")}]`};for(let s2 of["BigInt64Array","BigUint64Array"])o.prototype["$"+s2]=function(t){return`${s2}[${t.join("n,")}${t.length>0?"n":""}]`};return o})();import{createHash}from"node:crypto";var e=globalThis.process?.getBuiltinModule?.("crypto")?.hash,r="sha256",s="base64url";function digest(t){if(e)return e(r,t,s);let o=createHash(r).update(t);return globalThis.process?.versions?.webcontainer?o.digest().toString(s):o.digest(s)}__name(digest,"digest");function hash4(input){return digest(serialize(input))}__name(hash4,"hash");var _computedKey36;_computedKey36=Symbol.asyncIterator;var SQLiteOPFSAztecArray=class{static{__name(this,"SQLiteOPFSAztecArray")}store;#name;#container;#encoder;constructor(store,name){this.store=store,this.#encoder=new Encoder6,this.#name=name,this.#container=`array:${name}`}async lengthAsync(){let rows=await this.store.allAsync("SELECT COUNT(*) FROM data WHERE container = ? AND key = ?",[this.#container,this.#encodedKey()]);return Number(rows[0]?.[0]??0)}async push(...vals){return vals.length===0?this.lengthAsync():await this.store.transactionAsync(async()=>{let length=await this.lengthAsync();for(let val of vals)await this.store.runAsync(`INSERT INTO data (slot, container, key, key_count, hash, value)
|
|
215
|
+
to increase it!`);if(finalizedIndex!==void 0&&range.lowestIndex<=finalizedIndex)throw new Error(`Cannot store pending index range [${range.lowestIndex}, ${range.highestIndex}] for secret ${secretStr}: lowestIndex is lower than or equal to the last finalized index ${finalizedIndex}`);let existingEntry=pendingData.find(entry=>entry.txHash===txHashStr);if(existingEntry){if(existingEntry.lowestIndex!==range.lowestIndex||existingEntry.highestIndex!==range.highestIndex)throw new Error(`Conflicting range for secret ${secretStr} and txHash ${txHashStr}: existing [${existingEntry.lowestIndex}, ${existingEntry.highestIndex}] vs new [${range.lowestIndex}, ${range.highestIndex}]`)}else this.#writePendingIndexes(jobId,secretStr,[...pendingData,{lowestIndex:range.lowestIndex,highestIndex:range.highestIndex,txHash:txHashStr}])}})}getTxHashesOfPendingIndexes(secret,startIndex,endIndex,jobId){return this.#store.transactionAsync(async()=>{let txHashes=(await this.#readPendingIndexes(jobId,secret.toString())).filter(entry=>entry.highestIndex>=startIndex&&entry.highestIndex<endIndex).map(entry=>entry.txHash);return Array.from(new Set(txHashes)).map(TxHash.fromString)})}getLastFinalizedIndex(secret,jobId){return this.#store.transactionAsync(()=>this.#readLastFinalizedIndex(jobId,secret.toString()))}getLastUsedIndex(secret,jobId){let secretStr=secret.toString();return this.#store.transactionAsync(async()=>{let pendingPromise=this.#readPendingIndexes(jobId,secretStr),finalizedPromise=this.#readLastFinalizedIndex(jobId,secretStr),[pendingEntries,lastFinalized]=await Promise.all([pendingPromise,finalizedPromise]);return pendingEntries.length===0?lastFinalized:Math.max(...pendingEntries.map(entry=>entry.highestIndex))})}dropPendingIndexes(txHashes,jobId){if(txHashes.length===0)return Promise.resolve();let txHashStrings=new Set(txHashes.map(txHash=>txHash.toString()));return this.#store.transactionAsync(async()=>{let secretReadPromises=new Map;for await(let secret of this.#pendingIndexes.keysAsync())secretReadPromises.set(secret,this.#readPendingIndexes(jobId,secret));for(let secret of this.#getPendingIndexesForJob(jobId).keys())secretReadPromises.has(secret)||secretReadPromises.set(secret,Promise.resolve(this.#getPendingIndexesForJob(jobId).get(secret)??[]));let secrets=[...secretReadPromises.keys()],pendingDataResults=await Promise.all(secretReadPromises.values());for(let i=0;i<secrets.length;i++){let secret=secrets[i],pendingData=pendingDataResults[i];if(pendingData&&pendingData.length>0){let filtered=pendingData.filter(item=>!txHashStrings.has(item.txHash));filtered.length===0?this.#writePendingIndexes(jobId,secret,[]):filtered.length!==pendingData.length&&this.#writePendingIndexes(jobId,secret,filtered)}}})}#getSecretsWithPendingData(jobId){return this.#store.transactionAsync(async()=>{let secretDataPromises=new Map;for await(let secret of this.#pendingIndexes.keysAsync())secretDataPromises.set(secret,{pending:this.#readPendingIndexes(jobId,secret),finalized:this.#readLastFinalizedIndex(jobId,secret)});for(let secret of this.#getPendingIndexesForJob(jobId).keys())secretDataPromises.has(secret)||secretDataPromises.set(secret,{pending:Promise.resolve(this.#getPendingIndexesForJob(jobId).get(secret)??[]),finalized:Promise.resolve(this.#getLastFinalizedIndexesForJob(jobId).get(secret))});let secrets=[...secretDataPromises.keys()];return(await Promise.all(secrets.map(async secret=>({secret,pendingData:await secretDataPromises.get(secret).pending,lastFinalized:await secretDataPromises.get(secret).finalized})))).filter(r2=>r2.pendingData.length>0)})}async finalizePendingIndexes(txHashes,jobId){if(txHashes.length===0)return;let txHashStrings=new Set(txHashes.map(tx=>tx.toString())),secretsWithData=await this.#getSecretsWithPendingData(jobId);for(let{secret,pendingData,lastFinalized}of secretsWithData){let currentPending=pendingData,currentFinalized=lastFinalized;for(let txHashStr of txHashStrings){let matchingEntries=currentPending.filter(item=>item.txHash===txHashStr);if(matchingEntries.length===0)continue;if(matchingEntries.length>1)throw new Error(`Multiple pending entries found for tx hash ${txHashStr} and secret ${secret}`);let newFinalized=matchingEntries[0].highestIndex;if(newFinalized<(currentFinalized??0))throw new Error(`New finalized index ${newFinalized} is smaller than the current last finalized index ${currentFinalized}`);currentFinalized=newFinalized,currentPending=currentPending.filter(item=>item.highestIndex>currentFinalized)}currentFinalized!==lastFinalized&&this.#writeLastFinalizedIndex(jobId,secret,currentFinalized),currentPending!==pendingData&&this.#writePendingIndexes(jobId,secret,currentPending)}}async finalizePendingIndexesOfAPartiallyRevertedTx(txEffect,jobId){let txHashStr=txEffect.txHash.toString(),onChainTags=new Set(txEffect.privateLogs.map(log2=>log2.fields[0].toString())),secretsWithData=await this.#getSecretsWithPendingData(jobId);for(let{secret,pendingData,lastFinalized}of secretsWithData){let matchingEntries=pendingData.filter(item=>item.txHash===txHashStr);if(matchingEntries.length===0)continue;if(matchingEntries.length>1)throw new Error(`Multiple pending entries found for tx hash ${txHashStr} and secret ${secret}`);let pendingEntry=matchingEntries[0],appTaggingSecret=AppTaggingSecret.fromString(secret),highestSurvivingIndex;for(let index=pendingEntry.lowestIndex;index<=pendingEntry.highestIndex;index++){let siloedTag=await SiloedTag.compute({extendedSecret:appTaggingSecret,index});onChainTags.has(siloedTag.value.toString())&&(highestSurvivingIndex=highestSurvivingIndex!==void 0?Math.max(highestSurvivingIndex,index):index)}let currentPending=pendingData.filter(item=>item.txHash!==txHashStr);if(highestSurvivingIndex!==void 0){let newFinalized=Math.max(lastFinalized??0,highestSurvivingIndex);this.#writeLastFinalizedIndex(jobId,secret,newFinalized),currentPending=currentPending.filter(item=>item.highestIndex>newFinalized)}this.#writePendingIndexes(jobId,secret,currentPending)}}};var TaggingSecretSourcesStore=class{static{__name(this,"TaggingSecretSourcesStore")}#store;#senders;#sharedSecretsByRecipient;constructor(store){this.#store=store,this.#senders=this.#store.openMap("senders"),this.#sharedSecretsByRecipient=this.#store.openMultiMap("recipient_shared_secrets")}addSender(address){return this.#store.transactionAsync(async()=>await this.#senders.hasAsync(address.toString())?!1:(await this.#senders.set(address.toString(),!0),!0))}getSenders(){return this.#store.transactionAsync(async()=>(await toArray(this.#senders.keysAsync())).map(AztecAddress.fromStringUnsafe))}removeSender(address){return this.#store.transactionAsync(async()=>await this.#senders.hasAsync(address.toString())?(await this.#senders.delete(address.toString()),!0):!1)}addSharedSecret(recipient,kind,secret){return this.#store.transactionAsync(async()=>{let secretStr=secret.toString();for await(let existing of this.#sharedSecretsByRecipient.getValuesAsync(recipient.toString()))if(existing.secret===secretStr){if(existing.kind!==kind)throw new Error(`Secret already registered for recipient with kind '${existing.kind}', cannot re-register it as '${kind}'.`);return!1}return await this.#sharedSecretsByRecipient.set(recipient.toString(),{kind,secret:secretStr}),!0})}getSharedSecretsForRecipient(recipient){return this.#store.transactionAsync(async()=>(await toArray(this.#sharedSecretsByRecipient.getValuesAsync(recipient.toString()))).map(deserializeSharedSecret))}getAllSharedSecrets(){return this.#store.transactionAsync(async()=>(await toArray(this.#sharedSecretsByRecipient.entriesAsync())).map(([recipient,entry])=>({recipient:AztecAddress.fromStringUnsafe(recipient),...deserializeSharedSecret(entry)})))}removeSharedSecret(recipient,kind,secret){return this.#store.transactionAsync(async()=>{let secretStr=secret.toString();for await(let existing of this.#sharedSecretsByRecipient.getValuesAsync(recipient.toString()))if(existing.kind===kind&&existing.secret===secretStr)return await this.#sharedSecretsByRecipient.deleteValue(recipient.toString(),existing),!0;return!1})}};function deserializeSharedSecret(entry){return{kind:entry.kind,secret:Point.fromString(entry.secret)}}__name(deserializeSharedSecret,"deserializeSharedSecret");var RecipientTaggingStore=class{static{__name(this,"RecipientTaggingStore")}storeName="recipient_tagging";#store;#highestAgedIndex;#highestFinalizedIndex;#highestAgedIndexForJob;#highestFinalizedIndexForJob;constructor(store){this.#store=store,this.#highestAgedIndex=this.#store.openMap("highest_aged_index"),this.#highestFinalizedIndex=this.#store.openMap("highest_finalized_index"),this.#highestAgedIndexForJob=new Map,this.#highestFinalizedIndexForJob=new Map}#getHighestAgedIndexForJob(jobId){let highestAgedIndexForJob=this.#highestAgedIndexForJob.get(jobId);return highestAgedIndexForJob||(highestAgedIndexForJob=new Map,this.#highestAgedIndexForJob.set(jobId,highestAgedIndexForJob)),highestAgedIndexForJob}async#readHighestAgedIndex(jobId,secret){let dbValue=await this.#highestAgedIndex.getAsync(secret);return this.#getHighestAgedIndexForJob(jobId).get(secret)??dbValue}#writeHighestAgedIndex(jobId,secret,index){this.#getHighestAgedIndexForJob(jobId).set(secret,index)}#getHighestFinalizedIndexForJob(jobId){let jobStagedHighestFinalizedIndex=this.#highestFinalizedIndexForJob.get(jobId);return jobStagedHighestFinalizedIndex||(jobStagedHighestFinalizedIndex=new Map,this.#highestFinalizedIndexForJob.set(jobId,jobStagedHighestFinalizedIndex)),jobStagedHighestFinalizedIndex}async#readHighestFinalizedIndex(jobId,secret){let dbValue=await this.#highestFinalizedIndex.getAsync(secret);return this.#getHighestFinalizedIndexForJob(jobId).get(secret)??dbValue}#writeHighestFinalizedIndex(jobId,secret,index){this.#getHighestFinalizedIndexForJob(jobId).set(secret,index)}async commit(jobId){let highestAgedIndexForJob=this.#highestAgedIndexForJob.get(jobId);if(highestAgedIndexForJob)for(let[secret,index]of highestAgedIndexForJob.entries())await this.#highestAgedIndex.set(secret,index);let highestFinalizedIndexForJob=this.#highestFinalizedIndexForJob.get(jobId);if(highestFinalizedIndexForJob)for(let[secret,index]of highestFinalizedIndexForJob.entries())await this.#highestFinalizedIndex.set(secret,index);return this.discardStaged(jobId)}discardStaged(jobId){return this.#highestAgedIndexForJob.delete(jobId),this.#highestFinalizedIndexForJob.delete(jobId),Promise.resolve()}getHighestAgedIndex(secret,jobId){return this.#store.transactionAsync(()=>this.#readHighestAgedIndex(jobId,secret.toString()))}updateHighestAgedIndex(secret,index,jobId){return this.#store.transactionAsync(async()=>{let currentIndex=await this.#readHighestAgedIndex(jobId,secret.toString());if(currentIndex!==void 0&&index<=currentIndex)throw new Error(`New highest aged index (${index}) must be higher than the current one (${currentIndex})`);this.#writeHighestAgedIndex(jobId,secret.toString(),index)})}getHighestFinalizedIndex(secret,jobId){return this.#store.transactionAsync(()=>this.#readHighestFinalizedIndex(jobId,secret.toString()))}updateHighestFinalizedIndex(secret,index,jobId){return this.#store.transactionAsync(async()=>{let currentIndex=await this.#readHighestFinalizedIndex(jobId,secret.toString());if(currentIndex!==void 0&&index<currentIndex)throw new Error(`New highest finalized index (${index}) must be higher than the current one (${currentIndex})`);this.#writeHighestFinalizedIndex(jobId,secret.toString(),index)})}};import{pickL1ContractAddressMappings as pickL1ContractAddressMappings3}from"@aztec/ethereum/l1-contract-addresses";var emptyChainConfig={l1ChainId:0,rollupVersion:0,rollupAddress:EthAddress.ZERO},chainConfigMappings={l1ChainId:{env:"L1_CHAIN_ID",...numberConfigHelper(31337),description:"The chain ID of the ethereum host."},rollupVersion:{env:"ROLLUP_VERSION",description:"The version of the rollup.",parseEnv:__name(val=>{let parsed=parseInt(val,10);if(!Number.isSafeInteger(parsed))throw new Error(`Invalid rollup version: ${val}`);return parsed},"parseEnv")},...pickL1ContractAddressMappings3("rollupAddress")};import{l1ContractsConfigMappings,validateSlotDurations}from"@aztec/ethereum/config";var DEFAULT_BLOCK_DURATION_MS=3*1e3;var DEFAULT_MAX_BLOCKS_PER_CHECKPOINT=24,sharedSequencerConfigMappings={blockDurationMs:{env:"SEQ_BLOCK_DURATION_MS",description:"Duration per block in milliseconds, used to derive how many blocks fit in a slot.",...numberConfigHelper(DEFAULT_BLOCK_DURATION_MS)},expectedBlockProposalsPerSlot:{env:"SEQ_EXPECTED_BLOCK_PROPOSALS_PER_SLOT",description:"Expected number of block proposals per slot for P2P peer scoring. 0 (default) disables block proposal scoring. Set to a positive value to enable.",...numberConfigHelper(0)},checkpointProposalSyncGraceSeconds:{env:"CHECKPOINT_PROPOSAL_SYNC_GRACE_SECONDS",description:"Consensus grace in seconds for a received checkpoint proposal to materialize into local proposed state. Defaults to twice the block duration.",defaultValue:getDefaultCheckpointProposalSyncGrace(DEFAULT_BLOCK_DURATION_MS/1e3),...optionalNumberConfigHelper()},maxTxsPerBlock:{env:"SEQ_MAX_TX_PER_BLOCK",description:"The maximum number of txs to include in a block.",...optionalNumberConfigHelper()},attestationPropagationTime:{env:"SEQ_ATTESTATION_PROPAGATION_TIME",description:"How many seconds it takes for proposals and attestations to travel across the p2p layer (one-way).",defaultValue:2,...floatConfigHelper(2)},checkpointProposalPrepareTime:{env:"SEQ_CHECKPOINT_PROPOSAL_PREPARE_TIME",description:"Local time in seconds between the last block build finishing and the checkpoint proposal being ready for p2p send.",defaultValue:1,...floatConfigHelper(1)},minBlockDuration:{env:"SEQ_MIN_BLOCK_DURATION",description:"Minimum block-building time in seconds still worth allocating if the proposer starts late.",defaultValue:2,...floatConfigHelper(2)},maxBlocksPerCheckpoint:{env:"MAX_BLOCKS_PER_CHECKPOINT",description:"Maximum number of blocks the sequencer packs into a single checkpoint, and the maximum indexWithinCheckpoint accepted on inbound block proposals.",parseEnv:__name(val=>parseInt(val,10),"parseEnv"),defaultValue:DEFAULT_MAX_BLOCKS_PER_CHECKPOINT}};var networkConsensusConfigMappings={...pickConfigMappings(l1ContractsConfigMappings,["aztecSlotDuration","ethereumSlotDuration"]),...pickConfigMappings(sharedSequencerConfigMappings,["blockDurationMs","maxBlocksPerCheckpoint","checkpointProposalSyncGraceSeconds"])};var nodeRpcConfigMappings={rpcSimulatePublicMaxGasLimit:{env:"RPC_SIMULATE_PUBLIC_MAX_GAS_LIMIT",description:"Maximum gas limit for public tx simulation in the node on `simulatePublicCalls`.",...numberConfigHelper(1e10)},rpcSimulatePublicMaxDebugLogMemoryReads:{env:"RPC_SIMULATE_PUBLIC_MAX_DEBUG_LOG_MEMORY_READS",description:"Maximum memory reads for debug logs performed for public tx simulation in the node on `simulatePublicCalls`. ",...numberConfigHelper(125e3)},rpcMaxBatchSize:{env:"RPC_MAX_BATCH_SIZE",description:"Maximum allowed batch size for JSON RPC batch requests.",...numberConfigHelper(100)},rpcMaxBodySize:{env:"RPC_MAX_BODY_SIZE",description:"Maximum allowed batch size for JSON RPC batch requests.",defaultValue:"1mb"}};function composeHooks(hooks){if(!Object.values(hooks).every(v=>v===void 0))return hooks}__name(composeHooks,"composeHooks");var pxeConfigMappings={...dataConfigMappings,...chainConfigMappings,l2BlockBatchSize:{env:"PXE_L2_BLOCK_BATCH_SIZE",...numberConfigHelper(50),description:"Maximum amount of blocks to pull from the stream in one request when synchronizing"},proverEnabled:{env:"PXE_PROVER_ENABLED",description:"Enable real proofs",...booleanConfigHelper(!0)},syncChainTip:{env:"PXE_SYNC_CHAIN_TIP",description:"Which chain tip to sync to (proposed, checkpointed, proven, finalized)",...enumConfigHelper(["proposed","checkpointed","proven","finalized"],"proposed")},autoSync:{env:"PXE_AUTO_SYNC",description:"Whether PXE syncs with the node automatically before each operation. Disable to let the caller (e.g. a wallet) drive syncs explicitly via pxe.sync().",...booleanConfigHelper(!0)}};var pxeCliConfigMappings={nodeUrl:{env:"AZTEC_NODE_URL",description:"Custom Aztec Node URL to connect to"}},allPxeConfigMappings={...pxeConfigMappings,...pxeCliConfigMappings,...dataConfigMappings,proverEnabled:{env:"PXE_PROVER_ENABLED",parseEnv:__name(val=>parseBooleanEnv(val)||!!process.env.NETWORK,"parseEnv"),description:"Enable real proofs",isBoolean:!0,defaultValue:!0}};import{LazyArtifactProvider}from"@aztec/noir-protocol-circuits-types/client/lazy";import{AztecClientBackend,Barretenberg as Barretenberg2}from"@aztec/bb.js";import{serializeWitness as serializeWitness2}from"@aztec/noir-noirc_abi";import{convertHidingKernelPublicInputsToWitnessMapWithAbi,convertHidingKernelToRollupInputsToWitnessMapWithAbi,convertPrivateKernelInit2InputsToWitnessMapWithAbi,convertPrivateKernelInit2OutputsFromWitnessMapWithAbi,convertPrivateKernelInit3InputsToWitnessMapWithAbi,convertPrivateKernelInit3OutputsFromWitnessMapWithAbi,convertPrivateKernelInitInputsToWitnessMapWithAbi,convertPrivateKernelInitOutputsFromWitnessMapWithAbi,convertPrivateKernelInner2InputsToWitnessMapWithAbi,convertPrivateKernelInner2OutputsFromWitnessMapWithAbi,convertPrivateKernelInner3InputsToWitnessMapWithAbi,convertPrivateKernelInner3OutputsFromWitnessMapWithAbi,convertPrivateKernelInnerInputsToWitnessMapWithAbi,convertPrivateKernelInnerOutputsFromWitnessMapWithAbi,convertPrivateKernelResetInputsToWitnessMapWithAbi,convertPrivateKernelResetOutputsFromWitnessMapWithAbi,convertPrivateKernelTailForPublicOutputsFromWitnessMapWithAbi,convertPrivateKernelTailInputsToWitnessMapWithAbi,convertPrivateKernelTailOutputsFromWitnessMapWithAbi,convertPrivateKernelTailToPublicInputsToWitnessMapWithAbi,foreignCallHandler,getPrivateKernelResetArtifactName,updateResetCircuitSampleInputs}from"@aztec/noir-protocol-circuits-types/client";import{mapProtocolArtifactNameToCircuitName}from"@aztec/noir-protocol-circuits-types/types";import{ungzip}from"pako";var decoder;try{decoder=new TextDecoder}catch{}var src,srcEnd,position2=0;var EMPTY_ARRAY=[],strings=EMPTY_ARRAY,stringPosition=0,currentUnpackr={},currentStructures,srcString,srcStringStart=0,srcStringEnd=0,bundledStrings,referenceMap,currentExtensions=[],dataView,defaultOptions={useRecords:!1,mapsAsObjects:!0},C1Type=class{static{__name(this,"C1Type")}},C1=new C1Type;C1.name="MessagePack 0xC1";var sequentialMode=!1,inlineObjectReadThreshold=2,readStruct,onLoadedStructures,onSaveState;try{new Function("")}catch{inlineObjectReadThreshold=1/0}var Unpackr=class _Unpackr{static{__name(this,"Unpackr")}constructor(options){options&&(options.useRecords===!1&&options.mapsAsObjects===void 0&&(options.mapsAsObjects=!0),options.sequential&&options.trusted!==!1&&(options.trusted=!0,!options.structures&&options.useRecords!=!1&&(options.structures=[],options.maxSharedStructures||(options.maxSharedStructures=0))),options.structures?options.structures.sharedLength=options.structures.length:options.getStructures&&((options.structures=[]).uninitialized=!0,options.structures.sharedLength=0),options.int64AsNumber&&(options.int64AsType="number")),Object.assign(this,options)}unpack(source,options){if(src)return saveState(()=>(clearSource(),this?this.unpack(source,options):_Unpackr.prototype.unpack.call(defaultOptions,source,options)));!source.buffer&&source.constructor===ArrayBuffer&&(source=typeof Buffer<"u"?Buffer.from(source):new Uint8Array(source)),typeof options=="object"?(srcEnd=options.end||source.length,position2=options.start||0):(position2=0,srcEnd=options>-1?options:source.length),stringPosition=0,srcStringEnd=0,srcString=null,strings=EMPTY_ARRAY,bundledStrings=null,src=source;try{dataView=source.dataView||(source.dataView=new DataView(source.buffer,source.byteOffset,source.byteLength))}catch(error2){throw src=null,source instanceof Uint8Array?error2:new Error("Source must be a Uint8Array or Buffer but was a "+(source&&typeof source=="object"?source.constructor.name:typeof source))}if(this instanceof _Unpackr){if(currentUnpackr=this,this.structures)return currentStructures=this.structures,checkedRead(options);(!currentStructures||currentStructures.length>0)&&(currentStructures=[])}else currentUnpackr=defaultOptions,(!currentStructures||currentStructures.length>0)&&(currentStructures=[]);return checkedRead(options)}unpackMultiple(source,forEach){let values,lastPosition=0;try{sequentialMode=!0;let size=source.length,value=this?this.unpack(source,size):defaultUnpackr.unpack(source,size);if(forEach){if(forEach(value,lastPosition,position2)===!1)return;for(;position2<size;)if(lastPosition=position2,forEach(checkedRead(),lastPosition,position2)===!1)return}else{for(values=[value];position2<size;)lastPosition=position2,values.push(checkedRead());return values}}catch(error2){throw error2.lastPosition=lastPosition,error2.values=values,error2}finally{sequentialMode=!1,clearSource()}}_mergeStructures(loadedStructures,existingStructures){onLoadedStructures&&(loadedStructures=onLoadedStructures.call(this,loadedStructures)),loadedStructures=loadedStructures||[],Object.isFrozen(loadedStructures)&&(loadedStructures=loadedStructures.map(structure=>structure.slice(0)));for(let i=0,l=loadedStructures.length;i<l;i++){let structure=loadedStructures[i];structure&&(structure.isShared=!0,i>=32&&(structure.highByte=i-32>>5))}loadedStructures.sharedLength=loadedStructures.length;for(let id in existingStructures||[])if(id>=0){let structure=loadedStructures[id],existing=existingStructures[id];existing&&(structure&&((loadedStructures.restoreStructures||(loadedStructures.restoreStructures=[]))[id]=structure),loadedStructures[id]=existing)}return this.structures=loadedStructures}decode(source,options){return this.unpack(source,options)}};function checkedRead(options){try{if(!currentUnpackr.trusted&&!sequentialMode){let sharedLength=currentStructures.sharedLength||0;sharedLength<currentStructures.length&&(currentStructures.length=sharedLength)}let result;if(currentUnpackr.randomAccessStructure&&src[position2]<64&&src[position2]>=32&&readStruct?(result=readStruct(src,position2,srcEnd,currentUnpackr),src=null,!(options&&options.lazy)&&result&&(result=result.toJSON()),position2=srcEnd):result=read(),bundledStrings&&(position2=bundledStrings.postBundlePosition,bundledStrings=null),sequentialMode&&(currentStructures.restoreStructures=null),position2==srcEnd)currentStructures&¤tStructures.restoreStructures&&restoreStructures(),currentStructures=null,src=null,referenceMap&&(referenceMap=null);else{if(position2>srcEnd)throw new Error("Unexpected end of MessagePack data");if(!sequentialMode){let jsonView;try{jsonView=JSON.stringify(result,(_,value)=>typeof value=="bigint"?`${value}n`:value).slice(0,100)}catch(error2){jsonView="(JSON view not available "+error2+")"}throw new Error("Data read, but end of buffer not reached "+jsonView)}}return result}catch(error2){throw currentStructures&¤tStructures.restoreStructures&&restoreStructures(),clearSource(),(error2 instanceof RangeError||error2.message.startsWith("Unexpected end of buffer")||position2>srcEnd)&&(error2.incomplete=!0),error2}}__name(checkedRead,"checkedRead");function restoreStructures(){for(let id in currentStructures.restoreStructures)currentStructures[id]=currentStructures.restoreStructures[id];currentStructures.restoreStructures=null}__name(restoreStructures,"restoreStructures");function read(){let token=src[position2++];if(token<160)if(token<128){if(token<64)return token;{let structure=currentStructures[token&63]||currentUnpackr.getStructures&&loadStructures()[token&63];return structure?(structure.read||(structure.read=createStructureReader(structure,token&63)),structure.read()):token}}else if(token<144)if(token-=128,currentUnpackr.mapsAsObjects){let object2={};for(let i=0;i<token;i++){let key=readKey2();key==="__proto__"&&(key="__proto_"),object2[key]=read()}return object2}else{let map2=new Map;for(let i=0;i<token;i++)map2.set(read(),read());return map2}else{token-=144;let array2=new Array(token);for(let i=0;i<token;i++)array2[i]=read();return currentUnpackr.freezeData?Object.freeze(array2):array2}else if(token<192){let length=token-160;if(srcStringEnd>=position2)return srcString.slice(position2-srcStringStart,(position2+=length)-srcStringStart);if(srcStringEnd==0&&srcEnd<140){let string4=length<16?shortStringInJS(length):longStringInJS(length);if(string4!=null)return string4}return readFixedString(length)}else{let value;switch(token){case 192:return null;case 193:return bundledStrings?(value=read(),value>0?bundledStrings[1].slice(bundledStrings.position1,bundledStrings.position1+=value):bundledStrings[0].slice(bundledStrings.position0,bundledStrings.position0-=value)):C1;case 194:return!1;case 195:return!0;case 196:if(value=src[position2++],value===void 0)throw new Error("Unexpected end of buffer");return readBin(value);case 197:return value=dataView.getUint16(position2),position2+=2,readBin(value);case 198:return value=dataView.getUint32(position2),position2+=4,readBin(value);case 199:return readExt(src[position2++]);case 200:return value=dataView.getUint16(position2),position2+=2,readExt(value);case 201:return value=dataView.getUint32(position2),position2+=4,readExt(value);case 202:if(value=dataView.getFloat32(position2),currentUnpackr.useFloat32>2){let multiplier=mult10[(src[position2]&127)<<1|src[position2+1]>>7];return position2+=4,(multiplier*value+(value>0?.5:-.5)>>0)/multiplier}return position2+=4,value;case 203:return value=dataView.getFloat64(position2),position2+=8,value;case 204:return src[position2++];case 205:return value=dataView.getUint16(position2),position2+=2,value;case 206:return value=dataView.getUint32(position2),position2+=4,value;case 207:return currentUnpackr.int64AsType==="number"?(value=dataView.getUint32(position2)*4294967296,value+=dataView.getUint32(position2+4)):currentUnpackr.int64AsType==="string"?value=dataView.getBigUint64(position2).toString():currentUnpackr.int64AsType==="auto"?(value=dataView.getBigUint64(position2),value<=BigInt(2)<<BigInt(52)&&(value=Number(value))):value=dataView.getBigUint64(position2),position2+=8,value;case 208:return dataView.getInt8(position2++);case 209:return value=dataView.getInt16(position2),position2+=2,value;case 210:return value=dataView.getInt32(position2),position2+=4,value;case 211:return currentUnpackr.int64AsType==="number"?(value=dataView.getInt32(position2)*4294967296,value+=dataView.getUint32(position2+4)):currentUnpackr.int64AsType==="string"?value=dataView.getBigInt64(position2).toString():currentUnpackr.int64AsType==="auto"?(value=dataView.getBigInt64(position2),value>=BigInt(-2)<<BigInt(52)&&value<=BigInt(2)<<BigInt(52)&&(value=Number(value))):value=dataView.getBigInt64(position2),position2+=8,value;case 212:if(value=src[position2++],value==114)return recordDefinition(src[position2++]&63);{let extension=currentExtensions[value];if(extension)return extension.read?(position2++,extension.read(read())):extension.noBuffer?(position2++,extension()):extension(src.subarray(position2,++position2));throw new Error("Unknown extension "+value)}case 213:return value=src[position2],value==114?(position2++,recordDefinition(src[position2++]&63,src[position2++])):readExt(2);case 214:return readExt(4);case 215:return readExt(8);case 216:return readExt(16);case 217:return value=src[position2++],srcStringEnd>=position2?srcString.slice(position2-srcStringStart,(position2+=value)-srcStringStart):readString8(value);case 218:return value=dataView.getUint16(position2),position2+=2,srcStringEnd>=position2?srcString.slice(position2-srcStringStart,(position2+=value)-srcStringStart):readString16(value);case 219:return value=dataView.getUint32(position2),position2+=4,srcStringEnd>=position2?srcString.slice(position2-srcStringStart,(position2+=value)-srcStringStart):readString32(value);case 220:return value=dataView.getUint16(position2),position2+=2,readArray(value);case 221:return value=dataView.getUint32(position2),position2+=4,readArray(value);case 222:return value=dataView.getUint16(position2),position2+=2,readMap(value);case 223:return value=dataView.getUint32(position2),position2+=4,readMap(value);default:if(token>=224)return token-256;if(token===void 0){let error2=new Error("Unexpected end of MessagePack data");throw error2.incomplete=!0,error2}throw new Error("Unknown MessagePack token "+token)}}}__name(read,"read");var validName=/^[a-zA-Z_$][a-zA-Z\d_$]*$/;function createStructureReader(structure,firstId){function readObject(){if(readObject.count++>inlineObjectReadThreshold){let readObject2=structure.read=new Function("r","return function(){return "+(currentUnpackr.freezeData?"Object.freeze":"")+"({"+structure.map(key=>key==="__proto__"?"__proto_:r()":validName.test(key)?key+":r()":"["+JSON.stringify(key)+"]:r()").join(",")+"})}")(read);return structure.highByte===0&&(structure.read=createSecondByteReader(firstId,structure.read)),readObject2()}let object2={};for(let i=0,l=structure.length;i<l;i++){let key=structure[i];key==="__proto__"&&(key="__proto_"),object2[key]=read()}return currentUnpackr.freezeData?Object.freeze(object2):object2}return __name(readObject,"readObject"),readObject.count=0,structure.highByte===0?createSecondByteReader(firstId,readObject):readObject}__name(createStructureReader,"createStructureReader");var createSecondByteReader=__name((firstId,read0)=>function(){let highByte=src[position2++];if(highByte===0)return read0();let id=firstId<32?-(firstId+(highByte<<5)):firstId+(highByte<<5),structure=currentStructures[id]||loadStructures()[id];if(!structure)throw new Error("Record id is not defined for "+id);return structure.read||(structure.read=createStructureReader(structure,firstId)),structure.read()},"createSecondByteReader");function loadStructures(){let loadedStructures=saveState(()=>(src=null,currentUnpackr.getStructures()));return currentStructures=currentUnpackr._mergeStructures(loadedStructures,currentStructures)}__name(loadStructures,"loadStructures");var readFixedString=readStringJS,readString8=readStringJS,readString16=readStringJS,readString32=readStringJS,isNativeAccelerationEnabled=!1;function setExtractor(extractStrings){isNativeAccelerationEnabled=!0,readFixedString=readString3(1),readString8=readString3(2),readString16=readString3(3),readString32=readString3(5);function readString3(headerLength){return __name(function(length){let string4=strings[stringPosition++];if(string4==null){if(bundledStrings)return readStringJS(length);let byteOffset=src.byteOffset,extraction=extractStrings(position2-headerLength+byteOffset,srcEnd+byteOffset,src.buffer);if(typeof extraction=="string")string4=extraction,strings=EMPTY_ARRAY;else if(strings=extraction,stringPosition=1,srcStringEnd=1,string4=strings[0],string4===void 0)throw new Error("Unexpected end of buffer")}let srcStringLength=string4.length;return srcStringLength<=length?(position2+=length,string4):(srcString=string4,srcStringStart=position2,srcStringEnd=position2+srcStringLength,position2+=length,string4.slice(0,length))},"readString")}__name(readString3,"readString")}__name(setExtractor,"setExtractor");function readStringJS(length){let result;if(length<16&&(result=shortStringInJS(length)))return result;if(length>64&&decoder)return decoder.decode(src.subarray(position2,position2+=length));let end=position2+length,units=[];for(result="";position2<end;){let byte1=src[position2++];if((byte1&128)===0)units.push(byte1);else if((byte1&224)===192){let byte2=src[position2++]&63;units.push((byte1&31)<<6|byte2)}else if((byte1&240)===224){let byte2=src[position2++]&63,byte3=src[position2++]&63;units.push((byte1&31)<<12|byte2<<6|byte3)}else if((byte1&248)===240){let byte2=src[position2++]&63,byte3=src[position2++]&63,byte4=src[position2++]&63,unit=(byte1&7)<<18|byte2<<12|byte3<<6|byte4;unit>65535&&(unit-=65536,units.push(unit>>>10&1023|55296),unit=56320|unit&1023),units.push(unit)}else units.push(byte1);units.length>=4096&&(result+=fromCharCode2.apply(String,units),units.length=0)}return units.length>0&&(result+=fromCharCode2.apply(String,units)),result}__name(readStringJS,"readStringJS");function readString2(source,start,length){let existingSrc=src;src=source,position2=start;try{return readStringJS(length)}finally{src=existingSrc}}__name(readString2,"readString");function readArray(length){let array2=new Array(length);for(let i=0;i<length;i++)array2[i]=read();return currentUnpackr.freezeData?Object.freeze(array2):array2}__name(readArray,"readArray");function readMap(length){if(currentUnpackr.mapsAsObjects){let object2={};for(let i=0;i<length;i++){let key=readKey2();key==="__proto__"&&(key="__proto_"),object2[key]=read()}return object2}else{let map2=new Map;for(let i=0;i<length;i++)map2.set(read(),read());return map2}}__name(readMap,"readMap");var fromCharCode2=String.fromCharCode;function longStringInJS(length){let start=position2,bytes=new Array(length);for(let i=0;i<length;i++){let byte=src[position2++];if((byte&128)>0){position2=start;return}bytes[i]=byte}return fromCharCode2.apply(String,bytes)}__name(longStringInJS,"longStringInJS");function shortStringInJS(length){if(length<4)if(length<2){if(length===0)return"";{let a=src[position2++];if((a&128)>1){position2-=1;return}return fromCharCode2(a)}}else{let a=src[position2++],b=src[position2++];if((a&128)>0||(b&128)>0){position2-=2;return}if(length<3)return fromCharCode2(a,b);let c2=src[position2++];if((c2&128)>0){position2-=3;return}return fromCharCode2(a,b,c2)}else{let a=src[position2++],b=src[position2++],c2=src[position2++],d=src[position2++];if((a&128)>0||(b&128)>0||(c2&128)>0||(d&128)>0){position2-=4;return}if(length<6){if(length===4)return fromCharCode2(a,b,c2,d);{let e2=src[position2++];if((e2&128)>0){position2-=5;return}return fromCharCode2(a,b,c2,d,e2)}}else if(length<8){let e2=src[position2++],f=src[position2++];if((e2&128)>0||(f&128)>0){position2-=6;return}if(length<7)return fromCharCode2(a,b,c2,d,e2,f);let g=src[position2++];if((g&128)>0){position2-=7;return}return fromCharCode2(a,b,c2,d,e2,f,g)}else{let e2=src[position2++],f=src[position2++],g=src[position2++],h=src[position2++];if((e2&128)>0||(f&128)>0||(g&128)>0||(h&128)>0){position2-=8;return}if(length<10){if(length===8)return fromCharCode2(a,b,c2,d,e2,f,g,h);{let i=src[position2++];if((i&128)>0){position2-=9;return}return fromCharCode2(a,b,c2,d,e2,f,g,h,i)}}else if(length<12){let i=src[position2++],j=src[position2++];if((i&128)>0||(j&128)>0){position2-=10;return}if(length<11)return fromCharCode2(a,b,c2,d,e2,f,g,h,i,j);let k=src[position2++];if((k&128)>0){position2-=11;return}return fromCharCode2(a,b,c2,d,e2,f,g,h,i,j,k)}else{let i=src[position2++],j=src[position2++],k=src[position2++],l=src[position2++];if((i&128)>0||(j&128)>0||(k&128)>0||(l&128)>0){position2-=12;return}if(length<14){if(length===12)return fromCharCode2(a,b,c2,d,e2,f,g,h,i,j,k,l);{let m=src[position2++];if((m&128)>0){position2-=13;return}return fromCharCode2(a,b,c2,d,e2,f,g,h,i,j,k,l,m)}}else{let m=src[position2++],n=src[position2++];if((m&128)>0||(n&128)>0){position2-=14;return}if(length<15)return fromCharCode2(a,b,c2,d,e2,f,g,h,i,j,k,l,m,n);let o=src[position2++];if((o&128)>0){position2-=15;return}return fromCharCode2(a,b,c2,d,e2,f,g,h,i,j,k,l,m,n,o)}}}}}__name(shortStringInJS,"shortStringInJS");function readOnlyJSString(){let token=src[position2++],length;if(token<192)length=token-160;else switch(token){case 217:length=src[position2++];break;case 218:length=dataView.getUint16(position2),position2+=2;break;case 219:length=dataView.getUint32(position2),position2+=4;break;default:throw new Error("Expected string")}return readStringJS(length)}__name(readOnlyJSString,"readOnlyJSString");function readBin(length){return currentUnpackr.copyBuffers?Uint8Array.prototype.slice.call(src,position2,position2+=length):src.subarray(position2,position2+=length)}__name(readBin,"readBin");function readExt(length){let type=src[position2++];if(currentExtensions[type]){let end;return currentExtensions[type](src.subarray(position2,end=position2+=length),readPosition=>{position2=readPosition;try{return read()}finally{position2=end}})}else throw new Error("Unknown extension type "+type)}__name(readExt,"readExt");var keyCache=new Array(4096);function readKey2(){let length=src[position2++];if(length>=160&&length<192){if(length=length-160,srcStringEnd>=position2)return srcString.slice(position2-srcStringStart,(position2+=length)-srcStringStart);if(!(srcStringEnd==0&&srcEnd<180))return readFixedString(length)}else return position2--,asSafeString(read());let key=(length<<5^(length>1?dataView.getUint16(position2):length>0?src[position2]:0))&4095,entry=keyCache[key],checkPosition=position2,end=position2+length-3,chunk3,i=0;if(entry&&entry.bytes==length){for(;checkPosition<end;){if(chunk3=dataView.getUint32(checkPosition),chunk3!=entry[i++]){checkPosition=1879048192;break}checkPosition+=4}for(end+=3;checkPosition<end;)if(chunk3=src[checkPosition++],chunk3!=entry[i++]){checkPosition=1879048192;break}if(checkPosition===end)return position2=checkPosition,entry.string;end-=3,checkPosition=position2}for(entry=[],keyCache[key]=entry,entry.bytes=length;checkPosition<end;)chunk3=dataView.getUint32(checkPosition),entry.push(chunk3),checkPosition+=4;for(end+=3;checkPosition<end;)chunk3=src[checkPosition++],entry.push(chunk3);let string4=length<16?shortStringInJS(length):longStringInJS(length);return string4!=null?entry.string=string4:entry.string=readFixedString(length)}__name(readKey2,"readKey");function asSafeString(property){if(typeof property=="string")return property;if(typeof property=="number"||typeof property=="boolean"||typeof property=="bigint")return property.toString();if(property==null)return property+"";throw new Error("Invalid property type for record",typeof property)}__name(asSafeString,"asSafeString");var recordDefinition=__name((id,highByte)=>{let structure=read().map(asSafeString),firstByte=id;highByte!==void 0&&(id=id<32?-((highByte<<5)+id):(highByte<<5)+id,structure.highByte=highByte);let existingStructure=currentStructures[id];return existingStructure&&(existingStructure.isShared||sequentialMode)&&((currentStructures.restoreStructures||(currentStructures.restoreStructures=[]))[id]=existingStructure),currentStructures[id]=structure,structure.read=createStructureReader(structure,firstByte),structure.read()},"recordDefinition");currentExtensions[0]=()=>{};currentExtensions[0].noBuffer=!0;currentExtensions[66]=data=>{let length=data.length,value=BigInt(data[0]&128?data[0]-256:data[0]);for(let i=1;i<length;i++)value<<=BigInt(8),value+=BigInt(data[i]);return value};var errors={Error,TypeError,ReferenceError};currentExtensions[101]=()=>{let data=read();return(errors[data[0]]||Error)(data[1],{cause:data[2]})};currentExtensions[105]=data=>{if(currentUnpackr.structuredClone===!1)throw new Error("Structured clone extension is disabled");let id=dataView.getUint32(position2-4);referenceMap||(referenceMap=new Map);let token=src[position2],target2;token>=144&&token<160||token==220||token==221?target2=[]:target2={};let refEntry={target:target2};referenceMap.set(id,refEntry);let targetProperties=read();return refEntry.used?Object.assign(target2,targetProperties):(refEntry.target=targetProperties,targetProperties)};currentExtensions[112]=data=>{if(currentUnpackr.structuredClone===!1)throw new Error("Structured clone extension is disabled");let id=dataView.getUint32(position2-4),refEntry=referenceMap.get(id);return refEntry.used=!0,refEntry.target};currentExtensions[115]=()=>new Set(read());var typedArrays=["Int8","Uint8","Uint8Clamped","Int16","Uint16","Int32","Uint32","Float32","Float64","BigInt64","BigUint64"].map(type=>type+"Array"),glbl=typeof globalThis=="object"?globalThis:window;currentExtensions[116]=data=>{let typeCode=data[0],typedArrayName=typedArrays[typeCode];if(!typedArrayName){if(typeCode===16){let ab=new ArrayBuffer(data.length-1);return new Uint8Array(ab).set(data.subarray(1)),ab}throw new Error("Could not find typed array for code "+typeCode)}return new glbl[typedArrayName](Uint8Array.prototype.slice.call(data,1).buffer)};currentExtensions[120]=()=>{let data=read();return new RegExp(data[0],data[1])};var TEMP_BUNDLE=[];currentExtensions[98]=data=>{let dataSize=(data[0]<<24)+(data[1]<<16)+(data[2]<<8)+data[3],dataPosition=position2;return position2+=dataSize-data.length,bundledStrings=TEMP_BUNDLE,bundledStrings=[readOnlyJSString(),readOnlyJSString()],bundledStrings.position0=0,bundledStrings.position1=0,bundledStrings.postBundlePosition=position2,position2=dataPosition,read()};currentExtensions[255]=data=>data.length==4?new Date((data[0]*16777216+(data[1]<<16)+(data[2]<<8)+data[3])*1e3):data.length==8?new Date(((data[0]<<22)+(data[1]<<14)+(data[2]<<6)+(data[3]>>2))/1e6+((data[3]&3)*4294967296+data[4]*16777216+(data[5]<<16)+(data[6]<<8)+data[7])*1e3):data.length==12?new Date(((data[0]<<24)+(data[1]<<16)+(data[2]<<8)+data[3])/1e6+((data[4]&128?-281474976710656:0)+data[6]*1099511627776+data[7]*4294967296+data[8]*16777216+(data[9]<<16)+(data[10]<<8)+data[11])*1e3):new Date("invalid");function saveState(callback){onSaveState&&onSaveState();let savedSrcEnd=srcEnd,savedPosition=position2,savedStringPosition=stringPosition,savedSrcStringStart=srcStringStart,savedSrcStringEnd=srcStringEnd,savedSrcString=srcString,savedStrings=strings,savedReferenceMap=referenceMap,savedBundledStrings=bundledStrings,savedSrc=new Uint8Array(src.slice(0,srcEnd)),savedStructures=currentStructures,savedStructuresContents=currentStructures.slice(0,currentStructures.length),savedPackr=currentUnpackr,savedSequentialMode=sequentialMode,value=callback();return srcEnd=savedSrcEnd,position2=savedPosition,stringPosition=savedStringPosition,srcStringStart=savedSrcStringStart,srcStringEnd=savedSrcStringEnd,srcString=savedSrcString,strings=savedStrings,referenceMap=savedReferenceMap,bundledStrings=savedBundledStrings,src=savedSrc,sequentialMode=savedSequentialMode,currentStructures=savedStructures,currentStructures.splice(0,currentStructures.length,...savedStructuresContents),currentUnpackr=savedPackr,dataView=new DataView(src.buffer,src.byteOffset,src.byteLength),value}__name(saveState,"saveState");function clearSource(){src=null,referenceMap=null,currentStructures=null}__name(clearSource,"clearSource");var mult10=new Array(147);for(let i=0;i<256;i++)mult10[i]=+("1e"+Math.floor(45.15-i*.30103));var defaultUnpackr=new Unpackr({useRecords:!1}),unpack=defaultUnpackr.unpack,unpackMultiple=defaultUnpackr.unpackMultiple,decode3=defaultUnpackr.unpack,FLOAT32_OPTIONS={NEVER:0,ALWAYS:1,DECIMAL_ROUND:3,DECIMAL_FIT:4},f32Array=new Float32Array(1),u8Array=new Uint8Array(f32Array.buffer,0,4);function setReadStruct(updatedReadStruct,loadedStructs,saveState3){readStruct=updatedReadStruct,onLoadedStructures=loadedStructs,onSaveState=saveState3}__name(setReadStruct,"setReadStruct");var textEncoder2;try{textEncoder2=new TextEncoder}catch{}var extensions,extensionClasses,hasNodeBuffer2=typeof Buffer<"u",ByteArrayAllocate2=hasNodeBuffer2?function(length){return Buffer.allocUnsafeSlow(length)}:Uint8Array,ByteArray=hasNodeBuffer2?Buffer:Uint8Array,MAX_BUFFER_SIZE=hasNodeBuffer2?4294967296:2144337920,target,keysTarget,targetView,position3=0,safeEnd,bundledStrings2=null,writeStructSlots,MAX_BUNDLE_SIZE=21760,hasNonLatin=/[\u0080-\uFFFF]/,RECORD_SYMBOL=Symbol("record-id"),Packr=class extends Unpackr{static{__name(this,"Packr")}constructor(options){super(options),this.offset=0;let typeBuffer,start,hasSharedUpdate,structures,referenceMap2,encodeUtf82=ByteArray.prototype.utf8Write?function(string4,position4){return target.utf8Write(string4,position4,target.byteLength-position4)}:textEncoder2&&textEncoder2.encodeInto?function(string4,position4){return textEncoder2.encodeInto(string4,target.subarray(position4)).written}:!1,packr=this;options||(options={});let isSequential=options&&options.sequential,hasSharedStructures=options.structures||options.saveStructures,maxSharedStructures=options.maxSharedStructures;if(maxSharedStructures==null&&(maxSharedStructures=hasSharedStructures?32:0),maxSharedStructures>8160)throw new Error("Maximum maxSharedStructure is 8160");options.structuredClone&&options.moreTypes==null&&(this.moreTypes=!0);let maxOwnStructures=options.maxOwnStructures;maxOwnStructures==null&&(maxOwnStructures=hasSharedStructures?32:64),!this.structures&&options.useRecords!=!1&&(this.structures=[]);let useTwoByteRecords=maxSharedStructures>32||maxOwnStructures+maxSharedStructures>64,sharedLimitId=maxSharedStructures+64,maxStructureId=maxSharedStructures+maxOwnStructures+64;if(maxStructureId>8256)throw new Error("Maximum maxSharedStructure + maxOwnStructure is 8192");let recordIdsToRemove=[],transitionsCount=0,serializationsSinceTransitionRebuild=0;this.pack=this.encode=function(value,encodeOptions){if(target||(target=new ByteArrayAllocate2(8192),targetView=target.dataView||(target.dataView=new DataView(target.buffer,0,8192)),position3=0),safeEnd=target.length-10,safeEnd-position3<2048?(target=new ByteArrayAllocate2(target.length),targetView=target.dataView||(target.dataView=new DataView(target.buffer,0,target.length)),safeEnd=target.length-10,position3=0):position3=position3+7&2147483640,start=position3,encodeOptions&RESERVE_START_SPACE&&(position3+=encodeOptions&255),referenceMap2=packr.structuredClone?new Map:null,packr.bundleStrings&&typeof value!="string"?(bundledStrings2=[],bundledStrings2.size=1/0):bundledStrings2=null,structures=packr.structures,structures){structures.uninitialized&&(structures=packr._mergeStructures(packr.getStructures()));let sharedLength=structures.sharedLength||0;if(sharedLength>maxSharedStructures)throw new Error("Shared structures is larger than maximum shared structures, try increasing maxSharedStructures to "+structures.sharedLength);if(!structures.transitions){structures.transitions=Object.create(null);for(let i=0;i<sharedLength;i++){let keys=structures[i];if(!keys)continue;let nextTransition,transition=structures.transitions;for(let j=0,l=keys.length;j<l;j++){let key=keys[j];nextTransition=transition[key],nextTransition||(nextTransition=transition[key]=Object.create(null)),transition=nextTransition}transition[RECORD_SYMBOL]=i+64}this.lastNamedStructuresLength=sharedLength}isSequential||(structures.nextId=sharedLength+64)}hasSharedUpdate&&(hasSharedUpdate=!1);let encodingError;try{packr.randomAccessStructure&&value&&value.constructor&&value.constructor===Object?writeStruct2(value):pack2(value);let lastBundle=bundledStrings2;if(bundledStrings2&&writeBundles(start,pack2,0),referenceMap2&&referenceMap2.idsToInsert){let idsToInsert=referenceMap2.idsToInsert.sort((a,b)=>a.offset>b.offset?1:-1),i=idsToInsert.length,incrementPosition=-1;for(;lastBundle&&i>0;){let insertionPoint=idsToInsert[--i].offset+start;insertionPoint<lastBundle.stringsPosition+start&&incrementPosition===-1&&(incrementPosition=0),insertionPoint>lastBundle.position+start?incrementPosition>=0&&(incrementPosition+=6):(incrementPosition>=0&&(targetView.setUint32(lastBundle.position+start,targetView.getUint32(lastBundle.position+start)+incrementPosition),incrementPosition=-1),lastBundle=lastBundle.previous,i++)}incrementPosition>=0&&lastBundle&&targetView.setUint32(lastBundle.position+start,targetView.getUint32(lastBundle.position+start)+incrementPosition),position3+=idsToInsert.length*6,position3>safeEnd&&makeRoom(position3),packr.offset=position3;let serialized=insertIds(target.subarray(start,position3),idsToInsert);return referenceMap2=null,serialized}return packr.offset=position3,encodeOptions&REUSE_BUFFER_MODE?(target.start=start,target.end=position3,target):target.subarray(start,position3)}catch(error2){throw encodingError=error2,error2}finally{if(structures&&(resetStructures(),hasSharedUpdate&&packr.saveStructures)){let sharedLength=structures.sharedLength||0,returnBuffer=target.subarray(start,position3),newSharedData=prepareStructures(structures,packr);if(!encodingError)return packr.saveStructures(newSharedData,newSharedData.isCompatible)===!1?packr.pack(value,encodeOptions):(packr.lastNamedStructuresLength=sharedLength,target.length>1073741824&&(target=null),returnBuffer)}target.length>1073741824&&(target=null),encodeOptions&RESET_BUFFER_MODE&&(position3=start)}};let resetStructures=__name(()=>{serializationsSinceTransitionRebuild<10&&serializationsSinceTransitionRebuild++;let sharedLength=structures.sharedLength||0;if(structures.length>sharedLength&&!isSequential&&(structures.length=sharedLength),transitionsCount>1e4)structures.transitions=null,serializationsSinceTransitionRebuild=0,transitionsCount=0,recordIdsToRemove.length>0&&(recordIdsToRemove=[]);else if(recordIdsToRemove.length>0&&!isSequential){for(let i=0,l=recordIdsToRemove.length;i<l;i++)recordIdsToRemove[i][RECORD_SYMBOL]=0;recordIdsToRemove=[]}},"resetStructures"),packArray=__name(value=>{var length=value.length;length<16?target[position3++]=144|length:length<65536?(target[position3++]=220,target[position3++]=length>>8,target[position3++]=length&255):(target[position3++]=221,targetView.setUint32(position3,length),position3+=4);for(let i=0;i<length;i++)pack2(value[i])},"packArray"),pack2=__name(value=>{position3>safeEnd&&(target=makeRoom(position3));var type=typeof value,length;if(type==="string"){let strLength=value.length;if(bundledStrings2&&strLength>=4&&strLength<4096){if((bundledStrings2.size+=strLength)>MAX_BUNDLE_SIZE){let extStart,maxBytes2=(bundledStrings2[0]?bundledStrings2[0].length*3+bundledStrings2[1].length:0)+10;position3+maxBytes2>safeEnd&&(target=makeRoom(position3+maxBytes2));let lastBundle;bundledStrings2.position?(lastBundle=bundledStrings2,target[position3]=200,position3+=3,target[position3++]=98,extStart=position3-start,position3+=4,writeBundles(start,pack2,0),targetView.setUint16(extStart+start-3,position3-start-extStart)):(target[position3++]=214,target[position3++]=98,extStart=position3-start,position3+=4),bundledStrings2=["",""],bundledStrings2.previous=lastBundle,bundledStrings2.size=0,bundledStrings2.position=extStart}let twoByte=hasNonLatin.test(value);bundledStrings2[twoByte?0:1]+=value,target[position3++]=193,pack2(twoByte?-strLength:strLength);return}let headerSize;strLength<32?headerSize=1:strLength<256?headerSize=2:strLength<65536?headerSize=3:headerSize=5;let maxBytes=strLength*3;if(position3+maxBytes>safeEnd&&(target=makeRoom(position3+maxBytes)),strLength<64||!encodeUtf82){let i,c1,c2,strPosition=position3+headerSize;for(i=0;i<strLength;i++)c1=value.charCodeAt(i),c1<128?target[strPosition++]=c1:c1<2048?(target[strPosition++]=c1>>6|192,target[strPosition++]=c1&63|128):(c1&64512)===55296&&((c2=value.charCodeAt(i+1))&64512)===56320?(c1=65536+((c1&1023)<<10)+(c2&1023),i++,target[strPosition++]=c1>>18|240,target[strPosition++]=c1>>12&63|128,target[strPosition++]=c1>>6&63|128,target[strPosition++]=c1&63|128):(target[strPosition++]=c1>>12|224,target[strPosition++]=c1>>6&63|128,target[strPosition++]=c1&63|128);length=strPosition-position3-headerSize}else length=encodeUtf82(value,position3+headerSize);length<32?target[position3++]=160|length:length<256?(headerSize<2&&target.copyWithin(position3+2,position3+1,position3+1+length),target[position3++]=217,target[position3++]=length):length<65536?(headerSize<3&&target.copyWithin(position3+3,position3+2,position3+2+length),target[position3++]=218,target[position3++]=length>>8,target[position3++]=length&255):(headerSize<5&&target.copyWithin(position3+5,position3+3,position3+3+length),target[position3++]=219,targetView.setUint32(position3,length),position3+=4),position3+=length}else if(type==="number")if(value>>>0===value)value<32||value<128&&this.useRecords===!1||value<64&&!this.randomAccessStructure?target[position3++]=value:value<256?(target[position3++]=204,target[position3++]=value):value<65536?(target[position3++]=205,target[position3++]=value>>8,target[position3++]=value&255):(target[position3++]=206,targetView.setUint32(position3,value),position3+=4);else if(value>>0===value)value>=-32?target[position3++]=256+value:value>=-128?(target[position3++]=208,target[position3++]=value+256):value>=-32768?(target[position3++]=209,targetView.setInt16(position3,value),position3+=2):(target[position3++]=210,targetView.setInt32(position3,value),position3+=4);else{let useFloat32;if((useFloat32=this.useFloat32)>0&&value<4294967296&&value>=-2147483648){target[position3++]=202,targetView.setFloat32(position3,value);let xShifted;if(useFloat32<4||(xShifted=value*mult10[(target[position3]&127)<<1|target[position3+1]>>7])>>0===xShifted){position3+=4;return}else position3--}target[position3++]=203,targetView.setFloat64(position3,value),position3+=8}else if(type==="object"||type==="function")if(!value)target[position3++]=192;else{if(referenceMap2){let referee=referenceMap2.get(value);if(referee){if(!referee.id){let idsToInsert=referenceMap2.idsToInsert||(referenceMap2.idsToInsert=[]);referee.id=idsToInsert.push(referee)}target[position3++]=214,target[position3++]=112,targetView.setUint32(position3,referee.id),position3+=4;return}else referenceMap2.set(value,{offset:position3-start})}let constructor=value.constructor;if(constructor===Object)writeObject(value);else if(constructor===Array)packArray(value);else if(constructor===Map)if(this.mapAsEmptyObject)target[position3++]=128;else{length=value.size,length<16?target[position3++]=128|length:length<65536?(target[position3++]=222,target[position3++]=length>>8,target[position3++]=length&255):(target[position3++]=223,targetView.setUint32(position3,length),position3+=4);for(let[key,entryValue]of value)pack2(key),pack2(entryValue)}else{for(let i=0,l=extensions.length;i<l;i++){let extensionClass=extensionClasses[i];if(value instanceof extensionClass){let extension=extensions[i];if(extension.write){extension.type&&(target[position3++]=212,target[position3++]=extension.type,target[position3++]=0);let writeResult=extension.write.call(this,value);writeResult===value?Array.isArray(value)?packArray(value):writeObject(value):pack2(writeResult);return}let currentTarget=target,currentTargetView=targetView,currentPosition=position3;target=null;let result;try{result=extension.pack.call(this,value,size=>(target=currentTarget,currentTarget=null,position3+=size,position3>safeEnd&&makeRoom(position3),{target,targetView,position:position3-size}),pack2)}finally{currentTarget&&(target=currentTarget,targetView=currentTargetView,position3=currentPosition,safeEnd=target.length-10)}result&&(result.length+position3>safeEnd&&makeRoom(result.length+position3),position3=writeExtensionData(result,target,position3,extension.type));return}}if(Array.isArray(value))packArray(value);else{if(value.toJSON){let json2=value.toJSON();if(json2!==value)return pack2(json2)}if(type==="function")return pack2(this.writeFunction&&this.writeFunction(value));writeObject(value)}}}else if(type==="boolean")target[position3++]=value?195:194;else if(type==="bigint"){if(value<BigInt(1)<<BigInt(63)&&value>=-(BigInt(1)<<BigInt(63)))target[position3++]=211,targetView.setBigInt64(position3,value);else if(value<BigInt(1)<<BigInt(64)&&value>0)target[position3++]=207,targetView.setBigUint64(position3,value);else if(this.largeBigIntToFloat)target[position3++]=203,targetView.setFloat64(position3,Number(value));else{if(this.largeBigIntToString)return pack2(value.toString());if(this.useBigIntExtension&&value<BigInt(2)**BigInt(1023)&&value>-(BigInt(2)**BigInt(1023))){target[position3++]=199,position3++,target[position3++]=66;let bytes=[],alignedSign;do{let byte=value&BigInt(255);alignedSign=(byte&BigInt(128))===(value<BigInt(0)?BigInt(128):BigInt(0)),bytes.push(byte),value>>=BigInt(8)}while(!((value===BigInt(0)||value===BigInt(-1))&&alignedSign));target[position3-2]=bytes.length;for(let i=bytes.length;i>0;)target[position3++]=Number(bytes[--i]);return}else throw new RangeError(value+" was too large to fit in MessagePack 64-bit integer format, use useBigIntExtension, or set largeBigIntToFloat to convert to float-64, or set largeBigIntToString to convert to string")}position3+=8}else if(type==="undefined")this.encodeUndefinedAsNil?target[position3++]=192:(target[position3++]=212,target[position3++]=0,target[position3++]=0);else throw new Error("Unknown type: "+type)},"pack"),writePlainObject=this.variableMapSize||this.coercibleKeyAsNumber||this.skipValues?object2=>{let keys;if(this.skipValues){keys=[];for(let key2 in object2)(typeof object2.hasOwnProperty!="function"||object2.hasOwnProperty(key2))&&!this.skipValues.includes(object2[key2])&&keys.push(key2)}else keys=Object.keys(object2);let length=keys.length;length<16?target[position3++]=128|length:length<65536?(target[position3++]=222,target[position3++]=length>>8,target[position3++]=length&255):(target[position3++]=223,targetView.setUint32(position3,length),position3+=4);let key;if(this.coercibleKeyAsNumber)for(let i=0;i<length;i++){key=keys[i];let num=Number(key);pack2(isNaN(num)?key:num),pack2(object2[key])}else for(let i=0;i<length;i++)pack2(key=keys[i]),pack2(object2[key])}:object2=>{target[position3++]=222;let objectOffset=position3-start;position3+=2;let size=0;for(let key in object2)(typeof object2.hasOwnProperty!="function"||object2.hasOwnProperty(key))&&(pack2(key),pack2(object2[key]),size++);if(size>65535)throw new Error('Object is too large to serialize with fast 16-bit map size, use the "variableMapSize" option to serialize this object');target[objectOffset+++start]=size>>8,target[objectOffset+start]=size&255},writeRecord=this.useRecords===!1?writePlainObject:options.progressiveRecords&&!useTwoByteRecords?object2=>{let nextTransition,transition=structures.transitions||(structures.transitions=Object.create(null)),objectOffset=position3++-start,wroteKeys;for(let key in object2)if(typeof object2.hasOwnProperty!="function"||object2.hasOwnProperty(key)){if(nextTransition=transition[key],nextTransition)transition=nextTransition;else{let keys=Object.keys(object2),lastTransition=transition;transition=structures.transitions;let newTransitions=0;for(let i=0,l=keys.length;i<l;i++){let key2=keys[i];nextTransition=transition[key2],nextTransition||(nextTransition=transition[key2]=Object.create(null),newTransitions++),transition=nextTransition}objectOffset+start+1==position3?(position3--,newRecord(transition,keys,newTransitions)):insertNewRecord(transition,keys,objectOffset,newTransitions),wroteKeys=!0,transition=lastTransition[key]}pack2(object2[key])}if(!wroteKeys){let recordId=transition[RECORD_SYMBOL];recordId?target[objectOffset+start]=recordId:insertNewRecord(transition,Object.keys(object2),objectOffset,0)}}:object2=>{let nextTransition,transition=structures.transitions||(structures.transitions=Object.create(null)),newTransitions=0;for(let key in object2)(typeof object2.hasOwnProperty!="function"||object2.hasOwnProperty(key))&&(nextTransition=transition[key],nextTransition||(nextTransition=transition[key]=Object.create(null),newTransitions++),transition=nextTransition);let recordId=transition[RECORD_SYMBOL];recordId?recordId>=96&&useTwoByteRecords?(target[position3++]=((recordId-=96)&31)+96,target[position3++]=recordId>>5):target[position3++]=recordId:newRecord(transition,transition.__keys__||Object.keys(object2),newTransitions);for(let key in object2)(typeof object2.hasOwnProperty!="function"||object2.hasOwnProperty(key))&&pack2(object2[key])},checkUseRecords=typeof this.useRecords=="function"&&this.useRecords,writeObject=checkUseRecords?object2=>{checkUseRecords(object2)?writeRecord(object2):writePlainObject(object2)}:writeRecord,makeRoom=__name(end=>{let newSize;if(end>16777216){if(end-start>MAX_BUFFER_SIZE)throw new Error("Packed buffer would be larger than maximum buffer size");newSize=Math.min(MAX_BUFFER_SIZE,Math.round(Math.max((end-start)*(end>67108864?1.25:2),4194304)/4096)*4096)}else newSize=(Math.max(end-start<<2,target.length-1)>>12)+1<<12;let newBuffer=new ByteArrayAllocate2(newSize);return targetView=newBuffer.dataView||(newBuffer.dataView=new DataView(newBuffer.buffer,0,newSize)),end=Math.min(end,target.length),target.copy?target.copy(newBuffer,0,start,end):newBuffer.set(target.slice(start,end)),position3-=start,start=0,safeEnd=newBuffer.length-10,target=newBuffer},"makeRoom"),newRecord=__name((transition,keys,newTransitions)=>{let recordId=structures.nextId;recordId||(recordId=64),recordId<sharedLimitId&&this.shouldShareStructure&&!this.shouldShareStructure(keys)?(recordId=structures.nextOwnId,recordId<maxStructureId||(recordId=sharedLimitId),structures.nextOwnId=recordId+1):(recordId>=maxStructureId&&(recordId=sharedLimitId),structures.nextId=recordId+1);let highByte=keys.highByte=recordId>=96&&useTwoByteRecords?recordId-96>>5:-1;transition[RECORD_SYMBOL]=recordId,transition.__keys__=keys,structures[recordId-64]=keys,recordId<sharedLimitId?(keys.isShared=!0,structures.sharedLength=recordId-63,hasSharedUpdate=!0,highByte>=0?(target[position3++]=(recordId&31)+96,target[position3++]=highByte):target[position3++]=recordId):(highByte>=0?(target[position3++]=213,target[position3++]=114,target[position3++]=(recordId&31)+96,target[position3++]=highByte):(target[position3++]=212,target[position3++]=114,target[position3++]=recordId),newTransitions&&(transitionsCount+=serializationsSinceTransitionRebuild*newTransitions),recordIdsToRemove.length>=maxOwnStructures&&(recordIdsToRemove.shift()[RECORD_SYMBOL]=0),recordIdsToRemove.push(transition),pack2(keys))},"newRecord"),insertNewRecord=__name((transition,keys,insertionOffset,newTransitions)=>{let mainTarget=target,mainPosition=position3,mainSafeEnd=safeEnd,mainStart=start;target=keysTarget,position3=0,start=0,target||(keysTarget=target=new ByteArrayAllocate2(8192)),safeEnd=target.length-10,newRecord(transition,keys,newTransitions),keysTarget=target;let keysPosition=position3;if(target=mainTarget,position3=mainPosition,safeEnd=mainSafeEnd,start=mainStart,keysPosition>1){let newEnd=position3+keysPosition-1;newEnd>safeEnd&&makeRoom(newEnd);let insertionPosition=insertionOffset+start;target.copyWithin(insertionPosition+keysPosition,insertionPosition+1,position3),target.set(keysTarget.slice(0,keysPosition),insertionPosition),position3=newEnd}else target[insertionOffset+start]=keysTarget[0]},"insertNewRecord"),writeStruct2=__name(object2=>{let newPosition=writeStructSlots(object2,target,start,position3,structures,makeRoom,(value,newPosition2,notifySharedUpdate)=>{if(notifySharedUpdate)return hasSharedUpdate=!0;position3=newPosition2;let startTarget=target;return pack2(value),resetStructures(),startTarget!==target?{position:position3,targetView,target}:position3},this);if(newPosition===0)return writeObject(object2);position3=newPosition},"writeStruct")}useBuffer(buffer){target=buffer,target.dataView||(target.dataView=new DataView(target.buffer,target.byteOffset,target.byteLength)),position3=0}set position(value){position3=value}get position(){return position3}clearSharedData(){this.structures&&(this.structures=[]),this.typedStructs&&(this.typedStructs=[])}};extensionClasses=[Date,Set,Error,RegExp,ArrayBuffer,Object.getPrototypeOf(Uint8Array.prototype).constructor,C1Type];extensions=[{pack(date5,allocateForWrite,pack2){let seconds=date5.getTime()/1e3;if((this.useTimestamp32||date5.getMilliseconds()===0)&&seconds>=0&&seconds<4294967296){let{target:target2,targetView:targetView2,position:position4}=allocateForWrite(6);target2[position4++]=214,target2[position4++]=255,targetView2.setUint32(position4,seconds)}else if(seconds>0&&seconds<4294967296){let{target:target2,targetView:targetView2,position:position4}=allocateForWrite(10);target2[position4++]=215,target2[position4++]=255,targetView2.setUint32(position4,date5.getMilliseconds()*4e6+(seconds/1e3/4294967296>>0)),targetView2.setUint32(position4+4,seconds)}else if(isNaN(seconds)){if(this.onInvalidDate)return allocateForWrite(0),pack2(this.onInvalidDate());let{target:target2,targetView:targetView2,position:position4}=allocateForWrite(3);target2[position4++]=212,target2[position4++]=255,target2[position4++]=255}else{let{target:target2,targetView:targetView2,position:position4}=allocateForWrite(15);target2[position4++]=199,target2[position4++]=12,target2[position4++]=255,targetView2.setUint32(position4,date5.getMilliseconds()*1e6),targetView2.setBigInt64(position4+4,BigInt(Math.floor(seconds)))}}},{pack(set2,allocateForWrite,pack2){if(this.setAsEmptyObject)return allocateForWrite(0),pack2({});let array2=Array.from(set2),{target:target2,position:position4}=allocateForWrite(this.moreTypes?3:0);this.moreTypes&&(target2[position4++]=212,target2[position4++]=115,target2[position4++]=0),pack2(array2)}},{pack(error2,allocateForWrite,pack2){let{target:target2,position:position4}=allocateForWrite(this.moreTypes?3:0);this.moreTypes&&(target2[position4++]=212,target2[position4++]=101,target2[position4++]=0),pack2([error2.name,error2.message,error2.cause])}},{pack(regex,allocateForWrite,pack2){let{target:target2,position:position4}=allocateForWrite(this.moreTypes?3:0);this.moreTypes&&(target2[position4++]=212,target2[position4++]=120,target2[position4++]=0),pack2([regex.source,regex.flags])}},{pack(arrayBuffer,allocateForWrite){this.moreTypes?writeExtBuffer(arrayBuffer,16,allocateForWrite):writeBuffer(hasNodeBuffer2?Buffer.from(arrayBuffer):new Uint8Array(arrayBuffer),allocateForWrite)}},{pack(typedArray,allocateForWrite){let constructor=typedArray.constructor;constructor!==ByteArray&&this.moreTypes?writeExtBuffer(typedArray,typedArrays.indexOf(constructor.name),allocateForWrite):writeBuffer(typedArray,allocateForWrite)}},{pack(c1,allocateForWrite){let{target:target2,position:position4}=allocateForWrite(1);target2[position4]=193}}];function writeExtBuffer(typedArray,type,allocateForWrite,encode4){let length=typedArray.byteLength;if(length+1<256){var{target:target2,position:position4}=allocateForWrite(4+length);target2[position4++]=199,target2[position4++]=length+1}else if(length+1<65536){var{target:target2,position:position4}=allocateForWrite(5+length);target2[position4++]=200,target2[position4++]=length+1>>8,target2[position4++]=length+1&255}else{var{target:target2,position:position4,targetView:targetView2}=allocateForWrite(7+length);target2[position4++]=201,targetView2.setUint32(position4,length+1),position4+=4}target2[position4++]=116,target2[position4++]=type,typedArray.buffer||(typedArray=new Uint8Array(typedArray)),target2.set(new Uint8Array(typedArray.buffer,typedArray.byteOffset,typedArray.byteLength),position4)}__name(writeExtBuffer,"writeExtBuffer");function writeBuffer(buffer,allocateForWrite){let length=buffer.byteLength;var target2,position4;if(length<256){var{target:target2,position:position4}=allocateForWrite(length+2);target2[position4++]=196,target2[position4++]=length}else if(length<65536){var{target:target2,position:position4}=allocateForWrite(length+3);target2[position4++]=197,target2[position4++]=length>>8,target2[position4++]=length&255}else{var{target:target2,position:position4,targetView:targetView2}=allocateForWrite(length+5);target2[position4++]=198,targetView2.setUint32(position4,length),position4+=4}target2.set(buffer,position4)}__name(writeBuffer,"writeBuffer");function writeExtensionData(result,target2,position4,type){let length=result.length;switch(length){case 1:target2[position4++]=212;break;case 2:target2[position4++]=213;break;case 4:target2[position4++]=214;break;case 8:target2[position4++]=215;break;case 16:target2[position4++]=216;break;default:length<256?(target2[position4++]=199,target2[position4++]=length):length<65536?(target2[position4++]=200,target2[position4++]=length>>8,target2[position4++]=length&255):(target2[position4++]=201,target2[position4++]=length>>24,target2[position4++]=length>>16&255,target2[position4++]=length>>8&255,target2[position4++]=length&255)}return target2[position4++]=type,target2.set(result,position4),position4+=length,position4}__name(writeExtensionData,"writeExtensionData");function insertIds(serialized,idsToInsert){let nextId,distanceToMove=idsToInsert.length*6,lastEnd=serialized.length-distanceToMove;for(;nextId=idsToInsert.pop();){let offset=nextId.offset,id=nextId.id;serialized.copyWithin(offset+distanceToMove,offset,lastEnd),distanceToMove-=6;let position4=offset+distanceToMove;serialized[position4++]=214,serialized[position4++]=105,serialized[position4++]=id>>24,serialized[position4++]=id>>16&255,serialized[position4++]=id>>8&255,serialized[position4++]=id&255,lastEnd=offset}return serialized}__name(insertIds,"insertIds");function writeBundles(start,pack2,incrementPosition){if(bundledStrings2.length>0){targetView.setUint32(bundledStrings2.position+start,position3+incrementPosition-bundledStrings2.position-start),bundledStrings2.stringsPosition=position3-start;let writeStrings=bundledStrings2;bundledStrings2=null,pack2(writeStrings[0]),pack2(writeStrings[1])}}__name(writeBundles,"writeBundles");function prepareStructures(structures,packr){return structures.isCompatible=existingStructures=>{let compatible=!existingStructures||(packr.lastNamedStructuresLength||0)===existingStructures.length;return compatible||packr._mergeStructures(existingStructures),compatible},structures}__name(prepareStructures,"prepareStructures");function setWriteStructSlots(writeSlots,makeStructures){writeStructSlots=writeSlots,prepareStructures=makeStructures}__name(setWriteStructSlots,"setWriteStructSlots");var defaultPackr=new Packr({useRecords:!1}),pack=defaultPackr.pack,encode3=defaultPackr.pack,Encoder6=Packr,{NEVER:NEVER2,ALWAYS,DECIMAL_ROUND,DECIMAL_FIT}=FLOAT32_OPTIONS,REUSE_BUFFER_MODE=512,RESET_BUFFER_MODE=1024,RESERVE_START_SPACE=2048;var ASCII=3,NUMBER=0,UTF8=2,OBJECT_DATA=1,DATE=16,TYPE_NAMES=["num","object","string","ascii"];TYPE_NAMES[DATE]="date";var float32Headers=[!1,!0,!0,!1,!1,!0,!0,!1],evalSupported;try{new Function(""),evalSupported=!0}catch{}var updatedPosition,hasNodeBuffer3=typeof Buffer<"u",textEncoder3,currentSource;try{textEncoder3=new TextEncoder}catch{}var encodeUtf8=hasNodeBuffer3?function(target2,string4,position4){return target2.utf8Write(string4,position4,target2.byteLength-position4)}:textEncoder3&&textEncoder3.encodeInto?function(target2,string4,position4){return textEncoder3.encodeInto(string4,target2.subarray(position4)).written}:!1;setWriteStructSlots(writeStruct,prepareStructures2);function writeStruct(object2,target2,encodingStart,position4,structures,makeRoom,pack2,packr){let typedStructs=packr.typedStructs||(packr.typedStructs=[]),targetView2=target2.dataView,refsStartPosition=(typedStructs.lastStringStart||100)+position4,safeEnd2=target2.length-10,start=position4;position4>safeEnd2&&(target2=makeRoom(position4),targetView2=target2.dataView,position4-=encodingStart,start-=encodingStart,refsStartPosition-=encodingStart,encodingStart=0,safeEnd2=target2.length-10);let refOffset,refPosition=refsStartPosition,transition=typedStructs.transitions||(typedStructs.transitions=Object.create(null)),nextId=typedStructs.nextId||typedStructs.length,headerSize=nextId<15?1:nextId<240?2:nextId<61440?3:nextId<15728640?4:0;if(headerSize===0)return 0;position4+=headerSize;let queuedReferences=[],usedAscii0,keyIndex=0;for(let key in object2){let value=object2[key],nextTransition=transition[key];switch(nextTransition||(transition[key]=nextTransition={key,parent:transition,enumerationOffset:0,ascii0:null,ascii8:null,num8:null,string16:null,object16:null,num32:null,float64:null,date64:null}),position4>safeEnd2&&(target2=makeRoom(position4),targetView2=target2.dataView,position4-=encodingStart,start-=encodingStart,refsStartPosition-=encodingStart,refPosition-=encodingStart,encodingStart=0,safeEnd2=target2.length-10),typeof value){case"number":let number4=value;if(nextId<200||!nextTransition.num64){if(number4>>0===number4&&number4<536870912&&number4>-520093696){number4<246&&number4>=0&&(nextTransition.num8&&!(nextId>200&&nextTransition.num32)||number4<32&&!nextTransition.num32)?(transition=nextTransition.num8||createTypeTransition(nextTransition,NUMBER,1),target2[position4++]=number4):(transition=nextTransition.num32||createTypeTransition(nextTransition,NUMBER,4),targetView2.setUint32(position4,number4,!0),position4+=4);break}else if(number4<4294967296&&number4>=-2147483648&&(targetView2.setFloat32(position4,number4,!0),float32Headers[target2[position4+3]>>>5])){let xShifted;if((xShifted=number4*mult10[(target2[position4+3]&127)<<1|target2[position4+2]>>7])>>0===xShifted){transition=nextTransition.num32||createTypeTransition(nextTransition,NUMBER,4),position4+=4;break}}}transition=nextTransition.num64||createTypeTransition(nextTransition,NUMBER,8),targetView2.setFloat64(position4,number4,!0),position4+=8;break;case"string":let strLength=value.length;if(refOffset=refPosition-refsStartPosition,(strLength<<2)+refPosition>safeEnd2&&(target2=makeRoom((strLength<<2)+refPosition),targetView2=target2.dataView,position4-=encodingStart,start-=encodingStart,refsStartPosition-=encodingStart,refPosition-=encodingStart,encodingStart=0,safeEnd2=target2.length-10),strLength>65280+refOffset>>2){queuedReferences.push(key,value,position4-start);break}let isNotAscii,strStart=refPosition;if(strLength<64){let i,c1,c2;for(i=0;i<strLength;i++)c1=value.charCodeAt(i),c1<128?target2[refPosition++]=c1:c1<2048?(isNotAscii=!0,target2[refPosition++]=c1>>6|192,target2[refPosition++]=c1&63|128):(c1&64512)===55296&&((c2=value.charCodeAt(i+1))&64512)===56320?(isNotAscii=!0,c1=65536+((c1&1023)<<10)+(c2&1023),i++,target2[refPosition++]=c1>>18|240,target2[refPosition++]=c1>>12&63|128,target2[refPosition++]=c1>>6&63|128,target2[refPosition++]=c1&63|128):(isNotAscii=!0,target2[refPosition++]=c1>>12|224,target2[refPosition++]=c1>>6&63|128,target2[refPosition++]=c1&63|128)}else refPosition+=encodeUtf8(target2,value,refPosition),isNotAscii=refPosition-strStart>strLength;if(refOffset<160||refOffset<246&&(nextTransition.ascii8||nextTransition.string8)){if(isNotAscii)(transition=nextTransition.string8)||(typedStructs.length>10&&(transition=nextTransition.ascii8)?(transition.__type=UTF8,nextTransition.ascii8=null,nextTransition.string8=transition,pack2(null,0,!0)):transition=createTypeTransition(nextTransition,UTF8,1));else if(refOffset===0&&!usedAscii0){usedAscii0=!0,transition=nextTransition.ascii0||createTypeTransition(nextTransition,ASCII,0);break}else!(transition=nextTransition.ascii8)&&!(typedStructs.length>10&&(transition=nextTransition.string8))&&(transition=createTypeTransition(nextTransition,ASCII,1));target2[position4++]=refOffset}else transition=nextTransition.string16||createTypeTransition(nextTransition,UTF8,2),targetView2.setUint16(position4,refOffset,!0),position4+=2;break;case"object":if(value){value.constructor===Date?(transition=nextTransition.date64||createTypeTransition(nextTransition,DATE,8),targetView2.setFloat64(position4,value.getTime(),!0),position4+=8):queuedReferences.push(key,value,keyIndex);break}else nextTransition=anyType(nextTransition,position4,targetView2,-10),nextTransition?(transition=nextTransition,position4=updatedPosition):queuedReferences.push(key,value,keyIndex);break;case"boolean":transition=nextTransition.num8||nextTransition.ascii8||createTypeTransition(nextTransition,NUMBER,1),target2[position4++]=value?249:248;break;case"undefined":nextTransition=anyType(nextTransition,position4,targetView2,-9),nextTransition?(transition=nextTransition,position4=updatedPosition):queuedReferences.push(key,value,keyIndex);break;default:queuedReferences.push(key,value,keyIndex)}keyIndex++}for(let i=0,l=queuedReferences.length;i<l;){let key=queuedReferences[i++],value=queuedReferences[i++],propertyIndex=queuedReferences[i++],nextTransition=transition[key];nextTransition||(transition[key]=nextTransition={key,parent:transition,enumerationOffset:propertyIndex-keyIndex,ascii0:null,ascii8:null,num8:null,string16:null,object16:null,num32:null,float64:null});let newPosition;if(value){let size;refOffset=refPosition-refsStartPosition,refOffset<65280?(transition=nextTransition.object16,transition?size=2:(transition=nextTransition.object32)?size=4:(transition=createTypeTransition(nextTransition,OBJECT_DATA,2),size=2)):(transition=nextTransition.object32||createTypeTransition(nextTransition,OBJECT_DATA,4),size=4),newPosition=pack2(value,refPosition),typeof newPosition=="object"?(refPosition=newPosition.position,targetView2=newPosition.targetView,target2=newPosition.target,refsStartPosition-=encodingStart,position4-=encodingStart,start-=encodingStart,encodingStart=0):refPosition=newPosition,size===2?(targetView2.setUint16(position4,refOffset,!0),position4+=2):(targetView2.setUint32(position4,refOffset,!0),position4+=4)}else transition=nextTransition.object16||createTypeTransition(nextTransition,OBJECT_DATA,2),targetView2.setInt16(position4,value===null?-10:-9,!0),position4+=2;keyIndex++}let recordId=transition[RECORD_SYMBOL];if(recordId==null){recordId=packr.typedStructs.length;let structure=[],nextTransition=transition,key,type;for(;(type=nextTransition.__type)!==void 0;){let size=nextTransition.__size;nextTransition=nextTransition.__parent,key=nextTransition.key;let property=[type,size,key];nextTransition.enumerationOffset&&property.push(nextTransition.enumerationOffset),structure.push(property),nextTransition=nextTransition.parent}structure.reverse(),transition[RECORD_SYMBOL]=recordId,packr.typedStructs[recordId]=structure,pack2(null,0,!0)}switch(headerSize){case 1:if(recordId>=16)return 0;target2[start]=recordId+32;break;case 2:if(recordId>=256)return 0;target2[start]=56,target2[start+1]=recordId;break;case 3:if(recordId>=65536)return 0;target2[start]=57,targetView2.setUint16(start+1,recordId,!0);break;case 4:if(recordId>=16777216)return 0;targetView2.setUint32(start,(recordId<<8)+58,!0);break}if(position4<refsStartPosition){if(refsStartPosition===refPosition)return position4;target2.copyWithin(position4,refsStartPosition,refPosition),refPosition+=position4-refsStartPosition,typedStructs.lastStringStart=position4-start}else if(position4>refsStartPosition)return refsStartPosition===refPosition?position4:(typedStructs.lastStringStart=position4-start,writeStruct(object2,target2,encodingStart,start,structures,makeRoom,pack2,packr));return refPosition}__name(writeStruct,"writeStruct");function anyType(transition,position4,targetView2,value){let nextTransition;if(nextTransition=transition.ascii8||transition.num8)return targetView2.setInt8(position4,value,!0),updatedPosition=position4+1,nextTransition;if(nextTransition=transition.string16||transition.object16)return targetView2.setInt16(position4,value,!0),updatedPosition=position4+2,nextTransition;if(nextTransition=transition.num32)return targetView2.setUint32(position4,3758096640+value,!0),updatedPosition=position4+4,nextTransition;if(nextTransition=transition.num64)return targetView2.setFloat64(position4,NaN,!0),targetView2.setInt8(position4,value),updatedPosition=position4+8,nextTransition;updatedPosition=position4}__name(anyType,"anyType");function createTypeTransition(transition,type,size){let typeName=TYPE_NAMES[type]+(size<<3),newTransition=transition[typeName]||(transition[typeName]=Object.create(null));return newTransition.__type=type,newTransition.__size=size,newTransition.__parent=transition,newTransition}__name(createTypeTransition,"createTypeTransition");function onLoadedStructures2(sharedData){if(!(sharedData instanceof Map))return sharedData;let typed=sharedData.get("typed")||[];Object.isFrozen(typed)&&(typed=typed.map(structure=>structure.slice(0)));let named=sharedData.get("named"),transitions=Object.create(null);for(let i=0,l=typed.length;i<l;i++){let structure=typed[i],transition=transitions;for(let[type,size,key]of structure){let nextTransition=transition[key];nextTransition||(transition[key]=nextTransition={key,parent:transition,enumerationOffset:0,ascii0:null,ascii8:null,num8:null,string16:null,object16:null,num32:null,float64:null,date64:null}),transition=createTypeTransition(nextTransition,type,size)}transition[RECORD_SYMBOL]=i}return typed.transitions=transitions,this.typedStructs=typed,this.lastTypedStructuresLength=typed.length,named}__name(onLoadedStructures2,"onLoadedStructures");var sourceSymbol=Symbol.for("source");function readStruct2(src2,position4,srcEnd2,unpackr){let recordId=src2[position4++]-32;if(recordId>=24)switch(recordId){case 24:recordId=src2[position4++];break;case 25:recordId=src2[position4++]+(src2[position4++]<<8);break;case 26:recordId=src2[position4++]+(src2[position4++]<<8)+(src2[position4++]<<16);break;case 27:recordId=src2[position4++]+(src2[position4++]<<8)+(src2[position4++]<<16)+(src2[position4++]<<24);break}let structure=unpackr.typedStructs&&unpackr.typedStructs[recordId];if(!structure){if(src2=Uint8Array.prototype.slice.call(src2,position4,srcEnd2),srcEnd2-=position4,position4=0,!unpackr.getStructures)throw new Error(`Reference to shared structure ${recordId} without getStructures method`);if(unpackr._mergeStructures(unpackr.getStructures()),!unpackr.typedStructs)throw new Error("Could not find any shared typed structures");if(unpackr.lastTypedStructuresLength=unpackr.typedStructs.length,structure=unpackr.typedStructs[recordId],!structure)throw new Error("Could not find typed structure "+recordId)}var construct=structure.construct;if(!construct){construct=structure.construct=__name(function(){},"LazyObject");var prototype=construct.prototype;let properties=[],currentOffset=0,lastRefProperty;for(let i=0,l=structure.length;i<l;i++){let definition=structure[i],[type,size,key,enumerationOffset]=definition;key==="__proto__"&&(key="__proto_");let property={key,offset:currentOffset};enumerationOffset?properties.splice(i+enumerationOffset,0,property):properties.push(property);let getRef;switch(size){case 0:getRef=__name(()=>0,"getRef");break;case 1:getRef=__name((source,position5)=>{let ref=source.bytes[position5+property.offset];return ref>=246?toConstant(ref):ref},"getRef");break;case 2:getRef=__name((source,position5)=>{let src3=source.bytes,ref=(src3.dataView||(src3.dataView=new DataView(src3.buffer,src3.byteOffset,src3.byteLength))).getUint16(position5+property.offset,!0);return ref>=65280?toConstant(ref&255):ref},"getRef");break;case 4:getRef=__name((source,position5)=>{let src3=source.bytes,ref=(src3.dataView||(src3.dataView=new DataView(src3.buffer,src3.byteOffset,src3.byteLength))).getUint32(position5+property.offset,!0);return ref>=4294967040?toConstant(ref&255):ref},"getRef");break}property.getRef=getRef,currentOffset+=size;let get;switch(type){case ASCII:lastRefProperty&&!lastRefProperty.next&&(lastRefProperty.next=property),lastRefProperty=property,property.multiGetCount=0,get=__name(function(source){let src3=source.bytes,position5=source.position,refStart=currentOffset+position5,ref=getRef(source,position5);if(typeof ref!="number")return ref;let end,next=property.next;for(;next&&(end=next.getRef(source,position5),typeof end!="number");)end=null,next=next.next;return end==null&&(end=source.bytesEnd-refStart),source.srcString?source.srcString.slice(ref,end):readString2(src3,ref+refStart,end-ref)},"get");break;case UTF8:case OBJECT_DATA:lastRefProperty&&!lastRefProperty.next&&(lastRefProperty.next=property),lastRefProperty=property,get=__name(function(source){let position5=source.position,refStart=currentOffset+position5,ref=getRef(source,position5);if(typeof ref!="number")return ref;let src3=source.bytes,end,next=property.next;for(;next&&(end=next.getRef(source,position5),typeof end!="number");)end=null,next=next.next;if(end==null&&(end=source.bytesEnd-refStart),type===UTF8)return src3.toString("utf8",ref+refStart,end+refStart);currentSource=source;try{return unpackr.unpack(src3,{start:ref+refStart,end:end+refStart})}finally{currentSource=null}},"get");break;case NUMBER:switch(size){case 4:get=__name(function(source){let src3=source.bytes,dataView2=src3.dataView||(src3.dataView=new DataView(src3.buffer,src3.byteOffset,src3.byteLength)),position5=source.position+property.offset,value=dataView2.getInt32(position5,!0);if(value<536870912){if(value>-520093696)return value;if(value>-536870912)return toConstant(value&255)}let fValue=dataView2.getFloat32(position5,!0),multiplier=mult10[(src3[position5+3]&127)<<1|src3[position5+2]>>7];return(multiplier*fValue+(fValue>0?.5:-.5)>>0)/multiplier},"get");break;case 8:get=__name(function(source){let src3=source.bytes,value=(src3.dataView||(src3.dataView=new DataView(src3.buffer,src3.byteOffset,src3.byteLength))).getFloat64(source.position+property.offset,!0);if(isNaN(value)){let byte=src3[source.position+property.offset];if(byte>=246)return toConstant(byte)}return value},"get");break;case 1:get=__name(function(source){let value=source.bytes[source.position+property.offset];return value<246?value:toConstant(value)},"get");break}break;case DATE:get=__name(function(source){let src3=source.bytes,dataView2=src3.dataView||(src3.dataView=new DataView(src3.buffer,src3.byteOffset,src3.byteLength));return new Date(dataView2.getFloat64(source.position+property.offset,!0))},"get");break}property.get=get}if(evalSupported){let objectLiteralProperties=[],args=[],i=0,hasInheritedProperties;for(let property of properties){if(unpackr.alwaysLazyProperty&&unpackr.alwaysLazyProperty(property.key)){hasInheritedProperties=!0;continue}Object.defineProperty(prototype,property.key,{get:withSource(property.get),enumerable:!0});let valueFunction="v"+i++;args.push(valueFunction),objectLiteralProperties.push("["+JSON.stringify(property.key)+"]:"+valueFunction+"(s)")}hasInheritedProperties&&objectLiteralProperties.push("__proto__:this");let toObject=new Function(...args,"return function(s){return{"+objectLiteralProperties.join(",")+"}}").apply(null,properties.map(prop=>prop.get));Object.defineProperty(prototype,"toJSON",{value(omitUnderscoredProperties){return toObject.call(this,this[sourceSymbol])}})}else Object.defineProperty(prototype,"toJSON",{value(omitUnderscoredProperties){let resolved={};for(let i=0,l=properties.length;i<l;i++){let key=properties[i].key;resolved[key]=this[key]}return resolved}})}var instance=new construct;return instance[sourceSymbol]={bytes:src2,position:position4,srcString:"",bytesEnd:srcEnd2},instance}__name(readStruct2,"readStruct");function toConstant(code){switch(code){case 246:return null;case 247:return;case 248:return!1;case 249:return!0}throw new Error("Unknown constant")}__name(toConstant,"toConstant");function withSource(get){return function(){return get(this[sourceSymbol])}}__name(withSource,"withSource");function saveState2(){currentSource&&(currentSource.bytes=Uint8Array.prototype.slice.call(currentSource.bytes,currentSource.position,currentSource.bytesEnd),currentSource.position=0,currentSource.bytesEnd=currentSource.bytes.length)}__name(saveState2,"saveState");function prepareStructures2(structures,packr){if(packr.typedStructs){let structMap=new Map;structMap.set("named",structures),structMap.set("typed",packr.typedStructs),structures=structMap}let lastTypedStructuresLength=packr.lastTypedStructuresLength||0;return structures.isCompatible=existing=>{let compatible=!0;return existing instanceof Map?((existing.get("named")||[]).length!==(packr.lastNamedStructuresLength||0)&&(compatible=!1),(existing.get("typed")||[]).length!==lastTypedStructuresLength&&(compatible=!1)):(existing instanceof Array||Array.isArray(existing))&&existing.length!==(packr.lastNamedStructuresLength||0)&&(compatible=!1),compatible||packr._mergeStructures(existing),compatible},packr.lastTypedStructuresLength=packr.typedStructs&&packr.typedStructs.length,structures}__name(prepareStructures2,"prepareStructures");setReadStruct(readStruct2,onLoadedStructures2,saveState2);import{createRequire}from"module";var nativeAccelerationDisabled=process.env.MSGPACKR_NATIVE_ACCELERATION_DISABLED!==void 0&&process.env.MSGPACKR_NATIVE_ACCELERATION_DISABLED.toLowerCase()==="true";if(!nativeAccelerationDisabled){let extractor;try{typeof __require=="function"?extractor=__require("msgpackr-extract"):extractor=createRequire(import.meta.url)("msgpackr-extract"),extractor&&setExtractor(extractor.extractStrings)}catch{}}function serialize(o){return typeof o=="string"?`'${o}'`:new c().serialize(o)}__name(serialize,"serialize");var c=(function(){class o{static{__name(this,"o")}#t=new Map;compare(t,r2){let e2=typeof t,n=typeof r2;return e2==="string"&&n==="string"?t.localeCompare(r2):e2==="number"&&n==="number"?t-r2:String.prototype.localeCompare.call(this.serialize(t,!0),this.serialize(r2,!0))}serialize(t,r2){if(t===null)return"null";switch(typeof t){case"string":return r2?t:`'${t}'`;case"bigint":return`${t}n`;case"object":return this.$object(t);case"function":return this.$function(t)}return String(t)}serializeObject(t){let r2=Object.prototype.toString.call(t);if(r2!=="[object Object]")return this.serializeBuiltInType(r2.length<10?`unknown:${r2}`:r2.slice(8,-1),t);let e2=t.constructor,n=e2===Object||e2===void 0?"":e2.name;if(n!==""&&globalThis[n]===e2)return this.serializeBuiltInType(n,t);if(typeof t.toJSON=="function"){let i=t.toJSON();return n+(i!==null&&typeof i=="object"?this.$object(i):`(${this.serialize(i)})`)}return this.serializeObjectEntries(n,Object.entries(t))}serializeBuiltInType(t,r2){let e2=this["$"+t];if(e2)return e2.call(this,r2);if(typeof r2?.entries=="function")return this.serializeObjectEntries(t,r2.entries());throw new Error(`Cannot serialize ${t}`)}serializeObjectEntries(t,r2){let e2=Array.from(r2).sort((i,a)=>this.compare(i[0],a[0])),n=`${t}{`;for(let i=0;i<e2.length;i++){let[a,l]=e2[i];n+=`${this.serialize(a,!0)}:${this.serialize(l)}`,i<e2.length-1&&(n+=",")}return n+"}"}$object(t){let r2=this.#t.get(t);return r2===void 0&&(this.#t.set(t,`#${this.#t.size}`),r2=this.serializeObject(t),this.#t.set(t,r2)),r2}$function(t){let r2=Function.prototype.toString.call(t);return r2.slice(-15)==="[native code] }"?`${t.name||""}()[native]`:`${t.name}(${t.length})${r2.replace(/\s*\n\s*/g,"")}`}$Array(t){let r2="[";for(let e2=0;e2<t.length;e2++)r2+=this.serialize(t[e2]),e2<t.length-1&&(r2+=",");return r2+"]"}$Date(t){try{return`Date(${t.toISOString()})`}catch{return"Date(null)"}}$ArrayBuffer(t){return`ArrayBuffer[${new Uint8Array(t).join(",")}]`}$Set(t){return`Set${this.$Array(Array.from(t).sort((r2,e2)=>this.compare(r2,e2)))}`}$Map(t){return this.serializeObjectEntries("Map",t.entries())}}for(let s2 of["Error","RegExp","URL"])o.prototype["$"+s2]=function(t){return`${s2}(${t})`};for(let s2 of["Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array"])o.prototype["$"+s2]=function(t){return`${s2}[${t.join(",")}]`};for(let s2 of["BigInt64Array","BigUint64Array"])o.prototype["$"+s2]=function(t){return`${s2}[${t.join("n,")}${t.length>0?"n":""}]`};return o})();import{createHash}from"node:crypto";var e=globalThis.process?.getBuiltinModule?.("crypto")?.hash,r="sha256",s="base64url";function digest(t){if(e)return e(r,t,s);let o=createHash(r).update(t);return globalThis.process?.versions?.webcontainer?o.digest().toString(s):o.digest(s)}__name(digest,"digest");function hash4(input){return digest(serialize(input))}__name(hash4,"hash");var _computedKey36;_computedKey36=Symbol.asyncIterator;var SQLiteOPFSAztecArray=class{static{__name(this,"SQLiteOPFSAztecArray")}store;#name;#container;#encoder;constructor(store,name){this.store=store,this.#encoder=new Encoder6,this.#name=name,this.#container=`array:${name}`}async lengthAsync(){let rows=await this.store.allAsync("SELECT COUNT(*) FROM data WHERE container = ? AND key = ?",[this.#container,this.#encodedKey()]);return Number(rows[0]?.[0]??0)}async push(...vals){return vals.length===0?this.lengthAsync():await this.store.transactionAsync(async()=>{let length=await this.lengthAsync();for(let val of vals)await this.store.runAsync(`INSERT INTO data (slot, container, key, key_count, hash, value)
|
|
216
216
|
VALUES (?, ?, ?, ?, ?, ?)`,[this.#slot(length),this.#container,this.#encodedKey(),length+1,hash4(val),this.#encoder.pack(val)]),length+=1;return length})}async pop(){return await this.store.transactionAsync(async()=>{let length=await this.lengthAsync();if(length===0)return;let slot=this.#slot(length-1),rows=await this.store.allAsync("SELECT value FROM data WHERE slot = ? LIMIT 1",[slot]);await this.store.runAsync("DELETE FROM data WHERE slot = ?",[slot]);let raw=rows[0]?.[0];return raw instanceof Uint8Array?this.#encoder.unpack(raw):void 0})}async atAsync(index){let length=await this.lengthAsync(),resolved=index<0?length+index:index;if(resolved<0||resolved>=length)return;let raw=(await this.store.allAsync("SELECT value FROM data WHERE slot = ? LIMIT 1",[this.#slot(resolved)]))[0]?.[0];return raw instanceof Uint8Array?this.#encoder.unpack(raw):void 0}async setAt(index,val){return await this.store.transactionAsync(async()=>{let length=await this.lengthAsync(),resolved=index<0?length+index:index;return resolved<0||resolved>=length?!1:(await this.store.runAsync(`INSERT OR REPLACE INTO data (slot, container, key, key_count, hash, value)
|
|
217
|
-
VALUES (?, ?, ?, ?, ?, ?)`,[this.#slot(resolved),this.#container,this.#encodedKey(),resolved+1,hash4(val),this.#encoder.pack(val)]),!0)})}async*entriesAsync(){let rows=await this.store.allAsync("SELECT key_count, value FROM data WHERE container = ? AND key = ? ORDER BY key_count ASC",[this.#container,this.#encodedKey()]);for(let row of rows){let keyCount=Number(row[0]),raw=row[1];raw instanceof Uint8Array&&(yield[keyCount-1,this.#encoder.unpack(raw)])}}async*valuesAsync(){for await(let[,val]of this.entriesAsync())yield val}[_computedKey36](){return this.valuesAsync()}#encodedKey(){return toBufferKey([this.#name])}#slot(index){return`array:${this.#name}:slot:${index}`}};function makeProtocolContract(name,artifact){let address=ProtocolContractAddress[name],salt=ProtocolContractSalt[name],classId=ProtocolContractClassId[name],{artifactHash,privateFunctionsRoot,publicBytecodeCommitment}=ProtocolContractClassIdPreimage[name],initializationHash=ProtocolContractInitializationHash[name],contractClass={id:classId,version:1,artifactHash,privateFunctionsRoot,publicBytecodeCommitment,packedBytecode:artifact.functions.find(f=>f.name==="public_dispatch")?.bytecode??Buffer.alloc(0),privateFunctions:ProtocolContractPrivateFunctions[name]};return{instance:{version:2,currentContractClassId:classId,originalContractClassId:classId,initializationHash,immutablesHash:Fr.ZERO,publicKeys:PublicKeys.default(),salt,deployer:address,address},contractClass,artifact,address}}__name(makeProtocolContract,"makeProtocolContract");var ContractClassPublishedEvent=class _ContractClassPublishedEvent{static{__name(this,"ContractClassPublishedEvent")}contractClassId;version;artifactHash;privateFunctionsRoot;packedPublicBytecode;constructor(contractClassId,version2,artifactHash,privateFunctionsRoot,packedPublicBytecode){this.contractClassId=contractClassId,this.version=version2,this.artifactHash=artifactHash,this.privateFunctionsRoot=privateFunctionsRoot,this.packedPublicBytecode=packedPublicBytecode}static isContractClassPublishedEvent(log2){return log2.contractAddress.equals(ProtocolContractAddress.ContractClassRegistry)&&log2.fields.fields[0].toBigInt()===CONTRACT_CLASS_PUBLISHED_MAGIC_VALUE}static fromLog(log2){let fieldsWithoutTag=log2.fields.fields.slice(1),reader=new FieldReader(fieldsWithoutTag),contractClassId=reader.readField(),version2=reader.readField().toNumber(),artifactHash=reader.readField(),privateFunctionsRoot=reader.readField(),bytecodeFields=reader.readFieldArray(fieldsWithoutTag.length-reader.cursor),maxByteLength=(bytecodeFields.length-1)*(Fr.SIZE_IN_BYTES-1),packedPublicBytecode=bufferFromFields(bytecodeFields,maxByteLength);return new _ContractClassPublishedEvent(contractClassId,version2,artifactHash,privateFunctionsRoot,packedPublicBytecode)}toContractClassPublic(){return{id:this.contractClassId,artifactHash:this.artifactHash,packedBytecode:this.packedPublicBytecode,privateFunctionsRoot:this.privateFunctionsRoot,version:this.version}}async toContractClassPublicWithBytecodeCommitment(){let publicBytecodeCommitment=await computePublicBytecodeCommitment(this.packedPublicBytecode);return{...this.toContractClassPublic(),publicBytecodeCommitment}}static extractContractClassEvents(logs){return logs.filter(log2=>_ContractClassPublishedEvent.isContractClassPublishedEvent(log2)).map(log2=>_ContractClassPublishedEvent.fromLog(log2))}};var protocolContract,protocolContractArtifact;async function getContractClassRegistryArtifact(){if(!protocolContractArtifact){let{default:contractClassRegistryJson}=await import("./ContractClassRegistry-5RDBM6TC.js");protocolContractArtifact=loadContractArtifact(contractClassRegistryJson)}return protocolContractArtifact}__name(getContractClassRegistryArtifact,"getContractClassRegistryArtifact");async function getCanonicalClassRegistry(){if(!protocolContract){let contractClassRegistryArtifact=await getContractClassRegistryArtifact();protocolContract=makeProtocolContract("ContractClassRegistry",contractClassRegistryArtifact)}return protocolContract}__name(getCanonicalClassRegistry,"getCanonicalClassRegistry");var protocolContract2,protocolContractArtifact2;async function getFeeJuiceArtifact(){if(!protocolContractArtifact2){let{default:feeJuiceJson}=await import("./FeeJuice-O3KOSZO5.js");protocolContractArtifact2=loadContractArtifact(feeJuiceJson)}return protocolContractArtifact2}__name(getFeeJuiceArtifact,"getFeeJuiceArtifact");async function getCanonicalFeeJuice(){if(!protocolContract2){let feeJuiceArtifact=await getFeeJuiceArtifact();protocolContract2=makeProtocolContract("FeeJuice",feeJuiceArtifact)}return protocolContract2}__name(getCanonicalFeeJuice,"getCanonicalFeeJuice");var ContractInstancePublishedEvent=class _ContractInstancePublishedEvent{static{__name(this,"ContractInstancePublishedEvent")}address;version;salt;contractClassId;initializationHash;immutablesHash;publicKeys;deployer;constructor(address,version2,salt,contractClassId,initializationHash,immutablesHash,publicKeys,deployer){this.address=address,this.version=version2,this.salt=salt,this.contractClassId=contractClassId,this.initializationHash=initializationHash,this.immutablesHash=immutablesHash,this.publicKeys=publicKeys,this.deployer=deployer}static isContractInstancePublishedEvent(log2){return log2.fields[0].equals(CONTRACT_INSTANCE_PUBLISHED_EVENT_TAG)}static fromLog(log2){let bufferWithoutTag=log2.toBuffer().subarray(32),reader=new BufferReader(bufferWithoutTag),address=reader.readObject(AztecAddress),version2=reader.readObject(Fr).toNumber(),salt=reader.readObject(Fr),contractClassId=reader.readObject(Fr),initializationHash=reader.readObject(Fr),immutablesHash=reader.readObject(Fr),publicKeys=reader.readObject(PublicKeys),deployer=reader.readObject(AztecAddress);return new _ContractInstancePublishedEvent(address,version2,salt,contractClassId,initializationHash,immutablesHash,publicKeys,deployer)}toContractInstance(){if(this.version!==2)throw new Error(`Unexpected contract instance version ${this.version}`);return{address:this.address,version:this.version,currentContractClassId:this.contractClassId,originalContractClassId:this.contractClassId,initializationHash:this.initializationHash,immutablesHash:this.immutablesHash,publicKeys:this.publicKeys,salt:this.salt,deployer:this.deployer}}static extractContractInstanceEvents(logs){return logs.filter(log2=>_ContractInstancePublishedEvent.isContractInstancePublishedEvent(log2)).map(log2=>_ContractInstancePublishedEvent.fromLog(log2))}};var ContractInstanceUpdatedEvent=class _ContractInstanceUpdatedEvent{static{__name(this,"ContractInstanceUpdatedEvent")}address;prevContractClassId;newContractClassId;timestampOfChange;constructor(address,prevContractClassId,newContractClassId,timestampOfChange){this.address=address,this.prevContractClassId=prevContractClassId,this.newContractClassId=newContractClassId,this.timestampOfChange=timestampOfChange}static isContractInstanceUpdatedEvent(log2){return log2.contractAddress.equals(ProtocolContractAddress.ContractInstanceRegistry)&&log2.fields[0].toBigInt()===CONTRACT_INSTANCE_UPDATED_MAGIC_VALUE}static fromLog(log2){let reader=new FieldReader(log2.fields.slice(1)),address=reader.readObject(AztecAddress),prevContractClassId=reader.readField(),newContractClassId=reader.readField(),timestampOfChange=reader.readField().toBigInt();return new _ContractInstanceUpdatedEvent(address,prevContractClassId,newContractClassId,timestampOfChange)}toContractInstanceUpdate(){return{address:this.address,prevContractClassId:this.prevContractClassId,newContractClassId:this.newContractClassId,timestampOfChange:this.timestampOfChange}}};var protocolContract3,protocolContractArtifact3;async function getContractInstanceRegistryArtifact(){if(!protocolContractArtifact3){let{default:contractInstanceRegistryJson}=await import("./ContractInstanceRegistry-GCR4G4D7.js");protocolContractArtifact3=loadContractArtifact(contractInstanceRegistryJson)}return protocolContractArtifact3}__name(getContractInstanceRegistryArtifact,"getContractInstanceRegistryArtifact");async function getCanonicalInstanceRegistry(){if(!protocolContract3){let contractInstanceRegistryArtifact=await getContractInstanceRegistryArtifact();protocolContract3=makeProtocolContract("ContractInstanceRegistry",contractInstanceRegistryArtifact)}return protocolContract3}__name(getCanonicalInstanceRegistry,"getCanonicalInstanceRegistry");var LazyProtocolContractsProvider=class{static{__name(this,"LazyProtocolContractsProvider")}getProtocolContractArtifact(name){switch(name){case"ContractInstanceRegistry":return getCanonicalInstanceRegistry();case"ContractClassRegistry":return getCanonicalClassRegistry();case"FeeJuice":return getCanonicalFeeJuice();default:throw new Error(`Unknown protocol contract name: ${name}`)}}};function makeStandardContract(name,artifact){let address=StandardContractAddress[name],salt=StandardContractSalt[name],classId=StandardContractClassId[name],{artifactHash,privateFunctionsRoot,publicBytecodeCommitment}=StandardContractClassIdPreimage[name],initializationHash=StandardContractInitializationHash[name],contractClass={id:classId,version:1,artifactHash,privateFunctionsRoot,publicBytecodeCommitment,packedBytecode:artifact.functions.find(f=>f.name==="public_dispatch")?.bytecode??Buffer.alloc(0),privateFunctions:StandardContractPrivateFunctions[name]};return{instance:{version:2,currentContractClassId:classId,originalContractClassId:classId,initializationHash,immutablesHash:Fr.ZERO,publicKeys:PublicKeys.default(),salt,deployer:AztecAddress.ZERO,address},contractClass,artifact,address}}__name(makeStandardContract,"makeStandardContract");var STANDARD_AUTH_REGISTRY_ADDRESS=StandardContractAddress.AuthRegistry,STANDARD_AUTH_REGISTRY_CLASS_ID=StandardContractClassId.AuthRegistry,STANDARD_AUTH_REGISTRY_SALT=StandardContractSalt.AuthRegistry;var standardContract,standardContractArtifact;async function getAuthRegistryArtifact(){if(!standardContractArtifact){let{default:authRegistryJson}=await import("./AuthRegistry-HBL4YLHF.js");standardContractArtifact=loadContractArtifact(authRegistryJson)}return standardContractArtifact}__name(getAuthRegistryArtifact,"getAuthRegistryArtifact");async function getStandardAuthRegistry(){if(!standardContract){let artifact=await getAuthRegistryArtifact();standardContract=makeStandardContract("AuthRegistry",artifact)}return standardContract}__name(getStandardAuthRegistry,"getStandardAuthRegistry");var standardContract2,standardContractArtifact2;async function getHandshakeRegistryArtifact(){if(!standardContractArtifact2){let{default:handshakeRegistryJson}=await import("./HandshakeRegistry-RLXDBPFJ.js");standardContractArtifact2=loadContractArtifact(handshakeRegistryJson)}return standardContractArtifact2}__name(getHandshakeRegistryArtifact,"getHandshakeRegistryArtifact");async function getStandardHandshakeRegistry(){if(!standardContract2){let artifact=await getHandshakeRegistryArtifact();standardContract2=makeStandardContract("HandshakeRegistry",artifact)}return standardContract2}__name(getStandardHandshakeRegistry,"getStandardHandshakeRegistry");var STANDARD_MULTI_CALL_ENTRYPOINT_ADDRESS=StandardContractAddress.MultiCallEntrypoint,STANDARD_MULTI_CALL_ENTRYPOINT_CLASS_ID=StandardContractClassId.MultiCallEntrypoint,STANDARD_MULTI_CALL_ENTRYPOINT_SALT=StandardContractSalt.MultiCallEntrypoint;import{join as join5}from"path";import{addExtension as addExtension4}from"msgpackr";addExtension4({Class:Fr,write:__name(fr=>fr.toBuffer(),"write")});import{BundleArtifactProvider}from"@aztec/noir-protocol-circuits-types/client/bundle";import{strict as assert4}from"assert";function computeEffectiveGasFees(gasFees,gasSettings){let{maxFeesPerGas,maxPriorityFeesPerGas}=gasSettings,minBigInt=__name((f1,f2)=>f1<f2?f1:f2,"minBigInt");assert4(maxFeesPerGas.feePerDaGas>=gasFees.feePerDaGas,`maxFeesPerGas.feePerDaGas must be greater than or equal to gasFees.feePerDaGas, but got maxFeesPerGas.feePerDaGas=${maxFeesPerGas.feePerDaGas} and gasFees.feePerDaGas=${gasFees.feePerDaGas}`),assert4(maxFeesPerGas.feePerL2Gas>=gasFees.feePerL2Gas,`maxFeesPerGas.feePerL2Gas must be greater than or equal to gasFees.feePerL2Gas, but got maxFeesPerGas.feePerL2Gas=${maxFeesPerGas.feePerL2Gas} and gasFees.feePerL2Gas=${gasFees.feePerL2Gas}`);let priorityFees=new GasFees(minBigInt(maxPriorityFeesPerGas.feePerDaGas,maxFeesPerGas.feePerDaGas-gasFees.feePerDaGas),minBigInt(maxPriorityFeesPerGas.feePerL2Gas,maxFeesPerGas.feePerL2Gas-gasFees.feePerL2Gas));return new GasFees(gasFees.feePerDaGas+priorityFees.feePerDaGas,gasFees.feePerL2Gas+priorityFees.feePerL2Gas)}__name(computeEffectiveGasFees,"computeEffectiveGasFees");function computeTransactionFee(gasFees,gasSettings,gasUsed){let effectiveFees=computeEffectiveGasFees(gasFees,gasSettings);return gasUsed.computeFee(effectiveFees)}__name(computeTransactionFee,"computeTransactionFee");var WorldStateRevision=class _WorldStateRevision{static{__name(this,"WorldStateRevision")}forkId;blockNumber;includeUncommitted;static LATEST=4294967295;constructor(forkId,blockNumber,includeUncommitted){this.forkId=forkId,this.blockNumber=blockNumber,this.includeUncommitted=includeUncommitted}toString(){return`WorldStateRevision(forkId: ${this.forkId}, blockNumber: ${this.blockNumber}, includeUncommitted: ${this.includeUncommitted})`}static empty(){return new _WorldStateRevision(0,_WorldStateRevision.LATEST,!1)}static get schema(){return external_exports.object({forkId:external_exports.number(),blockNumber:external_exports.number(),includeUncommitted:external_exports.boolean()}).transform(({forkId,blockNumber,includeUncommitted})=>new _WorldStateRevision(forkId,blockNumber,includeUncommitted))}},WorldStateRevisionWithHandle=class _WorldStateRevisionWithHandle extends WorldStateRevision{static{__name(this,"WorldStateRevisionWithHandle")}handle;constructor(forkId,blockNumber,includeUncommitted,handle){super(forkId,blockNumber,includeUncommitted),this.handle=handle}toWorldStateRevision(){return new WorldStateRevision(this.forkId,this.blockNumber,this.includeUncommitted)}static fromWorldStateRevision(revision,handle){return new _WorldStateRevisionWithHandle(revision.forkId,revision.blockNumber,revision.includeUncommitted,handle)}static get schema(){return external_exports.object({forkId:external_exports.number(),blockNumber:external_exports.number(),includeUncommitted:external_exports.boolean(),handle:external_exports.any()}).transform(({forkId,blockNumber,includeUncommitted,handle})=>new _WorldStateRevisionWithHandle(forkId,blockNumber,includeUncommitted,handle))}};import{inspect as inspect37}from"util";import{inspect as inspect36}from"util";var _computedKey37,_computedKey113;_computedKey37=inspect36.custom;var AvmAccumulatedData=class _AvmAccumulatedData{static{__name(this,"AvmAccumulatedData")}noteHashes;nullifiers;l2ToL1Msgs;publicLogs;publicDataWrites;constructor(noteHashes,nullifiers,l2ToL1Msgs,publicLogs,publicDataWrites){this.noteHashes=noteHashes,this.nullifiers=nullifiers,this.l2ToL1Msgs=l2ToL1Msgs,this.publicLogs=publicLogs,this.publicDataWrites=publicDataWrites}static get schema(){return external_exports.object({noteHashes:schemas.Fr.array().min(64).max(64),nullifiers:schemas.Fr.array().min(64).max(64),l2ToL1Msgs:ScopedL2ToL1Message.schema.array().min(8).max(8),publicLogs:FlatPublicLogs.schema,publicDataWrites:PublicDataWrite.schema.array().min(64).max(64)}).transform(({noteHashes,nullifiers,l2ToL1Msgs,publicLogs,publicDataWrites})=>new _AvmAccumulatedData(assertLength(noteHashes,64),assertLength(nullifiers,64),assertLength(l2ToL1Msgs,8),publicLogs,assertLength(publicDataWrites,64)))}getSize(){return arraySerializedSizeOfNonEmpty(this.noteHashes)+arraySerializedSizeOfNonEmpty(this.nullifiers)+arraySerializedSizeOfNonEmpty(this.l2ToL1Msgs)+this.publicLogs.toBuffer().length+arraySerializedSizeOfNonEmpty(this.publicDataWrites)}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new this(reader.readArray(64,Fr),reader.readArray(64,Fr),reader.readArray(8,ScopedL2ToL1Message),reader.readObject(FlatPublicLogs),reader.readArray(64,PublicDataWrite))}toBuffer(){return serializeToBuffer(this.noteHashes,this.nullifiers,this.l2ToL1Msgs,this.publicLogs,this.publicDataWrites)}static getFields(fields){return[fields.noteHashes,fields.nullifiers,fields.l2ToL1Msgs,fields.publicLogs,fields.publicDataWrites]}static fromFields(fields){let reader=FieldReader.asReader(fields);return new this(reader.readFieldArray(64),reader.readFieldArray(64),reader.readArray(8,ScopedL2ToL1Message),reader.readObject(FlatPublicLogs),reader.readArray(64,PublicDataWrite))}toFields(){let fields=serializeToFields(..._AvmAccumulatedData.getFields(this));if(fields.length!==4377)throw new Error(`Invalid number of fields for AvmAccumulatedData. Expected ${4377}, got ${fields.length}`);return fields}static fromString(str){return this.fromBuffer(hexToBuffer(str))}toString(){return bufferToHex(this.toBuffer())}static empty(){return new this(makeTuple(64,Fr.zero),makeTuple(64,Fr.zero),makeTuple(8,ScopedL2ToL1Message.empty),FlatPublicLogs.empty(),makeTuple(64,PublicDataWrite.empty))}static fromPlainObject(obj){return new _AvmAccumulatedData(assertLength(obj.noteHashes.map(h=>Fr.fromPlainObject(h)),64),assertLength(obj.nullifiers.map(n=>Fr.fromPlainObject(n)),64),assertLength(obj.l2ToL1Msgs.map(m=>ScopedL2ToL1Message.fromPlainObject(m)),8),FlatPublicLogs.fromPlainObject(obj.publicLogs),assertLength(obj.publicDataWrites.map(w=>PublicDataWrite.fromPlainObject(w)),64))}isEmpty(){return this.noteHashes.every(x=>x.isZero())&&this.nullifiers.every(x=>x.isZero())&&this.l2ToL1Msgs.every(x=>x.isEmpty())&&this.publicLogs.isEmpty()&&this.publicDataWrites.every(x=>x.isEmpty())}[_computedKey37](){return`AvmAccumulatedData {
|
|
217
|
+
VALUES (?, ?, ?, ?, ?, ?)`,[this.#slot(resolved),this.#container,this.#encodedKey(),resolved+1,hash4(val),this.#encoder.pack(val)]),!0)})}async*entriesAsync(){let rows=await this.store.allAsync("SELECT key_count, value FROM data WHERE container = ? AND key = ? ORDER BY key_count ASC",[this.#container,this.#encodedKey()]);for(let row of rows){let keyCount=Number(row[0]),raw=row[1];raw instanceof Uint8Array&&(yield[keyCount-1,this.#encoder.unpack(raw)])}}async*valuesAsync(){for await(let[,val]of this.entriesAsync())yield val}[_computedKey36](){return this.valuesAsync()}#encodedKey(){return toBufferKey([this.#name])}#slot(index){return`array:${this.#name}:slot:${index}`}};function makeProtocolContract(name,artifact){let address=ProtocolContractAddress[name],salt=ProtocolContractSalt[name],classId=ProtocolContractClassId[name],{artifactHash,privateFunctionsRoot,publicBytecodeCommitment}=ProtocolContractClassIdPreimage[name],initializationHash=ProtocolContractInitializationHash[name],contractClass={id:classId,version:1,artifactHash,privateFunctionsRoot,publicBytecodeCommitment,packedBytecode:artifact.functions.find(f=>f.name==="public_dispatch")?.bytecode??Buffer.alloc(0),privateFunctions:ProtocolContractPrivateFunctions[name]};return{instance:{version:2,currentContractClassId:classId,originalContractClassId:classId,initializationHash,immutablesHash:Fr.ZERO,publicKeys:PublicKeys.default(),salt,deployer:address,address},contractClass,artifact,address}}__name(makeProtocolContract,"makeProtocolContract");var ContractClassPublishedEvent=class _ContractClassPublishedEvent{static{__name(this,"ContractClassPublishedEvent")}contractClassId;version;artifactHash;privateFunctionsRoot;packedPublicBytecode;constructor(contractClassId,version2,artifactHash,privateFunctionsRoot,packedPublicBytecode){this.contractClassId=contractClassId,this.version=version2,this.artifactHash=artifactHash,this.privateFunctionsRoot=privateFunctionsRoot,this.packedPublicBytecode=packedPublicBytecode}static isContractClassPublishedEvent(log2){return log2.contractAddress.equals(ProtocolContractAddress.ContractClassRegistry)&&log2.fields.fields[0].toBigInt()===CONTRACT_CLASS_PUBLISHED_MAGIC_VALUE}static fromLog(log2){let fieldsWithoutTag=log2.fields.fields.slice(1),reader=new FieldReader(fieldsWithoutTag),contractClassId=reader.readField(),version2=reader.readField().toNumber(),artifactHash=reader.readField(),privateFunctionsRoot=reader.readField(),bytecodeFields=reader.readFieldArray(fieldsWithoutTag.length-reader.cursor),maxByteLength=(bytecodeFields.length-1)*(Fr.SIZE_IN_BYTES-1),packedPublicBytecode=bufferFromFields(bytecodeFields,maxByteLength);return new _ContractClassPublishedEvent(contractClassId,version2,artifactHash,privateFunctionsRoot,packedPublicBytecode)}toContractClassPublic(){return{id:this.contractClassId,artifactHash:this.artifactHash,packedBytecode:this.packedPublicBytecode,privateFunctionsRoot:this.privateFunctionsRoot,version:this.version}}async toContractClassPublicWithBytecodeCommitment(){let publicBytecodeCommitment=await computePublicBytecodeCommitment(this.packedPublicBytecode);return{...this.toContractClassPublic(),publicBytecodeCommitment}}static extractContractClassEvents(logs){return logs.filter(log2=>_ContractClassPublishedEvent.isContractClassPublishedEvent(log2)).map(log2=>_ContractClassPublishedEvent.fromLog(log2))}};var protocolContract,protocolContractArtifact;async function getContractClassRegistryArtifact(){if(!protocolContractArtifact){let{default:contractClassRegistryJson}=await import("./ContractClassRegistry-5RDBM6TC.js");protocolContractArtifact=loadContractArtifact(contractClassRegistryJson)}return protocolContractArtifact}__name(getContractClassRegistryArtifact,"getContractClassRegistryArtifact");async function getCanonicalClassRegistry(){if(!protocolContract){let contractClassRegistryArtifact=await getContractClassRegistryArtifact();protocolContract=makeProtocolContract("ContractClassRegistry",contractClassRegistryArtifact)}return protocolContract}__name(getCanonicalClassRegistry,"getCanonicalClassRegistry");var protocolContract2,protocolContractArtifact2;async function getFeeJuiceArtifact(){if(!protocolContractArtifact2){let{default:feeJuiceJson}=await import("./FeeJuice-O3KOSZO5.js");protocolContractArtifact2=loadContractArtifact(feeJuiceJson)}return protocolContractArtifact2}__name(getFeeJuiceArtifact,"getFeeJuiceArtifact");async function getCanonicalFeeJuice(){if(!protocolContract2){let feeJuiceArtifact=await getFeeJuiceArtifact();protocolContract2=makeProtocolContract("FeeJuice",feeJuiceArtifact)}return protocolContract2}__name(getCanonicalFeeJuice,"getCanonicalFeeJuice");var ContractInstancePublishedEvent=class _ContractInstancePublishedEvent{static{__name(this,"ContractInstancePublishedEvent")}address;version;salt;contractClassId;initializationHash;immutablesHash;publicKeys;deployer;constructor(address,version2,salt,contractClassId,initializationHash,immutablesHash,publicKeys,deployer){this.address=address,this.version=version2,this.salt=salt,this.contractClassId=contractClassId,this.initializationHash=initializationHash,this.immutablesHash=immutablesHash,this.publicKeys=publicKeys,this.deployer=deployer}static isContractInstancePublishedEvent(log2){return log2.fields[0].equals(CONTRACT_INSTANCE_PUBLISHED_EVENT_TAG)}static fromLog(log2){let bufferWithoutTag=log2.toBuffer().subarray(32),reader=new BufferReader(bufferWithoutTag),address=reader.readObject(AztecAddress),version2=reader.readObject(Fr).toNumber(),salt=reader.readObject(Fr),contractClassId=reader.readObject(Fr),initializationHash=reader.readObject(Fr),immutablesHash=reader.readObject(Fr),publicKeys=reader.readObject(PublicKeys),deployer=reader.readObject(AztecAddress);return new _ContractInstancePublishedEvent(address,version2,salt,contractClassId,initializationHash,immutablesHash,publicKeys,deployer)}toContractInstance(){if(this.version!==2)throw new Error(`Unexpected contract instance version ${this.version}`);return{address:this.address,version:this.version,currentContractClassId:this.contractClassId,originalContractClassId:this.contractClassId,initializationHash:this.initializationHash,immutablesHash:this.immutablesHash,publicKeys:this.publicKeys,salt:this.salt,deployer:this.deployer}}static extractContractInstanceEvents(logs){return logs.filter(log2=>_ContractInstancePublishedEvent.isContractInstancePublishedEvent(log2)).map(log2=>_ContractInstancePublishedEvent.fromLog(log2))}};var ContractInstanceUpdatedEvent=class _ContractInstanceUpdatedEvent{static{__name(this,"ContractInstanceUpdatedEvent")}address;prevContractClassId;newContractClassId;timestampOfChange;constructor(address,prevContractClassId,newContractClassId,timestampOfChange){this.address=address,this.prevContractClassId=prevContractClassId,this.newContractClassId=newContractClassId,this.timestampOfChange=timestampOfChange}static isContractInstanceUpdatedEvent(log2){return log2.contractAddress.equals(ProtocolContractAddress.ContractInstanceRegistry)&&log2.fields[0].toBigInt()===CONTRACT_INSTANCE_UPDATED_MAGIC_VALUE}static fromLog(log2){let reader=new FieldReader(log2.fields.slice(1)),address=reader.readObject(AztecAddress),prevContractClassId=reader.readField(),newContractClassId=reader.readField(),timestampOfChange=reader.readField().toBigInt();return new _ContractInstanceUpdatedEvent(address,prevContractClassId,newContractClassId,timestampOfChange)}toContractInstanceUpdate(){return{address:this.address,prevContractClassId:this.prevContractClassId,newContractClassId:this.newContractClassId,timestampOfChange:this.timestampOfChange}}};var protocolContract3,protocolContractArtifact3;async function getContractInstanceRegistryArtifact(){if(!protocolContractArtifact3){let{default:contractInstanceRegistryJson}=await import("./ContractInstanceRegistry-GCR4G4D7.js");protocolContractArtifact3=loadContractArtifact(contractInstanceRegistryJson)}return protocolContractArtifact3}__name(getContractInstanceRegistryArtifact,"getContractInstanceRegistryArtifact");async function getCanonicalInstanceRegistry(){if(!protocolContract3){let contractInstanceRegistryArtifact=await getContractInstanceRegistryArtifact();protocolContract3=makeProtocolContract("ContractInstanceRegistry",contractInstanceRegistryArtifact)}return protocolContract3}__name(getCanonicalInstanceRegistry,"getCanonicalInstanceRegistry");var LazyProtocolContractsProvider=class{static{__name(this,"LazyProtocolContractsProvider")}getProtocolContractArtifact(name){switch(name){case"ContractInstanceRegistry":return getCanonicalInstanceRegistry();case"ContractClassRegistry":return getCanonicalClassRegistry();case"FeeJuice":return getCanonicalFeeJuice();default:throw new Error(`Unknown protocol contract name: ${name}`)}}};function makeStandardContract(name,artifact){let address=StandardContractAddress[name],salt=StandardContractSalt[name],classId=StandardContractClassId[name],{artifactHash,privateFunctionsRoot,publicBytecodeCommitment}=StandardContractClassIdPreimage[name],initializationHash=StandardContractInitializationHash[name],contractClass={id:classId,version:1,artifactHash,privateFunctionsRoot,publicBytecodeCommitment,packedBytecode:artifact.functions.find(f=>f.name==="public_dispatch")?.bytecode??Buffer.alloc(0),privateFunctions:StandardContractPrivateFunctions[name]};return{instance:{version:2,currentContractClassId:classId,originalContractClassId:classId,initializationHash,immutablesHash:Fr.ZERO,publicKeys:PublicKeys.default(),salt,deployer:AztecAddress.ZERO,address},contractClass,artifact,address}}__name(makeStandardContract,"makeStandardContract");var STANDARD_AUTH_REGISTRY_ADDRESS=StandardContractAddress.AuthRegistry,STANDARD_AUTH_REGISTRY_CLASS_ID=StandardContractClassId.AuthRegistry,STANDARD_AUTH_REGISTRY_SALT=StandardContractSalt.AuthRegistry;var standardContract,standardContractArtifact;async function getAuthRegistryArtifact(){if(!standardContractArtifact){let{default:authRegistryJson}=await import("./AuthRegistry-D774QM2G.js");standardContractArtifact=loadContractArtifact(authRegistryJson)}return standardContractArtifact}__name(getAuthRegistryArtifact,"getAuthRegistryArtifact");async function getStandardAuthRegistry(){if(!standardContract){let artifact=await getAuthRegistryArtifact();standardContract=makeStandardContract("AuthRegistry",artifact)}return standardContract}__name(getStandardAuthRegistry,"getStandardAuthRegistry");var standardContract2,standardContractArtifact2;async function getHandshakeRegistryArtifact(){if(!standardContractArtifact2){let{default:handshakeRegistryJson}=await import("./HandshakeRegistry-4AIT55KH.js");standardContractArtifact2=loadContractArtifact(handshakeRegistryJson)}return standardContractArtifact2}__name(getHandshakeRegistryArtifact,"getHandshakeRegistryArtifact");async function getStandardHandshakeRegistry(){if(!standardContract2){let artifact=await getHandshakeRegistryArtifact();standardContract2=makeStandardContract("HandshakeRegistry",artifact)}return standardContract2}__name(getStandardHandshakeRegistry,"getStandardHandshakeRegistry");var STANDARD_MULTI_CALL_ENTRYPOINT_ADDRESS=StandardContractAddress.MultiCallEntrypoint,STANDARD_MULTI_CALL_ENTRYPOINT_CLASS_ID=StandardContractClassId.MultiCallEntrypoint,STANDARD_MULTI_CALL_ENTRYPOINT_SALT=StandardContractSalt.MultiCallEntrypoint;import{join as join5}from"path";import{addExtension as addExtension4}from"msgpackr";addExtension4({Class:Fr,write:__name(fr=>fr.toBuffer(),"write")});import{BundleArtifactProvider}from"@aztec/noir-protocol-circuits-types/client/bundle";import{strict as assert4}from"assert";function computeEffectiveGasFees(gasFees,gasSettings){let{maxFeesPerGas,maxPriorityFeesPerGas}=gasSettings,minBigInt=__name((f1,f2)=>f1<f2?f1:f2,"minBigInt");assert4(maxFeesPerGas.feePerDaGas>=gasFees.feePerDaGas,`maxFeesPerGas.feePerDaGas must be greater than or equal to gasFees.feePerDaGas, but got maxFeesPerGas.feePerDaGas=${maxFeesPerGas.feePerDaGas} and gasFees.feePerDaGas=${gasFees.feePerDaGas}`),assert4(maxFeesPerGas.feePerL2Gas>=gasFees.feePerL2Gas,`maxFeesPerGas.feePerL2Gas must be greater than or equal to gasFees.feePerL2Gas, but got maxFeesPerGas.feePerL2Gas=${maxFeesPerGas.feePerL2Gas} and gasFees.feePerL2Gas=${gasFees.feePerL2Gas}`);let priorityFees=new GasFees(minBigInt(maxPriorityFeesPerGas.feePerDaGas,maxFeesPerGas.feePerDaGas-gasFees.feePerDaGas),minBigInt(maxPriorityFeesPerGas.feePerL2Gas,maxFeesPerGas.feePerL2Gas-gasFees.feePerL2Gas));return new GasFees(gasFees.feePerDaGas+priorityFees.feePerDaGas,gasFees.feePerL2Gas+priorityFees.feePerL2Gas)}__name(computeEffectiveGasFees,"computeEffectiveGasFees");function computeTransactionFee(gasFees,gasSettings,gasUsed){let effectiveFees=computeEffectiveGasFees(gasFees,gasSettings);return gasUsed.computeFee(effectiveFees)}__name(computeTransactionFee,"computeTransactionFee");var WorldStateRevision=class _WorldStateRevision{static{__name(this,"WorldStateRevision")}forkId;blockNumber;includeUncommitted;static LATEST=4294967295;constructor(forkId,blockNumber,includeUncommitted){this.forkId=forkId,this.blockNumber=blockNumber,this.includeUncommitted=includeUncommitted}toString(){return`WorldStateRevision(forkId: ${this.forkId}, blockNumber: ${this.blockNumber}, includeUncommitted: ${this.includeUncommitted})`}static empty(){return new _WorldStateRevision(0,_WorldStateRevision.LATEST,!1)}static get schema(){return external_exports.object({forkId:external_exports.number(),blockNumber:external_exports.number(),includeUncommitted:external_exports.boolean()}).transform(({forkId,blockNumber,includeUncommitted})=>new _WorldStateRevision(forkId,blockNumber,includeUncommitted))}},WorldStateRevisionWithHandle=class _WorldStateRevisionWithHandle extends WorldStateRevision{static{__name(this,"WorldStateRevisionWithHandle")}handle;constructor(forkId,blockNumber,includeUncommitted,handle){super(forkId,blockNumber,includeUncommitted),this.handle=handle}toWorldStateRevision(){return new WorldStateRevision(this.forkId,this.blockNumber,this.includeUncommitted)}static fromWorldStateRevision(revision,handle){return new _WorldStateRevisionWithHandle(revision.forkId,revision.blockNumber,revision.includeUncommitted,handle)}static get schema(){return external_exports.object({forkId:external_exports.number(),blockNumber:external_exports.number(),includeUncommitted:external_exports.boolean(),handle:external_exports.any()}).transform(({forkId,blockNumber,includeUncommitted,handle})=>new _WorldStateRevisionWithHandle(forkId,blockNumber,includeUncommitted,handle))}};import{inspect as inspect37}from"util";import{inspect as inspect36}from"util";var _computedKey37,_computedKey113;_computedKey37=inspect36.custom;var AvmAccumulatedData=class _AvmAccumulatedData{static{__name(this,"AvmAccumulatedData")}noteHashes;nullifiers;l2ToL1Msgs;publicLogs;publicDataWrites;constructor(noteHashes,nullifiers,l2ToL1Msgs,publicLogs,publicDataWrites){this.noteHashes=noteHashes,this.nullifiers=nullifiers,this.l2ToL1Msgs=l2ToL1Msgs,this.publicLogs=publicLogs,this.publicDataWrites=publicDataWrites}static get schema(){return external_exports.object({noteHashes:schemas.Fr.array().min(64).max(64),nullifiers:schemas.Fr.array().min(64).max(64),l2ToL1Msgs:ScopedL2ToL1Message.schema.array().min(8).max(8),publicLogs:FlatPublicLogs.schema,publicDataWrites:PublicDataWrite.schema.array().min(64).max(64)}).transform(({noteHashes,nullifiers,l2ToL1Msgs,publicLogs,publicDataWrites})=>new _AvmAccumulatedData(assertLength(noteHashes,64),assertLength(nullifiers,64),assertLength(l2ToL1Msgs,8),publicLogs,assertLength(publicDataWrites,64)))}getSize(){return arraySerializedSizeOfNonEmpty(this.noteHashes)+arraySerializedSizeOfNonEmpty(this.nullifiers)+arraySerializedSizeOfNonEmpty(this.l2ToL1Msgs)+this.publicLogs.toBuffer().length+arraySerializedSizeOfNonEmpty(this.publicDataWrites)}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new this(reader.readArray(64,Fr),reader.readArray(64,Fr),reader.readArray(8,ScopedL2ToL1Message),reader.readObject(FlatPublicLogs),reader.readArray(64,PublicDataWrite))}toBuffer(){return serializeToBuffer(this.noteHashes,this.nullifiers,this.l2ToL1Msgs,this.publicLogs,this.publicDataWrites)}static getFields(fields){return[fields.noteHashes,fields.nullifiers,fields.l2ToL1Msgs,fields.publicLogs,fields.publicDataWrites]}static fromFields(fields){let reader=FieldReader.asReader(fields);return new this(reader.readFieldArray(64),reader.readFieldArray(64),reader.readArray(8,ScopedL2ToL1Message),reader.readObject(FlatPublicLogs),reader.readArray(64,PublicDataWrite))}toFields(){let fields=serializeToFields(..._AvmAccumulatedData.getFields(this));if(fields.length!==4377)throw new Error(`Invalid number of fields for AvmAccumulatedData. Expected ${4377}, got ${fields.length}`);return fields}static fromString(str){return this.fromBuffer(hexToBuffer(str))}toString(){return bufferToHex(this.toBuffer())}static empty(){return new this(makeTuple(64,Fr.zero),makeTuple(64,Fr.zero),makeTuple(8,ScopedL2ToL1Message.empty),FlatPublicLogs.empty(),makeTuple(64,PublicDataWrite.empty))}static fromPlainObject(obj){return new _AvmAccumulatedData(assertLength(obj.noteHashes.map(h=>Fr.fromPlainObject(h)),64),assertLength(obj.nullifiers.map(n=>Fr.fromPlainObject(n)),64),assertLength(obj.l2ToL1Msgs.map(m=>ScopedL2ToL1Message.fromPlainObject(m)),8),FlatPublicLogs.fromPlainObject(obj.publicLogs),assertLength(obj.publicDataWrites.map(w=>PublicDataWrite.fromPlainObject(w)),64))}isEmpty(){return this.noteHashes.every(x=>x.isZero())&&this.nullifiers.every(x=>x.isZero())&&this.l2ToL1Msgs.every(x=>x.isEmpty())&&this.publicLogs.isEmpty()&&this.publicDataWrites.every(x=>x.isEmpty())}[_computedKey37](){return`AvmAccumulatedData {
|
|
218
218
|
noteHashes: [${this.noteHashes.filter(x=>!x.isZero()).map(h=>inspect36(h)).join(", ")}],
|
|
219
219
|
nullifiers: [${this.nullifiers.filter(x=>!x.isZero()).map(h=>inspect36(h)).join(", ")}],
|
|
220
220
|
l2ToL1Msgs: [${this.l2ToL1Msgs.filter(x=>!x.isEmpty()).map(h=>inspect36(h)).join(", ")}],
|
|
@@ -265,4 +265,4 @@ Details: ${e2.message}`,[])),new TxSimRevertibleInsertionsRevert):e2}this.contra
|
|
|
265
265
|
z: ${inspect44(this.z)},
|
|
266
266
|
y: ${inspect44(this.y)},
|
|
267
267
|
c: ${inspect44(this.c)},
|
|
268
|
-
}`}};var FinalBlobBatchingChallenges=class _FinalBlobBatchingChallenges{static{__name(this,"FinalBlobBatchingChallenges")}z;gamma;constructor(z2,gamma){this.z=z2,this.gamma=gamma}equals(other){return this.z.equals(other.z)&&this.gamma.equals(other.gamma)}static empty(){return new _FinalBlobBatchingChallenges(Fr.ZERO,BLS12Fr.ZERO)}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _FinalBlobBatchingChallenges(Fr.fromBuffer(reader),reader.readObject(BLS12Fr))}toBuffer(){return serializeToBuffer(this.z,this.gamma)}};var ParityBasePrivateInputs=class _ParityBasePrivateInputs{static{__name(this,"ParityBasePrivateInputs")}msgs;vkTreeRoot;proverId;constructor(msgs,vkTreeRoot,proverId){this.msgs=msgs,this.vkTreeRoot=vkTreeRoot,this.proverId=proverId}static fromSlice(array2,index,vkTreeRoot,proverId){if(array2.length!==1024)throw new Error(`Msgs array length must be NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP=${1024}`);let start=index*256,end=start+256,msgs=array2.slice(start,end);return new _ParityBasePrivateInputs(msgs,vkTreeRoot,proverId)}toBuffer(){return serializeToBuffer(this.msgs,this.vkTreeRoot,this.proverId)}toString(){return bufferToHex(this.toBuffer())}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _ParityBasePrivateInputs(reader.readArray(256,Fr),Fr.fromBuffer(reader),Fr.fromBuffer(reader))}static fromString(str){return _ParityBasePrivateInputs.fromBuffer(hexToBuffer(str))}toJSON(){return this.toBuffer()}static get schema(){return bufferSchemaFor(_ParityBasePrivateInputs)}};var ParityPublicInputs=class _ParityPublicInputs{static{__name(this,"ParityPublicInputs")}shaRoot;convertedRoot;vkTreeRoot;proverId;constructor(shaRoot,convertedRoot,vkTreeRoot,proverId){if(this.shaRoot=shaRoot,this.convertedRoot=convertedRoot,this.vkTreeRoot=vkTreeRoot,this.proverId=proverId,shaRoot.toBuffer()[0]!=0)throw new Error("shaRoot buffer must be 31 bytes. Got 32 bytes")}toBuffer(){return serializeToBuffer(..._ParityPublicInputs.getFields(this))}toString(){return bufferToHex(this.toBuffer())}toJSON(){return this.toBuffer()}static from(fields){return new _ParityPublicInputs(..._ParityPublicInputs.getFields(fields))}static getFields(fields){return[fields.shaRoot,fields.convertedRoot,fields.vkTreeRoot,fields.proverId]}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _ParityPublicInputs(reader.readObject(Fr),reader.readObject(Fr),Fr.fromBuffer(reader),Fr.fromBuffer(reader))}static fromString(str){return _ParityPublicInputs.fromBuffer(hexToBuffer(str))}static get schema(){return bufferSchemaFor(_ParityPublicInputs)}};var ParityRootPrivateInputs=class _ParityRootPrivateInputs{static{__name(this,"ParityRootPrivateInputs")}children;constructor(children){this.children=children}toBuffer(){return serializeToBuffer(this.children)}toString(){return bufferToHex(this.toBuffer())}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _ParityRootPrivateInputs(makeTuple(4,()=>ProofData.fromBuffer(reader,ParityPublicInputs)))}static fromString(str){return _ParityRootPrivateInputs.fromBuffer(hexToBuffer(str))}toJSON(){return this.toBuffer()}static get schema(){return bufferSchemaFor(_ParityRootPrivateInputs)}};var BlockConstantData=class _BlockConstantData{static{__name(this,"BlockConstantData")}lastArchive;l1ToL2TreeSnapshot;vkTreeRoot;protocolContractsHash;globalVariables;proverId;constructor(lastArchive,l1ToL2TreeSnapshot,vkTreeRoot,protocolContractsHash2,globalVariables,proverId){this.lastArchive=lastArchive,this.l1ToL2TreeSnapshot=l1ToL2TreeSnapshot,this.vkTreeRoot=vkTreeRoot,this.protocolContractsHash=protocolContractsHash2,this.globalVariables=globalVariables,this.proverId=proverId}static from(fields){return new _BlockConstantData(..._BlockConstantData.getFields(fields))}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _BlockConstantData(reader.readObject(AppendOnlyTreeSnapshot),reader.readObject(AppendOnlyTreeSnapshot),Fr.fromBuffer(reader),Fr.fromBuffer(reader),reader.readObject(GlobalVariables),Fr.fromBuffer(reader))}static getFields(fields){return[fields.lastArchive,fields.l1ToL2TreeSnapshot,fields.vkTreeRoot,fields.protocolContractsHash,fields.globalVariables,fields.proverId]}static empty(){return new _BlockConstantData(AppendOnlyTreeSnapshot.empty(),AppendOnlyTreeSnapshot.empty(),Fr.ZERO,Fr.ZERO,GlobalVariables.empty(),Fr.ZERO)}toBuffer(){return serializeToBuffer(..._BlockConstantData.getFields(this))}};var TreeSnapshotDiffHints=class _TreeSnapshotDiffHints{static{__name(this,"TreeSnapshotDiffHints")}noteHashSubtreeRootSiblingPath;nullifierPredecessorPreimages;nullifierPredecessorMembershipWitnesses;sortedNullifiers;sortedNullifierIndexes;nullifierSubtreeRootSiblingPath;feePayerBalanceMembershipWitness;constructor(noteHashSubtreeRootSiblingPath,nullifierPredecessorPreimages,nullifierPredecessorMembershipWitnesses,sortedNullifiers,sortedNullifierIndexes,nullifierSubtreeRootSiblingPath,feePayerBalanceMembershipWitness){this.noteHashSubtreeRootSiblingPath=noteHashSubtreeRootSiblingPath,this.nullifierPredecessorPreimages=nullifierPredecessorPreimages,this.nullifierPredecessorMembershipWitnesses=nullifierPredecessorMembershipWitnesses,this.sortedNullifiers=sortedNullifiers,this.sortedNullifierIndexes=sortedNullifierIndexes,this.nullifierSubtreeRootSiblingPath=nullifierSubtreeRootSiblingPath,this.feePayerBalanceMembershipWitness=feePayerBalanceMembershipWitness}static from(fields){return new _TreeSnapshotDiffHints(..._TreeSnapshotDiffHints.getFields(fields))}static getFields(fields){return[fields.noteHashSubtreeRootSiblingPath,fields.nullifierPredecessorPreimages,fields.nullifierPredecessorMembershipWitnesses,fields.sortedNullifiers,fields.sortedNullifierIndexes,fields.nullifierSubtreeRootSiblingPath,fields.feePayerBalanceMembershipWitness]}toBuffer(){return serializeToBuffer(..._TreeSnapshotDiffHints.getFields(this))}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _TreeSnapshotDiffHints(reader.readArray(36,Fr),reader.readArray(64,NullifierLeafPreimage),reader.readArray(64,{fromBuffer:__name(buffer2=>MembershipWitness.fromBuffer(buffer2,42),"fromBuffer")}),reader.readArray(64,Fr),reader.readNumbers(64),reader.readArray(36,Fr),MembershipWitness.fromBuffer(reader,40))}static empty(){return new _TreeSnapshotDiffHints(makeTuple(36,Fr.zero),makeTuple(64,NullifierLeafPreimage.empty),makeTuple(64,()=>MembershipWitness.empty(42)),makeTuple(64,Fr.zero),makeTuple(64,()=>0),makeTuple(36,Fr.zero),MembershipWitness.empty(40))}};var PrivateBaseRollupHints=class _PrivateBaseRollupHints{static{__name(this,"PrivateBaseRollupHints")}start;startSpongeBlob;treeSnapshotDiffHints;feePayerBalanceLeafPreimage;anchorBlockArchiveSiblingPath;contractClassLogsFields;constants;constructor(start,startSpongeBlob,treeSnapshotDiffHints,feePayerBalanceLeafPreimage,anchorBlockArchiveSiblingPath,contractClassLogsFields,constants){this.start=start,this.startSpongeBlob=startSpongeBlob,this.treeSnapshotDiffHints=treeSnapshotDiffHints,this.feePayerBalanceLeafPreimage=feePayerBalanceLeafPreimage,this.anchorBlockArchiveSiblingPath=anchorBlockArchiveSiblingPath,this.contractClassLogsFields=contractClassLogsFields,this.constants=constants}static from(fields){return new _PrivateBaseRollupHints(..._PrivateBaseRollupHints.getFields(fields))}static getFields(fields){return[fields.start,fields.startSpongeBlob,fields.treeSnapshotDiffHints,fields.feePayerBalanceLeafPreimage,fields.anchorBlockArchiveSiblingPath,fields.contractClassLogsFields,fields.constants]}toBuffer(){return serializeToBuffer(..._PrivateBaseRollupHints.getFields(this))}toString(){return bufferToHex(this.toBuffer())}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _PrivateBaseRollupHints(reader.readObject(PartialStateReference),reader.readObject(SpongeBlob),reader.readObject(TreeSnapshotDiffHints),reader.readObject(PublicDataTreeLeafPreimage),reader.readArray(30,Fr),makeTuple(1,()=>reader.readObject(ContractClassLogFields)),reader.readObject(BlockConstantData))}static fromString(str){return _PrivateBaseRollupHints.fromBuffer(hexToBuffer(str))}static empty(){return new _PrivateBaseRollupHints(PartialStateReference.empty(),SpongeBlob.empty(),TreeSnapshotDiffHints.empty(),PublicDataTreeLeafPreimage.empty(),makeTuple(30,Fr.zero),makeTuple(1,ContractClassLogFields.empty),BlockConstantData.empty())}},PublicBaseRollupHints=class _PublicBaseRollupHints{static{__name(this,"PublicBaseRollupHints")}startSpongeBlob;lastArchive;anchorBlockArchiveSiblingPath;contractClassLogsFields;constructor(startSpongeBlob,lastArchive,anchorBlockArchiveSiblingPath,contractClassLogsFields){this.startSpongeBlob=startSpongeBlob,this.lastArchive=lastArchive,this.anchorBlockArchiveSiblingPath=anchorBlockArchiveSiblingPath,this.contractClassLogsFields=contractClassLogsFields}static from(fields){return new _PublicBaseRollupHints(..._PublicBaseRollupHints.getFields(fields))}static getFields(fields){return[fields.startSpongeBlob,fields.lastArchive,fields.anchorBlockArchiveSiblingPath,fields.contractClassLogsFields]}toBuffer(){return serializeToBuffer(..._PublicBaseRollupHints.getFields(this))}toString(){return bufferToHex(this.toBuffer())}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _PublicBaseRollupHints(reader.readObject(SpongeBlob),reader.readObject(AppendOnlyTreeSnapshot),reader.readArray(30,Fr),makeTuple(1,()=>reader.readObject(ContractClassLogFields)))}static fromString(str){return _PublicBaseRollupHints.fromBuffer(hexToBuffer(str))}static empty(){return new _PublicBaseRollupHints(SpongeBlob.empty(),AppendOnlyTreeSnapshot.empty(),makeTuple(30,Fr.zero),makeTuple(1,ContractClassLogFields.empty))}};import{inspect as inspect45}from"util";var _computedKey47;_computedKey47=inspect45.custom;var CheckpointConstantData=class _CheckpointConstantData{static{__name(this,"CheckpointConstantData")}chainId;version;vkTreeRoot;protocolContractsHash;proverId;slotNumber;coinbase;feeRecipient;gasFees;constructor(chainId,version2,vkTreeRoot,protocolContractsHash2,proverId,slotNumber,coinbase,feeRecipient,gasFees){this.chainId=chainId,this.version=version2,this.vkTreeRoot=vkTreeRoot,this.protocolContractsHash=protocolContractsHash2,this.proverId=proverId,this.slotNumber=slotNumber,this.coinbase=coinbase,this.feeRecipient=feeRecipient,this.gasFees=gasFees}static from(fields){return new _CheckpointConstantData(..._CheckpointConstantData.getFields(fields))}static getFields(fields){return[fields.chainId,fields.version,fields.vkTreeRoot,fields.protocolContractsHash,fields.proverId,fields.slotNumber,fields.coinbase,fields.feeRecipient,fields.gasFees]}static empty(){return new _CheckpointConstantData(Fr.ZERO,Fr.ZERO,Fr.ZERO,Fr.ZERO,Fr.ZERO,SlotNumber.ZERO,EthAddress.ZERO,AztecAddress.ZERO,GasFees.empty())}toBuffer(){return serializeToBuffer(this.chainId,this.version,this.vkTreeRoot,this.protocolContractsHash,this.proverId,new Fr(this.slotNumber),this.coinbase,this.feeRecipient,this.gasFees)}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _CheckpointConstantData(Fr.fromBuffer(reader),Fr.fromBuffer(reader),Fr.fromBuffer(reader),Fr.fromBuffer(reader),Fr.fromBuffer(reader),SlotNumber(Fr.fromBuffer(reader).toNumber()),reader.readObject(EthAddress),reader.readObject(AztecAddress),reader.readObject(GasFees))}getSlotNumber(){return this.slotNumber}toInspect(){return{chainId:this.chainId.toNumber(),version:this.version.toNumber(),vkTreeRoot:this.vkTreeRoot.toString(),protocolContractsHash:this.protocolContractsHash.toString(),proverId:this.proverId.toString(),slotNumber:this.slotNumber,coinbase:this.coinbase.toString(),feeRecipient:this.feeRecipient.toString(),gasFees:this.gasFees.toInspect()}}[_computedKey47](){return`CheckpointConstantData ${inspect45(this.toInspect())}`}};var BlockRollupPublicInputs=class _BlockRollupPublicInputs{static{__name(this,"BlockRollupPublicInputs")}constants;previousArchive;newArchive;startState;endState;startSpongeBlob;endSpongeBlob;timestamp;blockHeadersHash;inHash;outHash;accumulatedFees;accumulatedManaUsed;constructor(constants,previousArchive,newArchive,startState,endState,startSpongeBlob,endSpongeBlob,timestamp,blockHeadersHash,inHash,outHash,accumulatedFees,accumulatedManaUsed){this.constants=constants,this.previousArchive=previousArchive,this.newArchive=newArchive,this.startState=startState,this.endState=endState,this.startSpongeBlob=startSpongeBlob,this.endSpongeBlob=endSpongeBlob,this.timestamp=timestamp,this.blockHeadersHash=blockHeadersHash,this.inHash=inHash,this.outHash=outHash,this.accumulatedFees=accumulatedFees,this.accumulatedManaUsed=accumulatedManaUsed}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _BlockRollupPublicInputs(reader.readObject(CheckpointConstantData),reader.readObject(AppendOnlyTreeSnapshot),reader.readObject(AppendOnlyTreeSnapshot),reader.readObject(StateReference),reader.readObject(StateReference),reader.readObject(SpongeBlob),reader.readObject(SpongeBlob),reader.readUInt64(),Fr.fromBuffer(reader),Fr.fromBuffer(reader),Fr.fromBuffer(reader),Fr.fromBuffer(reader),Fr.fromBuffer(reader))}toBuffer(){return serializeToBuffer(this.constants,this.previousArchive,this.newArchive,this.startState,this.endState,this.startSpongeBlob,this.endSpongeBlob,bigintToUInt64BE(this.timestamp),this.blockHeadersHash,this.inHash,this.outHash,this.accumulatedFees,this.accumulatedManaUsed)}toString(){return bufferToHex(this.toBuffer())}static fromString(str){return _BlockRollupPublicInputs.fromBuffer(hexToBuffer(str))}toJSON(){return this.toBuffer()}toInspect(){return{previousArchiveRoot:this.previousArchive.root.toString(),newArchiveRoot:this.newArchive.root.toString(),blockHeadersHash:this.blockHeadersHash.toString(),inHash:this.inHash.toString(),outHash:this.outHash.toString(),timestamp:this.timestamp.toString(),accumulatedFees:this.accumulatedFees.toString(),accumulatedManaUsed:this.accumulatedManaUsed.toString()}}static get schema(){return bufferSchemaFor(_BlockRollupPublicInputs)}};var BlockMergeRollupPrivateInputs=class _BlockMergeRollupPrivateInputs{static{__name(this,"BlockMergeRollupPrivateInputs")}previousRollups;constructor(previousRollups){this.previousRollups=previousRollups}toBuffer(){return serializeToBuffer(this.previousRollups)}toString(){return bufferToHex(this.toBuffer())}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _BlockMergeRollupPrivateInputs([ProofData.fromBuffer(reader,BlockRollupPublicInputs),ProofData.fromBuffer(reader,BlockRollupPublicInputs)])}static fromString(str){return _BlockMergeRollupPrivateInputs.fromBuffer(hexToBuffer(str))}toJSON(){return this.toBuffer()}static get schema(){return bufferSchemaFor(_BlockMergeRollupPrivateInputs)}};var TxRollupPublicInputs=class _TxRollupPublicInputs{static{__name(this,"TxRollupPublicInputs")}numTxs;constants;startTreeSnapshots;endTreeSnapshots;startSpongeBlob;endSpongeBlob;outHash;accumulatedFees;accumulatedManaUsed;constructor(numTxs,constants,startTreeSnapshots,endTreeSnapshots,startSpongeBlob,endSpongeBlob,outHash,accumulatedFees,accumulatedManaUsed){this.numTxs=numTxs,this.constants=constants,this.startTreeSnapshots=startTreeSnapshots,this.endTreeSnapshots=endTreeSnapshots,this.startSpongeBlob=startSpongeBlob,this.endSpongeBlob=endSpongeBlob,this.outHash=outHash,this.accumulatedFees=accumulatedFees,this.accumulatedManaUsed=accumulatedManaUsed}static empty(){return new _TxRollupPublicInputs(0,BlockConstantData.empty(),PartialStateReference.empty(),PartialStateReference.empty(),SpongeBlob.empty(),SpongeBlob.empty(),Fr.zero(),Fr.zero(),Fr.zero())}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _TxRollupPublicInputs(reader.readNumber(),reader.readObject(BlockConstantData),reader.readObject(PartialStateReference),reader.readObject(PartialStateReference),reader.readObject(SpongeBlob),reader.readObject(SpongeBlob),Fr.fromBuffer(reader),Fr.fromBuffer(reader),Fr.fromBuffer(reader))}toBuffer(){return serializeToBuffer(this.numTxs,this.constants,this.startTreeSnapshots,this.endTreeSnapshots,this.startSpongeBlob,this.endSpongeBlob,this.outHash,this.accumulatedFees,this.accumulatedManaUsed)}toString(){return bufferToHex(this.toBuffer())}static fromString(str){return _TxRollupPublicInputs.fromBuffer(hexToBuffer(str))}toJSON(){return this.toBuffer()}static get schema(){return bufferSchemaFor(_TxRollupPublicInputs)}};var BlockRootFirstRollupPrivateInputs=class _BlockRootFirstRollupPrivateInputs{static{__name(this,"BlockRootFirstRollupPrivateInputs")}l1ToL2Roots;previousRollups;previousL1ToL2;newL1ToL2MessageSubtreeRootSiblingPath;newArchiveSiblingPath;constructor(l1ToL2Roots,previousRollups,previousL1ToL2,newL1ToL2MessageSubtreeRootSiblingPath,newArchiveSiblingPath){this.l1ToL2Roots=l1ToL2Roots,this.previousRollups=previousRollups,this.previousL1ToL2=previousL1ToL2,this.newL1ToL2MessageSubtreeRootSiblingPath=newL1ToL2MessageSubtreeRootSiblingPath,this.newArchiveSiblingPath=newArchiveSiblingPath}static from(fields){return new _BlockRootFirstRollupPrivateInputs(..._BlockRootFirstRollupPrivateInputs.getFields(fields))}static getFields(fields){return[fields.l1ToL2Roots,fields.previousRollups,fields.previousL1ToL2,fields.newL1ToL2MessageSubtreeRootSiblingPath,fields.newArchiveSiblingPath]}toBuffer(){return serializeToBuffer(..._BlockRootFirstRollupPrivateInputs.getFields(this))}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _BlockRootFirstRollupPrivateInputs(ProofData.fromBuffer(reader,ParityPublicInputs),[ProofData.fromBuffer(reader,TxRollupPublicInputs),ProofData.fromBuffer(reader,TxRollupPublicInputs)],AppendOnlyTreeSnapshot.fromBuffer(reader),reader.readArray(26,Fr),reader.readArray(30,Fr))}toJSON(){return this.toBuffer()}static get schema(){return bufferSchemaFor(_BlockRootFirstRollupPrivateInputs)}},BlockRootSingleTxFirstRollupPrivateInputs=class _BlockRootSingleTxFirstRollupPrivateInputs{static{__name(this,"BlockRootSingleTxFirstRollupPrivateInputs")}l1ToL2Roots;previousRollup;previousL1ToL2;newL1ToL2MessageSubtreeRootSiblingPath;newArchiveSiblingPath;constructor(l1ToL2Roots,previousRollup,previousL1ToL2,newL1ToL2MessageSubtreeRootSiblingPath,newArchiveSiblingPath){this.l1ToL2Roots=l1ToL2Roots,this.previousRollup=previousRollup,this.previousL1ToL2=previousL1ToL2,this.newL1ToL2MessageSubtreeRootSiblingPath=newL1ToL2MessageSubtreeRootSiblingPath,this.newArchiveSiblingPath=newArchiveSiblingPath}static from(fields){return new _BlockRootSingleTxFirstRollupPrivateInputs(..._BlockRootSingleTxFirstRollupPrivateInputs.getFields(fields))}static getFields(fields){return[fields.l1ToL2Roots,fields.previousRollup,fields.previousL1ToL2,fields.newL1ToL2MessageSubtreeRootSiblingPath,fields.newArchiveSiblingPath]}toBuffer(){return serializeToBuffer(..._BlockRootSingleTxFirstRollupPrivateInputs.getFields(this))}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _BlockRootSingleTxFirstRollupPrivateInputs(ProofData.fromBuffer(reader,ParityPublicInputs),ProofData.fromBuffer(reader,TxRollupPublicInputs),AppendOnlyTreeSnapshot.fromBuffer(reader),reader.readArray(26,Fr),reader.readArray(30,Fr))}toJSON(){return this.toBuffer()}static get schema(){return bufferSchemaFor(_BlockRootSingleTxFirstRollupPrivateInputs)}},BlockRootEmptyTxFirstRollupPrivateInputs=class _BlockRootEmptyTxFirstRollupPrivateInputs{static{__name(this,"BlockRootEmptyTxFirstRollupPrivateInputs")}l1ToL2Roots;previousArchive;previousState;constants;timestamp;newL1ToL2MessageSubtreeRootSiblingPath;newArchiveSiblingPath;constructor(l1ToL2Roots,previousArchive,previousState,constants,timestamp,newL1ToL2MessageSubtreeRootSiblingPath,newArchiveSiblingPath){this.l1ToL2Roots=l1ToL2Roots,this.previousArchive=previousArchive,this.previousState=previousState,this.constants=constants,this.timestamp=timestamp,this.newL1ToL2MessageSubtreeRootSiblingPath=newL1ToL2MessageSubtreeRootSiblingPath,this.newArchiveSiblingPath=newArchiveSiblingPath}static from(fields){return new _BlockRootEmptyTxFirstRollupPrivateInputs(..._BlockRootEmptyTxFirstRollupPrivateInputs.getFields(fields))}static getFields(fields){return[fields.l1ToL2Roots,fields.previousArchive,fields.previousState,fields.constants,fields.timestamp,fields.newL1ToL2MessageSubtreeRootSiblingPath,fields.newArchiveSiblingPath]}toBuffer(){return serializeToBuffer([this.l1ToL2Roots,this.previousArchive,this.previousState,this.constants,bigintToUInt64BE(this.timestamp),this.newL1ToL2MessageSubtreeRootSiblingPath,this.newArchiveSiblingPath])}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _BlockRootEmptyTxFirstRollupPrivateInputs(ProofData.fromBuffer(reader,ParityPublicInputs),AppendOnlyTreeSnapshot.fromBuffer(reader),StateReference.fromBuffer(reader),CheckpointConstantData.fromBuffer(reader),reader.readUInt64(),reader.readArray(26,Fr),reader.readArray(30,Fr))}toJSON(){return this.toBuffer()}static get schema(){return bufferSchemaFor(_BlockRootEmptyTxFirstRollupPrivateInputs)}},BlockRootRollupPrivateInputs=class _BlockRootRollupPrivateInputs{static{__name(this,"BlockRootRollupPrivateInputs")}previousRollups;newArchiveSiblingPath;constructor(previousRollups,newArchiveSiblingPath){this.previousRollups=previousRollups,this.newArchiveSiblingPath=newArchiveSiblingPath}static from(fields){return new _BlockRootRollupPrivateInputs(..._BlockRootRollupPrivateInputs.getFields(fields))}static getFields(fields){return[fields.previousRollups,fields.newArchiveSiblingPath]}toBuffer(){return serializeToBuffer(..._BlockRootRollupPrivateInputs.getFields(this))}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _BlockRootRollupPrivateInputs([ProofData.fromBuffer(reader,TxRollupPublicInputs),ProofData.fromBuffer(reader,TxRollupPublicInputs)],reader.readArray(30,Fr))}toJSON(){return this.toBuffer()}static get schema(){return bufferSchemaFor(_BlockRootRollupPrivateInputs)}},BlockRootSingleTxRollupPrivateInputs=class _BlockRootSingleTxRollupPrivateInputs{static{__name(this,"BlockRootSingleTxRollupPrivateInputs")}previousRollup;newArchiveSiblingPath;constructor(previousRollup,newArchiveSiblingPath){this.previousRollup=previousRollup,this.newArchiveSiblingPath=newArchiveSiblingPath}static from(fields){return new _BlockRootSingleTxRollupPrivateInputs(..._BlockRootSingleTxRollupPrivateInputs.getFields(fields))}static getFields(fields){return[fields.previousRollup,fields.newArchiveSiblingPath]}toBuffer(){return serializeToBuffer(..._BlockRootSingleTxRollupPrivateInputs.getFields(this))}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _BlockRootSingleTxRollupPrivateInputs(ProofData.fromBuffer(reader,TxRollupPublicInputs),reader.readArray(30,Fr))}toJSON(){return this.toBuffer()}static get schema(){return bufferSchemaFor(_BlockRootSingleTxRollupPrivateInputs)}};var EpochConstantData=class _EpochConstantData{static{__name(this,"EpochConstantData")}chainId;version;vkTreeRoot;protocolContractsHash;proverId;constructor(chainId,version2,vkTreeRoot,protocolContractsHash2,proverId){this.chainId=chainId,this.version=version2,this.vkTreeRoot=vkTreeRoot,this.protocolContractsHash=protocolContractsHash2,this.proverId=proverId}static from(fields){return new _EpochConstantData(..._EpochConstantData.getFields(fields))}static getFields(fields){return[fields.chainId,fields.version,fields.vkTreeRoot,fields.protocolContractsHash,fields.proverId]}toFields(){return serializeToFields(..._EpochConstantData.getFields(this))}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _EpochConstantData(Fr.fromBuffer(reader),Fr.fromBuffer(reader),Fr.fromBuffer(reader),Fr.fromBuffer(reader),Fr.fromBuffer(reader))}toBuffer(){return serializeToBuffer(..._EpochConstantData.getFields(this))}static empty(){return new _EpochConstantData(Fr.ZERO,Fr.ZERO,Fr.ZERO,Fr.ZERO,Fr.ZERO)}};var CheckpointRollupPublicInputs=class _CheckpointRollupPublicInputs{static{__name(this,"CheckpointRollupPublicInputs")}constants;previousArchive;newArchive;previousOutHash;newOutHash;checkpointHeaderHashes;fees;startBlobAccumulator;endBlobAccumulator;finalBlobChallenges;constructor(constants,previousArchive,newArchive,previousOutHash,newOutHash,checkpointHeaderHashes,fees,startBlobAccumulator,endBlobAccumulator,finalBlobChallenges){this.constants=constants,this.previousArchive=previousArchive,this.newArchive=newArchive,this.previousOutHash=previousOutHash,this.newOutHash=newOutHash,this.checkpointHeaderHashes=checkpointHeaderHashes,this.fees=fees,this.startBlobAccumulator=startBlobAccumulator,this.endBlobAccumulator=endBlobAccumulator,this.finalBlobChallenges=finalBlobChallenges}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _CheckpointRollupPublicInputs(reader.readObject(EpochConstantData),reader.readObject(AppendOnlyTreeSnapshot),reader.readObject(AppendOnlyTreeSnapshot),reader.readObject(AppendOnlyTreeSnapshot),reader.readObject(AppendOnlyTreeSnapshot),reader.readArray(32,Fr),reader.readArray(32,FeeRecipient),reader.readObject(BlobAccumulator),reader.readObject(BlobAccumulator),reader.readObject(FinalBlobBatchingChallenges))}toBuffer(){return serializeToBuffer(this.constants,this.previousArchive,this.newArchive,this.previousOutHash,this.newOutHash,this.checkpointHeaderHashes,this.fees,this.startBlobAccumulator,this.endBlobAccumulator,this.finalBlobChallenges)}toString(){return bufferToHex(this.toBuffer())}static fromString(str){return _CheckpointRollupPublicInputs.fromBuffer(hexToBuffer(str))}toJSON(){return this.toBuffer()}toInspect(){return{checkpointHeaderHash:this.checkpointHeaderHashes[0].toString(),previousArchiveRoot:this.previousArchive.root.toString(),newArchiveRoot:this.newArchive.root.toString(),previousOutHashRoot:this.previousOutHash.root.toString(),newOutHashRoot:this.newOutHash.root.toString()}}static get schema(){return bufferSchemaFor(_CheckpointRollupPublicInputs)}},FeeRecipient=class _FeeRecipient{static{__name(this,"FeeRecipient")}recipient;value;constructor(recipient,value){this.recipient=recipient,this.value=value}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _FeeRecipient(reader.readObject(EthAddress),Fr.fromBuffer(reader))}toBuffer(){return serializeToBuffer(this.recipient,this.value)}static getFields(fields){return[fields.recipient,fields.value]}toFields(){return serializeToFields(..._FeeRecipient.getFields(this))}static empty(){return new _FeeRecipient(EthAddress.ZERO,Fr.ZERO)}isEmpty(){return this.value.isZero()&&this.recipient.isZero()}toFriendlyJSON(){return this.isEmpty()?{}:{recipient:this.recipient.toString(),value:this.value.toString()}}static random(){return new _FeeRecipient(EthAddress.random(),Fr.random())}};var PrivateTxBaseRollupPrivateInputs=class _PrivateTxBaseRollupPrivateInputs{static{__name(this,"PrivateTxBaseRollupPrivateInputs")}hidingKernelProofData;hints;constructor(hidingKernelProofData,hints){this.hidingKernelProofData=hidingKernelProofData,this.hints=hints}static from(fields){return new _PrivateTxBaseRollupPrivateInputs(..._PrivateTxBaseRollupPrivateInputs.getFields(fields))}static getFields(fields){return[fields.hidingKernelProofData,fields.hints]}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _PrivateTxBaseRollupPrivateInputs(ProofData.fromBuffer(reader,PrivateToRollupKernelCircuitPublicInputs),reader.readObject(PrivateBaseRollupHints))}toBuffer(){return serializeToBuffer(..._PrivateTxBaseRollupPrivateInputs.getFields(this))}static fromString(str){return _PrivateTxBaseRollupPrivateInputs.fromBuffer(hexToBuffer(str))}toString(){return bufferToHex(this.toBuffer())}toJSON(){return this.toBuffer()}static get schema(){return bufferSchemaFor(_PrivateTxBaseRollupPrivateInputs)}};var PublicChonkVerifierPublicInputs=class _PublicChonkVerifierPublicInputs{static{__name(this,"PublicChonkVerifierPublicInputs")}privateTail;proverId;constructor(privateTail,proverId){this.privateTail=privateTail,this.proverId=proverId}static from(fields){return new _PublicChonkVerifierPublicInputs(..._PublicChonkVerifierPublicInputs.getFields(fields))}static getFields(fields){return[fields.privateTail,fields.proverId]}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _PublicChonkVerifierPublicInputs(reader.readObject(PrivateToPublicKernelCircuitPublicInputs),reader.readObject(Fr))}toBuffer(){return serializeToBuffer(..._PublicChonkVerifierPublicInputs.getFields(this))}static fromString(str){return _PublicChonkVerifierPublicInputs.fromBuffer(hexToBuffer(str))}toString(){return bufferToHex(this.toBuffer())}toJSON(){return this.toBuffer()}static get schema(){return bufferSchemaFor(_PublicChonkVerifierPublicInputs)}};var PublicTxBaseRollupPrivateInputs=class _PublicTxBaseRollupPrivateInputs{static{__name(this,"PublicTxBaseRollupPrivateInputs")}publicChonkVerifierProofData;avmProofData;hints;constructor(publicChonkVerifierProofData,avmProofData,hints){this.publicChonkVerifierProofData=publicChonkVerifierProofData,this.avmProofData=avmProofData,this.hints=hints}static from(fields){return new _PublicTxBaseRollupPrivateInputs(..._PublicTxBaseRollupPrivateInputs.getFields(fields))}static getFields(fields){return[fields.publicChonkVerifierProofData,fields.avmProofData,fields.hints]}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _PublicTxBaseRollupPrivateInputs(ProofData.fromBuffer(reader,PublicChonkVerifierPublicInputs),ProofDataForFixedVk.fromBuffer(reader,AvmCircuitPublicInputs),reader.readObject(PublicBaseRollupHints))}toBuffer(){return serializeToBuffer(..._PublicTxBaseRollupPrivateInputs.getFields(this))}static fromString(str){return _PublicTxBaseRollupPrivateInputs.fromBuffer(hexToBuffer(str))}toString(){return bufferToHex(this.toBuffer())}toJSON(){return this.toBuffer()}static get schema(){return bufferSchemaFor(_PublicTxBaseRollupPrivateInputs)}};var RootRollupPublicInputs=class _RootRollupPublicInputs{static{__name(this,"RootRollupPublicInputs")}previousArchiveRoot;endArchiveRoot;outHash;checkpointHeaderHashes;fees;constants;blobPublicInputs;constructor(previousArchiveRoot,endArchiveRoot,outHash,checkpointHeaderHashes,fees,constants,blobPublicInputs){this.previousArchiveRoot=previousArchiveRoot,this.endArchiveRoot=endArchiveRoot,this.outHash=outHash,this.checkpointHeaderHashes=checkpointHeaderHashes,this.fees=fees,this.constants=constants,this.blobPublicInputs=blobPublicInputs}static getFields(fields){return[fields.previousArchiveRoot,fields.endArchiveRoot,fields.outHash,fields.checkpointHeaderHashes,fields.fees,fields.constants,fields.blobPublicInputs]}toBuffer(){return serializeToBuffer(..._RootRollupPublicInputs.getFields(this))}toFields(){return serializeToFields(..._RootRollupPublicInputs.getFields(this))}static from(fields){return new _RootRollupPublicInputs(..._RootRollupPublicInputs.getFields(fields))}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _RootRollupPublicInputs(Fr.fromBuffer(reader),Fr.fromBuffer(reader),Fr.fromBuffer(reader),reader.readArray(32,Fr),reader.readArray(32,FeeRecipient),EpochConstantData.fromBuffer(reader),reader.readObject(FinalBlobAccumulator))}toString(){return bufferToHex(this.toBuffer())}static fromString(str){return _RootRollupPublicInputs.fromBuffer(hexToBuffer(str))}toJSON(){return this.toBuffer()}static get schema(){return bufferSchemaFor(_RootRollupPublicInputs)}static random(){return new _RootRollupPublicInputs(Fr.random(),Fr.random(),Fr.random(),makeTuple(32,Fr.random),makeTuple(32,FeeRecipient.random),new EpochConstantData(Fr.random(),Fr.random(),Fr.random(),Fr.random(),Fr.random()),FinalBlobAccumulator.random())}};var TxMergeRollupPrivateInputs=class _TxMergeRollupPrivateInputs{static{__name(this,"TxMergeRollupPrivateInputs")}previousRollups;constructor(previousRollups){this.previousRollups=previousRollups}toBuffer(){return serializeToBuffer(this.previousRollups)}toString(){return bufferToHex(this.toBuffer())}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _TxMergeRollupPrivateInputs([ProofData.fromBuffer(reader,TxRollupPublicInputs),ProofData.fromBuffer(reader,TxRollupPublicInputs)])}static fromString(str){return _TxMergeRollupPrivateInputs.fromBuffer(hexToBuffer(str))}toJSON(){return this.toBuffer()}static get schema(){return bufferSchemaFor(_TxMergeRollupPrivateInputs)}};function makeGlobalVariables(seed=1,overrides={}){return GlobalVariables.from({chainId:new Fr(seed),version:new Fr(seed+1),blockNumber:BlockNumber(seed+2),slotNumber:SlotNumber(seed+3),timestamp:BigInt(seed+4),coinbase:EthAddress.fromField(new Fr(seed+5)),feeRecipient:AztecAddress.fromFieldUnsafe(new Fr(seed+6)),gasFees:new GasFees(seed+7,seed+8),...compact(overrides)})}__name(makeGlobalVariables,"makeGlobalVariables");import{hashTypedData as hashTypedData2}from"viem";var TEST_COORDINATION_SIGNATURE_CONTEXT={chainId:31337,rollupAddress:EthAddress.fromNumber(1)};var DEFAULT_ADDRESS=AztecAddress.fromNumberUnsafe(42),MAX_PRIVATE_EVENT_LEN=10,MAX_PRIVATE_EVENTS_PER_TXE_QUERY=5,MAX_OFFCHAIN_EFFECTS_PER_TXE_QUERY=64,MAX_OFFCHAIN_EFFECT_LEN=17;function getSingleTxBlockRequestHash(blockNumber){return new Fr(blockNumber+9999)}__name(getSingleTxBlockRequestHash,"getSingleTxBlockRequestHash");async function insertTxEffectIntoWorldTrees(txEffect,worldTrees,l1ToL2Messages=[]){await worldTrees.appendLeaves(MerkleTreeId.NOTE_HASH_TREE,padArrayEnd(txEffect.noteHashes,Fr.ZERO,64)),await worldTrees.batchInsert(MerkleTreeId.NULLIFIER_TREE,padArrayEnd(txEffect.nullifiers,Fr.ZERO,64).map(nullifier=>nullifier.toBuffer()),6),await worldTrees.appendLeaves(MerkleTreeId.L1_TO_L2_MESSAGE_TREE,padArrayEnd(l1ToL2Messages,Fr.ZERO,1024))}__name(insertTxEffectIntoWorldTrees,"insertTxEffectIntoWorldTrees");async function makeTXEBlockHeader(worldTrees,globalVariables){let stateReference=await worldTrees.getStateReference(),archiveInfo=await worldTrees.getTreeInfo(MerkleTreeId.ARCHIVE);return BlockHeader.from({lastArchive:new AppendOnlyTreeSnapshot(new Fr(archiveInfo.root),Number(archiveInfo.size)),spongeBlobHash:Fr.ZERO,state:stateReference,globalVariables,totalFees:Fr.ZERO,totalManaUsed:Fr.ZERO})}__name(makeTXEBlockHeader,"makeTXEBlockHeader");async function makeTXEBlock(worldTrees,globalVariables,txEffects){let header=await makeTXEBlockHeader(worldTrees,globalVariables);await worldTrees.updateArchive(header);let newArchiveInfo=await worldTrees.getTreeInfo(MerkleTreeId.ARCHIVE),newArchive=new AppendOnlyTreeSnapshot(new Fr(newArchiveInfo.root),Number(newArchiveInfo.size)),checkpointNumber=CheckpointNumber.fromBlockNumber(globalVariables.blockNumber),indexWithinCheckpoint=IndexWithinCheckpoint(0);return new L2Block(newArchive,header,new Body(txEffects),checkpointNumber,indexWithinCheckpoint)}__name(makeTXEBlock,"makeTXEBlock");var TXEOraclePublicContext=class{constructor(contractAddress,forkedWorldTrees,txRequestHash,globalVariables,contractStore){this.contractAddress=contractAddress;this.forkedWorldTrees=forkedWorldTrees;this.txRequestHash=txRequestHash;this.globalVariables=globalVariables;this.contractStore=contractStore;this.logger=createLogger("txe:public_context"),this.logger.debug("Entering Public Context",{contractAddress,blockNumber:globalVariables.blockNumber,timestamp:globalVariables.timestamp})}static{__name(this,"TXEOraclePublicContext")}isAvm=!0;logger;transientUniqueNoteHashes=[];transientSiloedNullifiers=[];publicDataWrites=[];address(){return Promise.resolve(this.contractAddress)}sender(){return Promise.resolve(AztecAddress.ZERO)}blockNumber(){return Promise.resolve(this.globalVariables.blockNumber)}timestamp(){return Promise.resolve(this.globalVariables.timestamp)}isStaticCall(){return Promise.resolve(!1)}chainId(){return Promise.resolve(this.globalVariables.chainId)}version(){return Promise.resolve(this.globalVariables.version)}async emitNullifier(nullifier){let siloedNullifier=await siloNullifier(this.contractAddress,nullifier);this.transientSiloedNullifiers.push(siloedNullifier)}async emitNoteHash(noteHash){let siloedNoteHash=await siloNoteHash(this.contractAddress,noteHash);this.transientUniqueNoteHashes.push(siloedNoteHash)}async nullifierExists(siloedNullifier){let treeIndex=(await this.forkedWorldTrees.findLeafIndices(MerkleTreeId.NULLIFIER_TREE,[siloedNullifier.toBuffer()]))[0],transientIndex=this.transientSiloedNullifiers.find(n=>n.equals(siloedNullifier));return treeIndex!==void 0||transientIndex!==void 0}async storageWrite(slot,value){this.logger.debug("AVM storage write",{slot,value});let dataWrite=new PublicDataWrite(await computePublicDataTreeLeafSlot(this.contractAddress,slot),value);this.publicDataWrites.push(dataWrite),await this.forkedWorldTrees.sequentialInsert(MerkleTreeId.PUBLIC_DATA_TREE,[new PublicDataTreeLeaf(dataWrite.leafSlot,dataWrite.value).toBuffer()])}async storageRead(slot,contractAddress){let leafSlot=await computePublicDataTreeLeafSlot(contractAddress,slot),lowLeafResult=await this.forkedWorldTrees.getPreviousValueIndex(MerkleTreeId.PUBLIC_DATA_TREE,leafSlot.toBigInt()),value=!lowLeafResult||!lowLeafResult.alreadyPresent?Fr.ZERO:(await this.forkedWorldTrees.getLeafPreimage(MerkleTreeId.PUBLIC_DATA_TREE,lowLeafResult.index)).leaf.value;return this.logger.debug("AVM storage read",{slot,contractAddress,value}),value}getContractInstanceDeployer(address){return this.getContractInstanceMember(address,i=>i.deployer.toField())}getContractInstanceClassId(address){return this.getContractInstanceMember(address,i=>i.originalContractClassId)}getContractInstanceInitializationHash(address){return this.getContractInstanceMember(address,i=>i.initializationHash)}getContractInstanceImmutablesHash(address){return this.getContractInstanceMember(address,i=>i.immutablesHash)}async getContractInstanceMember(address,accessor){let instance=await this.contractStore.getContractInstance(address);return instance?{member:accessor(instance),exists:!0}:{member:Fr.ZERO,exists:!1}}returndataSize(){throw new Error("Contract calls are forbidden inside a `TestEnvironment::public_context`, use `public_call` instead")}returndataCopy(_rdOffset,_copySize){throw new Error("Contract calls are forbidden inside a `TestEnvironment::public_context`, use `public_call` instead")}call(_l2Gas,_daGas,_address,_argsLength,_args){throw new Error("Contract calls are forbidden inside a `TestEnvironment::public_context`, use `public_call` instead")}staticCall(_l2Gas,_daGas,_address,_argsLength,_args){throw new Error("Contract calls are forbidden inside a `TestEnvironment::public_context`, use `public_call` instead")}successCopy(){throw new Error("Contract calls are forbidden inside a `TestEnvironment::public_context`, use `public_call` instead")}async close(){this.logger.debug("Exiting Public Context, building block with collected side effects",{blockNumber:this.globalVariables.blockNumber});let txEffect=this.makeTxEffect();await insertTxEffectIntoWorldTrees(txEffect,this.forkedWorldTrees);let block=await makeTXEBlock(this.forkedWorldTrees,this.globalVariables,[txEffect]);return await this.forkedWorldTrees.close(),this.logger.debug("Exited PublicContext with built block",{blockNumber:block.number,txEffects:block.body.txEffects}),block}makeTxEffect(){let txEffect=TxEffect.empty();return txEffect.noteHashes=this.transientUniqueNoteHashes,txEffect.nullifiers=[this.txRequestHash,...this.transientSiloedNullifiers],txEffect.publicDataWrites=this.publicDataWrites,txEffect.txHash=new TxHash(new Fr(this.globalVariables.blockNumber)),txEffect}};var GAS_SETTINGS={deserialization:{fn:__name(([reader])=>GasSettings.fromFields(reader.readFieldArray(8)),"fn")},shape:[{len:8}]},STRATEGY_NON_INTERACTIVE_HANDSHAKE=1,STRATEGY_ARBITRARY_SECRET=2,STRATEGY_ADDRESS_DERIVED=3,TAGGING_SECRET_STRATEGY={serialization:{fn:__name(strategy=>{switch(strategy.type){case"non-interactive-handshake":return[new Fr(STRATEGY_NON_INTERACTIVE_HANDSHAKE),Fr.ZERO,Fr.ZERO];case"address-derived":return[new Fr(STRATEGY_ADDRESS_DERIVED),Fr.ZERO,Fr.ZERO];case"arbitrary-secret":return[new Fr(STRATEGY_ARBITRARY_SECRET),strategy.secret.x,strategy.secret.y]}},"fn")},deserialization:{fn:__name(([kindReader,xReader,yReader])=>{let kind=kindReader.readField().toNumber(),[x,y]=[xReader.readField(),yReader.readField()];switch(kind){case STRATEGY_NON_INTERACTIVE_HANDSHAKE:return{type:"non-interactive-handshake"};case STRATEGY_ADDRESS_DERIVED:return{type:"address-derived"};case STRATEGY_ARBITRARY_SECRET:return{type:"arbitrary-secret",secret:Point.fromFields([x,y])};default:throw new Error(`Unrecognized tagging secret strategy kind: ${kind}`)}},"fn")},shape:["scalar","scalar","scalar"]},PRIVATE_CONTEXT_INPUTS={serialization:{fn:__name(v=>v.toFields(),"fn")},shape:Array(37).fill("scalar")},COMPLETE_ADDRESS={serialization:{fn:__name(v=>[v.address.toField(),...v.publicKeys.toFields()],"fn")},shape:Array(8).fill("scalar")},TXE_TX_EFFECTS={serialization:{fn:__name(({txHash,noteHashes,nullifiers,privateLogs})=>{let emittedLogs=privateLogs.map(log2=>log2.getEmittedFields()),rawLogStorage=emittedLogs.map(fields=>fields.concat(Array(16-fields.length).fill(Fr.ZERO))).concat(Array(64-emittedLogs.length).fill(Array(16).fill(Fr.ZERO))).flat(),logLengths=emittedLogs.map(fields=>new Fr(fields.length)).concat(Array(64-emittedLogs.length).fill(Fr.ZERO)),paddedNoteHashes=noteHashes.concat(Array(64-noteHashes.length).fill(Fr.ZERO)),paddedNullifiers=nullifiers.concat(Array(64-nullifiers.length).fill(Fr.ZERO));return[txHash.hash,paddedNoteHashes,new Fr(noteHashes.length),paddedNullifiers,new Fr(nullifiers.length),rawLogStorage,logLengths,new Fr(emittedLogs.length)]},"fn")},shape:["scalar",{len:64},"scalar",{len:64},"scalar",{len:1024},{len:64},"scalar"]},TXE_OFFCHAIN_EFFECTS={serialization:{fn:__name(({effects})=>{let rawArrayStorage=effects.map(e2=>e2.concat(Array(MAX_OFFCHAIN_EFFECT_LEN-e2.length).fill(Fr.ZERO))).concat(Array(MAX_OFFCHAIN_EFFECTS_PER_TXE_QUERY-effects.length).fill(Array(MAX_OFFCHAIN_EFFECT_LEN).fill(Fr.ZERO))).flat(),effectLengths=effects.map(e2=>new Fr(e2.length)).concat(Array(MAX_OFFCHAIN_EFFECTS_PER_TXE_QUERY-effects.length).fill(Fr.ZERO));return[rawArrayStorage,effectLengths,new Fr(effects.length)]},"fn")},shape:[{len:MAX_OFFCHAIN_EFFECTS_PER_TXE_QUERY*MAX_OFFCHAIN_EFFECT_LEN},{len:MAX_OFFCHAIN_EFFECTS_PER_TXE_QUERY},"scalar"]},TXE_CALL_CONTEXT={serialization:{fn:__name(({txHash,anchorBlockTimestamp})=>{let isSome=txHash.isZero()?0:1;return[new Fr(isSome),txHash,new Fr(anchorBlockTimestamp)]},"fn")},shape:["scalar","scalar","scalar"]},CONTRACT_INSTANCE_MEMBER={serialization:{fn:__name(({member,exists})=>[member,new Fr(exists)],"fn")},shape:["scalar","scalar"]},EVENT_SELECTOR={serialization:{fn:__name(v=>[v.toField()],"fn")},deserialization:{fn:__name(([reader])=>EventSelector.fromField(reader.readField()),"fn")},shape:["scalar"]},TXE_PRIVATE_EVENTS={serialization:{fn:__name(events=>{let rawArrayStorage=events.map(e2=>e2.concat(Array(MAX_PRIVATE_EVENT_LEN-e2.length).fill(Fr.ZERO))).concat(Array(MAX_PRIVATE_EVENTS_PER_TXE_QUERY-events.length).fill(Array(MAX_PRIVATE_EVENT_LEN).fill(Fr.ZERO))).flat(),eventLengths=events.map(e2=>new Fr(e2.length)).concat(Array(MAX_PRIVATE_EVENTS_PER_TXE_QUERY-events.length).fill(Fr.ZERO));return[rawArrayStorage,eventLengths,new Fr(events.length)]},"fn")},shape:[{len:MAX_PRIVATE_EVENTS_PER_TXE_QUERY*MAX_PRIVATE_EVENT_LEN},{len:MAX_PRIVATE_EVENTS_PER_TXE_QUERY},"scalar"]},TXE_ORACLE_REGISTRY={...ORACLE_REGISTRY,aztec_txe_assertCompatibleOracleVersion:makeEntry({params:[{name:"major",type:U32},{name:"minor",type:U32}]}),aztec_txe_setTopLevelTXEContext:makeEntry(),aztec_txe_setPrivateTXEContext:makeEntry({params:[{name:"contractAddress",type:OPTION(AZTEC_ADDRESS)},{name:"anchorBlockNumber",type:OPTION(BLOCK_NUMBER)},{name:"gasSettings",type:GAS_SETTINGS}],returnType:PRIVATE_CONTEXT_INPUTS}),aztec_txe_setPublicTXEContext:makeEntry({params:[{name:"contractAddress",type:OPTION(AZTEC_ADDRESS)}]}),aztec_txe_setUtilityTXEContext:makeEntry({params:[{name:"contractAddress",type:OPTION(AZTEC_ADDRESS)}]}),aztec_txe_getDefaultAddress:makeEntry({returnType:AZTEC_ADDRESS}),aztec_txe_getNextBlockNumber:makeEntry({returnType:BLOCK_NUMBER}),aztec_txe_getNextBlockTimestamp:makeEntry({returnType:BIGINT}),aztec_txe_advanceBlocksBy:makeEntry({params:[{name:"blocks",type:U32}]}),aztec_txe_advanceTimestampBy:makeEntry({params:[{name:"duration",type:BIGINT}]}),aztec_txe_deploy:makeEntry({params:[{name:"contractPath",type:STR},{name:"initializer",type:STR},{name:"argsLength",type:U32},{name:"args",type:ARRAY(FIELD)},{name:"secret",type:FIELD},{name:"salt",type:FIELD},{name:"deployer",type:AZTEC_ADDRESS}],returnType:ARRAY(FIELD)}),aztec_txe_createAccount:makeEntry({params:[{name:"secret",type:FIELD}],returnType:COMPLETE_ADDRESS}),aztec_txe_addAccount:makeEntry({params:[{name:"secret",type:FIELD}],returnType:COMPLETE_ADDRESS}),aztec_txe_addAuthWitness:makeEntry({params:[{name:"address",type:AZTEC_ADDRESS},{name:"messageHash",type:FIELD}]}),aztec_txe_sendL1ToL2Message:makeEntry({params:[{name:"content",type:FIELD},{name:"secretHash",type:FIELD},{name:"sender",type:ETH_ADDRESS},{name:"recipient",type:AZTEC_ADDRESS}],returnType:FIELD}),aztec_txe_setTaggingSecretStrategy:makeEntry({params:[{name:"strategy",type:OPTION(TAGGING_SECRET_STRATEGY)}]}),aztec_txe_getLastBlockTimestamp:makeEntry({returnType:BIGINT}),aztec_txe_getLastTxEffects:makeEntry({returnType:TXE_TX_EFFECTS}),aztec_txe_getLastCallOffchainEffects:makeEntry({returnType:TXE_OFFCHAIN_EFFECTS}),aztec_txe_getLastCallContext:makeEntry({returnType:TXE_CALL_CONTEXT}),aztec_txe_getPrivateEvents:makeEntry({params:[{name:"selector",type:EVENT_SELECTOR},{name:"contractAddress",type:AZTEC_ADDRESS},{name:"scope",type:AZTEC_ADDRESS}],returnType:TXE_PRIVATE_EVENTS}),aztec_txe_privateCallNewFlow:makeEntry({params:[{name:"from",type:OPTION(AZTEC_ADDRESS)},{name:"targetContractAddress",type:AZTEC_ADDRESS},{name:"functionSelector",type:FUNCTION_SELECTOR},{name:"args",type:ARRAY(FIELD)},{name:"argsHash",type:FIELD},{name:"isStaticCall",type:BOOL},{name:"additionalScopes",type:ARRAY(AZTEC_ADDRESS)},{name:"authorizedUtilityCallTargets",type:ARRAY(AZTEC_ADDRESS)},{name:"gasSettings",type:GAS_SETTINGS}],returnType:ARRAY(FIELD)}),aztec_txe_executeUtilityFunction:makeEntry({params:[{name:"from",type:OPTION(AZTEC_ADDRESS)},{name:"targetContractAddress",type:AZTEC_ADDRESS},{name:"functionSelector",type:FUNCTION_SELECTOR},{name:"args",type:ARRAY(FIELD)},{name:"authorizedUtilityCallTargets",type:ARRAY(AZTEC_ADDRESS)}],returnType:ARRAY(FIELD)}),aztec_txe_publicCallNewFlow:makeEntry({params:[{name:"from",type:OPTION(AZTEC_ADDRESS)},{name:"address",type:AZTEC_ADDRESS},{name:"calldata",type:ARRAY(FIELD)},{name:"isStaticCall",type:BOOL},{name:"gasSettings",type:GAS_SETTINGS}],returnType:ARRAY(FIELD)}),aztec_avm_address:makeEntry({returnType:AZTEC_ADDRESS}),aztec_avm_sender:makeEntry({returnType:AZTEC_ADDRESS}),aztec_avm_blockNumber:makeEntry({returnType:BLOCK_NUMBER}),aztec_avm_timestamp:makeEntry({returnType:BIGINT}),aztec_avm_isStaticCall:makeEntry({returnType:BOOL}),aztec_avm_chainId:makeEntry({returnType:FIELD}),aztec_avm_version:makeEntry({returnType:FIELD}),aztec_avm_emitNullifier:makeEntry({params:[{name:"nullifier",type:FIELD}]}),aztec_avm_emitNoteHash:makeEntry({params:[{name:"noteHash",type:FIELD}]}),aztec_avm_nullifierExists:makeEntry({params:[{name:"siloedNullifier",type:FIELD}],returnType:BOOL}),aztec_avm_storageRead:makeEntry({params:[{name:"slot",type:FIELD},{name:"contractAddress",type:AZTEC_ADDRESS}],returnType:FIELD}),aztec_avm_storageWrite:makeEntry({params:[{name:"slot",type:FIELD},{name:"value",type:FIELD}]}),aztec_avm_emitPublicLog:makeEntry({params:[{name:"message",type:ARRAY(FIELD)}]}),aztec_avm_returndataSize:makeEntry({returnType:U32}),aztec_avm_returndataCopy:makeEntry({params:[{name:"rdOffset",type:U32},{name:"copySize",type:U32}],returnType:ARRAY(FIELD)}),aztec_avm_call:makeEntry({params:[{name:"l2Gas",type:U32},{name:"daGas",type:U32},{name:"address",type:AZTEC_ADDRESS},{name:"argsLength",type:U32},{name:"args",type:ARRAY(FIELD)}]}),aztec_avm_staticCall:makeEntry({params:[{name:"l2Gas",type:U32},{name:"daGas",type:U32},{name:"address",type:AZTEC_ADDRESS},{name:"argsLength",type:U32},{name:"args",type:ARRAY(FIELD)}]}),aztec_avm_successCopy:makeEntry({returnType:BOOL}),aztec_avm_getContractInstanceDeployer:makeEntry({params:[{name:"address",type:AZTEC_ADDRESS}],returnType:CONTRACT_INSTANCE_MEMBER}),aztec_avm_getContractInstanceClassId:makeEntry({params:[{name:"address",type:AZTEC_ADDRESS}],returnType:CONTRACT_INSTANCE_MEMBER}),aztec_avm_getContractInstanceInitializationHash:makeEntry({params:[{name:"address",type:AZTEC_ADDRESS}],returnType:CONTRACT_INSTANCE_MEMBER}),aztec_avm_getContractInstanceImmutablesHash:makeEntry({params:[{name:"address",type:AZTEC_ADDRESS}],returnType:CONTRACT_INSTANCE_MEMBER})};function toInputSlots(inputs){return inputs.map(v=>Array.isArray(v)?v.map(withHexPrefix):[withHexPrefix(v)])}__name(toInputSlots,"toInputSlots");async function callTxeHandler({oracle,inputs,handler}){let entry=TXE_ORACLE_REGISTRY[oracle],positional=entry.deserializeParams(toInputSlots(inputs)).map(p=>p.value),result=await handler(positional);return outputSlotsToForeignCallResult(entry.serializeReturn(result))}__name(callTxeHandler,"callTxeHandler");var legacyCallbacksByHandler=new WeakMap;async function callTxeLegacyHandler(oracle,inputs,oracleHandler){let callback=legacyCallbacksByHandler.get(oracleHandler);callback||(callback=buildACIRCallback(oracleHandler),legacyCallbacksByHandler.set(oracleHandler,callback));let outputSlots=await callback[oracle](...toInputSlots(inputs));return outputSlotsToForeignCallResult(outputSlots)}__name(callTxeLegacyHandler,"callTxeLegacyHandler");function outputSlotsToForeignCallResult(outputSlots){return{values:outputSlots.map(slot=>Array.isArray(slot)?slot.map(withoutHexPrefix):withoutHexPrefix(slot))}}__name(outputSlotsToForeignCallResult,"outputSlotsToForeignCallResult");import{BarretenbergSync as BarretenbergSync8}from"@aztec/bb.js";var SchnorrSignature=class _SchnorrSignature{static{__name(this,"SchnorrSignature")}buffer;static SIZE=64;constructor(buffer){if(this.buffer=buffer,buffer.length!==_SchnorrSignature.SIZE)throw new Error(`Invalid signature buffer of length ${buffer.length}.`)}get s(){return this.buffer.subarray(0,32)}get e(){return this.buffer.subarray(32)}toBuffer(){return this.buffer}toString(){return`0x${this.buffer.toString("hex")}`}toFields(){let sig=this.toBuffer(),buf1=Buffer.alloc(32),buf2=Buffer.alloc(32),buf3=Buffer.alloc(32);return sig.copy(buf1,1,0,31),sig.copy(buf2,1,31,62),sig.copy(buf3,1,62,64),mapTuple([buf1,buf2,buf3],Fr.fromBuffer)}toLimbFields(){let limb=__name(start=>{let buf=Buffer.alloc(32);return this.buffer.copy(buf,16,start,start+16),Fr.fromBuffer(buf)},"limb");return[limb(16),limb(0),limb(48),limb(32)]}};var Schnorr=class{static{__name(this,"Schnorr")}async computePublicKey(privateKey){await BarretenbergSync8.initSingleton();let response=BarretenbergSync8.getSingleton().schnorrComputePublicKey({privateKey:privateKey.toBuffer()});return Point.fromBuffer(Buffer.concat([Buffer.from(response.publicKey.x),Buffer.from(response.publicKey.y)]))}async constructSignature(msg,privateKey){await BarretenbergSync8.initSingleton();let response=BarretenbergSync8.getSingleton().schnorrConstructSignature({messageField:msg.toBuffer(),privateKey:privateKey.toBuffer()});return new SchnorrSignature(Buffer.from([...response.s,...response.e]))}async verifySignature(msg,pubKey,sig){return await BarretenbergSync8.initSingleton(),BarretenbergSync8.getSingleton().schnorrVerifySignature({messageField:msg.toBuffer(),publicKey:{x:pubKey.x.toBuffer(),y:pubKey.y.toBuffer()},s:sig.s,e:sig.e}).verified}};var TXEPublicContractDataSource=class{constructor(blockNumber,contractStore){this.blockNumber=blockNumber;this.contractStore=contractStore}static{__name(this,"TXEPublicContractDataSource")}getBlockNumber(){return Promise.resolve(this.blockNumber)}async getContractClass(id){let contractClass=await this.contractStore.getContractClassWithPreimage(id);if(contractClass)return{id:contractClass.id,artifactHash:contractClass.artifactHash,packedBytecode:contractClass.packedBytecode,privateFunctionsRoot:contractClass.privateFunctionsRoot,version:contractClass.version}}async getBytecodeCommitment(id){return(await this.contractStore.getContractClassWithPreimage(id))?.publicBytecodeCommitment}async getContract(address){let instance=await this.contractStore.getContractInstance(address);return instance&&{...instance,address,currentContractClassId:instance.originalContractClassId}}getContractClassIds(){throw new Error("Method not implemented.")}async getContractArtifact(address){let instance=await this.getContract(address);return instance&&this.contractStore.getContractArtifact(instance.originalContractClassId)}async getDebugFunctionName(address,selector){let instance=await this.getContract(address);return instance&&this.contractStore.getDebugFunctionName(instance.originalContractClassId,selector)}registerContractFunctionSignatures(_signatures){return Promise.resolve()}};var TXEOracleTopLevelContext=class{constructor(stateMachine,contractStore,noteStore,keyStore,addressStore,accountStore,senderTaggingStore,recipientTaggingStore,taggingSecretSourcesStore,capsuleStore,factStore,privateEventStore,nextBlockTimestamp,version2,chainId,authwits,taggingSecretStrategy,artifactResolver,rootPath,packageName){this.stateMachine=stateMachine;this.contractStore=contractStore;this.noteStore=noteStore;this.keyStore=keyStore;this.addressStore=addressStore;this.accountStore=accountStore;this.senderTaggingStore=senderTaggingStore;this.recipientTaggingStore=recipientTaggingStore;this.taggingSecretSourcesStore=taggingSecretSourcesStore;this.capsuleStore=capsuleStore;this.factStore=factStore;this.privateEventStore=privateEventStore;this.nextBlockTimestamp=nextBlockTimestamp;this.version=version2;this.chainId=chainId;this.authwits=authwits;this.taggingSecretStrategy=taggingSecretStrategy;this.artifactResolver=artifactResolver;this.rootPath=rootPath;this.packageName=packageName;this.logger=createLogger("txe:top_level_context"),this.logger.debug("Entering Top Level Context")}static{__name(this,"TXEOracleTopLevelContext")}isMisc=!0;isTxe=!0;logger;contractOracleVersion;assertCompatibleOracleVersion(major2,minor){if(major2!==30){let hint=major2>30?"The contract was compiled with a newer version of Aztec.nr than this aztec cli version supports. Upgrade your aztec cli version to a compatible version.":"The contract was compiled with an older version of Aztec.nr than this aztec cli version supports. Recompile the contract with a compatible version of Aztec.nr.";throw new Error(`Incompatible aztec cli version: ${hint} See https://docs.aztec.network/errors/8 (expected oracle major version ${30}, got ${major2})`)}this.contractOracleVersion={major:major2,minor}}nonOracleFunctionGetContractOracleVersion(){return this.contractOracleVersion}getRandomField(){return Fr.random()}log(level,message,_fieldsSize,fields){if(!LogLevels[level])throw new Error(`Invalid log level: ${level}`);let levelName=LogLevels[level];return this.logger[levelName](`${applyStringFormatting(message,fields)}`,{module:`${this.logger.module}:debug_log`}),Promise.resolve()}getDefaultAddress(){return DEFAULT_ADDRESS}async getNextBlockNumber(){return BlockNumber(await this.getLastBlockNumber()+1)}getNextBlockTimestamp(){return Promise.resolve(this.nextBlockTimestamp)}async getLastBlockTimestamp(){return(await this.stateMachine.node.getBlockData("latest")).header.globalVariables.timestamp}async getLastTxEffects(){let latestBlockNumber=await this.stateMachine.archiver.getBlockNumber(),block=await this.stateMachine.archiver.getBlock({number:latestBlockNumber});if(block.body.txEffects.length!=1)throw new Error(`Expected a single transaction in the last block, found ${block.body.txEffects.length}`);let txEffects=block.body.txEffects[0],privateLogs=txEffects.privateLogs;if(privateLogs.length>64)throw new Error(`${privateLogs.length} private logs exceed max ${64}`);return{txHash:txEffects.txHash,noteHashes:txEffects.noteHashes,nullifiers:txEffects.nullifiers,privateLogs}}async syncContractNonOracleMethod(contractAddress,scope,jobId){if(contractAddress.equals(DEFAULT_ADDRESS)){this.logger.debug("Skipping sync in getPrivateEvents because the events correspond to the default address.");return}let blockHeader=await this.stateMachine.anchorBlockStore.getBlockHeader();await this.stateMachine.contractSyncService.ensureContractSynced(contractAddress,null,async(call,execScopes)=>{await this.executeUtilityCall(call,{scopes:execScopes,jobId})},blockHeader,jobId,[scope])}async getPrivateEvents(selector,contractAddress,scope){let events=(await this.privateEventStore.getPrivateEvents(selector,{contractAddress,scopes:[scope],fromBlock:0,toBlock:await this.getLastBlockNumber()+1})).map(e2=>e2.packedEvent);if(events.length>MAX_PRIVATE_EVENTS_PER_TXE_QUERY)throw new Error(`Array of length ${events.length} larger than maxLen ${MAX_PRIVATE_EVENTS_PER_TXE_QUERY}`);if(events.some(e2=>e2.length>MAX_PRIVATE_EVENT_LEN))throw new Error(`Some private event has length larger than maxLen ${MAX_PRIVATE_EVENT_LEN}`);return events}async advanceBlocksBy(blocks){this.logger.debug(`time traveling ${blocks} blocks`);for(let i=0;i<blocks;i++)await this.mineBlock()}advanceTimestampBy(duration3){this.logger.debug(`time traveling ${duration3} seconds`),this.nextBlockTimestamp+=duration3}deploymentNullifier(address){return siloNullifier(AztecAddress.fromNumberUnsafe(2),address.toField())}async deploy(contractPath,initializer3,args,secret,salt,deployer){let{artifact,instance}=await this.artifactResolver.resolveDeployArtifact({rootPath:this.rootPath,packageName:this.packageName,contractPath,initializer:initializer3,args,secret,salt,deployer});return await this.mineBlock({nullifiers:[await this.deploymentNullifier(instance.address)]}),secret.equals(Fr.ZERO)?(await this.contractStore.addContractInstance(instance),await this.contractStore.addContractArtifact(artifact),this.logger.debug(`Deployed ${artifact.name} at ${instance.address}`)):await this.registerContractAndAddAccount(artifact,instance,secret),CONTRACT_INSTANCE.serialization.fn(instance).flat()}async mineDeploymentNullifiers(addresses){await this.mineBlock({nullifiers:await Promise.all(addresses.map(address=>this.deploymentNullifier(address)))})}async addAccount(secret){let{artifact,instance}=await this.artifactResolver.resolveAccountArtifact(secret);return this.registerContractAndAddAccount(artifact,instance,secret)}async registerContractAndAddAccount(artifact,instance,secret){let partialAddress=await computePartialAddress(instance);this.logger.debug(`Deployed ${artifact.name} at ${instance.address}`),await this.contractStore.addContractInstance(instance),await this.contractStore.addContractArtifact(artifact);let completeAddress=await this.keyStore.addAccount(await deriveKeys(secret),partialAddress);return await this.accountStore.setAccount(completeAddress.address,completeAddress),await this.addressStore.addCompleteAddress(completeAddress),this.logger.debug(`Created account ${completeAddress.address}`),completeAddress}async createAccount(secret){let completeAddress=await this.keyStore.addAccount(await deriveKeys(secret),secret);return await this.accountStore.setAccount(completeAddress.address,completeAddress),await this.addressStore.addCompleteAddress(completeAddress),this.logger.debug(`Created account ${completeAddress.address}`),completeAddress}async addAuthWitness(address,messageHash){let account=await this.accountStore.getAccount(address),ivpkMHash=await hashPublicKey(account.publicKeys.ivpkM),privateKey=await this.keyStore.getMasterSecretKey(ivpkMHash),signature=await new Schnorr().constructSignature(messageHash,privateKey),authWitness=new AuthWitness(messageHash,signature.toLimbFields());this.authwits.set(authWitness.requestHash.toString(),authWitness)}setTaggingSecretStrategy(strategy){this.taggingSecretStrategy=strategy.value}async sendL1ToL2Message(content,secretHash,sender,recipient){let{size}=await this.stateMachine.synchronizer.getCommitted().getTreeInfo(MerkleTreeId.L1_TO_L2_MESSAGE_TREE),leafIndex=new Fr(size),message=new L1ToL2Message(new L1Actor(sender,this.chainId.toNumber()),new L2Actor(recipient,this.version.toNumber()),content,secretHash,leafIndex);return await this.mineBlock({l1ToL2Messages:[message.hash()]}),leafIndex}async mineBlock(options={}){let blockNumber=await this.getNextBlockNumber(),txEffect=TxEffect.empty();txEffect.nullifiers=[getSingleTxBlockRequestHash(blockNumber),...options.nullifiers??[]],txEffect.txHash=new TxHash(new Fr(blockNumber));let forkedWorldTrees=await this.stateMachine.synchronizer.nativeWorldStateService.fork();await insertTxEffectIntoWorldTrees(txEffect,forkedWorldTrees,options.l1ToL2Messages??[]);let globals=makeGlobalVariables(void 0,{blockNumber,timestamp:this.nextBlockTimestamp,version:this.version,chainId:this.chainId}),block=await makeTXEBlock(forkedWorldTrees,globals,[txEffect]);await forkedWorldTrees.close(),this.logger.info(`Created block ${blockNumber} with timestamp ${block.header.globalVariables.timestamp}`),await this.stateMachine.handleL2Block(block,options.l1ToL2Messages??[])}async privateCallNewFlow(from,targetContractAddress=AztecAddress.zero(),functionSelector=FunctionSelector.empty(),args,argsHash=Fr.zero(),isStaticCall=!1,additionalScopes=[],jobId,authorizedUtilityCallTargets,gasSettings){let blockHeader=await this.stateMachine.anchorBlockStore.getBlockHeader(),anchoredContractData=new AnchoredContractData(this.contractStore,this.stateMachine.contractClassService,blockHeader);this.logger.verbose(`Executing external function ${await anchoredContractData.getDebugFunctionName(targetContractAddress,functionSelector)}@${targetContractAddress} isStaticCall=${isStaticCall}`);let artifact=await anchoredContractData.getFunctionArtifact(targetContractAddress,functionSelector);if(!artifact){let message=functionSelector.equals(await FunctionSelector.fromSignature("verify_private_authwit(Field)"))?"Found no account contract artifact for a private authwit check - use `create_contract_account` instead of `create_light_account` for authwit support.":"Function Artifact does not exist";throw new Error(message)}let scopes=from===void 0?additionalScopes:[from,...additionalScopes],utilityExecutor=__name(async(call,execScopes)=>{await this.executeUtilityCall(call,{scopes:execScopes,jobId})},"utilityExecutor");await this.stateMachine.contractSyncService.ensureContractSynced(targetContractAddress,functionSelector,utilityExecutor,blockHeader,jobId,scopes);let blockNumber=await this.getNextBlockNumber(),msgSender=from??AztecAddress.NULL_MSG_SENDER,callContext=new CallContext(msgSender,targetContractAddress,functionSelector,isStaticCall),txContext=new TxContext(this.chainId,this.version,gasSettings),protocolNullifier=await computeProtocolNullifier(getSingleTxBlockRequestHash(blockNumber)),noteCache=new ExecutionNoteCache(protocolNullifier),minRevertibleSideEffectCounter=1;await noteCache.setMinRevertibleSideEffectCounter(minRevertibleSideEffectCounter);let taggingIndexCache=new ExecutionTaggingIndexCache,simulator=new WASMSimulator,transientArrayService=new TransientArrayService,taggingSecretStrategy=this.taggingSecretStrategy,privateExecutionOracle=new PrivateExecutionOracle({argsHash,txContext,callContext,anchorBlockHeader:blockHeader,utilityExecutor,authWitnesses:Array.from(this.authwits.values()),capsules:[],executionCache:HashedValuesCache.create([new HashedValues(args,argsHash)]),noteCache,taggingIndexCache,anchoredContractData,noteStore:this.noteStore,keyStore:this.keyStore,addressStore:this.addressStore,aztecNode:this.stateMachine.node,senderTaggingStore:this.senderTaggingStore,recipientTaggingStore:this.recipientTaggingStore,taggingSecretSourcesStore:this.taggingSecretSourcesStore,capsuleService:new CapsuleService(this.capsuleStore,scopes),factService:new FactService(this.factStore,scopes),privateEventStore:this.privateEventStore,contractSyncService:this.stateMachine.contractSyncService,jobId,totalPublicCalldataCount:0,sideEffectCounter:minRevertibleSideEffectCounter,scopes,senderForTags:from,simulator,txResolver:this.stateMachine.txResolver,l2TipsStore:this.stateMachine.l2TipsProvider,hooks:composeHooks({authorizeUtilityCall:this.buildAuthorizeUtilityCallHook(isStaticCall?"private view":"private",authorizedUtilityCallTargets),resolveTaggingSecretStrategy:taggingSecretStrategy?()=>Promise.resolve(taggingSecretStrategy):void 0}),transientArrayService}),result,executionResult;try{executionResult=await executePrivateFunction(simulator,privateExecutionOracle,artifact,targetContractAddress,functionSelector);let publicCallRequests=collectNested([executionResult],r2=>r2.publicInputs.publicCallRequests.getActiveItems().map(r3=>r3.inner).concat(r2.publicInputs.publicTeardownCallRequest.isEmpty()?[]:[r2.publicInputs.publicTeardownCallRequest])),publicFunctionsCalldata=await Promise.all(publicCallRequests.map(async r2=>{let calldata=await privateExecutionOracle.getHashPreimage(r2.calldataHash);return new HashedValues(calldata,r2.calldataHash)}));noteCache.finish();let nonceGenerator=noteCache.getNonceGenerator();result=new PrivateExecutionResult(executionResult,nonceGenerator,publicFunctionsCalldata)}catch(err){throw createSimulationError(err instanceof Error?err:new Error("Unknown error during private execution"))}let{publicInputs}=await generateSimulatedProvingResult(result,(addr,sel)=>anchoredContractData.getDebugFunctionName(addr,sel),this.stateMachine.node,minRevertibleSideEffectCounter),globals=makeGlobalVariables();globals.blockNumber=blockNumber,globals.timestamp=this.nextBlockTimestamp,globals.chainId=this.chainId,globals.version=this.version,globals.gasFees=GasFees.empty();let forkedWorldTrees=await this.stateMachine.synchronizer.nativeWorldStateService.fork(),bindings=this.logger.getBindings(),contractsDB=new PublicContractsDB(new TXEPublicContractDataSource(blockNumber,this.contractStore),bindings),guardedMerkleTrees=new GuardedMerkleTreeOperations(forkedWorldTrees),config2=PublicSimulatorConfig.from({skipFeeEnforcement:!0,collectDebugLogs:!0,collectHints:!1,collectStatistics:!1,collectCallMetadata:!0}),processor=new PublicProcessor(globals,guardedMerkleTrees,contractsDB,new CppPublicTxSimulator(guardedMerkleTrees,contractsDB,globals,config2,bindings),new TestDateProvider,void 0,createLogger("simulator:public-processor",bindings)),tx=await Tx.create({data:publicInputs,chonkProof:ChonkProof.empty(),contractClassLogFields:[],publicFunctionCalldata:result.publicFunctionCalldata}),checkpoint;isStaticCall&&(checkpoint=await ForkCheckpoint.new(forkedWorldTrees));let results=await processor.process([tx]),[processedTx]=results[0],failedTxs=results[1];if(failedTxs.length!==0)throw new Error(`Public execution has failed: ${failedTxs[0].error}`);if(!processedTx.revertCode.isOK())if(processedTx.revertReason){try{await enrichPublicSimulationError(processedTx.revertReason,this.contractStore,this.stateMachine.contractClassService,await this.stateMachine.anchorBlockStore.getBlockHeader(),this.logger)}catch{}throw new Error(`Contract execution has reverted: ${processedTx.revertReason.getMessage()}`)}else throw new Error("Contract execution has reverted");let offchainEffects=collectNested([executionResult],r2=>r2.offchainEffects.map(e2=>e2.data));if(isStaticCall)return await checkpoint.revert(),await forkedWorldTrees.close(),{returnValues:executionResult.returnValues??[],offchainEffects};let txEffect=TxEffect.empty();txEffect.noteHashes=processedTx.txEffect.noteHashes,txEffect.nullifiers=processedTx.txEffect.nullifiers,txEffect.privateLogs=processedTx.txEffect.privateLogs,txEffect.publicLogs=processedTx.txEffect.publicLogs,txEffect.publicDataWrites=processedTx.txEffect.publicDataWrites,txEffect.txHash=new TxHash(new Fr(blockNumber));let l1ToL2Messages=Array(1024).fill(0).map(Fr.zero);await forkedWorldTrees.appendLeaves(MerkleTreeId.L1_TO_L2_MESSAGE_TREE,l1ToL2Messages);let l2Block=await makeTXEBlock(forkedWorldTrees,globals,[txEffect]);return await this.stateMachine.handleL2Block(l2Block),await forkedWorldTrees.close(),{returnValues:executionResult.returnValues??[],offchainEffects}}async publicCallNewFlow(from,targetContractAddress,calldata,isStaticCall,gasSettings){let anchorBlockHeader=await this.stateMachine.anchorBlockStore.getBlockHeader(),anchoredContractData=new AnchoredContractData(this.contractStore,this.stateMachine.contractClassService,anchorBlockHeader);this.logger.verbose(`Executing public function ${await anchoredContractData.getDebugFunctionName(targetContractAddress,FunctionSelector.fromField(calldata[0]))}@${targetContractAddress} isStaticCall=${isStaticCall}`);let blockNumber=await this.getNextBlockNumber(),txContext=new TxContext(this.chainId,this.version,gasSettings),calldataHash=await computeCalldataHash(calldata),calldataHashedValues=new HashedValues(calldata,calldataHash),globals=makeGlobalVariables();globals.blockNumber=blockNumber,globals.timestamp=this.nextBlockTimestamp,globals.chainId=this.chainId,globals.version=this.version,globals.gasFees=GasFees.empty();let forkedWorldTrees=await this.stateMachine.synchronizer.nativeWorldStateService.fork(),bindings2=this.logger.getBindings(),contractsDB=new PublicContractsDB(new TXEPublicContractDataSource(blockNumber,this.contractStore),bindings2),guardedMerkleTrees=new GuardedMerkleTreeOperations(forkedWorldTrees),config2=PublicSimulatorConfig.from({skipFeeEnforcement:!0,collectDebugLogs:!0,collectHints:!1,collectStatistics:!1,collectCallMetadata:!0}),simulator=new CppPublicTxSimulator(guardedMerkleTrees,contractsDB,globals,config2,bindings2),processor=new PublicProcessor(globals,guardedMerkleTrees,contractsDB,simulator,new TestDateProvider,void 0,createLogger("simulator:public-processor",bindings2)),nonRevertibleAccumulatedData=PrivateToPublicAccumulatedData.empty();nonRevertibleAccumulatedData.nullifiers[0]=getSingleTxBlockRequestHash(blockNumber);let revertibleAccumulatedData=PrivateToPublicAccumulatedData.empty();revertibleAccumulatedData.publicCallRequests[0]=new PublicCallRequest(from??AztecAddress.NULL_MSG_SENDER,targetContractAddress,isStaticCall,calldataHash);let inputsForPublic=new PartialPrivateTailPublicInputsForPublic(nonRevertibleAccumulatedData,revertibleAccumulatedData,PublicCallRequest.empty()),constantData=new TxConstantData(anchorBlockHeader,txContext,Fr.zero(),Fr.zero()),txData=new PrivateKernelTailCircuitPublicInputs(constantData,new Gas(0,0),AztecAddress.zero(),0n,inputsForPublic,void 0),tx=await Tx.create({data:txData,chonkProof:ChonkProof.empty(),contractClassLogFields:[],publicFunctionCalldata:[calldataHashedValues]}),checkpoint;isStaticCall&&(checkpoint=await ForkCheckpoint.new(forkedWorldTrees));let results=await processor.process([tx]),[processedTx]=results[0],failedTxs=results[1];if(failedTxs.length!==0)throw new Error(`Public execution has failed: ${failedTxs[0].error}`);if(!processedTx.revertCode.isOK())if(processedTx.revertReason){try{await enrichPublicSimulationError(processedTx.revertReason,this.contractStore,this.stateMachine.contractClassService,anchorBlockHeader,this.logger)}catch{}throw new Error(`Contract execution has reverted: ${processedTx.revertReason.getMessage()}`)}else throw new Error("Contract execution has reverted");let returnValues=results[3][0].values;if(isStaticCall)return await checkpoint.revert(),await forkedWorldTrees.close(),returnValues??[];let txEffect=TxEffect.empty();txEffect.noteHashes=processedTx.txEffect.noteHashes,txEffect.nullifiers=processedTx.txEffect.nullifiers,txEffect.privateLogs=processedTx.txEffect.privateLogs,txEffect.publicLogs=processedTx.txEffect.publicLogs,txEffect.publicDataWrites=processedTx.txEffect.publicDataWrites,txEffect.txHash=new TxHash(new Fr(blockNumber));let l1ToL2Messages=Array(1024).fill(0).map(Fr.zero);await forkedWorldTrees.appendLeaves(MerkleTreeId.L1_TO_L2_MESSAGE_TREE,l1ToL2Messages);let l2Block=await makeTXEBlock(forkedWorldTrees,globals,[txEffect]);return await this.stateMachine.handleL2Block(l2Block),await forkedWorldTrees.close(),returnValues??[]}async executeUtilityFunction(from,targetContractAddress,functionSelector,args,jobId,authorizedUtilityCallTargets){let blockHeader=await this.stateMachine.anchorBlockStore.getBlockHeader(),artifact=await new AnchoredContractData(this.contractStore,this.stateMachine.contractClassService,blockHeader).getFunctionArtifact(targetContractAddress,functionSelector);if(!artifact)throw new Error(`Cannot call ${functionSelector} as there is no artifact found at ${targetContractAddress}.`);await this.stateMachine.contractSyncService.ensureContractSynced(targetContractAddress,functionSelector,async(call2,execScopes)=>{await this.executeUtilityCall(call2,{scopes:execScopes,jobId})},blockHeader,jobId,await this.keyStore.getAccounts());let call=FunctionCall.from({name:artifact.name,to:targetContractAddress,selector:functionSelector,type:FunctionType.UTILITY,hideMsgSender:!1,isStatic:!1,args,returnTypes:[]});return this.executeUtilityCall(call,{from,scopes:await this.keyStore.getAccounts(),jobId,authorizedUtilityCallTargets})}async executeUtilityCall(call,{from=AztecAddress.NULL_MSG_SENDER,scopes,jobId,authorizedUtilityCallTargets=[]}){let anchorBlockHeader=await this.stateMachine.anchorBlockStore.getBlockHeader(),anchoredContractData=new AnchoredContractData(this.contractStore,this.stateMachine.contractClassService,anchorBlockHeader),entryPointArtifact=await anchoredContractData.getFunctionArtifactWithDebugMetadata(call.to,call.selector);if(!entryPointArtifact)throw new Error(`Cannot run function ${call.selector} on ${call.to}: the contract is not registered.`);if(entryPointArtifact.functionType!==FunctionType.UTILITY)throw new Error(`Cannot run ${entryPointArtifact.functionType} function as utility`);this.logger.verbose(`Executing utility function ${entryPointArtifact.name}`,{contract:call.to,selector:call.selector});try{let simulator=new WASMSimulator,utilityExecutor=__name(async(syncCall,execScopes)=>{await this.executeUtilityCall(syncCall,{scopes:execScopes,jobId})},"utilityExecutor"),oracle=new UtilityExecutionOracle({callContext:CallContext.from({msgSender:from,contractAddress:call.to,functionSelector:call.selector,isStaticCall:!0}),authWitnesses:[],capsules:[],anchorBlockHeader,anchoredContractData,noteStore:this.noteStore,keyStore:this.keyStore,addressStore:this.addressStore,aztecNode:this.stateMachine.node,recipientTaggingStore:this.recipientTaggingStore,taggingSecretSourcesStore:this.taggingSecretSourcesStore,capsuleService:new CapsuleService(this.capsuleStore,scopes),factService:new FactService(this.factStore,scopes),privateEventStore:this.privateEventStore,txResolver:this.stateMachine.txResolver,contractSyncService:this.stateMachine.contractSyncService,l2TipsStore:this.stateMachine.l2TipsProvider,jobId,scopes,simulator,hooks:composeHooks({authorizeUtilityCall:this.buildAuthorizeUtilityCallHook("utility",authorizedUtilityCallTargets)}),utilityExecutor,transientArrayService:new TransientArrayService}),acirExecutionResult=await simulator.executeUserCircuit(toACVMWitness(0,call.args),entryPointArtifact,buildACIRCallback(oracle)).catch(err=>{throw err.message=resolveAssertionMessageFromError(err,entryPointArtifact),new ExecutionError(err.message,{contractAddress:call.to,functionSelector:call.selector},extractCallStack(err,entryPointArtifact.debug),{cause:err})});return this.logger.verbose(`Utility execution for ${call.to}.${call.selector} completed`),witnessMapToFields(acirExecutionResult.returnWitness)}catch(err){throw createSimulationError(err instanceof Error?err:new Error("Unknown error during utility execution"))}}close(){return this.logger.debug("Exiting Top Level Context"),[this.nextBlockTimestamp,this.authwits,this.taggingSecretStrategy]}async getLastBlockNumber(){let block=await this.stateMachine.node.getBlock("latest");return block?block.header.globalVariables.blockNumber:BlockNumber.ZERO}buildAuthorizeUtilityCallHook(callerContext,authorizedTargets){if(authorizedTargets.length!==0)return req=>Promise.resolve({authorized:req.callerContext===callerContext&&authorizedTargets.some(t=>t.equals(req.target))})}};var TXEPrivateExecutionOracle=class extends PrivateExecutionOracle{static{__name(this,"TXEPrivateExecutionOracle")}callPrivateFunction(_targetContractAddress,_functionSelector,_argsHash,_sideEffectCounter,_isStaticCall){throw new Error("Contract calls are forbidden inside a `TestEnvironment::private_context`, use `private_call` instead")}assertValidPublicCalldata(_calldataHash){throw new Error("Enqueueing public calls is not supported in TestEnvironment::private_context")}notifyRevertiblePhaseStart(_minRevertibleSideEffectCounter){throw new Error("Enqueueing public calls is not supported in TestEnvironment::private_context")}};var UnavailableOracleError2=class extends Error{static{__name(this,"UnavailableOracleError")}constructor(oracleName){super(`${oracleName} oracles not available with the current handler`)}},RPCTranslator=class{constructor(stateHandler,oracleHandler){this.stateHandler=stateHandler;this.oracleHandler=oracleHandler}static{__name(this,"RPCTranslator")}handlerAsMisc(){if(!("isMisc"in this.oracleHandler))throw new UnavailableOracleError2("Misc");return this.oracleHandler}handlerAsUtility(){if(!("isUtility"in this.oracleHandler))throw new UnavailableOracleError2("Utility");return this.oracleHandler}handlerAsPrivate(){if(!("isPrivate"in this.oracleHandler))throw new UnavailableOracleError2("Private");return this.oracleHandler}handlerAsAvm(){if(!("isAvm"in this.oracleHandler))throw new UnavailableOracleError2("Avm");return this.oracleHandler}handlerAsTxe(){if(!("isTxe"in this.oracleHandler))throw new UnavailableOracleError2("Txe");return this.oracleHandler}aztec_txe_assertCompatibleOracleVersion(...inputs){return callTxeHandler({oracle:"aztec_txe_assertCompatibleOracleVersion",inputs,handler:__name(([major2,minor])=>{this.stateHandler.setTxeOracleVersion(major2,minor)},"handler")})}aztec_txe_setTopLevelTXEContext(){return callTxeHandler({oracle:"aztec_txe_setTopLevelTXEContext",inputs:[],handler:__name(()=>this.stateHandler.enterTopLevelState(),"handler")})}aztec_txe_setPrivateTXEContext(...inputs){return callTxeHandler({oracle:"aztec_txe_setPrivateTXEContext",inputs,handler:__name(([contractAddress,anchorBlockNumber,gasSettings])=>this.stateHandler.enterPrivateState(contractAddress,anchorBlockNumber,gasSettings),"handler")})}aztec_txe_setPublicTXEContext(...inputs){return callTxeHandler({oracle:"aztec_txe_setPublicTXEContext",inputs,handler:__name(([contractAddress])=>this.stateHandler.enterPublicState(contractAddress),"handler")})}aztec_txe_setUtilityTXEContext(...inputs){return callTxeHandler({oracle:"aztec_txe_setUtilityTXEContext",inputs,handler:__name(([contractAddress])=>this.stateHandler.enterUtilityState(contractAddress),"handler")})}aztec_txe_getDefaultAddress(){return callTxeHandler({oracle:"aztec_txe_getDefaultAddress",inputs:[],handler:__name(()=>this.handlerAsTxe().getDefaultAddress(),"handler")})}aztec_txe_getNextBlockNumber(){return callTxeHandler({oracle:"aztec_txe_getNextBlockNumber",inputs:[],handler:__name(()=>this.handlerAsTxe().getNextBlockNumber(),"handler")})}aztec_txe_getNextBlockTimestamp(){return callTxeHandler({oracle:"aztec_txe_getNextBlockTimestamp",inputs:[],handler:__name(()=>this.handlerAsTxe().getNextBlockTimestamp(),"handler")})}aztec_txe_advanceBlocksBy(...inputs){return callTxeHandler({oracle:"aztec_txe_advanceBlocksBy",inputs,handler:__name(([blocks])=>this.handlerAsTxe().advanceBlocksBy(blocks),"handler")})}aztec_txe_advanceTimestampBy(...inputs){return callTxeHandler({oracle:"aztec_txe_advanceTimestampBy",inputs,handler:__name(([duration3])=>this.handlerAsTxe().advanceTimestampBy(duration3),"handler")})}aztec_txe_deploy(...inputs){return callTxeHandler({oracle:"aztec_txe_deploy",inputs,handler:__name(([contractPath,initializer3,_,args,secret,salt,deployer])=>this.handlerAsTxe().deploy(contractPath,initializer3,args,secret,salt,deployer),"handler")})}aztec_txe_createAccount(...inputs){return callTxeHandler({oracle:"aztec_txe_createAccount",inputs,handler:__name(([secret])=>this.handlerAsTxe().createAccount(secret),"handler")})}aztec_txe_addAccount(...inputs){return callTxeHandler({oracle:"aztec_txe_addAccount",inputs,handler:__name(([secret])=>this.handlerAsTxe().addAccount(secret),"handler")})}aztec_txe_addAuthWitness(...inputs){return callTxeHandler({oracle:"aztec_txe_addAuthWitness",inputs,handler:__name(([address,messageHash])=>this.handlerAsTxe().addAuthWitness(address,messageHash),"handler")})}aztec_txe_sendL1ToL2Message(...inputs){return callTxeHandler({oracle:"aztec_txe_sendL1ToL2Message",inputs,handler:__name(([content,secretHash,sender,recipient])=>this.handlerAsTxe().sendL1ToL2Message(content,secretHash,sender,recipient),"handler")})}aztec_txe_setTaggingSecretStrategy(...inputs){return callTxeHandler({oracle:"aztec_txe_setTaggingSecretStrategy",inputs,handler:__name(([strategy])=>this.handlerAsTxe().setTaggingSecretStrategy(strategy),"handler")})}aztec_misc_assertCompatibleOracleVersion(...inputs){return callTxeHandler({oracle:"aztec_misc_assertCompatibleOracleVersion",inputs,handler:__name(([major2,minor])=>this.handlerAsMisc().assertCompatibleOracleVersion(major2,minor),"handler")})}aztec_misc_getRandomField(){return callTxeHandler({oracle:"aztec_misc_getRandomField",inputs:[],handler:__name(()=>this.handlerAsMisc().getRandomField(),"handler")})}aztec_txe_getLastBlockTimestamp(){return callTxeHandler({oracle:"aztec_txe_getLastBlockTimestamp",inputs:[],handler:__name(()=>this.handlerAsTxe().getLastBlockTimestamp(),"handler")})}aztec_txe_getLastTxEffects(){return callTxeHandler({oracle:"aztec_txe_getLastTxEffects",inputs:[],handler:__name(()=>this.handlerAsTxe().getLastTxEffects(),"handler")})}aztec_txe_getLastCallOffchainEffects(){return callTxeHandler({oracle:"aztec_txe_getLastCallOffchainEffects",inputs:[],handler:__name(()=>this.stateHandler.getLastCallOffchainEffects(),"handler")})}aztec_txe_getLastCallContext(){return callTxeHandler({oracle:"aztec_txe_getLastCallContext",inputs:[],handler:__name(()=>this.stateHandler.getLastCallContext(),"handler")})}aztec_txe_getPrivateEvents(...inputs){return callTxeHandler({oracle:"aztec_txe_getPrivateEvents",inputs,handler:__name(([selector,contractAddress,scope])=>this.stateHandler.getPrivateEvents(selector,contractAddress,scope),"handler")})}aztec_prv_setHashPreimage(...inputs){return callTxeHandler({oracle:"aztec_prv_setHashPreimage",inputs,handler:__name(([values,hash5])=>this.handlerAsPrivate().setHashPreimage(values,hash5),"handler")})}aztec_prv_getHashPreimage(...inputs){return callTxeHandler({oracle:"aztec_prv_getHashPreimage",inputs,handler:__name(([hash5])=>this.handlerAsPrivate().getHashPreimage(hash5),"handler")})}aztec_misc_log(...inputs){return callTxeHandler({oracle:"aztec_misc_log",inputs,handler:__name(([level,message,fieldsSize,fields])=>this.handlerAsMisc().log(level,message,fieldsSize,fields),"handler")})}aztec_utl_getFromPublicStorage(...inputs){return callTxeHandler({oracle:"aztec_utl_getFromPublicStorage",inputs,handler:__name(([blockHash,contractAddress,startStorageSlot,numberOfElements])=>this.handlerAsUtility().getFromPublicStorage(blockHash,contractAddress,startStorageSlot,numberOfElements),"handler")})}aztec_utl_getPublicDataWitness(...inputs){return callTxeHandler({oracle:"aztec_utl_getPublicDataWitness",inputs,handler:__name(([blockHash,leafSlot])=>this.handlerAsUtility().getPublicDataWitness(blockHash,leafSlot),"handler")})}aztec_utl_getNotes(...inputs){return callTxeHandler({oracle:"aztec_utl_getNotes",inputs,handler:__name(([owner,storageSlot,numSelects,selectByIndexes,selectByOffsets,selectByLengths,selectValues,selectComparators,sortByIndexes,sortByOffsets,sortByLengths,sortOrder,limit,offset,status,maxNotes,packedHintedNoteLength])=>this.handlerAsUtility().getNotes(owner,storageSlot,numSelects,selectByIndexes,selectByOffsets,selectByLengths,selectValues,selectComparators,sortByIndexes,sortByOffsets,sortByLengths,sortOrder,limit,offset,status,maxNotes,packedHintedNoteLength),"handler")})}aztec_prv_notifyCreatedNote(...inputs){return callTxeHandler({oracle:"aztec_prv_notifyCreatedNote",inputs,handler:__name(([owner,storageSlot,randomness,noteTypeId,note,noteHash,counter])=>this.handlerAsPrivate().notifyCreatedNote(owner,storageSlot,randomness,noteTypeId,note,noteHash,counter),"handler")})}aztec_prv_notifyNullifiedNote(...inputs){return callTxeHandler({oracle:"aztec_prv_notifyNullifiedNote",inputs,handler:__name(([innerNullifier,noteHash,counter])=>this.handlerAsPrivate().notifyNullifiedNote(innerNullifier,noteHash,counter),"handler")})}aztec_prv_notifyCreatedNullifier(...inputs){return callTxeHandler({oracle:"aztec_prv_notifyCreatedNullifier",inputs,handler:__name(([innerNullifier])=>this.handlerAsPrivate().notifyCreatedNullifier(innerNullifier),"handler")})}aztec_prv_isNullifierPending(...inputs){return callTxeHandler({oracle:"aztec_prv_isNullifierPending",inputs,handler:__name(([innerNullifier,contractAddress])=>this.handlerAsPrivate().isNullifierPending(innerNullifier,contractAddress),"handler")})}aztec_utl_doesNullifierExist(...inputs){return callTxeHandler({oracle:"aztec_utl_doesNullifierExist",inputs,handler:__name(([innerNullifier])=>this.handlerAsUtility().doesNullifierExist(innerNullifier),"handler")})}aztec_utl_getContractInstance(...inputs){return callTxeHandler({oracle:"aztec_utl_getContractInstance",inputs,handler:__name(([address])=>this.handlerAsUtility().getContractInstance(address),"handler")})}aztec_utl_getPublicKeysAndPartialAddress(...inputs){return callTxeHandler({oracle:"aztec_utl_getPublicKeysAndPartialAddress",inputs,handler:__name(([address])=>this.handlerAsUtility().getPublicKeysAndPartialAddress(address),"handler")})}aztec_utl_getKeyValidationRequest(...inputs){return callTxeHandler({oracle:"aztec_utl_getKeyValidationRequest",inputs,handler:__name(([pkMHash,keyIndex])=>this.handlerAsUtility().getKeyValidationRequest(pkMHash,keyIndex),"handler")})}aztec_prv_callPrivateFunction(...inputs){return callTxeHandler({oracle:"aztec_prv_callPrivateFunction",inputs,handler:__name(([contractAddress,functionSelector,argsHash,sideEffectCounter,isStaticCall])=>this.handlerAsPrivate().callPrivateFunction(contractAddress,functionSelector,argsHash,sideEffectCounter,isStaticCall),"handler")})}aztec_utl_getNullifierMembershipWitness(...inputs){return callTxeHandler({oracle:"aztec_utl_getNullifierMembershipWitness",inputs,handler:__name(([blockHash,nullifier])=>this.handlerAsUtility().getNullifierMembershipWitness(blockHash,nullifier),"handler")})}aztec_utl_getL1ToL2MembershipWitness(...inputs){return callTxeHandler({oracle:"aztec_utl_getL1ToL2MembershipWitness",inputs,handler:__name(([contractAddress,messageHash,secret])=>this.handlerAsUtility().getL1ToL2MembershipWitness(contractAddress,messageHash,secret),"handler")})}aztec_utl_getAuthWitness(...inputs){return callTxeHandler({oracle:"aztec_utl_getAuthWitness",inputs,handler:__name(([messageHash])=>this.handlerAsUtility().getAuthWitness(messageHash),"handler")})}aztec_prv_assertValidPublicCalldata(...inputs){return callTxeHandler({oracle:"aztec_prv_assertValidPublicCalldata",inputs,handler:__name(([calldataHash])=>this.handlerAsPrivate().assertValidPublicCalldata(calldataHash),"handler")})}aztec_prv_notifyRevertiblePhaseStart(...inputs){return callTxeHandler({oracle:"aztec_prv_notifyRevertiblePhaseStart",inputs,handler:__name(([minRevertibleSideEffectCounter])=>this.handlerAsPrivate().notifyRevertiblePhaseStart(minRevertibleSideEffectCounter),"handler")})}aztec_prv_isExecutionInRevertiblePhase(...inputs){return callTxeHandler({oracle:"aztec_prv_isExecutionInRevertiblePhase",inputs,handler:__name(([sideEffectCounter])=>this.handlerAsPrivate().isExecutionInRevertiblePhase(sideEffectCounter),"handler")})}aztec_utl_getUtilityContext(){return callTxeHandler({oracle:"aztec_utl_getUtilityContext",inputs:[],handler:__name(()=>this.handlerAsUtility().getUtilityContext(),"handler")})}aztec_utl_getBlockHeader(...inputs){return callTxeHandler({oracle:"aztec_utl_getBlockHeader",inputs,handler:__name(([blockNumber])=>this.handlerAsUtility().getBlockHeader(blockNumber),"handler")})}aztec_utl_getNoteHashMembershipWitness(...inputs){return callTxeHandler({oracle:"aztec_utl_getNoteHashMembershipWitness",inputs,handler:__name(([blockHash,noteHash])=>this.handlerAsUtility().getNoteHashMembershipWitness(blockHash,noteHash),"handler")})}aztec_utl_getBlockHashMembershipWitness(...inputs){return callTxeHandler({oracle:"aztec_utl_getBlockHashMembershipWitness",inputs,handler:__name(([anchorBlockHash,blockHash])=>this.handlerAsUtility().getBlockHashMembershipWitness(anchorBlockHash,blockHash),"handler")})}aztec_utl_getLowNullifierMembershipWitness(...inputs){return callTxeHandler({oracle:"aztec_utl_getLowNullifierMembershipWitness",inputs,handler:__name(([blockHash,nullifier])=>this.handlerAsUtility().getLowNullifierMembershipWitness(blockHash,nullifier),"handler")})}aztec_utl_getPendingTaggedLogs(...inputs){return callTxeHandler({oracle:"aztec_utl_getPendingTaggedLogs",inputs,handler:__name(([scope,providedSecrets])=>this.handlerAsUtility().getPendingTaggedLogs(scope,providedSecrets),"handler")})}aztec_utl_validateAndStoreEnqueuedNotesAndEvents(...inputs){return callTxeHandler({oracle:"aztec_utl_validateAndStoreEnqueuedNotesAndEvents",inputs,handler:__name(([noteValidationRequests,eventValidationRequests,scope])=>this.handlerAsUtility().validateAndStoreEnqueuedNotesAndEvents(noteValidationRequests,eventValidationRequests,scope),"handler")})}aztec_utl_getLogsByTagV2(...inputs){return callTxeHandler({oracle:"aztec_utl_getLogsByTagV2",inputs,handler:__name(([requestArrayBaseSlot])=>this.handlerAsUtility().getLogsByTagV2(requestArrayBaseSlot),"handler")})}aztec_utl_getResolvedTxs(...inputs){return callTxeHandler({oracle:"aztec_utl_getResolvedTxs",inputs,handler:__name(([requestArrayBaseSlot])=>this.handlerAsUtility().getResolvedTxs(requestArrayBaseSlot),"handler")})}aztec_utl_setCapsule(...inputs){return callTxeHandler({oracle:"aztec_utl_setCapsule",inputs,handler:__name(([contractAddress,slot,capsule,scope])=>this.handlerAsUtility().setCapsule(contractAddress,slot,capsule,scope),"handler")})}aztec_utl_getCapsule(...inputs){return callTxeHandler({oracle:"aztec_utl_getCapsule",inputs,handler:__name(([contractAddress,slot,tSize,scope])=>this.handlerAsUtility().getCapsule(contractAddress,slot,tSize,scope),"handler")})}aztec_utl_deleteCapsule(...inputs){return callTxeHandler({oracle:"aztec_utl_deleteCapsule",inputs,handler:__name(([contractAddress,slot,scope])=>this.handlerAsUtility().deleteCapsule(contractAddress,slot,scope),"handler")})}aztec_utl_copyCapsule(...inputs){return callTxeHandler({oracle:"aztec_utl_copyCapsule",inputs,handler:__name(([contractAddress,srcSlot,dstSlot,numEntries,scope])=>this.handlerAsUtility().copyCapsule(contractAddress,srcSlot,dstSlot,numEntries,scope),"handler")})}aztec_utl_pushEphemeral(...inputs){return callTxeHandler({oracle:"aztec_utl_pushEphemeral",inputs,handler:__name(([slot,elements])=>this.handlerAsUtility().pushEphemeral(slot,elements),"handler")})}aztec_utl_popEphemeral(...inputs){return callTxeHandler({oracle:"aztec_utl_popEphemeral",inputs,handler:__name(([slot])=>this.handlerAsUtility().popEphemeral(slot),"handler")})}aztec_utl_getEphemeral(...inputs){return callTxeHandler({oracle:"aztec_utl_getEphemeral",inputs,handler:__name(([slot,index])=>this.handlerAsUtility().getEphemeral(slot,index),"handler")})}aztec_utl_setEphemeral(...inputs){return callTxeHandler({oracle:"aztec_utl_setEphemeral",inputs,handler:__name(([slot,index,elements])=>this.handlerAsUtility().setEphemeral(slot,index,elements),"handler")})}aztec_utl_getEphemeralLen(...inputs){return callTxeHandler({oracle:"aztec_utl_getEphemeralLen",inputs,handler:__name(([slot])=>this.handlerAsUtility().getEphemeralLen(slot),"handler")})}aztec_utl_removeEphemeral(...inputs){return callTxeHandler({oracle:"aztec_utl_removeEphemeral",inputs,handler:__name(([slot,index])=>this.handlerAsUtility().removeEphemeral(slot,index),"handler")})}aztec_utl_clearEphemeral(...inputs){return callTxeHandler({oracle:"aztec_utl_clearEphemeral",inputs,handler:__name(([slot])=>this.handlerAsUtility().clearEphemeral(slot),"handler")})}aztec_utl_pushTransient(...inputs){return callTxeHandler({oracle:"aztec_utl_pushTransient",inputs,handler:__name(([slot,elements])=>this.handlerAsUtility().pushTransient(slot,elements),"handler")})}aztec_utl_popTransient(...inputs){return callTxeHandler({oracle:"aztec_utl_popTransient",inputs,handler:__name(([slot])=>this.handlerAsUtility().popTransient(slot),"handler")})}aztec_utl_getTransient(...inputs){return callTxeHandler({oracle:"aztec_utl_getTransient",inputs,handler:__name(([slot,index])=>this.handlerAsUtility().getTransient(slot,index),"handler")})}aztec_utl_setTransient(...inputs){return callTxeHandler({oracle:"aztec_utl_setTransient",inputs,handler:__name(([slot,index,elements])=>this.handlerAsUtility().setTransient(slot,index,elements),"handler")})}aztec_utl_getTransientLen(...inputs){return callTxeHandler({oracle:"aztec_utl_getTransientLen",inputs,handler:__name(([slot])=>this.handlerAsUtility().getTransientLen(slot),"handler")})}aztec_utl_removeTransient(...inputs){return callTxeHandler({oracle:"aztec_utl_removeTransient",inputs,handler:__name(([slot,index])=>this.handlerAsUtility().removeTransient(slot,index),"handler")})}aztec_utl_clearTransient(...inputs){return callTxeHandler({oracle:"aztec_utl_clearTransient",inputs,handler:__name(([slot])=>this.handlerAsUtility().clearTransient(slot),"handler")})}aztec_utl_decryptAes128(...inputs){return callTxeHandler({oracle:"aztec_utl_decryptAes128",inputs,handler:__name(([ciphertext,iv,symKey])=>this.handlerAsUtility().decryptAes128(ciphertext,iv,symKey),"handler")})}aztec_utl_getSharedSecrets(...inputs){return callTxeHandler({oracle:"aztec_utl_getSharedSecrets",inputs,handler:__name(([address,ephPksSlot,contractAddress])=>this.handlerAsUtility().getSharedSecrets(address,ephPksSlot,contractAddress),"handler")})}aztec_utl_setContractSyncCacheInvalid(...inputs){return callTxeHandler({oracle:"aztec_utl_setContractSyncCacheInvalid",inputs,handler:__name(([contractAddress,scopes])=>this.handlerAsUtility().setContractSyncCacheInvalid(contractAddress,scopes),"handler")})}aztec_utl_emitOffchainEffect(...inputs){return callTxeHandler({oracle:"aztec_utl_emitOffchainEffect",inputs,handler:__name(([data])=>{this.stateHandler.recordOffchainEffect(data)},"handler")})}aztec_utl_recordFact(...inputs){return callTxeHandler({oracle:"aztec_utl_recordFact",inputs,handler:__name(([contractAddress,scope,factCollectionTypeId,factCollectionId,factTypeId,payload,originBlock])=>this.handlerAsUtility().recordFact(contractAddress,scope,factCollectionTypeId,factCollectionId,factTypeId,payload,originBlock),"handler")})}aztec_utl_deleteFactCollection(...inputs){return callTxeHandler({oracle:"aztec_utl_deleteFactCollection",inputs,handler:__name(([contractAddress,scope,factCollectionTypeId,factCollectionId])=>this.handlerAsUtility().deleteFactCollection(contractAddress,scope,factCollectionTypeId,factCollectionId),"handler")})}aztec_utl_getFactCollection(...inputs){return callTxeHandler({oracle:"aztec_utl_getFactCollection",inputs,handler:__name(([contractAddress,scope,factCollectionTypeId,factCollectionId])=>this.handlerAsUtility().getFactCollection(contractAddress,scope,factCollectionTypeId,factCollectionId),"handler")})}aztec_utl_getFactCollectionsByType(...inputs){return callTxeHandler({oracle:"aztec_utl_getFactCollectionsByType",inputs,handler:__name(([contractAddress,scope,factCollectionTypeId])=>this.handlerAsUtility().getFactCollectionsByType(contractAddress,scope,factCollectionTypeId),"handler")})}aztec_avm_emitPublicLog(){return callTxeHandler({oracle:"aztec_avm_emitPublicLog",inputs:[],handler:__name(()=>{},"handler")})}aztec_avm_storageRead(...inputs){return callTxeHandler({oracle:"aztec_avm_storageRead",inputs,handler:__name(([slot,contractAddress])=>this.handlerAsAvm().storageRead(slot,contractAddress),"handler")})}aztec_avm_storageWrite(...inputs){return callTxeHandler({oracle:"aztec_avm_storageWrite",inputs,handler:__name(([slot,value])=>this.handlerAsAvm().storageWrite(slot,value),"handler")})}aztec_avm_getContractInstanceDeployer(...inputs){return callTxeHandler({oracle:"aztec_avm_getContractInstanceDeployer",inputs,handler:__name(([address])=>this.handlerAsAvm().getContractInstanceDeployer(address),"handler")})}aztec_avm_getContractInstanceClassId(...inputs){return callTxeHandler({oracle:"aztec_avm_getContractInstanceClassId",inputs,handler:__name(([address])=>this.handlerAsAvm().getContractInstanceClassId(address),"handler")})}aztec_avm_getContractInstanceInitializationHash(...inputs){return callTxeHandler({oracle:"aztec_avm_getContractInstanceInitializationHash",inputs,handler:__name(([address])=>this.handlerAsAvm().getContractInstanceInitializationHash(address),"handler")})}aztec_avm_getContractInstanceImmutablesHash(...inputs){return callTxeHandler({oracle:"aztec_avm_getContractInstanceImmutablesHash",inputs,handler:__name(([address])=>this.handlerAsAvm().getContractInstanceImmutablesHash(address),"handler")})}aztec_avm_sender(){return callTxeHandler({oracle:"aztec_avm_sender",inputs:[],handler:__name(()=>this.handlerAsAvm().sender(),"handler")})}aztec_avm_emitNullifier(...inputs){return callTxeHandler({oracle:"aztec_avm_emitNullifier",inputs,handler:__name(([nullifier])=>this.handlerAsAvm().emitNullifier(nullifier),"handler")})}aztec_avm_emitNoteHash(...inputs){return callTxeHandler({oracle:"aztec_avm_emitNoteHash",inputs,handler:__name(([noteHash])=>this.handlerAsAvm().emitNoteHash(noteHash),"handler")})}aztec_avm_nullifierExists(...inputs){return callTxeHandler({oracle:"aztec_avm_nullifierExists",inputs,handler:__name(([siloedNullifier])=>this.handlerAsAvm().nullifierExists(siloedNullifier),"handler")})}aztec_avm_address(){return callTxeHandler({oracle:"aztec_avm_address",inputs:[],handler:__name(()=>this.handlerAsAvm().address(),"handler")})}aztec_avm_blockNumber(){return callTxeHandler({oracle:"aztec_avm_blockNumber",inputs:[],handler:__name(()=>this.handlerAsAvm().blockNumber(),"handler")})}aztec_avm_timestamp(){return callTxeHandler({oracle:"aztec_avm_timestamp",inputs:[],handler:__name(()=>this.handlerAsAvm().timestamp(),"handler")})}aztec_avm_isStaticCall(){return callTxeHandler({oracle:"aztec_avm_isStaticCall",inputs:[],handler:__name(()=>this.handlerAsAvm().isStaticCall(),"handler")})}aztec_avm_chainId(){return callTxeHandler({oracle:"aztec_avm_chainId",inputs:[],handler:__name(()=>this.handlerAsAvm().chainId(),"handler")})}aztec_avm_version(){return callTxeHandler({oracle:"aztec_avm_version",inputs:[],handler:__name(()=>this.handlerAsAvm().version(),"handler")})}aztec_avm_returndataSize(){return callTxeHandler({oracle:"aztec_avm_returndataSize",inputs:[],handler:__name(()=>this.handlerAsAvm().returndataSize(),"handler")})}aztec_avm_returndataCopy(...inputs){return callTxeHandler({oracle:"aztec_avm_returndataCopy",inputs,handler:__name(([rdOffset,copySize])=>this.handlerAsAvm().returndataCopy(rdOffset,copySize),"handler")})}aztec_avm_call(...inputs){return callTxeHandler({oracle:"aztec_avm_call",inputs,handler:__name(([l2Gas,daGas,address,argsLength,args])=>this.handlerAsAvm().call(l2Gas,daGas,address,argsLength,args),"handler")})}aztec_avm_staticCall(...inputs){return callTxeHandler({oracle:"aztec_avm_staticCall",inputs,handler:__name(([l2Gas,daGas,address,argsLength,args])=>this.handlerAsAvm().staticCall(l2Gas,daGas,address,argsLength,args),"handler")})}aztec_avm_successCopy(){return callTxeHandler({oracle:"aztec_avm_successCopy",inputs:[],handler:__name(()=>this.handlerAsAvm().successCopy(),"handler")})}aztec_txe_privateCallNewFlow(...inputs){return callTxeHandler({oracle:"aztec_txe_privateCallNewFlow",inputs,handler:__name(([from,targetContractAddress,functionSelector,args,argsHash,isStaticCall,additionalScopes,authorizedUtilityCallTargets,gasSettings])=>this.stateHandler.executePrivateCall(from,targetContractAddress,functionSelector,args,argsHash,isStaticCall,additionalScopes,authorizedUtilityCallTargets,gasSettings),"handler")})}aztec_txe_executeUtilityFunction(...inputs){return callTxeHandler({oracle:"aztec_txe_executeUtilityFunction",inputs,handler:__name(([from,targetContractAddress,functionSelector,args,authorizedUtilityCallTargets])=>this.stateHandler.executeUtilityFunction(from,targetContractAddress,functionSelector,args,authorizedUtilityCallTargets),"handler")})}aztec_txe_publicCallNewFlow(...inputs){return callTxeHandler({oracle:"aztec_txe_publicCallNewFlow",inputs,handler:__name(([from,address,calldata,isStaticCall,gasSettings])=>this.stateHandler.executePublicCall(from,address,calldata,isStaticCall,gasSettings),"handler")})}aztec_prv_getSenderForTags(){return callTxeHandler({oracle:"aztec_prv_getSenderForTags",inputs:[],handler:__name(()=>this.handlerAsPrivate().getSenderForTags(),"handler")})}aztec_prv_resolveTaggingStrategy(...inputs){return callTxeHandler({oracle:"aztec_prv_resolveTaggingStrategy",inputs,handler:__name(([sender,recipient,deliveryMode])=>this.handlerAsPrivate().resolveTaggingStrategy(sender,recipient,deliveryMode),"handler")})}aztec_prv_resolveCustomRequest(...inputs){return callTxeHandler({oracle:"aztec_prv_resolveCustomRequest",inputs,handler:__name(([kind,payload])=>this.handlerAsPrivate().resolveCustomRequest(kind,payload),"handler")})}aztec_prv_getAppTaggingSecret(...inputs){return callTxeHandler({oracle:"aztec_prv_getAppTaggingSecret",inputs,handler:__name(([sender,recipient])=>this.handlerAsPrivate().getAppTaggingSecret(sender,recipient),"handler")})}aztec_prv_getNextTaggingIndex(...inputs){return callTxeHandler({oracle:"aztec_prv_getNextTaggingIndex",inputs,handler:__name(([secret,deliveryMode])=>this.handlerAsPrivate().getNextTaggingIndex(secret,deliveryMode),"handler")})}};function computeCheckpointPayloadDigest(args){let consensusPayload=new ConsensusPayload(args.header,args.archiveRoot,args.feeAssetPriceModifier,args.signatureContext);return getHashedSignaturePayloadTypedData(consensusPayload)}__name(computeCheckpointPayloadDigest,"computeCheckpointPayloadDigest");import{RollupContract,SimulationOverridesBuilder}from"@aztec/ethereum/contracts";async function buildCheckpointSimulationOverridesPlan(input){if(input.proposedCheckpointData&&input.invalidateToPendingCheckpointNumber!==void 0)throw new Error("Error in buildCheckpointSimulationOverridesPlan: proposedCheckpointData and invalidateToPendingCheckpointNumber are mutually exclusive");let builder=new SimulationOverridesBuilder,overridenChainTip=derivePendingCheckpointNumber(input)??input.checkpointedCheckpointNumber;if(builder.withChainTips({pending:overridenChainTip,proven:overridenChainTip}),input.proposedCheckpointData){let{header,archive,checkpointOutHash,feeAssetPriceModifier}=input.proposedCheckpointData;builder.withPendingArchive(archive.root),builder.withPendingTempCheckpointLogFields({headerHash:header.hash(),outHash:checkpointOutHash,slotNumber:header.slotNumber,payloadDigest:computeCheckpointPayloadDigest({header,archiveRoot:archive.root,feeAssetPriceModifier,signatureContext:input.signatureContext})});let feeHeader=await computePipelinedParentFeeHeader({checkpointNumber:input.checkpointNumber,proposedCheckpointData:input.proposedCheckpointData,rollup:input.rollup,log:input.log});feeHeader&&builder.withPendingFeeHeader(feeHeader)}return builder.build()}__name(buildCheckpointSimulationOverridesPlan,"buildCheckpointSimulationOverridesPlan");function derivePendingCheckpointNumber(input){if(input.invalidateToPendingCheckpointNumber!==void 0)return input.invalidateToPendingCheckpointNumber;if(!input.proposedCheckpointData)return;if(input.checkpointNumber<1)throw new Error(`Cannot build simulation override for checkpoint ${input.checkpointNumber}: no parent exists`);let expectedParent=CheckpointNumber(input.checkpointNumber-1);if(input.proposedCheckpointData.checkpointNumber!==expectedParent)throw new Error(`Cannot build simulation override for checkpoint ${input.checkpointNumber}: proposedCheckpointData.checkpointNumber (${input.proposedCheckpointData.checkpointNumber}) does not match expected parent ${expectedParent}`);return expectedParent}__name(derivePendingCheckpointNumber,"derivePendingCheckpointNumber");async function computePipelinedParentFeeHeader(input){if(input.checkpointNumber<2)return;let grandparentCheckpointNumber=CheckpointNumber(input.checkpointNumber-2),[grandparentCheckpoint,manaTarget]=await Promise.all([input.rollup.getCheckpoint(grandparentCheckpointNumber),input.rollup.getManaTarget()]);if(!grandparentCheckpoint?.feeHeader)throw new Error(`Grandparent checkpoint or feeHeader missing for checkpoint ${grandparentCheckpointNumber.toString()}`);return RollupContract.computeChildFeeHeader(grandparentCheckpoint.feeHeader,input.proposedCheckpointData.totalManaUsed,input.proposedCheckpointData.feeAssetPriceModifier,manaTarget)}__name(computePipelinedParentFeeHeader,"computePipelinedParentFeeHeader");var CheckpointValidationError=class extends Error{static{__name(this,"CheckpointValidationError")}checkpointNumber;slot;constructor(message,checkpointNumber,slot){super(message),this.checkpointNumber=checkpointNumber,this.slot=slot,this.name="CheckpointValidationError"}};function validateCheckpoint(checkpoint,opts){validateCheckpointStructure(checkpoint,{maxBlocksPerCheckpoint:opts.maxBlocksPerCheckpoint}),validateCheckpointLimits(checkpoint,opts),validateCheckpointBlocksLimits(checkpoint,opts)}__name(validateCheckpoint,"validateCheckpoint");function validateCheckpointStructure(checkpoint,opts={}){let{maxBlocksPerCheckpoint=MAX_ATTESTABLE_BLOCKS_PER_CHECKPOINT}=opts,{blocks,number:number4,slot}=checkpoint;if(blocks.length===0)throw new CheckpointValidationError("Checkpoint has no blocks",number4,slot);if(blocks.length>maxBlocksPerCheckpoint)throw new CheckpointValidationError(`Checkpoint has ${blocks.length} blocks, exceeding limit of ${maxBlocksPerCheckpoint}`,number4,slot);let firstBlock=blocks[0];if(!checkpoint.header.lastArchiveRoot.equals(firstBlock.header.lastArchive.root))throw new CheckpointValidationError("Checkpoint lastArchiveRoot does not match first block's lastArchive root",number4,slot);for(let i=0;i<blocks.length;i++){let block=blocks[i];if(block.indexWithinCheckpoint!==i)throw new CheckpointValidationError(`Block at index ${i} has indexWithinCheckpoint ${block.indexWithinCheckpoint}, expected ${i}`,number4,slot);if(block.slot!==slot)throw new CheckpointValidationError(`Block ${block.number} has slot ${block.slot}, expected ${slot} (all blocks must share the same slot)`,number4,slot);if(!checkpoint.header.matchesGlobalVariables(block.header.globalVariables))throw new CheckpointValidationError(`Block ${block.number} global variables (slot, timestamp, coinbase, feeRecipient, gasFees) do not match checkpoint header`,number4,slot);if(i>0){let prev=blocks[i-1];if(block.number!==prev.number+1)throw new CheckpointValidationError(`Block numbers are not sequential: block at index ${i-1} has number ${prev.number}, block at index ${i} has number ${block.number}`,number4,slot);if(!block.header.lastArchive.root.equals(prev.archive.root))throw new CheckpointValidationError(`Block ${block.number} lastArchive root does not match archive root of block ${prev.number}`,number4,slot)}}}__name(validateCheckpointStructure,"validateCheckpointStructure");function validateCheckpointBlocksLimits(checkpoint,opts){let{maxL2BlockGas,maxDABlockGas,maxTxsPerBlock}=opts;if(maxL2BlockGas!==void 0)for(let block of checkpoint.blocks){let blockL2Gas=block.header.totalManaUsed.toNumber();if(blockL2Gas>maxL2BlockGas)throw new CheckpointValidationError(`Block ${block.number} in checkpoint has L2 gas used ${blockL2Gas} exceeding limit of ${maxL2BlockGas}`,checkpoint.number,checkpoint.slot)}if(maxDABlockGas!==void 0)for(let block of checkpoint.blocks){let blockDAGas=block.computeDAGasUsed();if(blockDAGas>maxDABlockGas)throw new CheckpointValidationError(`Block ${block.number} in checkpoint has DA gas used ${blockDAGas} exceeding limit of ${maxDABlockGas}`,checkpoint.number,checkpoint.slot)}if(maxTxsPerBlock!==void 0)for(let block of checkpoint.blocks){let blockTxCount=block.body.txEffects.length;if(blockTxCount>maxTxsPerBlock)throw new CheckpointValidationError(`Block ${block.number} in checkpoint has ${blockTxCount} txs exceeding limit of ${maxTxsPerBlock}`,checkpoint.number,checkpoint.slot)}}__name(validateCheckpointBlocksLimits,"validateCheckpointBlocksLimits");function validateCheckpointLimits(checkpoint,opts){let{rollupManaLimit,maxTxsPerCheckpoint}=opts,maxBlobFields=6*4096,maxDAGas=MAX_PROCESSABLE_DA_GAS_PER_CHECKPOINT2;if(rollupManaLimit!==void 0){let checkpointMana=sum(checkpoint.blocks.map(block=>block.header.totalManaUsed.toNumber()));if(checkpointMana>rollupManaLimit)throw new CheckpointValidationError(`Checkpoint mana cost ${checkpointMana} exceeds rollup limit of ${rollupManaLimit}`,checkpoint.number,checkpoint.slot)}let checkpointDAGas=sum(checkpoint.blocks.map(block=>block.computeDAGasUsed()));if(checkpointDAGas>maxDAGas)throw new CheckpointValidationError(`Checkpoint DA gas cost ${checkpointDAGas} exceeds limit of ${maxDAGas}`,checkpoint.number,checkpoint.slot);let checkpointBlobFields=checkpoint.toBlobFields().length;if(checkpointBlobFields>maxBlobFields)throw new CheckpointValidationError(`Checkpoint blob field count ${checkpointBlobFields} exceeds limit of ${maxBlobFields}`,checkpoint.number,checkpoint.slot);if(maxTxsPerCheckpoint!==void 0){let checkpointTxCount=sum(checkpoint.blocks.map(block=>block.body.txEffects.length));if(checkpointTxCount>maxTxsPerCheckpoint)throw new CheckpointValidationError(`Checkpoint tx count ${checkpointTxCount} exceeds limit of ${maxTxsPerCheckpoint}`,checkpoint.number,checkpoint.slot)}}__name(validateCheckpointLimits,"validateCheckpointLimits");var ArchiverDataSourceBase=class{static{__name(this,"ArchiverDataSourceBase")}stores;l1Constants;initialHeader;initialBlockHash;genesisArchiveRoot;genesisBlock;genesisBlockData;constructor(stores,l1Constants,initialHeader,initialBlockHash,genesisArchiveRoot){this.stores=stores,this.l1Constants=l1Constants,this.initialHeader=initialHeader,this.initialBlockHash=initialBlockHash,this.genesisArchiveRoot=genesisArchiveRoot;let genesisArchive=new AppendOnlyTreeSnapshot(genesisArchiveRoot,1);this.genesisBlock=new L2Block(genesisArchive,initialHeader,Body.empty(),CheckpointNumber.ZERO,IndexWithinCheckpoint(0)),this.genesisBlockData={header:initialHeader,archive:genesisArchive,blockHash:initialBlockHash,checkpointNumber:CheckpointNumber.ZERO,indexWithinCheckpoint:IndexWithinCheckpoint(0)}}getGenesisBlockHash(){return this.initialBlockHash}getGenesisBlock(){return this.genesisBlock}getGenesisBlockData(){return this.genesisBlockData}isGenesisBlockQuery(query){return"genesis"in query}async isPruneDueAtSlot(slot){if(!this.l1Constants)throw new Error("isPruneDueAtSlot requires l1Constants");let tips=await this.getL2Tips(),proven=tips.proven.checkpoint.number;if(tips.checkpointed.checkpoint.number===proven)return!1;let oldestUnproven=await this.getCheckpointData({number:CheckpointNumber(Number(proven)+1)});if(!oldestUnproven)return!1;let slotTs=getLastL1SlotTimestampForL2Slot(slot,this.l1Constants),slotEpoch=getEpochNumberAtTimestamp(slotTs,this.l1Constants),oldestUnprovenEpoch=getEpochAtSlot(oldestUnproven.header.slotNumber,this.l1Constants),deadlineEpoch=getProofSubmissionDeadlineEpoch(oldestUnprovenEpoch,this.l1Constants);return slotEpoch>=deadlineEpoch}getCheckpointNumber(){return this.stores.blocks.getLatestCheckpointNumber()}getProvenCheckpointNumber(){return this.stores.blocks.getProvenCheckpointNumber()}async getBlockNumber(query){if(!query)return this.stores.blocks.getLatestL2BlockNumber();let resolved=await this.resolveBlockQuery(query);if(resolved!==void 0)return this.isGenesisBlockQuery(resolved)?BlockNumber.ZERO:this.stores.blocks.getBlockNumber(resolved)}resolveCheckpointQuery(query){if("number"in query)return Promise.resolve(query.number);if("slot"in query)return this.stores.blocks.getCheckpointNumberBySlot(query.slot);switch(query.tag){case"checkpointed":return this.stores.blocks.getLatestCheckpointNumber();case"proven":return this.stores.blocks.getProvenCheckpointNumber();case"finalized":return this.stores.blocks.getFinalizedCheckpointNumber()}}async resolveCheckpointsQuery(query){if("from"in query)return query;let numbers=await this.getCheckpointNumbersForEpoch(query.epoch);if(numbers.length!==0)return{from:numbers[0],limit:numbers.length}}async getCheckpoint(query){let number4=await this.resolveCheckpointQuery(query);if(number4===void 0||number4===0)return;let data=await this.stores.blocks.getCheckpointData(number4);if(data)return this.getPublishedCheckpointFromCheckpointData(data)}async getCheckpoints(query){let resolved=await this.resolveCheckpointsQuery(query);if(!resolved)return[];let checkpoints=await this.stores.blocks.getRangeOfCheckpoints(resolved.from,resolved.limit);return Promise.all(checkpoints.map(ch=>this.getPublishedCheckpointFromCheckpointData(ch)))}async getCheckpointData(query){let number4=await this.resolveCheckpointQuery(query);if(!(number4===void 0||number4===0))return this.stores.blocks.getCheckpointData(number4)}async getCheckpointsData(query){let resolved=await this.resolveCheckpointsQuery(query);return resolved?this.stores.blocks.getRangeOfCheckpoints(resolved.from,resolved.limit):[]}getProposedCheckpointData(query){return!query||"tag"in query?this.stores.blocks.getLastProposedCheckpoint():"number"in query?this.stores.blocks.getProposedCheckpointByNumber(query.number):this.stores.blocks.getProposedCheckpointBySlot(query.slot)}getTxEffect(txHash){return this.stores.blocks.getTxEffect(txHash)}isPendingChainInvalid(){return this.getPendingChainValidationStatus().then(status=>!status.valid)}async getPendingChainValidationStatus(){return await this.stores.blocks.getPendingChainValidationStatus()??{valid:!0}}getPrivateLogsByTags(query){return this.stores.logs.getPrivateLogsByTags(query)}getPublicLogsByTags(query){return this.stores.logs.getPublicLogsByTags(query)}getContractClass(id){return this.stores.contractClasses.getContractClass(id)}getBytecodeCommitment(id){return this.stores.contractClasses.getBytecodeCommitment(id)}getContract(address,timestamp){return this.stores.contractInstances.getContractInstance(address,timestamp)}getContractClassIds(){return this.stores.contractClasses.getContractClassIds()}getDebugFunctionName(_address,selector){return Promise.resolve(this.stores.functionNames.get(selector))}registerContractFunctionSignatures(signatures){return this.stores.functionNames.register(signatures)}getL1ToL2Messages(checkpointNumber){return this.stores.messages.getL1ToL2Messages(checkpointNumber)}getL1ToL2MessageIndex(l1ToL2Message){return this.stores.messages.getL1ToL2MessageIndex(l1ToL2Message)}async getPublishedCheckpointFromCheckpointData(checkpoint){let blocksForCheckpoint=await this.stores.blocks.getBlocksForCheckpoint(checkpoint.checkpointNumber);if(!blocksForCheckpoint)throw new Error(`Blocks for checkpoint ${checkpoint.checkpointNumber} not found`);let fullCheckpoint=new Checkpoint(checkpoint.archive,checkpoint.header,blocksForCheckpoint,checkpoint.checkpointNumber,checkpoint.feeAssetPriceModifier);return new PublishedCheckpoint(fullCheckpoint,checkpoint.l1,checkpoint.attestations)}getBlocksForSlot(slotNumber){return this.stores.blocks.getBlocksForSlot(slotNumber)}getCheckpointNumbersForEpoch(epochNumber){if(!this.l1Constants)throw new Error("L1 constants not set");let[start,end]=getSlotRangeForEpoch(epochNumber,this.l1Constants);return this.stores.blocks.getCheckpointNumbersForSlotRange(start,end)}async getBlock(query){let resolved=await this.resolveBlockQuery(query);if(resolved!==void 0)return this.isGenesisBlockQuery(resolved)?this.getGenesisBlock():this.stores.blocks.getBlock(resolved)}async getBlocks(query){let resolved=await this.resolveBlocksQuery(query);return resolved?this.stores.blocks.getBlocks(resolved):[]}async getBlockData(query){let resolved=await this.resolveBlockQuery(query);if(resolved!==void 0)return this.isGenesisBlockQuery(resolved)?this.getGenesisBlockData():this.stores.blocks.getBlockData(resolved)}async getBlocksData(query){let resolved=await this.resolveBlocksQuery(query);return resolved?this.stores.blocks.getBlocksData(resolved):[]}async resolveBlockQuery(query){if("number"in query)return query.number===BlockNumber.ZERO?{genesis:!0}:query;if("hash"in query)return query.hash.equals(this.initialBlockHash)?{genesis:!0}:query;if("archive"in query)return query.archive.equals(this.genesisArchiveRoot)?{genesis:!0}:query;let number4=await this.resolveBlockTag(query.tag);return number4===BlockNumber.ZERO?{genesis:!0}:{number:number4}}resolveBlockTag(tag){switch(tag){case"latest":case"proposed":return this.stores.blocks.getLatestL2BlockNumber();case"checkpointed":return this.stores.blocks.getCheckpointedL2BlockNumber();case"proven":return this.stores.blocks.getProvenBlockNumber();case"finalized":return this.stores.blocks.getFinalizedL2BlockNumber()}}async resolveBlocksQuery(query){if(!("epoch"in query)){if(query.from<INITIAL_L2_BLOCK_NUM2)throw new Error(`getBlocks/getBlocksData: 'from' must be >= ${INITIAL_L2_BLOCK_NUM2}, got ${query.from}. Use getBlock({number:0})/getBlockData({number:0}) for genesis-aware single-block lookups.`);return query}let checkpointNumbers=await this.getCheckpointNumbersForEpoch(query.epoch);if(checkpointNumbers.length===0)return;let firstNumber=checkpointNumbers[0],lastNumber=checkpointNumbers[checkpointNumbers.length-1],first=await this.stores.blocks.getCheckpointData(firstNumber);if(!first)return;let last=firstNumber===lastNumber?first:await this.stores.blocks.getCheckpointData(lastNumber);if(!last)return;let from=BlockNumber(first.startBlock),limit=last.startBlock+last.blockCount-first.startBlock;return{from,limit,onlyCheckpointed:!0}}};var Operation=(function(Operation2){return Operation2[Operation2.Store=0]="Store",Operation2[Operation2.Delete=1]="Delete",Operation2})(Operation||{}),ArchiverDataStoreUpdater=class{static{__name(this,"ArchiverDataStoreUpdater")}stores;l2TipsCache;opts;log;constructor(stores,l2TipsCache,opts={}){this.stores=stores,this.l2TipsCache=l2TipsCache,this.opts=opts,this.log=createLogger("archiver:store_updater")}async addProposedBlock(block,pendingChainValidationStatus){let result=await this.stores.db.transactionAsync(async()=>(await this.stores.blocks.addProposedBlock(block),(await Promise.all([pendingChainValidationStatus&&this.stores.blocks.setPendingChainValidationStatus(pendingChainValidationStatus),this.stores.logs.addLogs([block]),this.addContractDataToDb(block)])).every(Boolean)));return await this.l2TipsCache?.refresh(),result}async addCheckpoints(checkpoints,pendingChainValidationStatus,promoteProposed,evictProposedFrom){for(let checkpoint of checkpoints)validateCheckpoint(checkpoint.checkpoint,{rollupManaLimit:this.opts?.rollupManaLimit,maxBlocksPerCheckpoint:MAX_CAPACITY_BLOCKS_PER_CHECKPOINT});promoteProposed&&validateCheckpoint(promoteProposed.checkpoint.checkpoint,{rollupManaLimit:this.opts?.rollupManaLimit,maxBlocksPerCheckpoint:MAX_CAPACITY_BLOCKS_PER_CHECKPOINT});let result=await this.stores.db.transactionAsync(async()=>{let{prunedBlocks,lastAlreadyInsertedBlockNumber}=await this.pruneMismatchingLocalBlocks(checkpoints),newBlocks=(await this.stores.blocks.addCheckpoints(checkpoints)).flatMap(ch=>ch.checkpoint.blocks).filter(b=>lastAlreadyInsertedBlockNumber===void 0||b.number>lastAlreadyInsertedBlockNumber);return await Promise.all([pendingChainValidationStatus&&this.stores.blocks.setPendingChainValidationStatus(pendingChainValidationStatus),this.stores.logs.addLogs(newBlocks),...newBlocks.map(block=>this.addContractDataToDb(block)),promoteProposed?this.stores.blocks.promoteProposedToCheckpointed(promoteProposed.checkpoint.checkpoint.number,promoteProposed.l1,promoteProposed.attestations,promoteProposed.checkpoint.checkpoint.archive.root):void 0,evictProposedFrom!==void 0?this.stores.blocks.evictProposedCheckpointsFrom(evictProposedFrom):void 0]),{prunedBlocks,lastAlreadyInsertedBlockNumber}});return await this.l2TipsCache?.refresh(),result}async addProposedCheckpoint(proposedCheckpoint){let result=await this.stores.db.transactionAsync(async()=>{await this.stores.blocks.addProposedCheckpoint(proposedCheckpoint)});return await this.l2TipsCache?.refresh(),result}async pruneMismatchingLocalBlocks(checkpoints){let[lastCheckpointedBlockNumber,lastBlockNumber]=await Promise.all([this.stores.blocks.getCheckpointedL2BlockNumber(),this.stores.blocks.getLatestL2BlockNumber()]);if(lastBlockNumber===lastCheckpointedBlockNumber)return{prunedBlocks:void 0,lastAlreadyInsertedBlockNumber:void 0};let uncheckpointedLocalBlocks=await this.stores.blocks.getBlocksData({from:BlockNumber.add(lastCheckpointedBlockNumber,1),limit:lastBlockNumber-lastCheckpointedBlockNumber}),lastAlreadyInsertedBlockNumber;for(let publishedCheckpoint of checkpoints){let checkpointBlocks=publishedCheckpoint.checkpoint.blocks,slot=publishedCheckpoint.checkpoint.slot;if(checkpointBlocks.length===0){this.log.warn(`Checkpoint ${publishedCheckpoint.checkpoint.number} for slot ${slot} has no blocks`);continue}for(let checkpointBlock of checkpointBlocks){let blockNumber=checkpointBlock.number,existingBlock=uncheckpointedLocalBlocks.find(b=>b.header.getBlockNumber()===blockNumber),blockInfos={existingBlock:existingBlock?.header.toInspect(),checkpointBlock:checkpointBlock.toBlockInfo()};if(!existingBlock)this.log.verbose(`No local block found for checkpointed block number ${blockNumber}`,blockInfos);else if(existingBlock.archive.root.equals(checkpointBlock.archive.root))this.log.verbose(`Block number ${blockNumber} already inserted and matches checkpoint`,blockInfos),lastAlreadyInsertedBlockNumber=blockNumber;else{this.log.info(`Conflict detected at block ${blockNumber} between checkpointed and local block`,blockInfos);let prunedBlocks=await this.removeBlocksAfter(BlockNumber(blockNumber-1));return await this.evictProposedCheckpointsForPrunedBlocks(prunedBlocks),{prunedBlocks,lastAlreadyInsertedBlockNumber}}}let lastCheckpointBlockNumber=checkpointBlocks.at(-1).number,lastLocalBlockNumber=uncheckpointedLocalBlocks.filter(b=>b.header.getSlot()===slot).at(-1)?.header.getBlockNumber();if(lastLocalBlockNumber!==void 0&&lastLocalBlockNumber>lastCheckpointBlockNumber){this.log.warn(`Local chain for slot ${slot} ends at block ${lastLocalBlockNumber} but checkpoint ends at ${lastCheckpointBlockNumber}. Pruning blocks after block ${lastCheckpointBlockNumber}.`);let prunedBlocks=await this.removeBlocksAfter(lastCheckpointBlockNumber);return await this.evictProposedCheckpointsForPrunedBlocks(prunedBlocks),{prunedBlocks,lastAlreadyInsertedBlockNumber}}}return{prunedBlocks:void 0,lastAlreadyInsertedBlockNumber}}async removeUncheckpointedBlocksAfter(blockNumber){let result=await this.stores.db.transactionAsync(async()=>{let lastCheckpointedBlockNumber=await this.stores.blocks.getCheckpointedL2BlockNumber();if(blockNumber<lastCheckpointedBlockNumber)throw new Error(`Cannot remove blocks after ${blockNumber} because checkpointed blocks exist up to ${lastCheckpointedBlockNumber}`);let prunedBlocks=await this.removeBlocksAfter(blockNumber);return await this.evictProposedCheckpointsForPrunedBlocks(prunedBlocks),prunedBlocks});return await this.l2TipsCache?.refresh(),result}async removeBlocksWithoutProposedCheckpointAfter(blockNumber){let result=await this.stores.db.transactionAsync(async()=>{let lastCheckpointedBlockNumber=await this.stores.blocks.getProposedCheckpointL2BlockNumber();if(blockNumber<lastCheckpointedBlockNumber)throw new Error(`Cannot remove blocks after ${blockNumber} because proposed checkpointed blocks exist up to ${lastCheckpointedBlockNumber}`);return await this.removeBlocksAfter(blockNumber)});return await this.l2TipsCache?.refresh(),result}async evictProposedCheckpointsForPrunedBlocks(prunedBlocks){if(prunedBlocks.length===0)return;let fromCheckpointNumber=prunedBlocks[0].checkpointNumber;await this.stores.blocks.evictProposedCheckpointsFrom(fromCheckpointNumber)}async removeBlocksAfter(blockNumber){let removedBlocks=await this.stores.blocks.removeBlocksAfter(blockNumber);return await Promise.all([this.stores.logs.deleteLogs(removedBlocks),...removedBlocks.map(block=>this.removeContractDataFromDb(block))]),removedBlocks}async removeCheckpointsAfter(checkpointNumber){let result=await this.stores.db.transactionAsync(async()=>{let{blocksRemoved=[]}=await this.stores.blocks.removeCheckpointsAfter(checkpointNumber);return(await Promise.all([this.stores.blocks.setPendingChainValidationStatus({valid:!0}),...blocksRemoved.map(block=>this.removeContractDataFromDb(block)),this.stores.logs.deleteLogs(blocksRemoved)])).every(Boolean)});return await this.l2TipsCache?.refresh(),result}async setProvenCheckpointNumber(checkpointNumber){await this.stores.db.transactionAsync(async()=>{await this.stores.blocks.setProvenCheckpointNumber(checkpointNumber)}),await this.l2TipsCache?.refresh()}async setFinalizedCheckpointNumber(checkpointNumber){await this.stores.db.transactionAsync(async()=>{await this.stores.blocks.setFinalizedCheckpointNumber(checkpointNumber)}),await this.l2TipsCache?.refresh()}addContractDataToDb(block){return this.updateContractDataOnDb(block,0)}removeContractDataFromDb(block){return this.updateContractDataOnDb(block,1)}async updateContractDataOnDb(block,operation){let contractClassLogs=block.body.txEffects.flatMap(txEffect=>txEffect.contractClassLogs),privateLogs=block.body.txEffects.flatMap(txEffect=>txEffect.privateLogs),publicLogs=block.body.txEffects.flatMap(txEffect=>txEffect.publicLogs);return(await Promise.all([this.updatePublishedContractClasses(contractClassLogs,block.number,operation),this.updateDeployedContractInstances(privateLogs,block.number,operation),this.updateUpdatedContractInstances(publicLogs,block.header.globalVariables.timestamp,operation)])).every(Boolean)}async updatePublishedContractClasses(allLogs,blockNum,operation){let contractClassPublishedEvents=allLogs.filter(log2=>ContractClassPublishedEvent.isContractClassPublishedEvent(log2)).map(log2=>ContractClassPublishedEvent.fromLog(log2));if(operation==1){let contractClasses2=contractClassPublishedEvents.map(e2=>e2.toContractClassPublic());return contractClasses2.length>0?(contractClasses2.forEach(c2=>this.log.verbose(`${Operation[operation]} contract class ${c2.id.toString()}`)),await this.stores.contractClasses.deleteContractClasses(contractClasses2,blockNum)):!0}let contractClasses=[];for(let event of contractClassPublishedEvents){let contractClass=await event.toContractClassPublicWithBytecodeCommitment(),computedClassId=await computeContractClassId({artifactHash:contractClass.artifactHash,privateFunctionsRoot:contractClass.privateFunctionsRoot,publicBytecodeCommitment:contractClass.publicBytecodeCommitment});if(!computedClassId.equals(contractClass.id)){this.log.warn(`Skipping contract class with mismatched id at block ${blockNum}. Claimed ${contractClass.id}, computed ${computedClassId}`,{blockNum,contractClassId:event.contractClassId.toString()});continue}contractClasses.push(contractClass)}return contractClasses.length>0?(contractClasses.forEach(c2=>this.log.verbose(`${Operation[operation]} contract class ${c2.id.toString()}`)),await this.stores.contractClasses.addContractClasses(contractClasses,blockNum)):!0}async updateDeployedContractInstances(allLogs,blockNum,operation){let allInstances=allLogs.filter(log2=>ContractInstancePublishedEvent.isContractInstancePublishedEvent(log2)).map(log2=>ContractInstancePublishedEvent.fromLog(log2)).map(e2=>e2.toContractInstance()),contractInstances=operation===1?allInstances:await filterAsync(allInstances,async instance=>{let computedAddress=await computeContractAddressFromInstance(instance);return computedAddress.equals(instance.address)?!0:(this.log.warn(`Found contract instance with mismatched address at block ${blockNum}. Claimed ${instance.address} but computed ${computedAddress}.`,{instanceAddress:instance.address.toString(),computedAddress:computedAddress.toString(),blockNum}),!1)});if(contractInstances.length>0){if(contractInstances.forEach(c2=>this.log.verbose(`${Operation[operation]} contract instance at ${c2.address.toString()}`)),operation==0)return await this.stores.contractInstances.addContractInstances(contractInstances,blockNum);if(operation==1)return await this.stores.contractInstances.deleteContractInstances(contractInstances)}return!0}async updateUpdatedContractInstances(allLogs,timestamp,operation){let contractUpdates=allLogs.filter(log2=>ContractInstanceUpdatedEvent.isContractInstanceUpdatedEvent(log2)).map(log2=>ContractInstanceUpdatedEvent.fromLog(log2)).map(e2=>e2.toContractInstanceUpdate());if(contractUpdates.length>0){if(contractUpdates.forEach(c2=>this.log.verbose(`${Operation[operation]} contract instance update at ${c2.address.toString()}`)),operation==0)return await this.stores.contractInstances.addContractInstanceUpdates(contractUpdates,timestamp);if(operation==1)return await this.stores.contractInstances.deleteContractInstanceUpdates(contractUpdates,timestamp)}return!0}};var CheckpointMergeRollupPrivateInputs=class _CheckpointMergeRollupPrivateInputs{static{__name(this,"CheckpointMergeRollupPrivateInputs")}previousRollups;constructor(previousRollups){this.previousRollups=previousRollups}toBuffer(){return serializeToBuffer(this.previousRollups)}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _CheckpointMergeRollupPrivateInputs([ProofData.fromBuffer(reader,CheckpointRollupPublicInputs),ProofData.fromBuffer(reader,CheckpointRollupPublicInputs)])}toString(){return bufferToHex(this.toBuffer())}static fromString(str){return _CheckpointMergeRollupPrivateInputs.fromBuffer(hexToBuffer(str))}toJSON(){return this.toBuffer()}static get schema(){return bufferSchemaFor(_CheckpointMergeRollupPrivateInputs)}};var CheckpointRootRollupHints=class _CheckpointRootRollupHints{static{__name(this,"CheckpointRootRollupHints")}previousBlockHeader;previousArchiveSiblingPath;previousOutHash;newOutHashSiblingPath;startBlobAccumulator;finalBlobChallenges;blobFields;blobCommitments;blobsHash;constructor(previousBlockHeader,previousArchiveSiblingPath,previousOutHash,newOutHashSiblingPath,startBlobAccumulator,finalBlobChallenges,blobFields,blobCommitments,blobsHash){this.previousBlockHeader=previousBlockHeader,this.previousArchiveSiblingPath=previousArchiveSiblingPath,this.previousOutHash=previousOutHash,this.newOutHashSiblingPath=newOutHashSiblingPath,this.startBlobAccumulator=startBlobAccumulator,this.finalBlobChallenges=finalBlobChallenges,this.blobFields=blobFields,this.blobCommitments=blobCommitments,this.blobsHash=blobsHash}static from(fields){return new _CheckpointRootRollupHints(..._CheckpointRootRollupHints.getFields(fields))}static getFields(fields){return[fields.previousBlockHeader,fields.previousArchiveSiblingPath,fields.previousOutHash,fields.newOutHashSiblingPath,fields.startBlobAccumulator,fields.finalBlobChallenges,fields.blobFields,fields.blobCommitments,fields.blobsHash]}toBuffer(){return serializeToBuffer(..._CheckpointRootRollupHints.getFields(this))}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _CheckpointRootRollupHints(BlockHeader.fromBuffer(reader),reader.readArray(30,Fr),reader.readObject(AppendOnlyTreeSnapshot),reader.readArray(5,Fr),reader.readObject(BlobAccumulator),reader.readObject(FinalBlobBatchingChallenges),Array.from({length:4096*6},()=>Fr.fromBuffer(reader)),reader.readArray(6,BLS12Point),Fr.fromBuffer(reader))}toString(){return bufferToHex(this.toBuffer())}static fromString(str){return _CheckpointRootRollupHints.fromBuffer(hexToBuffer(str))}toJSON(){return this.toBuffer()}static get schema(){return bufferSchemaFor(_CheckpointRootRollupHints)}},CheckpointRootRollupPrivateInputs=class _CheckpointRootRollupPrivateInputs{static{__name(this,"CheckpointRootRollupPrivateInputs")}previousRollups;hints;constructor(previousRollups,hints){this.previousRollups=previousRollups,this.hints=hints}static from(fields){return new _CheckpointRootRollupPrivateInputs(..._CheckpointRootRollupPrivateInputs.getFields(fields))}static getFields(fields){return[fields.previousRollups,fields.hints]}toBuffer(){return serializeToBuffer(..._CheckpointRootRollupPrivateInputs.getFields(this))}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _CheckpointRootRollupPrivateInputs([ProofData.fromBuffer(reader,BlockRollupPublicInputs),ProofData.fromBuffer(reader,BlockRollupPublicInputs)],CheckpointRootRollupHints.fromBuffer(reader))}toString(){return bufferToHex(this.toBuffer())}static fromString(str){return _CheckpointRootRollupPrivateInputs.fromBuffer(hexToBuffer(str))}toJSON(){return this.toBuffer()}static get schema(){return bufferSchemaFor(_CheckpointRootRollupPrivateInputs)}},CheckpointRootSingleBlockRollupPrivateInputs=class _CheckpointRootSingleBlockRollupPrivateInputs{static{__name(this,"CheckpointRootSingleBlockRollupPrivateInputs")}previousRollup;hints;constructor(previousRollup,hints){this.previousRollup=previousRollup,this.hints=hints}static from(fields){return new _CheckpointRootSingleBlockRollupPrivateInputs(..._CheckpointRootSingleBlockRollupPrivateInputs.getFields(fields))}static getFields(fields){return[fields.previousRollup,fields.hints]}toBuffer(){return serializeToBuffer(..._CheckpointRootSingleBlockRollupPrivateInputs.getFields(this))}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _CheckpointRootSingleBlockRollupPrivateInputs(ProofData.fromBuffer(reader,BlockRollupPublicInputs),CheckpointRootRollupHints.fromBuffer(reader))}toString(){return bufferToHex(this.toBuffer())}static fromString(str){return _CheckpointRootSingleBlockRollupPrivateInputs.fromBuffer(hexToBuffer(str))}toJSON(){return this.toBuffer()}static get schema(){return bufferSchemaFor(_CheckpointRootSingleBlockRollupPrivateInputs)}},CheckpointPaddingRollupPrivateInputs=class _CheckpointPaddingRollupPrivateInputs{static{__name(this,"CheckpointPaddingRollupPrivateInputs")}constructor(){}toBuffer(){return Buffer.alloc(0)}static fromBuffer(_buffer){return new _CheckpointPaddingRollupPrivateInputs}toString(){return"0x"}static fromString(_str){return new _CheckpointPaddingRollupPrivateInputs}toJSON(){return this.toBuffer()}static get schema(){return bufferSchemaFor(_CheckpointPaddingRollupPrivateInputs)}};var PublicChonkVerifierPrivateInputs=class _PublicChonkVerifierPrivateInputs{static{__name(this,"PublicChonkVerifierPrivateInputs")}hidingKernelProofData;proverId;constructor(hidingKernelProofData,proverId){this.hidingKernelProofData=hidingKernelProofData,this.proverId=proverId}static from(fields){return new _PublicChonkVerifierPrivateInputs(..._PublicChonkVerifierPrivateInputs.getFields(fields))}static getFields(fields){return[fields.hidingKernelProofData,fields.proverId]}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _PublicChonkVerifierPrivateInputs(ProofData.fromBuffer(reader,PrivateToPublicKernelCircuitPublicInputs),Fr.fromBuffer(reader))}toBuffer(){return serializeToBuffer(..._PublicChonkVerifierPrivateInputs.getFields(this))}static fromString(str){return _PublicChonkVerifierPrivateInputs.fromBuffer(hexToBuffer(str))}toString(){return bufferToHex(this.toBuffer())}toJSON(){return this.toBuffer()}static get schema(){return bufferSchemaFor(_PublicChonkVerifierPrivateInputs)}};var RootRollupPrivateInputs=class _RootRollupPrivateInputs{static{__name(this,"RootRollupPrivateInputs")}previousRollups;constructor(previousRollups){this.previousRollups=previousRollups}toBuffer(){return serializeToBuffer(..._RootRollupPrivateInputs.getFields(this))}toString(){return bufferToHex(this.toBuffer())}static from(fields){return new _RootRollupPrivateInputs(..._RootRollupPrivateInputs.getFields(fields))}static getFields(fields){return[fields.previousRollups]}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _RootRollupPrivateInputs([ProofData.fromBuffer(reader,CheckpointRollupPublicInputs),ProofData.fromBuffer(reader,CheckpointRollupPublicInputs)])}static fromString(str){return _RootRollupPrivateInputs.fromBuffer(hexToBuffer(str))}toJSON(){return this.toBuffer()}static get schema(){return bufferSchemaFor(_RootRollupPrivateInputs)}};var BlockNumberNotSequentialError=class extends Error{static{__name(this,"BlockNumberNotSequentialError")}constructor(newBlockNumber,previous){super(`Cannot insert new block ${newBlockNumber} given previous block number is ${previous??"undefined"}`),this.name="BlockNumberNotSequentialError"}},InitialCheckpointNumberNotSequentialError=class extends Error{static{__name(this,"InitialCheckpointNumberNotSequentialError")}newCheckpointNumber;previousCheckpointNumber;constructor(newCheckpointNumber,previousCheckpointNumber){super(`Cannot insert new checkpoint ${newCheckpointNumber} given previous checkpoint number in store is ${previousCheckpointNumber??"undefined"}`),this.newCheckpointNumber=newCheckpointNumber,this.previousCheckpointNumber=previousCheckpointNumber,this.name="InitialCheckpointNumberNotSequentialError"}},CheckpointNumberNotSequentialError=class extends Error{static{__name(this,"CheckpointNumberNotSequentialError")}newCheckpointNumber;previousCheckpointNumber;constructor(newCheckpointNumber,previousCheckpointNumber,source){let qualifier=source?`${source} `:"";super(`Cannot insert new checkpoint ${newCheckpointNumber} given previous ${qualifier}checkpoint number is ${previousCheckpointNumber??"undefined"}`),this.newCheckpointNumber=newCheckpointNumber,this.previousCheckpointNumber=previousCheckpointNumber,this.name="CheckpointNumberNotSequentialError"}},BlockCheckpointNumberNotSequentialError=class extends Error{static{__name(this,"BlockCheckpointNumberNotSequentialError")}constructor(blockNumber,blockCheckpointNumber,previous){super(`Cannot insert new block ${blockNumber} for checkpoint ${blockCheckpointNumber} given previous checkpoint number is ${previous??"undefined"}`),this.name="BlockCheckpointNumberNotSequentialError"}},BlockIndexNotSequentialError=class extends Error{static{__name(this,"BlockIndexNotSequentialError")}constructor(newBlockIndex,previousBlockIndex){super(`Cannot insert new block at checkpoint index ${newBlockIndex} given previous block index is ${previousBlockIndex??"undefined"}`),this.name="BlockIndexNotSequentialError"}},BlockArchiveNotConsistentError=class extends Error{static{__name(this,"BlockArchiveNotConsistentError")}constructor(newBlockNumber,previousBlockNumber,newBlockArchive,previousBlockArchive){super(`Cannot insert new block number ${newBlockNumber} with archive ${newBlockArchive.toString()} previous block number is ${previousBlockNumber??"undefined"}, previous archive is ${previousBlockArchive?.toString()??"undefined"}`),this.name="BlockArchiveNotConsistentError"}},CheckpointNotFoundError=class extends Error{static{__name(this,"CheckpointNotFoundError")}constructor(checkpointNumber){super(`Failed to find expected checkpoint number ${checkpointNumber}`),this.name="CheckpointNotFoundError"}},BlockNotFoundError=class extends Error{static{__name(this,"BlockNotFoundError")}constructor(blockNumber){super(`Failed to find expected block number ${blockNumber}`),this.name="BlockNotFoundError"}},BlockAlreadyCheckpointedError=class extends Error{static{__name(this,"BlockAlreadyCheckpointedError")}blockNumber;constructor(blockNumber){super(`Block ${blockNumber} has already been checkpointed with the same content`),this.blockNumber=blockNumber,this.name="BlockAlreadyCheckpointedError"}},L1ToL2MessagesNotReadyError=class extends Error{static{__name(this,"L1ToL2MessagesNotReadyError")}checkpointNumber;inboxTreeInProgress;constructor(checkpointNumber,inboxTreeInProgress){super(`Cannot get L1 to L2 messages for checkpoint ${checkpointNumber}: inbox tree in progress is ${inboxTreeInProgress}, messages not yet sealed`),this.checkpointNumber=checkpointNumber,this.inboxTreeInProgress=inboxTreeInProgress,this.name="L1ToL2MessagesNotReadyError"}};var ProposedCheckpointNotSequentialError=class extends Error{static{__name(this,"ProposedCheckpointNotSequentialError")}proposedCheckpointNumber;latestTipNumber;constructor(proposedCheckpointNumber,latestTipNumber){super(`Proposed checkpoint ${proposedCheckpointNumber} is not sequential: expected ${latestTipNumber+1} (latest tip + 1, where tip is highest of confirmed or pending)`),this.proposedCheckpointNumber=proposedCheckpointNumber,this.latestTipNumber=latestTipNumber,this.name="ProposedCheckpointNotSequentialError"}};var NoProposedCheckpointToPromoteError=class extends Error{static{__name(this,"NoProposedCheckpointToPromoteError")}constructor(){super("Cannot promote proposed checkpoint: no proposed checkpoint exists"),this.name="NoProposedCheckpointToPromoteError"}},ProposedCheckpointArchiveRootMismatchError=class extends Error{static{__name(this,"ProposedCheckpointArchiveRootMismatchError")}expectedArchiveRoot;actualArchiveRoot;constructor(expectedArchiveRoot,actualArchiveRoot){super(`Cannot promote proposed checkpoint: archive root mismatch (expected ${expectedArchiveRoot}, got ${actualArchiveRoot})`),this.expectedArchiveRoot=expectedArchiveRoot,this.actualArchiveRoot=actualArchiveRoot,this.name="ProposedCheckpointArchiveRootMismatchError"}},ProposedCheckpointPromotionNotSequentialError=class extends Error{static{__name(this,"ProposedCheckpointPromotionNotSequentialError")}proposedCheckpointNumber;latestCheckpointNumber;constructor(proposedCheckpointNumber,latestCheckpointNumber){super(`Cannot promote proposed checkpoint: not sequential (latest ${latestCheckpointNumber}, proposed ${proposedCheckpointNumber})`),this.proposedCheckpointNumber=proposedCheckpointNumber,this.latestCheckpointNumber=latestCheckpointNumber,this.name="ProposedCheckpointPromotionNotSequentialError"}},CannotOverwriteCheckpointedBlockError=class extends Error{static{__name(this,"CannotOverwriteCheckpointedBlockError")}blockNumber;lastCheckpointedBlock;constructor(blockNumber,lastCheckpointedBlock){super(`Cannot add block ${blockNumber}: would overwrite checkpointed data (checkpointed up to block ${lastCheckpointedBlock})`),this.blockNumber=blockNumber,this.lastCheckpointedBlock=lastCheckpointedBlock,this.name="CannotOverwriteCheckpointedBlockError"}};var BlockStore=class{static{__name(this,"BlockStore")}db;#blocks;#proposedCheckpoints;#checkpoints;#slotToCheckpoint;#blockTxs;#txEffects;#lastSynchedL1Block;#lastProvenCheckpoint;#lastFinalizedCheckpoint;#pendingChainValidationStatus;#contractIndex;#blockHashIndex;#blockArchiveIndex;#rejectedCheckpoints;#rejectedCheckpointsByNumber;#log;constructor(db){this.db=db,this.#log=createLogger("archiver:block_store"),this.#blocks=db.openMap("archiver_blocks"),this.#blockTxs=db.openMap("archiver_block_txs"),this.#txEffects=db.openMap("archiver_tx_effects"),this.#contractIndex=db.openMap("archiver_contract_index"),this.#blockHashIndex=db.openMap("archiver_block_hash_index"),this.#blockArchiveIndex=db.openMap("archiver_block_archive_index"),this.#lastSynchedL1Block=db.openSingleton("archiver_last_synched_l1_block"),this.#lastProvenCheckpoint=db.openSingleton("archiver_last_proven_l2_checkpoint"),this.#lastFinalizedCheckpoint=db.openSingleton("archiver_last_finalized_l2_checkpoint"),this.#pendingChainValidationStatus=db.openSingleton("archiver_pending_chain_validation_status"),this.#checkpoints=db.openMap("archiver_checkpoints"),this.#slotToCheckpoint=db.openMap("archiver_slot_to_checkpoint"),this.#proposedCheckpoints=db.openMap("archiver_proposed_checkpoints"),this.#rejectedCheckpoints=db.openMap("archiver_rejected_checkpoints"),this.#rejectedCheckpointsByNumber=db.openMap("archiver_rejected_checkpoints_by_number")}async getFinalizedL2BlockNumber(){let finalizedCheckpointNumber=await this.getFinalizedCheckpointNumber();if(finalizedCheckpointNumber===INITIAL_CHECKPOINT_NUMBER2-1)return BlockNumber(INITIAL_L2_BLOCK_NUM2-1);let checkpointStorage=await this.#checkpoints.getAsync(finalizedCheckpointNumber);if(!checkpointStorage)throw new CheckpointNotFoundError(finalizedCheckpointNumber);return BlockNumber(checkpointStorage.startBlock+checkpointStorage.blockCount-1)}async addProposedBlock(block,opts={}){return await this.db.transactionAsync(async()=>{let blockNumber=block.number,blockCheckpointNumber=block.checkpointNumber,blockIndex=block.indexWithinCheckpoint,blockLastArchive=block.header.lastArchive.root,previousBlockNumber=await this.getLatestL2BlockNumber(),latestCheckpointNumber=await this.getLatestCheckpointNumber(),lastCheckpointedBlockNumber=await this.getCheckpointedL2BlockNumber();if(!opts.force&&blockNumber<=lastCheckpointedBlockNumber){let existingBlock=await this.getBlockData({number:BlockNumber(blockNumber)});throw existingBlock&&existingBlock.archive.root.equals(block.archive.root)?new BlockAlreadyCheckpointedError(blockNumber):new CannotOverwriteCheckpointedBlockError(blockNumber,lastCheckpointedBlockNumber)}if(!opts.force&&previousBlockNumber!==blockNumber-1)throw new BlockNumberNotSequentialError(blockNumber,previousBlockNumber);let expectedCheckpointNumber=blockCheckpointNumber-1,hasPendingAtExpected=await this.#proposedCheckpoints.hasAsync(expectedCheckpointNumber);if(!opts.force&&latestCheckpointNumber!==expectedCheckpointNumber&&!hasPendingAtExpected){let[latestPendingKey]=await toArray(this.#proposedCheckpoints.keysAsync({reverse:!0,limit:1})),previous=CheckpointNumber(Math.max(latestCheckpointNumber,latestPendingKey??0));throw new BlockCheckpointNumberNotSequentialError(BlockNumber(blockNumber),blockCheckpointNumber,previous)}let previousBlockResult=await this.getBlockData({number:previousBlockNumber}),expectedBlockIndex=0,previousBlockIndex;if(previousBlockResult!==void 0&&(previousBlockResult.checkpointNumber===blockCheckpointNumber&&(previousBlockIndex=previousBlockResult.indexWithinCheckpoint,expectedBlockIndex=previousBlockIndex+1),!previousBlockResult.archive.root.equals(blockLastArchive)))throw new BlockArchiveNotConsistentError(blockNumber,previousBlockResult.header.globalVariables.blockNumber,blockLastArchive,previousBlockResult.archive.root);if(!opts.force&&expectedBlockIndex!==blockIndex)throw new BlockIndexNotSequentialError(blockIndex,previousBlockIndex);return await this.addBlockToDatabase(block,block.checkpointNumber,block.indexWithinCheckpoint),!0})}async addCheckpoints(checkpoints,opts={}){return checkpoints.length===0?[]:await this.db.transactionAsync(async()=>{let firstCheckpointNumber=checkpoints[0].checkpoint.number,previousCheckpointNumber=await this.getLatestCheckpointNumber();if(!opts.force&&firstCheckpointNumber<=previousCheckpointNumber){if(checkpoints=await this.skipOrUpdateAlreadyStoredCheckpoints(checkpoints,previousCheckpointNumber),checkpoints.length===0)return[];let newFirstNumber=checkpoints[0].checkpoint.number;if(previousCheckpointNumber!==newFirstNumber-1)throw new InitialCheckpointNumberNotSequentialError(newFirstNumber,previousCheckpointNumber)}else if(previousCheckpointNumber!==firstCheckpointNumber-1&&!opts.force)throw new InitialCheckpointNumberNotSequentialError(firstCheckpointNumber,previousCheckpointNumber);let previousBlock=await this.getPreviousCheckpointBlock(checkpoints[0].checkpoint.number),previousCheckpoint;for(let checkpoint of checkpoints){if(!opts.force&&previousCheckpoint&&previousCheckpoint.checkpoint.number+1!==checkpoint.checkpoint.number)throw new CheckpointNumberNotSequentialError(checkpoint.checkpoint.number,previousCheckpoint.checkpoint.number);previousCheckpoint=checkpoint,this.validateCheckpointBlocks(checkpoint.checkpoint.blocks,previousBlock);for(let i=0;i<checkpoint.checkpoint.blocks.length;i++)await this.addBlockToDatabase(checkpoint.checkpoint.blocks[i],checkpoint.checkpoint.number,i);previousBlock=checkpoint.checkpoint.blocks.at(-1),await this.#checkpoints.set(checkpoint.checkpoint.number,{header:checkpoint.checkpoint.header.toBuffer(),archive:checkpoint.checkpoint.archive.toBuffer(),checkpointOutHash:checkpoint.checkpoint.getCheckpointOutHash().toBuffer(),l1:checkpoint.l1.toBuffer(),attestations:checkpoint.attestations.map(attestation=>attestation.toBuffer()),checkpointNumber:checkpoint.checkpoint.number,startBlock:checkpoint.checkpoint.blocks[0].number,blockCount:checkpoint.checkpoint.blocks.length,feeAssetPriceModifier:checkpoint.checkpoint.feeAssetPriceModifier.toString()}),await this.#slotToCheckpoint.set(checkpoint.checkpoint.header.slotNumber,checkpoint.checkpoint.number),await this.#proposedCheckpoints.delete(checkpoint.checkpoint.number),await this.removeRejectedCheckpointByArchiveRoot(checkpoint.checkpoint.archive.root)}return await this.advanceSynchedL1BlockNumber(checkpoints[checkpoints.length-1].l1.blockNumber),checkpoints})}async skipOrUpdateAlreadyStoredCheckpoints(checkpoints,latestStored){let i=0;for(;i<checkpoints.length&&checkpoints[i].checkpoint.number<=latestStored;i++){let incoming=checkpoints[i],stored=await this.getCheckpointData(incoming.checkpoint.number);if(!stored)break;if(!stored.archive.root.equals(incoming.checkpoint.archive.root))throw new Error(`Checkpoint ${incoming.checkpoint.number} already exists in store but with a different archive root. Stored: ${stored.archive.root}, incoming: ${incoming.checkpoint.archive.root}`);this.#log.warn(`Checkpoint ${incoming.checkpoint.number} already stored, updating L1 info (L1 block ${stored.l1.blockNumber} -> ${incoming.l1.blockNumber})`),await this.#checkpoints.set(incoming.checkpoint.number,{header:incoming.checkpoint.header.toBuffer(),archive:incoming.checkpoint.archive.toBuffer(),checkpointOutHash:incoming.checkpoint.getCheckpointOutHash().toBuffer(),l1:incoming.l1.toBuffer(),attestations:incoming.attestations.map(a=>a.toBuffer()),checkpointNumber:incoming.checkpoint.number,startBlock:incoming.checkpoint.blocks[0].number,blockCount:incoming.checkpoint.blocks.length,feeAssetPriceModifier:incoming.checkpoint.feeAssetPriceModifier.toString()}),await this.advanceSynchedL1BlockNumber(incoming.l1.blockNumber)}return checkpoints.slice(i)}async getPreviousCheckpointBlock(checkpointNumber){let previousCheckpointNumber=CheckpointNumber(checkpointNumber-1);if(previousCheckpointNumber===INITIAL_CHECKPOINT_NUMBER2-1)return;let predecessor=await this.getProposedCheckpointByNumber(previousCheckpointNumber)??await this.getCheckpointData(previousCheckpointNumber);if(!predecessor)throw new CheckpointNotFoundError(previousCheckpointNumber);let previousBlockNumber=BlockNumber(predecessor.startBlock+predecessor.blockCount-1),previousBlock=await this.getBlock({number:previousBlockNumber});if(previousBlock===void 0)throw new BlockNotFoundError(previousBlockNumber);return previousBlock}validateCheckpointBlocks(blocks,previousBlock){for(let block of blocks){if(previousBlock){if(previousBlock.number!==block.number-1)throw new BlockNumberNotSequentialError(block.number,previousBlock.number);if(previousBlock.checkpointNumber===block.checkpointNumber){if(previousBlock.indexWithinCheckpoint!==block.indexWithinCheckpoint-1)throw new BlockIndexNotSequentialError(block.indexWithinCheckpoint,previousBlock.indexWithinCheckpoint)}else if(block.indexWithinCheckpoint!==0)throw new BlockIndexNotSequentialError(block.indexWithinCheckpoint,previousBlock.indexWithinCheckpoint);if(!previousBlock.archive.root.equals(block.header.lastArchive.root))throw new BlockArchiveNotConsistentError(block.number,previousBlock.number,block.header.lastArchive.root,previousBlock.archive.root)}else{if(block.indexWithinCheckpoint!==0)throw new BlockIndexNotSequentialError(block.indexWithinCheckpoint,void 0);if(block.number!==INITIAL_L2_BLOCK_NUM2)throw new BlockNumberNotSequentialError(block.number,void 0)}previousBlock=block}}async addBlockToDatabase(block,checkpointNumber,indexWithinCheckpoint){let blockHash=await block.hash();await this.#blocks.set(block.number,{header:block.header.toBuffer(),blockHash:blockHash.toBuffer(),archive:block.archive.toBuffer(),checkpointNumber,indexWithinCheckpoint});for(let i=0;i<block.body.txEffects.length;i++){let txEffect={data:block.body.txEffects[i],l2BlockNumber:block.number,l2BlockHash:blockHash,txIndexInBlock:i,slotNumber:block.header.globalVariables.slotNumber};await this.#txEffects.set(txEffect.data.txHash.toString(),serializeIndexedTxEffect(txEffect))}await this.#blockTxs.set(blockHash.toString(),Buffer.concat(block.body.txEffects.map(tx=>tx.txHash.toBuffer()))),await this.#blockHashIndex.set(blockHash.toString(),block.number),await this.#blockArchiveIndex.set(block.archive.root.toString(),block.number)}async deleteBlock(block){await this.#blocks.delete(block.number),await Promise.all(block.body.txEffects.map(tx=>this.#txEffects.delete(tx.txHash.toString())));let blockHash=(await block.hash()).toString();await this.#blockTxs.delete(blockHash),await this.#blockHashIndex.delete(blockHash),await this.#blockArchiveIndex.delete(block.archive.root.toString())}async removeCheckpointsAfter(checkpointNumber){return await this.db.transactionAsync(async()=>{let latestCheckpointNumber=await this.getLatestCheckpointNumber();if(checkpointNumber>=latestCheckpointNumber)return this.#log.warn(`No checkpoints to remove after ${checkpointNumber} (latest is ${latestCheckpointNumber})`),{blocksRemoved:void 0};let proven=await this.getProvenCheckpointNumber();proven>checkpointNumber&&(this.#log.warn(`Updating proven checkpoint ${proven} to last valid checkpoint ${checkpointNumber}`),await this.setProvenCheckpointNumber(checkpointNumber));let lastBlockToKeep;if(checkpointNumber<=0)lastBlockToKeep=BlockNumber(INITIAL_L2_BLOCK_NUM2-1);else{let targetCheckpoint=await this.#checkpoints.getAsync(checkpointNumber);if(!targetCheckpoint)throw new Error(`Target checkpoint ${checkpointNumber} not found in store`);lastBlockToKeep=BlockNumber(targetCheckpoint.startBlock+targetCheckpoint.blockCount-1)}let blocksRemoved=await this.removeBlocksAfter(lastBlockToKeep);for(let c2=latestCheckpointNumber;c2>checkpointNumber;c2=CheckpointNumber(c2-1)){let checkpointStorage=await this.#checkpoints.getAsync(c2);if(checkpointStorage){let slotNumber=CheckpointHeader.fromBuffer(checkpointStorage.header).slotNumber;await this.#slotToCheckpoint.delete(slotNumber)}await this.#checkpoints.delete(c2),this.#log.debug(`Removed checkpoint ${c2}`)}return await this.evictProposedCheckpointsFrom(CheckpointNumber(checkpointNumber+1)),{blocksRemoved}})}async getCheckpointData(checkpointNumber){let checkpointStorage=await this.#checkpoints.getAsync(checkpointNumber);if(checkpointStorage)return this.checkpointDataFromCheckpointStorage(checkpointStorage)}async getRangeOfCheckpoints(from,limit){let checkpoints=[];for(let checkpointNumber=from;checkpointNumber<from+limit;checkpointNumber++){let checkpoint=await this.#checkpoints.getAsync(checkpointNumber);if(!checkpoint)break;checkpoints.push(this.checkpointDataFromCheckpointStorage(checkpoint))}return checkpoints}async getCheckpointDataForSlotRange(startSlot,endSlot){let result=[];for await(let[,checkpointNumber]of this.#slotToCheckpoint.entriesAsync({start:startSlot,end:endSlot+1})){let checkpointStorage=await this.#checkpoints.getAsync(checkpointNumber);checkpointStorage&&result.push(this.checkpointDataFromCheckpointStorage(checkpointStorage))}return result}async getCheckpointNumbersForSlotRange(startSlot,endSlot){let result=[];for await(let[,checkpointNumber]of this.#slotToCheckpoint.entriesAsync({start:startSlot,end:endSlot+1}))result.push(CheckpointNumber(checkpointNumber));return result}checkpointDataFromCheckpointStorage(checkpointStorage){return{header:CheckpointHeader.fromBuffer(checkpointStorage.header),archive:AppendOnlyTreeSnapshot.fromBuffer(checkpointStorage.archive),checkpointOutHash:Fr.fromBuffer(checkpointStorage.checkpointOutHash),checkpointNumber:CheckpointNumber(checkpointStorage.checkpointNumber),startBlock:BlockNumber(checkpointStorage.startBlock),blockCount:checkpointStorage.blockCount,feeAssetPriceModifier:BigInt(checkpointStorage.feeAssetPriceModifier),l1:L1PublishedData.fromBuffer(checkpointStorage.l1),attestations:checkpointStorage.attestations.map(buf=>CommitteeAttestation.fromBuffer(buf))}}async getBlocksForCheckpoint(checkpointNumber){let checkpoint=await this.#checkpoints.getAsync(checkpointNumber);if(!checkpoint)return;let blocksForCheckpoint=await toArray(this.#blocks.entriesAsync({start:checkpoint.startBlock,end:checkpoint.startBlock+checkpoint.blockCount}));return(await Promise.all(blocksForCheckpoint.map(x=>this.getBlockFromBlockStorage(x[0],x[1])))).filter(isDefined)}async getBlocksForSlot(slotNumber){let blocks=[];for await(let[blockNumber,blockStorage]of this.#blocks.entriesAsync({reverse:!0})){let block=await this.getBlockFromBlockStorage(blockNumber,blockStorage),blockSlot=block?.header.globalVariables.slotNumber;if(block&&blockSlot===slotNumber)blocks.push(block);else if(blockSlot&&blockSlot<slotNumber)break}return blocks.reverse()}async removeBlocksAfter(blockNumber){return await this.db.transactionAsync(async()=>{let removedBlocks=[],latestBlockNumber=await this.getLatestL2BlockNumber();for(let bn=blockNumber+1;bn<=latestBlockNumber;bn++){let block=await this.getBlock({number:BlockNumber(bn)});if(block===void 0){this.#log.warn(`Cannot remove block ${bn} from the store since we don't have it`);continue}removedBlocks.push(block),await this.deleteBlock(block),this.#log.debug(`Removed block ${bn} ${(await block.hash()).toString()}`)}return removedBlocks})}async getProvenBlockNumber(){let provenCheckpointNumber=await this.getProvenCheckpointNumber();if(provenCheckpointNumber===INITIAL_CHECKPOINT_NUMBER2-1)return BlockNumber(INITIAL_L2_BLOCK_NUM2-1);let checkpointStorage=await this.#checkpoints.getAsync(provenCheckpointNumber);if(checkpointStorage)return BlockNumber(checkpointStorage.startBlock+checkpointStorage.blockCount-1);throw new CheckpointNotFoundError(provenCheckpointNumber)}async getLatestCheckpointNumber(){let[latestCheckpointNumber]=await toArray(this.#checkpoints.keysAsync({reverse:!0,limit:1}));return latestCheckpointNumber===void 0?CheckpointNumber(INITIAL_CHECKPOINT_NUMBER2-1):CheckpointNumber(latestCheckpointNumber)}async hasProposedCheckpoint(){let[key]=await toArray(this.#proposedCheckpoints.keysAsync({limit:1}));return key!==void 0}async deleteProposedCheckpoints(){for await(let key of this.#proposedCheckpoints.keysAsync())await this.#proposedCheckpoints.delete(key)}async promoteProposedToCheckpointed(checkpointNumber,l1,attestations,expectedArchiveRoot){return await this.db.transactionAsync(async()=>{let proposed=await this.getProposedCheckpointByNumber(checkpointNumber);if(!proposed)throw new NoProposedCheckpointToPromoteError;if(!proposed.archive.root.equals(expectedArchiveRoot))throw new ProposedCheckpointArchiveRootMismatchError(expectedArchiveRoot,proposed.archive.root);let latestCheckpointNumber=await this.getLatestCheckpointNumber();if(latestCheckpointNumber!==proposed.checkpointNumber-1)throw new ProposedCheckpointPromotionNotSequentialError(proposed.checkpointNumber,latestCheckpointNumber);await this.#checkpoints.set(proposed.checkpointNumber,{header:proposed.header.toBuffer(),archive:proposed.archive.toBuffer(),checkpointOutHash:proposed.checkpointOutHash.toBuffer(),l1:l1.toBuffer(),attestations:attestations.map(attestation=>attestation.toBuffer()),checkpointNumber:proposed.checkpointNumber,startBlock:proposed.startBlock,blockCount:proposed.blockCount,feeAssetPriceModifier:proposed.feeAssetPriceModifier.toString()}),await this.#slotToCheckpoint.set(proposed.header.slotNumber,proposed.checkpointNumber),await this.#proposedCheckpoints.delete(proposed.checkpointNumber),await this.removeRejectedCheckpointByArchiveRoot(proposed.archive.root),await this.advanceSynchedL1BlockNumber(l1.blockNumber)})}async getLastProposedCheckpoint(){let[key]=await toArray(this.#proposedCheckpoints.keysAsync({reverse:!0,limit:1}));if(key===void 0)return;let stored=await this.#proposedCheckpoints.getAsync(key);return stored?this.convertToProposedCheckpointData(stored):void 0}async getProposedCheckpointByNumber(n){let stored=await this.#proposedCheckpoints.getAsync(n);return stored?this.convertToProposedCheckpointData(stored):void 0}async getProposedCheckpointBySlot(slot){for await(let[,stored]of this.#proposedCheckpoints.entriesAsync())if(CheckpointHeader.fromBuffer(stored.header).slotNumber===slot)return this.convertToProposedCheckpointData(stored)}async evictProposedCheckpointsFrom(fromNumber){let keysToDelete=[];for await(let key of this.#proposedCheckpoints.keysAsync())key>=fromNumber&&keysToDelete.push(key);for(let key of keysToDelete)await this.#proposedCheckpoints.delete(key)}async getLastCheckpoint(){let latest=await this.getLastProposedCheckpoint();return latest||this.getCheckpointData(await this.getLatestCheckpointNumber())}convertToProposedCheckpointData(stored){return{checkpointNumber:CheckpointNumber(stored.checkpointNumber),header:CheckpointHeader.fromBuffer(stored.header),archive:AppendOnlyTreeSnapshot.fromBuffer(stored.archive),checkpointOutHash:Fr.fromBuffer(stored.checkpointOutHash),startBlock:BlockNumber(stored.startBlock),blockCount:stored.blockCount,totalManaUsed:BigInt(stored.totalManaUsed),feeAssetPriceModifier:BigInt(stored.feeAssetPriceModifier)}}async getProposedCheckpointNumber(){let proposed=await this.getLastCheckpoint();return proposed?CheckpointNumber(proposed.checkpointNumber):await this.getLatestCheckpointNumber()}async getProposedCheckpointL2BlockNumber(){let proposed=await this.getLastCheckpoint();return proposed?BlockNumber(proposed.startBlock+proposed.blockCount-1):await this.getCheckpointedL2BlockNumber()}async getCheckpointNumberBySlot(slot){let checkpointNumber=await this.#slotToCheckpoint.getAsync(slot);return checkpointNumber===void 0?void 0:CheckpointNumber(checkpointNumber)}async getBlock(query){let blockNumber=await this.getBlockNumber(query);if(blockNumber===void 0)return;let blockStorage=await this.#blocks.getAsync(blockNumber);if(blockStorage)return this.getBlockFromBlockStorage(blockNumber,blockStorage)}getBlocks(query){return toArray(this.iterateBlocks(query))}async getBlockData(query){let blockNumber=await this.getBlockNumber(query);if(blockNumber===void 0)return;let blockStorage=await this.#blocks.getAsync(blockNumber);if(!(!blockStorage||!blockStorage.header))return this.getBlockDataFromBlockStorage(blockStorage)}getBlocksData(query){return toArray(this.iterateBlocksData(query))}async*iterateBlocks(query){let cap=query.onlyCheckpointed?await this.getCheckpointedL2BlockNumber():void 0;for await(let[blockNumber,blockStorage]of this.getBlockStorages(query.from,query.limit)){if(cap!==void 0&&blockNumber>cap)break;let block=await this.getBlockFromBlockStorage(blockNumber,blockStorage);block&&(yield block)}}async*iterateBlocksData(query){let cap=query.onlyCheckpointed?await this.getCheckpointedL2BlockNumber():void 0;for await(let[blockNumber,blockStorage]of this.getBlockStorages(query.from,query.limit)){if(cap!==void 0&&blockNumber>cap)break;yield this.getBlockDataFromBlockStorage(blockStorage)}}async*getBlockStorages(start,limit){let expectedBlockNumber=start;for await(let[blockNumber,blockStorage]of this.#blocks.entriesAsync(this.#computeBlockRange(start,limit))){if(blockNumber!==expectedBlockNumber)throw new Error(`Block number mismatch when iterating blocks from archive (expected ${expectedBlockNumber} but got ${blockNumber})`);expectedBlockNumber++,yield[blockNumber,blockStorage]}}async getBlockNumber(query){let blockNumber;if("number"in query)blockNumber=query.number;else if("hash"in query){let n=await this.#blockHashIndex.getAsync(query.hash.toString());blockNumber=n!==void 0?BlockNumber(n):void 0}else{let n=await this.#blockArchiveIndex.getAsync(query.archive.toString());blockNumber=n!==void 0?BlockNumber(n):void 0}if(blockNumber!==void 0)return blockNumber}getBlockDataFromBlockStorage(blockStorage){return{header:BlockHeader.fromBuffer(blockStorage.header),archive:AppendOnlyTreeSnapshot.fromBuffer(blockStorage.archive),blockHash:BlockHash.fromBuffer(blockStorage.blockHash),checkpointNumber:CheckpointNumber(blockStorage.checkpointNumber),indexWithinCheckpoint:IndexWithinCheckpoint(blockStorage.indexWithinCheckpoint)}}async getBlockFromBlockStorage(blockNumber,blockStorage){let{header,archive,blockHash,checkpointNumber,indexWithinCheckpoint}=this.getBlockDataFromBlockStorage(blockStorage);header.setHash(blockHash);let blockHashString=bufferToHex(blockStorage.blockHash),blockTxsBuffer=await this.#blockTxs.getAsync(blockHashString);if(blockTxsBuffer===void 0){this.#log.warn(`Could not find body for block ${header.globalVariables.blockNumber} ${blockHash}`);return}let txEffects=[],reader=BufferReader.asReader(blockTxsBuffer);for(;!reader.isEmpty();){let txHash=reader.readObject(TxHash),txEffect=await this.#txEffects.getAsync(txHash.toString());if(txEffect===void 0){this.#log.warn(`Could not find tx effect for tx ${txHash} in block ${blockNumber}`);return}txEffects.push(deserializeIndexedTxEffect(txEffect).data)}let body=new Body(txEffects),block=new L2Block(archive,header,body,checkpointNumber,indexWithinCheckpoint);if(block.number!==blockNumber)throw new Error(`Block number mismatch when retrieving block from archive (expected ${blockNumber} but got ${block.number} with hash ${blockHashString})`);return block}async getTxEffect(txHash){let buffer=await this.#txEffects.getAsync(txHash.toString());if(buffer)return deserializeIndexedTxEffect(buffer)}async getTxLocation(txHash){let txEffect=await this.#txEffects.getAsync(txHash.toString());if(!txEffect)return;let view=Buffer.from(txEffect.buffer,txEffect.byteOffset,txEffect.byteLength),l2BlockNumber=view.readUInt32BE(32),txIndexInBlock=view.readUInt32BE(36);return[l2BlockNumber,txIndexInBlock]}getNoteHashesAndNullifiers(txHashes){return Promise.all(txHashes.map(async txHash=>{let buffer=await this.#txEffects.getAsync(txHash.toString());if(!buffer)return[[],[]];let reader=BufferReader.asReader(buffer);reader.readBytes(109);let noteHashes=reader.readVectorUint8Prefix(Fr),nullifiers=reader.readVectorUint8Prefix(Fr);return[noteHashes,nullifiers]}))}getContractLocation(contractAddress){return this.#contractIndex.getAsync(contractAddress.toString())}async getCheckpointedL2BlockNumber(){let latestCheckpointNumber=await this.getLatestCheckpointNumber(),checkpoint=await this.getCheckpointData(latestCheckpointNumber);return checkpoint?BlockNumber(checkpoint.startBlock+checkpoint.blockCount-1):BlockNumber(INITIAL_L2_BLOCK_NUM2-1)}async getLatestL2BlockNumber(){let[lastBlockNumber]=await toArray(this.#blocks.keysAsync({reverse:!0,limit:1}));return typeof lastBlockNumber=="number"?BlockNumber(lastBlockNumber):BlockNumber(INITIAL_L2_BLOCK_NUM2-1)}async getL2TipsData(genesisBlockHash){return await this.db.transactionAsync(async()=>{let genesisBlockNumber=BlockNumber(INITIAL_L2_BLOCK_NUM2-1),genesisCheckpointNumber=CheckpointNumber(INITIAL_CHECKPOINT_NUMBER2-1),genesisBlockId={number:genesisBlockNumber,hash:genesisBlockHash.toString()},genesisCheckpointId={number:genesisCheckpointNumber,hash:GENESIS_CHECKPOINT_HEADER_HASH.toString()},genesisTip={block:genesisBlockId,checkpoint:genesisCheckpointId},[latestBlockEntry]=await toArray(this.#blocks.entriesAsync({reverse:!0,limit:1})),[latestCheckpointEntry]=await toArray(this.#checkpoints.entriesAsync({reverse:!0,limit:1})),latestCheckpointNumber=latestCheckpointEntry?CheckpointNumber(latestCheckpointEntry[0]):genesisCheckpointNumber,[provenRaw,finalizedRaw]=await Promise.all([this.#lastProvenCheckpoint.getAsync(),this.#lastFinalizedCheckpoint.getAsync()]),provenCheckpointNumber=CheckpointNumber(Math.min(provenRaw??0,latestCheckpointNumber)),finalizedCheckpointNumber=CheckpointNumber(Math.min(finalizedRaw??0,provenCheckpointNumber)),checkpointStorageCache=new Map;latestCheckpointEntry&&checkpointStorageCache.set(CheckpointNumber(latestCheckpointEntry[0]),latestCheckpointEntry[1]);let loadCheckpointStorage=__name(async n=>{if(n!==0){if(!checkpointStorageCache.has(n)){let checkpointStorage=await this.#checkpoints.getAsync(n);if(!checkpointStorage)throw new CheckpointNotFoundError(n);checkpointStorageCache.set(n,checkpointStorage)}return checkpointStorageCache.get(n)}},"loadCheckpointStorage"),provenCheckpoint=await loadCheckpointStorage(provenCheckpointNumber),finalizedCheckpoint=await loadCheckpointStorage(finalizedCheckpointNumber),blockHashCache=new Map;blockHashCache.set(genesisBlockNumber,genesisBlockHash.toString()),latestBlockEntry&&blockHashCache.set(latestBlockEntry[0],BlockHash.fromBuffer(latestBlockEntry[1].blockHash).toString());let loadBlockHash=__name(async n=>{if(!blockHashCache.has(n)){let blockStorage=await this.#blocks.getAsync(n);if(!blockStorage)throw new BlockNotFoundError(n);let blockHash=BlockHash.fromBuffer(blockStorage.blockHash).toString();blockHashCache.set(n,blockHash)}return blockHashCache.get(n)},"loadBlockHash"),proposedBlockId=latestBlockEntry===void 0?genesisBlockId:{number:BlockNumber(latestBlockEntry[0]),hash:BlockHash.fromBuffer(latestBlockEntry[1].blockHash).toString()},buildTipFromCheckpoint=__name(async stored=>{if(!stored)return genesisTip;let blockNumber=BlockNumber(stored.startBlock+stored.blockCount-1),blockHash=await loadBlockHash(blockNumber),header=CheckpointHeader.fromBuffer(stored.header);return{block:{number:blockNumber,hash:blockHash},checkpoint:{number:CheckpointNumber(stored.checkpointNumber),hash:header.hash().toString()}}},"buildTipFromCheckpoint"),checkpointedTip=await buildTipFromCheckpoint(latestCheckpointEntry?.[1]),provenTip=await buildTipFromCheckpoint(provenCheckpoint),finalizedTip=await buildTipFromCheckpoint(finalizedCheckpoint);if(proposedBlockId.number<checkpointedTip.block.number)throw new Error(`Inconsistent block store: latest block ${proposedBlockId.number} is behind checkpointed block ${checkpointedTip.block.number}`);if(finalizedTip.checkpoint.number>provenTip.checkpoint.number||provenTip.checkpoint.number>checkpointedTip.checkpoint.number)throw new Error(`Inconsistent checkpoint numbers in chain tips: finalized=${finalizedTip.checkpoint.number} proven=${provenTip.checkpoint.number} checkpointed=${checkpointedTip.checkpoint.number}`);if(finalizedTip.block.number>provenTip.block.number||provenTip.block.number>checkpointedTip.block.number||checkpointedTip.block.number>proposedBlockId.number)throw new Error(`Inconsistent block numbers in chain tips: finalized=${finalizedTip.block.number} proven=${provenTip.block.number} checkpointed=${checkpointedTip.block.number} proposed=${proposedBlockId.number}`);return{proposed:proposedBlockId,checkpointed:checkpointedTip,proven:provenTip,finalized:finalizedTip}})}getSynchedL1BlockNumber(){return this.#lastSynchedL1Block.getAsync()}setSynchedL1BlockNumber(l1BlockNumber){return this.#lastSynchedL1Block.set(l1BlockNumber)}async addProposedCheckpoint(proposed){return await this.db.transactionAsync(async()=>{let confirmed=await this.getLatestCheckpointNumber(),[latestPendingKey]=await toArray(this.#proposedCheckpoints.keysAsync({reverse:!0,limit:1})),latestTip=CheckpointNumber(latestPendingKey!==void 0?Math.max(latestPendingKey,confirmed):confirmed);if(proposed.checkpointNumber!==latestTip+1)throw new ProposedCheckpointNotSequentialError(proposed.checkpointNumber,latestTip);let previousBlock=await this.getPreviousCheckpointBlock(proposed.checkpointNumber),blocks=[];for(let i=0;i<proposed.blockCount;i++){let block=await this.getBlock({number:BlockNumber(proposed.startBlock+i)});if(!block)throw new BlockNotFoundError(proposed.startBlock+i);blocks.push(block)}this.validateCheckpointBlocks(blocks,previousBlock);let archive=blocks[blocks.length-1].archive,checkpointOutHash=Checkpoint.getCheckpointOutHash(blocks);await this.#proposedCheckpoints.set(proposed.checkpointNumber,{header:proposed.header.toBuffer(),archive:archive.toBuffer(),checkpointOutHash:checkpointOutHash.toBuffer(),checkpointNumber:proposed.checkpointNumber,startBlock:proposed.startBlock,blockCount:proposed.blockCount,totalManaUsed:proposed.totalManaUsed.toString(),feeAssetPriceModifier:proposed.feeAssetPriceModifier.toString()})})}async getProvenCheckpointNumber(){return await this.db.transactionAsync(async()=>{let[latestCheckpointNumber,provenCheckpointNumber]=await Promise.all([this.getLatestCheckpointNumber(),this.#lastProvenCheckpoint.getAsync()]);return(provenCheckpointNumber??0)>latestCheckpointNumber?latestCheckpointNumber:CheckpointNumber(provenCheckpointNumber??0)})}async setProvenCheckpointNumber(checkpointNumber){return await this.#lastProvenCheckpoint.set(checkpointNumber)}async getFinalizedCheckpointNumber(){return await this.db.transactionAsync(async()=>{let[provenCheckpointNumber,finalizedCheckpointNumber]=await Promise.all([this.getProvenCheckpointNumber(),this.#lastFinalizedCheckpoint.getAsync()]);return(finalizedCheckpointNumber??0)>provenCheckpointNumber?provenCheckpointNumber:CheckpointNumber(finalizedCheckpointNumber??0)})}setFinalizedCheckpointNumber(checkpointNumber){return this.#lastFinalizedCheckpoint.set(checkpointNumber)}#computeBlockRange(start,limit){if(limit<1)throw new Error(`Invalid limit: ${limit}`);if(start<INITIAL_L2_BLOCK_NUM2)throw new Error(`Invalid start: ${start}`);return{start,limit}}async getPendingChainValidationStatus(){let buffer=await this.#pendingChainValidationStatus.getAsync();if(buffer)return deserializeValidateCheckpointResult(buffer)}async setPendingChainValidationStatus(status){if(status){let buffer=serializeValidateCheckpointResult(status);await this.#pendingChainValidationStatus.set(buffer)}else await this.#pendingChainValidationStatus.delete()}async addRejectedCheckpoint(entry){let archiveRootHex=entry.archiveRoot.toString();await this.#rejectedCheckpoints.set(archiveRootHex,{checkpointNumber:entry.checkpointNumber,archiveRoot:entry.archiveRoot.toBuffer(),parentArchiveRoot:entry.parentArchiveRoot.toBuffer(),slotNumber:entry.slotNumber,l1:entry.l1.toBuffer(),reason:entry.reason}),await this.#rejectedCheckpointsByNumber.set(entry.checkpointNumber,archiveRootHex),await this.advanceSynchedL1BlockNumber(entry.l1.blockNumber)}async getRejectedCheckpointByArchiveRoot(archiveRoot){let stored=await this.#rejectedCheckpoints.getAsync(archiveRoot.toString());return stored?this.rejectedCheckpointFromStorage(stored):void 0}async getRejectedCheckpointByNumber(checkpointNumber){let archiveRootHex=await this.#rejectedCheckpointsByNumber.getAsync(checkpointNumber);if(archiveRootHex===void 0)return;let stored=await this.#rejectedCheckpoints.getAsync(archiveRootHex);return stored?this.rejectedCheckpointFromStorage(stored):void 0}async getLatestRejectedCheckpointNumber(){let[latest]=await toArray(this.#rejectedCheckpointsByNumber.keysAsync({reverse:!0,limit:1}));return CheckpointNumber(latest??INITIAL_CHECKPOINT_NUMBER2-1)}async removeRejectedCheckpointByArchiveRoot(archiveRoot){let archiveRootHex=archiveRoot.toString(),stored=await this.#rejectedCheckpoints.getAsync(archiveRootHex);await this.#rejectedCheckpoints.delete(archiveRootHex),stored&&await this.#rejectedCheckpointsByNumber.getAsync(stored.checkpointNumber)===archiveRootHex&&await this.#rejectedCheckpointsByNumber.delete(stored.checkpointNumber)}async advanceSynchedL1BlockNumber(l1BlockNumber){let current=await this.#lastSynchedL1Block.getAsync();(current===void 0||l1BlockNumber>current)&&await this.#lastSynchedL1Block.set(l1BlockNumber)}rejectedCheckpointFromStorage(stored){return{checkpointNumber:CheckpointNumber(stored.checkpointNumber),archiveRoot:Fr.fromBuffer(stored.archiveRoot),parentArchiveRoot:Fr.fromBuffer(stored.parentArchiveRoot),slotNumber:SlotNumber(stored.slotNumber),l1:L1PublishedData.fromBuffer(stored.l1),reason:stored.reason}}};var ContractClassStore=class{static{__name(this,"ContractClassStore")}db;#contractClasses;#bytecodeCommitments;constructor(db){this.db=db,this.#contractClasses=db.openMap("archiver_contract_classes"),this.#bytecodeCommitments=db.openMap("archiver_bytecode_commitments")}async addContractClasses(data,blockNumber){return(await Promise.all(data.map(c2=>this.addContractClass(c2,c2.publicBytecodeCommitment,blockNumber)))).every(Boolean)}async deleteContractClasses(data,blockNumber){return(await Promise.all(data.map(c2=>this.deleteContractClass(c2,blockNumber)))).every(Boolean)}async addContractClass(contractClass,bytecodeCommitment,blockNumber){await this.db.transactionAsync(async()=>{let key=contractClass.id.toString(),existing=await this.#contractClasses.getAsync(key);if(existing!==void 0){if(isProtocolContractClass(contractClass.id)||deserializeContractClassPublic(existing).l2BlockNumber===blockNumber)return;throw new Error(`Contract class ${key} already exists, cannot add again at block ${blockNumber}`)}await this.#contractClasses.set(key,serializeContractClassPublic({...contractClass,l2BlockNumber:blockNumber})),await this.#bytecodeCommitments.set(key,bytecodeCommitment.toBuffer())})}async deleteContractClass(contractClass,blockNumber){if(isProtocolContractClass(contractClass.id))return;let restoredContractClass=await this.#contractClasses.getAsync(contractClass.id.toString());restoredContractClass&&deserializeContractClassPublic(restoredContractClass).l2BlockNumber>=blockNumber&&await this.db.transactionAsync(async()=>{await this.#contractClasses.delete(contractClass.id.toString()),await this.#bytecodeCommitments.delete(contractClass.id.toString())})}async getContractClass(id){let contractClass=await this.#contractClasses.getAsync(id.toString());return contractClass&&{...deserializeContractClassPublic(contractClass),id}}async getBytecodeCommitment(id){let value=await this.#bytecodeCommitments.getAsync(id.toString());return value===void 0?void 0:Fr.fromBuffer(value)}async getContractClassIds(){return(await toArray(this.#contractClasses.keysAsync())).map(key=>Fr.fromHexString(key))}};function serializeContractClassPublic(contractClass){return serializeToBuffer(contractClass.l2BlockNumber,numToUInt8(contractClass.version),contractClass.artifactHash,contractClass.packedBytecode.length,contractClass.packedBytecode,contractClass.privateFunctionsRoot)}__name(serializeContractClassPublic,"serializeContractClassPublic");function deserializeContractClassPublic(buffer){let reader=BufferReader.asReader(buffer);return{l2BlockNumber:reader.readNumber(),version:reader.readUInt8(),artifactHash:reader.readObject(Fr),packedBytecode:reader.readBuffer(),privateFunctionsRoot:reader.readObject(Fr)}}__name(deserializeContractClassPublic,"deserializeContractClassPublic");var ContractInstanceStore=class{static{__name(this,"ContractInstanceStore")}db;#contractInstances;#contractInstancePublishedAt;#contractInstanceUpdates;constructor(db){this.db=db,this.#contractInstances=db.openMap("archiver_contract_instances"),this.#contractInstancePublishedAt=db.openMap("archiver_contract_instances_publication_block_number"),this.#contractInstanceUpdates=db.openMap("archiver_contract_instance_updates")}async addContractInstances(data,blockNumber){return(await Promise.all(data.map(c2=>this.addContractInstance(c2,blockNumber)))).every(Boolean)}async deleteContractInstances(data){return(await Promise.all(data.map(c2=>this.deleteContractInstance(c2)))).every(Boolean)}async addContractInstanceUpdates(data,timestamp){return(await Promise.all(data.map((update,logIndex)=>this.addContractInstanceUpdate(update,timestamp,logIndex)))).every(Boolean)}async deleteContractInstanceUpdates(data,timestamp){return(await Promise.all(data.map((update,logIndex)=>this.deleteContractInstanceUpdate(update,timestamp,logIndex)))).every(Boolean)}addContractInstance(contractInstance,blockNumber){return this.db.transactionAsync(async()=>{let key=contractInstance.address.toString();if(await this.#contractInstances.hasAsync(key)){if(isProtocolContract(contractInstance.address))return;let existingBlockNumber=await this.#contractInstancePublishedAt.getAsync(key);if(existingBlockNumber===blockNumber)return;throw new Error(`Contract instance at ${key} already exists (deployed at block ${existingBlockNumber}), cannot add again at block ${blockNumber}`)}await this.#contractInstances.set(key,new SerializableContractInstance(contractInstance).toBuffer()),await this.#contractInstancePublishedAt.set(key,blockNumber)})}deleteContractInstance(contractInstance){return isProtocolContract(contractInstance.address)?Promise.resolve():this.db.transactionAsync(async()=>{await this.#contractInstances.delete(contractInstance.address.toString()),await this.#contractInstancePublishedAt.delete(contractInstance.address.toString())})}getUpdateKey(contractAddress,timestamp,logIndex){return logIndex===void 0?[contractAddress.toString(),timestamp.toString()]:[contractAddress.toString(),timestamp.toString(),logIndex]}addContractInstanceUpdate(contractInstanceUpdate,timestamp,logIndex){return this.#contractInstanceUpdates.set(this.getUpdateKey(contractInstanceUpdate.address,timestamp,logIndex),new SerializableContractInstanceUpdate(contractInstanceUpdate).toBuffer())}deleteContractInstanceUpdate(contractInstanceUpdate,timestamp,logIndex){return this.#contractInstanceUpdates.delete(this.getUpdateKey(contractInstanceUpdate.address,timestamp,logIndex))}async getCurrentContractInstanceClassId(address,timestamp,originalClassId){let queryResult=await this.#contractInstanceUpdates.valuesAsync({reverse:!0,start:this.getUpdateKey(address,0n),end:this.getUpdateKey(address,timestamp+1n),limit:1}).next();if(queryResult.done)return originalClassId;let serializedUpdate=queryResult.value,update=SerializableContractInstanceUpdate.fromBuffer(serializedUpdate);return timestamp<update.timestampOfChange?update.prevContractClassId.isZero()?originalClassId:update.prevContractClassId:update.newContractClassId}async getContractInstance(address,timestamp){let contractInstance=await this.#contractInstances.getAsync(address.toString());if(!contractInstance)return;let instance=SerializableContractInstance.fromBuffer(contractInstance).withAddress(address);return instance.currentContractClassId=await this.getCurrentContractInstanceClassId(address,timestamp,instance.originalContractClassId),instance}getContractInstanceDeploymentBlockNumber(address){return this.#contractInstancePublishedAt.getAsync(address.toString())}};var MAX_FUNCTION_SIGNATURES=1e3,MAX_FUNCTION_NAME_LEN=256,FunctionNamesCache=class{static{__name(this,"FunctionNamesCache")}log=createLogger("archiver:data-stores");names=new Map;async register(signatures){for(let sig of signatures){if(this.names.size>MAX_FUNCTION_SIGNATURES)return;try{let selector=await FunctionSelector.fromSignature(sig);this.names.set(selector.toString(),sig.slice(0,sig.indexOf("(")).slice(0,MAX_FUNCTION_NAME_LEN))}catch{this.log.warn(`Failed to parse signature: ${sig}. Ignoring`)}}}get(selector){return this.names.get(selector.toString())}};var NUMERIC_HEX_LEN=8,SEP="-",HEX_SENTINEL="g";function fieldHex(value){return value.toString().slice(2)}__name(fieldHex,"fieldHex");function tagHexForLog(fields){return fields.length>0?fieldHex(fields[0]):""}__name(tagHexForLog,"tagHexForLog");function u32Hex(n){return n.toString(16).padStart(NUMERIC_HEX_LEN,"0")}__name(u32Hex,"u32Hex");function encodeKey(prefix,blockNumber,txIndex,logIndex){return`${prefix}${SEP}${u32Hex(blockNumber)}${SEP}${u32Hex(txIndex)}${SEP}${u32Hex(logIndex)}`}__name(encodeKey,"encodeKey");function decodeKeyTail(key){let parts=key.split(SEP),len=parts.length;return{blockNumber:BlockNumber(parseInt(parts[len-3],16)),txIndexWithinBlock:parseInt(parts[len-2],16),logIndexWithinTx:parseInt(parts[len-1],16)}}__name(decodeKeyTail,"decodeKeyTail");function endOfTagRange(prefix,upperBlockExclusive){return upperBlockExclusive===void 0?`${prefix}${SEP}${HEX_SENTINEL}`:encodeKey(prefix,upperBlockExclusive,0,0)}__name(endOfTagRange,"endOfTagRange");function endOfTxRange(prefix,txBlk,txIdx){return`${prefix}${SEP}${u32Hex(txBlk)}${SEP}${u32Hex(txIdx)}${SEP}${HEX_SENTINEL}`}__name(endOfTxRange,"endOfTxRange");function incKey(key){return key+HEX_SENTINEL}__name(incKey,"incKey");function encodeValue(value){let head=Buffer.allocUnsafe(76);value.txHash.toBuffer().copy(head,0),value.blockHash.toBuffer().copy(head,32),head.writeBigUInt64BE(value.blockTimestamp,64),head.writeUInt32BE(value.logData.length,72);let fieldBufs=value.logData.map(f=>f.toBuffer());return Buffer.concat([head,...fieldBufs])}__name(encodeValue,"encodeValue");function decodeValue(buffer){let buf=Buffer.isBuffer(buffer)?buffer:Buffer.from(buffer.buffer,buffer.byteOffset,buffer.byteLength),off=0,txHash=TxHash.fromBuffer(buf.subarray(off,off+32));off+=32;let blockHash=BlockHash.fromBuffer(buf.subarray(off,off+32));off+=32;let blockTimestamp=buf.readBigUInt64BE(off);off+=8;let logDataLen=buf.readUInt32BE(off);off+=4;let logData=new Array(logDataLen);for(let i=0;i<logDataLen;i++)logData[i]=Fr.fromBuffer(buf.subarray(off,off+32)),off+=32;return{txHash,blockHash,blockTimestamp,logData}}__name(decodeValue,"decodeValue");function encodePublicPrefix(contractHex,tagHex){return`${contractHex}${SEP}${tagHex}`}__name(encodePublicPrefix,"encodePublicPrefix");var LogStore=class _LogStore{static{__name(this,"LogStore")}db;blockStore;genesisBlockHash;#privateLogs;#publicLogs;#privateKeysByBlock;#publicKeysByBlock;#log;constructor(db,blockStore,genesisBlockHash){this.db=db,this.blockStore=blockStore,this.genesisBlockHash=genesisBlockHash,this.#log=createLogger("archiver:log_store"),this.#privateLogs=db.openMap("archiver_private_logs"),this.#publicLogs=db.openMap("archiver_public_logs"),this.#privateKeysByBlock=db.openMap("archiver_private_log_keys_by_block"),this.#publicKeysByBlock=db.openMap("archiver_public_log_keys_by_block")}addLogs(blocks){return this.db.transactionAsync(async()=>{for(let block of blocks){let blockHash=await block.hash(),blockNumber=block.number,blockTimestamp=block.timestamp,privateKeys=[],privateValues=[],publicKeys=[],publicValues=[];for(let txIndexWithinBlock=0;txIndexWithinBlock<block.body.txEffects.length;txIndexWithinBlock++){let txEffect=block.body.txEffects[txIndexWithinBlock],txHash=txEffect.txHash,privateLogIndexWithinTx=0,publicLogIndexWithinTx=0;for(let log2 of txEffect.privateLogs){let tagHex=tagHexForLog(log2.fields),key=encodeKey(tagHex,blockNumber,txIndexWithinBlock,privateLogIndexWithinTx),value=encodeValue({txHash,blockHash,blockTimestamp,logData:log2.getEmittedFields()});privateKeys.push(key),privateValues.push(value),privateLogIndexWithinTx++}for(let log2 of txEffect.publicLogs){let contractHex=fieldHex(log2.contractAddress),tagHex=tagHexForLog(log2.fields),key=encodeKey(encodePublicPrefix(contractHex,tagHex),blockNumber,txIndexWithinBlock,publicLogIndexWithinTx),value=encodeValue({txHash,blockHash,blockTimestamp,logData:log2.getEmittedFields()});publicKeys.push(key),publicValues.push(value),publicLogIndexWithinTx++}}for(let i=0;i<privateKeys.length;i++)await this.#privateLogs.set(privateKeys[i],privateValues[i]);for(let i=0;i<publicKeys.length;i++)await this.#publicLogs.set(publicKeys[i],publicValues[i]);await this.#privateKeysByBlock.set(blockNumber,privateKeys),await this.#publicKeysByBlock.set(blockNumber,publicKeys),this.#log.debug(`Indexed logs for block ${blockNumber}`,{blockNumber,privateCount:privateKeys.length,publicCount:publicKeys.length})}return!0})}deleteLogs(blocks){return this.db.transactionAsync(async()=>{for(let block of blocks){let blockNumber=block.number,[privateKeys,publicKeys]=await Promise.all([this.#privateKeysByBlock.getAsync(blockNumber),this.#publicKeysByBlock.getAsync(blockNumber)]);if(privateKeys){for(let key of privateKeys)await this.#privateLogs.delete(key);await this.#privateKeysByBlock.delete(blockNumber)}if(publicKeys){for(let key of publicKeys)await this.#publicLogs.delete(key);await this.#publicKeysByBlock.delete(blockNumber)}}return!0})}getPrivateLogsByTags(query){return _LogStore.#validateQuery(query),this.db.transactionAsync(()=>this.#runQuery(query,void 0))}getPublicLogsByTags(query){return _LogStore.#validateQuery(query),this.db.transactionAsync(()=>this.#runQuery(query,fieldHex(query.contractAddress)))}static#validateQuery(query){if(query.txHash!==void 0&&(query.fromBlock!==void 0||query.toBlock!==void 0))throw new Error("`txHash` is mutually exclusive with `fromBlock`/`toBlock`")}async#runQuery(query,contractHex){let isPublic=contractHex!==void 0,tags=query.tags??[],primaryMap=isPublic?this.#publicLogs:this.#privateLogs,referenceBlockNumber;if(query.referenceBlock)if(query.referenceBlock.equals(this.genesisBlockHash))referenceBlockNumber=INITIAL_L2_BLOCK_NUM2-1;else{let refBlk=await this.blockStore.getBlockData({hash:query.referenceBlock});if(!refBlk)throw new Error(`Reference block ${query.referenceBlock.toString()} not found in the node. This might indicate a reorg has occurred.`);referenceBlockNumber=refBlk.header.globalVariables.blockNumber}let upperExclusive;if(query.toBlock!==void 0&&(upperExclusive=query.toBlock),referenceBlockNumber!==void 0){let refExclusive=referenceBlockNumber+1;upperExclusive=upperExclusive===void 0?refExclusive:Math.min(upperExclusive,refExclusive)}let txLocation;if(query.txHash){let loc=await this.blockStore.getTxLocation(query.txHash);if(!loc)return tags.map(()=>[]);if(txLocation=loc,upperExclusive!==void 0&&txLocation[0]>=upperExclusive)return tags.map(()=>[])}let fromBlock=query.fromBlock??INITIAL_L2_BLOCK_NUM2,includeEffects=query.includeEffects===!0,perTagResults=[];for(let tagEntry of tags){let{tagHex,afterLog}=normalizeTagEntry(tagEntry),prefix=contractHex!==void 0?encodePublicPrefix(contractHex,tagHex):tagHex,end=txLocation?endOfTxRange(prefix,txLocation[0],txLocation[1]):endOfTagRange(prefix,upperExclusive),start;afterLog?start=incKey(encodeKey(prefix,afterLog.blockNumber,afterLog.txIndexWithinBlock,afterLog.logIndexWithinTx)):txLocation?start=encodeKey(prefix,txLocation[0],txLocation[1],0):start=encodeKey(prefix,fromBlock,0,0);let limit=query.limitPerTag??20,out=[];for await(let[rawKey,rawVal]of primaryMap.entriesAsync({start,end,limit})){let tail=decodeKeyTail(rawKey),value=decodeValue(rawVal);out.push({logData:value.logData,blockNumber:tail.blockNumber,blockHash:value.blockHash,blockTimestamp:value.blockTimestamp,txHash:value.txHash,txIndexWithinBlock:tail.txIndexWithinBlock,logIndexWithinTx:tail.logIndexWithinTx})}perTagResults.push(out)}if(includeEffects){let txHashByKey=new Map;for(let arr of perTagResults)for(let log2 of arr)txHashByKey.set(log2.txHash.toString(),log2.txHash);let uniqueTxs=Array.from(txHashByKey.values());if(uniqueTxs.length>0){let effects=await this.blockStore.getNoteHashesAndNullifiers(uniqueTxs),byTxHash=new Map;uniqueTxs.forEach((tx,i)=>byTxHash.set(tx.toString(),effects[i]));for(let i=0;i<perTagResults.length;i++)perTagResults[i]=perTagResults[i].map(log2=>{let[noteHashes,nullifiers]=byTxHash.get(log2.txHash.toString())??[[],[]];return{...log2,noteHashes,nullifiers}})}}return perTagResults}getPrivateLogsForBlock(blockNumber){return this.db.transactionAsync(()=>this.#readBlockLogs(this.#privateKeysByBlock,this.#privateLogs,blockNumber))}getPublicLogsForBlock(blockNumber){return this.db.transactionAsync(()=>this.#readBlockLogs(this.#publicKeysByBlock,this.#publicLogs,blockNumber))}async#readBlockLogs(keysByBlock,primaryMap,blockNumber){let keys=await keysByBlock.getAsync(blockNumber);if(!keys||keys.length===0)return[];let results=[];for(let key of keys){let raw=await primaryMap.getAsync(key);if(!raw)continue;let tail=decodeKeyTail(key),value=decodeValue(raw);results.push({logData:value.logData,blockNumber:tail.blockNumber,blockHash:value.blockHash,blockTimestamp:value.blockTimestamp,txHash:value.txHash,txIndexWithinBlock:tail.txIndexWithinBlock,logIndexWithinTx:tail.logIndexWithinTx})}return results}};function normalizeTagEntry(entry){return typeof entry=="object"&&entry!==null&&"tag"in entry?{tagHex:fieldHex(entry.tag.value),afterLog:entry.afterLog}:{tagHex:fieldHex(entry.value),afterLog:void 0}}__name(normalizeTagEntry,"normalizeTagEntry");function mapRange(range,mapFn){return{start:range.start?mapFn(range.start):void 0,end:range.end?mapFn(range.end):void 0,reverse:range.reverse,limit:range.limit}}__name(mapRange,"mapRange");function updateRollingHash(currentRollingHash,leaf){let input=Buffer.concat([currentRollingHash.toBuffer(),leaf.toBuffer()]);return Buffer16.fromBuffer(keccak256(input))}__name(updateRollingHash,"updateRollingHash");function serializeInboxMessage(message){return serializeToBuffer([bigintToUInt64BE(message.index),message.leaf,message.l1BlockHash,numToUInt32BE(Number(message.l1BlockNumber)),numToUInt32BE(message.checkpointNumber),message.rollingHash])}__name(serializeInboxMessage,"serializeInboxMessage");function deserializeInboxMessage(buffer){let reader=BufferReader.asReader(buffer),index=reader.readUInt64(),leaf=reader.readObject(Fr),l1BlockHash=reader.readObject(Buffer32),l1BlockNumber=BigInt(reader.readNumber()),checkpointNumber=CheckpointNumber(reader.readNumber()),rollingHash=reader.readObject(Buffer16);return{index,leaf,l1BlockHash,l1BlockNumber,checkpointNumber,rollingHash}}__name(deserializeInboxMessage,"deserializeInboxMessage");var MessageStoreError=class extends Error{static{__name(this,"MessageStoreError")}inboxMessage;constructor(message,inboxMessage){super(message),this.inboxMessage=inboxMessage,this.name="MessageStoreError"}},MessageStore=class{static{__name(this,"MessageStore")}db;#l1ToL2Messages;#l1ToL2MessageIndices;#lastSynchedL1Block;#totalMessageCount;#inboxTreeInProgress;#messagesFinalizedL1Block;#log;constructor(db){this.db=db,this.#log=createLogger("archiver:message_store"),this.#l1ToL2Messages=db.openMap("archiver_l1_to_l2_messages"),this.#l1ToL2MessageIndices=db.openMap("archiver_l1_to_l2_message_indices"),this.#lastSynchedL1Block=db.openSingleton("archiver_last_l1_block_id"),this.#totalMessageCount=db.openSingleton("archiver_l1_to_l2_message_count"),this.#inboxTreeInProgress=db.openSingleton("archiver_inbox_tree_in_progress"),this.#messagesFinalizedL1Block=db.openSingleton("archiver_messages_finalized_l1_block")}async getTotalL1ToL2MessageCount(){return await this.#totalMessageCount.getAsync()??0n}async getSynchedL1Block(){let buffer=await this.#lastSynchedL1Block.getAsync();if(!buffer)return;let reader=BufferReader.asReader(buffer);return{l1BlockNumber:reader.readUInt256(),l1BlockHash:Buffer32.fromBuffer(reader.readBytes(Buffer32.SIZE))}}async setSynchedL1Block(l1Block){let buffer=serializeToBuffer([l1Block.l1BlockNumber,l1Block.l1BlockHash]);await this.#lastSynchedL1Block.set(buffer)}async getMessagesFinalizedL1Block(){let buffer=await this.#messagesFinalizedL1Block.getAsync();if(!buffer)return;let reader=BufferReader.asReader(buffer);return{l1BlockNumber:reader.readUInt256(),l1BlockHash:Buffer32.fromBuffer(reader.readBytes(Buffer32.SIZE))}}async maybeAdvanceFinalizedL1Block(l1Block){let existing=await this.getMessagesFinalizedL1Block();if(existing&&l1Block.l1BlockNumber<=existing.l1BlockNumber)return;let buffer=serializeToBuffer([l1Block.l1BlockNumber,l1Block.l1BlockHash]);await this.#messagesFinalizedL1Block.set(buffer)}addL1ToL2Messages(messages){return messages.length===0?Promise.resolve():this.db.transactionAsync(async()=>{let lastMessage=await this.getLastMessage(),messageCount=0;for(let message of messages){if(lastMessage&&message.index<=lastMessage.index){let existing=await this.#l1ToL2Messages.getAsync(this.indexToKey(message.index));if(existing&&deserializeInboxMessage(existing).rollingHash.equals(message.rollingHash)){this.#log.trace(`Reinserting message with index ${message.index} in the store`),await this.#l1ToL2Messages.set(this.indexToKey(message.index),serializeInboxMessage(message));continue}throw new MessageStoreError(`Cannot insert L1 to L2 message with index ${message.index} before last message with index ${lastMessage.index}`,message)}let previousRollingHash=lastMessage?.rollingHash??Buffer16.ZERO,expectedRollingHash=updateRollingHash(previousRollingHash,message.leaf);if(!expectedRollingHash.equals(message.rollingHash))throw new MessageStoreError(`Invalid rolling hash for incoming L1 to L2 message ${message.leaf.toString()} with index ${message.index} (expected ${expectedRollingHash.toString()} from previous hash ${previousRollingHash} but got ${message.rollingHash.toString()})`,message);let[expectedStart,expectedEnd]=InboxLeaf.indexRangeForCheckpoint(message.checkpointNumber);if(message.index<expectedStart||message.index>=expectedEnd)throw new MessageStoreError(`Invalid index ${message.index} for incoming L1 to L2 message ${message.leaf.toString()} at checkpoint ${message.checkpointNumber} (expected value in range [${expectedStart}, ${expectedEnd}))`,message);if(lastMessage&&message.checkpointNumber===lastMessage.checkpointNumber&&message.index!==lastMessage.index+1n)throw new MessageStoreError(`Missing prior message for incoming L1 to L2 message ${message.leaf.toString()} with index ${message.index}`,message);if((!lastMessage||message.checkpointNumber>lastMessage.checkpointNumber)&&message.index!==expectedStart)throw new MessageStoreError(`Message ${message.leaf.toString()} for checkpoint ${message.checkpointNumber} has wrong index ${message.index} (expected ${expectedStart})`,message);await this.#l1ToL2Messages.set(this.indexToKey(message.index),serializeInboxMessage(message)),await this.#l1ToL2MessageIndices.set(this.leafToIndexKey(message.leaf),message.index),messageCount++,this.#log.trace(`Inserted L1 to L2 message ${message.leaf} with index ${message.index} into the store`),lastMessage=message}await this.increaseTotalMessageCount(messageCount)})}getL1ToL2MessageIndex(l1ToL2Message){return this.#l1ToL2MessageIndices.getAsync(this.leafToIndexKey(l1ToL2Message))}async getLastMessage(){let[msg]=await toArray(this.#l1ToL2Messages.valuesAsync({reverse:!0,limit:1}));return msg?deserializeInboxMessage(msg):void 0}getInboxTreeInProgress(){return this.#inboxTreeInProgress.getAsync()}setMessageSyncState(l1Block,treeInProgress,finalizedL1Block){return this.db.transactionAsync(async()=>{await this.setSynchedL1Block(l1Block),treeInProgress!==void 0?await this.#inboxTreeInProgress.set(treeInProgress):await this.#inboxTreeInProgress.delete(),finalizedL1Block!==void 0&&await this.maybeAdvanceFinalizedL1Block(finalizedL1Block)})}async getL1ToL2Messages(checkpointNumber){let treeInProgress=await this.#inboxTreeInProgress.getAsync();if(treeInProgress!==void 0&&BigInt(checkpointNumber)>=treeInProgress)throw new L1ToL2MessagesNotReadyError(checkpointNumber,treeInProgress);let messages=[],[startIndex,endIndex]=InboxLeaf.indexRangeForCheckpoint(checkpointNumber),lastIndex=startIndex-1n;for await(let msgBuffer of this.#l1ToL2Messages.valuesAsync({start:this.indexToKey(startIndex),end:this.indexToKey(endIndex)})){let msg=deserializeInboxMessage(msgBuffer);if(msg.checkpointNumber!==checkpointNumber)throw new Error(`L1 to L2 message with index ${msg.index} has invalid checkpoint number ${msg.checkpointNumber}`);if(msg.index!==lastIndex+1n)throw new Error(`Expected L1 to L2 message with index ${lastIndex+1n} but got ${msg.index}`);lastIndex=msg.index,messages.push(msg.leaf)}return messages}async*iterateL1ToL2Messages(range={}){let entriesRange=mapRange(range,this.indexToKey);for await(let msgBuffer of this.#l1ToL2Messages.valuesAsync(entriesRange))yield deserializeInboxMessage(msgBuffer)}removeL1ToL2Messages(startIndex){this.#log.debug(`Deleting L1 to L2 messages from index ${startIndex}`);let deleteCount=0;return this.db.transactionAsync(async()=>{for await(let[key,msgBuffer]of this.#l1ToL2Messages.entriesAsync({start:this.indexToKey(startIndex)}))this.#log.trace(`Deleting L1 to L2 message with index ${key-1} from the store`),await this.#l1ToL2Messages.delete(key),await this.#l1ToL2MessageIndices.delete(this.leafToIndexKey(deserializeInboxMessage(msgBuffer).leaf)),deleteCount++;await this.increaseTotalMessageCount(-deleteCount),this.#log.warn(`Deleted ${deleteCount} L1 to L2 messages from index ${startIndex} from the store`)})}rollbackL1ToL2MessagesToCheckpoint(targetCheckpointNumber){this.#log.debug(`Deleting L1 to L2 messages up to target checkpoint ${targetCheckpointNumber}`);let startIndex=InboxLeaf.smallestIndexForCheckpoint(CheckpointNumber(targetCheckpointNumber+1));return this.removeL1ToL2Messages(startIndex)}indexToKey(index){return Number(index)}leafToIndexKey(leaf){return leaf.toString()}async increaseTotalMessageCount(count2){if(count2!==0)return await this.db.transactionAsync(async()=>{let lastTotalMessageCount=await this.getTotalL1ToL2MessageCount();await this.#totalMessageCount.set(lastTotalMessageCount+BigInt(count2))})}};function createArchiverDataStores(db,genesisBlockHash){let blocks=new BlockStore(db);return{db,blocks,logs:new LogStore(db,blocks,genesisBlockHash),messages:new MessageStore(db),contractClasses:new ContractClassStore(db),contractInstances:new ContractInstanceStore(db),functionNames:new FunctionNamesCache}}__name(createArchiverDataStores,"createArchiverDataStores");var L1ToL2MessagesNotReadyError2=class extends Error{static{__name(this,"L1ToL2MessagesNotReadyError")}constructor(message){super(message),this.name="L1ToL2MessagesNotReadyError"}};var TXEArchiver=class extends ArchiverDataSourceBase{static{__name(this,"TXEArchiver")}updater=new ArchiverDataStoreUpdater(this.stores);constructor(db){super(createArchiverDataStores(db,GENESIS_BLOCK_HEADER_HASH3),void 0,BlockHeader.empty(),GENESIS_BLOCK_HEADER_HASH3,new Fr(GENESIS_ARCHIVE_ROOT))}async addCheckpoints(checkpoints,result){await this.updater.addCheckpoints(checkpoints,result)}getRollupAddress(){throw new Error('TXE Archiver does not implement "getRollupAddress"')}getRegistryAddress(){throw new Error('TXE Archiver does not implement "getRegistryAddress"')}getL1Constants(){return Promise.resolve(EmptyL1RollupConstants)}getGenesisValues(){return Promise.resolve({genesisArchiveRoot:new Fr(GENESIS_ARCHIVE_ROOT)})}getL1Timestamp(){throw new Error('TXE Archiver does not implement "getL1Timestamp"')}async getL2Tips(){let latestBlockNumber=await this.stores.blocks.getLatestL2BlockNumber();if(latestBlockNumber===0)throw new Error("L2Tips requested from TXE Archiver but no block found");let latestBlockData=await this.stores.blocks.getBlockData({number:latestBlockNumber});if(!latestBlockData)throw new Error("L2Tips requested from TXE Archiver but no block header found");let number4=latestBlockData.header.globalVariables.blockNumber,hash5=latestBlockData.blockHash.toString(),checkpoint=await this.stores.blocks.getRangeOfCheckpoints(CheckpointNumber.fromBlockNumber(number4),1);if(checkpoint.length===0)throw new Error(`L2Tips requested from TXE Archiver but no checkpoint found for block number ${number4}`);let blockId={number:number4,hash:hash5},checkpointId={number:checkpoint[0].checkpointNumber,hash:checkpoint[0].header.hash().toString()},tipId={block:blockId,checkpoint:checkpointId};return{proposed:blockId,proven:tipId,finalized:tipId,checkpointed:tipId}}getSyncedL2SlotNumber(){throw new Error('TXE Archiver does not implement "getSyncedL2SlotNumber"')}getSyncedL2EpochNumber(){throw new Error('TXE Archiver does not implement "getSyncedL2EpochNumber"')}isEpochComplete(_epochNumber){throw new Error('TXE Archiver does not implement "isEpochComplete"')}syncImmediate(){throw new Error('TXE Archiver does not implement "syncImmediate"')}getL2ToL1MembershipWitness(){return Promise.resolve(void 0)}};var import_config15=__toESM(require_empty_stub(),1);import{l1ContractsConfigMappings as l1ContractsConfigMappings2}from"@aztec/ethereum/config";import{l1ReaderConfigMappings}from"@aztec/ethereum/l1-reader";var archiverConfigMappings={...import_config15.blobClientConfigMapping,archiverPollingIntervalMS:{env:"ARCHIVER_POLLING_INTERVAL_MS",description:"The polling interval in ms for retrieving new L2 blocks and encrypted logs.",...numberConfigHelper(500)},archiverBatchSize:{env:"ARCHIVER_BATCH_SIZE",description:"The number of L2 blocks the archiver will attempt to download at a time.",...numberConfigHelper(100)},archiverStoreMapSizeKb:{env:"ARCHIVER_STORE_MAP_SIZE_KB",...optionalNumberConfigHelper(),description:"The maximum possible size of the archiver DB in KB. Overwrites the general dataStoreMapSizeKb."},blockDurationMs:{env:"SEQ_BLOCK_DURATION_MS",description:"Duration per block in milliseconds when building multiple blocks per slot. Used to derive orphan proposed block pruning timing.",...optionalNumberConfigHelper()},checkpointProposalSyncGraceSeconds:{env:"CHECKPOINT_PROPOSAL_SYNC_GRACE_SECONDS",description:"Consensus grace in seconds for a received checkpoint proposal to materialize into local proposed state.",...optionalNumberConfigHelper()},skipValidateCheckpointAttestations:{description:"Skip validating checkpoint attestations (for testing purposes only)",...booleanConfigHelper(!1)},skipPromoteProposedCheckpointDuringL1Sync:{description:"Skip promoting proposed checkpoints during L1 sync (for testing purposes only)",...booleanConfigHelper(!1)},maxAllowedEthClientDriftSeconds:{env:"MAX_ALLOWED_ETH_CLIENT_DRIFT_SECONDS",description:"Maximum allowed drift in seconds between the Ethereum client and current time.",...numberConfigHelper(300)},ethereumAllowNoDebugHosts:{env:"ETHEREUM_ALLOW_NO_DEBUG_HOSTS",description:"Whether to allow starting the archiver without debug/trace method support on Ethereum hosts",...booleanConfigHelper(!0)},archiverSkipHistoricalLogsCheck:{env:"ARCHIVER_SKIP_HISTORICAL_LOGS_CHECK",description:"Skip the startup check that probes the L1 RPC for historical Rollup contract logs. Set to true to bypass the check when the connected RPC node is known to prune old logs.",...booleanConfigHelper(!1)},orphanPruneNoProposalTolerance:{env:"ARCHIVER_ORPHAN_PRUNE_NO_PROPOSAL_TOLERANCE",description:"Local tolerance in seconds before pruning an orphan block when no checkpoint proposal was received.",...numberConfigHelper(1)},skipOrphanProposedBlockPruning:{env:"ARCHIVER_SKIP_ORPHAN_PROPOSED_BLOCK_PRUNING",description:"Skip pruning orphan proposed blocks that have no matching proposed checkpoint.",...booleanConfigHelper(!1)},...chainConfigMappings,...l1ReaderConfigMappings,viemPollingIntervalMS:{env:"ARCHIVER_VIEM_POLLING_INTERVAL_MS",description:"The polling interval viem uses in ms",...numberConfigHelper(1e3)},...l1ContractsConfigMappings2};import{genesisStateConfigMappings}from"@aztec/ethereum/config";var import_node_keystore=__toESM(require_empty_stub(),1),import_config24=__toESM(require_empty_stub(),1),import_config25=__toESM(require_empty_stub(),1),import_config26=__toESM(require_empty_stub(),1),import_config27=__toESM(require_empty_stub(),1),import_config28=__toESM(require_empty_stub(),1),import_slasher2=__toESM(require_empty_stub(),1);var import_config30=__toESM(require_empty_stub(),1);var worldStateConfigMappings={worldStateBlockCheckIntervalMS:{env:"WS_BLOCK_CHECK_INTERVAL_MS",...numberConfigHelper(100),description:"The frequency in which to check."},worldStateBlockRequestBatchSize:{env:"WS_BLOCK_REQUEST_BATCH_SIZE",...optionalNumberConfigHelper(),description:"Size of the batch for each get-blocks request from the synchronizer to the archiver."},worldStateDbMapSizeKb:{env:"WS_DB_MAP_SIZE_KB",...optionalNumberConfigHelper(),description:"The maximum possible size of the world state DB in KB. Overwrites the general dataStoreMapSizeKb."},archiveTreeMapSizeKb:{env:"ARCHIVE_TREE_MAP_SIZE_KB",...optionalNumberConfigHelper(),description:"The maximum possible size of the world state archive tree in KB. Overwrites the general worldStateDbMapSizeKb."},nullifierTreeMapSizeKb:{env:"NULLIFIER_TREE_MAP_SIZE_KB",...optionalNumberConfigHelper(),description:"The maximum possible size of the world state nullifier tree in KB. Overwrites the general worldStateDbMapSizeKb."},noteHashTreeMapSizeKb:{env:"NOTE_HASH_TREE_MAP_SIZE_KB",...optionalNumberConfigHelper(),description:"The maximum possible size of the world state note hash tree in KB. Overwrites the general worldStateDbMapSizeKb."},messageTreeMapSizeKb:{env:"MESSAGE_TREE_MAP_SIZE_KB",...optionalNumberConfigHelper(),description:"The maximum possible size of the world state message tree in KB. Overwrites the general worldStateDbMapSizeKb."},publicDataTreeMapSizeKb:{env:"PUBLIC_DATA_TREE_MAP_SIZE_KB",...optionalNumberConfigHelper(),description:"The maximum possible size of the world state public data tree in KB. Overwrites the general worldStateDbMapSizeKb."},worldStateDataDirectory:{env:"WS_DATA_DIRECTORY",description:"Optional directory for the world state database"},worldStateCheckpointHistory:{env:"WS_NUM_HISTORIC_CHECKPOINTS",description:"The number of historic checkpoints worth of blocks to maintain. Values less than 1 mean all history is maintained",fallback:["WS_NUM_HISTORIC_BLOCKS"],...numberConfigHelper(64)}};import{privateKeyToAddress}from"viem/accounts";var sentinelConfigMappings={sentinelHistoryLengthInEpochs:{description:"The number of L2 epochs kept of history for each validator for computing their stats.",env:"SENTINEL_HISTORY_LENGTH_IN_EPOCHS",...numberConfigHelper(24)},sentinelHistoricEpochPerformanceLengthInEpochs:{description:"The number of L2 epochs kept of per-epoch performance history for each validator.",env:"SENTINEL_HISTORIC_EPOCH_PERFORMANCE_LENGTH_IN_EPOCHS",...numberConfigHelper(2e3)},sentinelEnabled:{description:"Whether the sentinel is enabled or not.",env:"SENTINEL_ENABLED",...booleanConfigHelper(!1)},sentinelEpochEndBufferSlots:{description:"Number of L2 slots after the end of an epoch before the sentinel evaluates it.",env:"SENTINEL_EPOCH_END_BUFFER_SLOTS",...numberConfigHelper(2)}};var aztecNodeConfigMappings={...dataConfigMappings,...import_node_keystore.keyStoreConfigMappings,...archiverConfigMappings,...import_config28.sequencerClientConfigMappings,...import_config27.proverNodeConfigMappings,...import_config30.validatorClientConfigMappings,...import_config26.proverClientConfigMappings,...worldStateConfigMappings,...import_config25.p2pConfigMappings,...sentinelConfigMappings,...import_config24.sharedNodeConfigMappings,...genesisStateConfigMappings,...nodeRpcConfigMappings,...import_slasher2.slasherConfigMappings,...import_config27.specificProverNodeConfigMappings,disableValidator:{env:"VALIDATOR_DISABLED",description:"Whether the validator is disabled for this node.",...booleanConfigHelper()},skipArchiverInitialSync:{env:"SKIP_ARCHIVER_INITIAL_SYNC",description:"Whether to skip waiting for the archiver to be fully synced before starting other services.",...booleanConfigHelper(!1)},debugForceTxProofVerification:{env:"DEBUG_FORCE_TX_PROOF_VERIFICATION",description:"Whether to skip waiting for the archiver to be fully synced before starting other services.",...booleanConfigHelper(!1)},enableProverNode:{env:"ENABLE_PROVER_NODE",description:"Whether to enable the prover node as a subsystem.",...booleanConfigHelper(!1)},enableOffenseCollection:{env:"OFFENSE_COLLECTION_ENABLED",description:"Whether to run the slashing watchers to collect offenses even if not a validator.",...booleanConfigHelper(!1)},useAutomineSequencer:{env:"USE_AUTOMINE_SEQUENCER",description:"Test-only: use AutomineSequencer instead of the production Sequencer.",...booleanConfigHelper(!1)},automineEnableProveEpoch:{env:"AUTOMINE_ENABLE_PROVE_EPOCH",description:"Test-only: have the AutomineSequencer automatically prove epochs as checkpoints land.",...booleanConfigHelper(!1)}};var P2PBootstrapApiSchema={getEncodedEnr:external_exports.function({input:external_exports.tuple([]),output:external_exports.string()}),getRoutingTable:external_exports.function({input:external_exports.tuple([]),output:external_exports.array(external_exports.string())})};var ProverAgentStatusSchema=external_exports.discriminatedUnion("status",[external_exports.object({status:external_exports.literal("stopped")}),external_exports.object({status:external_exports.literal("running")}),external_exports.object({status:external_exports.literal("proving"),jobId:external_exports.string(),proofType:external_exports.number(),startedAtISO:external_exports.string()})]),ProverAgentApiSchema={getStatus:external_exports.function({input:external_exports.tuple([]),output:ProverAgentStatusSchema})};var EpochProvingJobState=["initialized","awaiting-checkpoints","awaiting-root","awaiting-predecessor","publishing-proof","completed","superseded","failed","stopped","cancelled","timed-out"];var ProverNodeApiSchema={getJobs:external_exports.function({input:external_exports.tuple([]),output:external_exports.array(external_exports.object({uuid:external_exports.string(),status:external_exports.enum(EpochProvingJobState),epochNumber:external_exports.number()}))}),startProof:external_exports.function({input:external_exports.tuple([schemas2.Integer]),output:external_exports.string()})};function schemaForPublicInputsAndRecursiveProof(inputs,proofSize){return external_exports.object({inputs,proof:RecursiveProof.schemaFor(proofSize),verificationKey:VerificationKeyData.schema})}__name(schemaForPublicInputsAndRecursiveProof,"schemaForPublicInputsAndRecursiveProof");var ProvingJobInputs=external_exports.discriminatedUnion("type",[AvmProvingRequestSchema,external_exports.object({type:external_exports.literal(ProvingRequestType.PARITY_BASE),inputs:ParityBasePrivateInputs.schema}),external_exports.object({type:external_exports.literal(ProvingRequestType.PARITY_ROOT),inputs:ParityRootPrivateInputs.schema}),external_exports.object({type:external_exports.literal(ProvingRequestType.PUBLIC_CHONK_VERIFIER),inputs:PublicChonkVerifierPrivateInputs.schema}),external_exports.object({type:external_exports.literal(ProvingRequestType.PRIVATE_TX_BASE_ROLLUP),inputs:PrivateTxBaseRollupPrivateInputs.schema}),external_exports.object({type:external_exports.literal(ProvingRequestType.PUBLIC_TX_BASE_ROLLUP),inputs:PublicTxBaseRollupPrivateInputs.schema}),external_exports.object({type:external_exports.literal(ProvingRequestType.TX_MERGE_ROLLUP),inputs:TxMergeRollupPrivateInputs.schema}),external_exports.object({type:external_exports.literal(ProvingRequestType.BLOCK_ROOT_FIRST_ROLLUP),inputs:BlockRootFirstRollupPrivateInputs.schema}),external_exports.object({type:external_exports.literal(ProvingRequestType.BLOCK_ROOT_SINGLE_TX_FIRST_ROLLUP),inputs:BlockRootSingleTxFirstRollupPrivateInputs.schema}),external_exports.object({type:external_exports.literal(ProvingRequestType.BLOCK_ROOT_EMPTY_TX_FIRST_ROLLUP),inputs:BlockRootEmptyTxFirstRollupPrivateInputs.schema}),external_exports.object({type:external_exports.literal(ProvingRequestType.BLOCK_ROOT_ROLLUP),inputs:BlockRootRollupPrivateInputs.schema}),external_exports.object({type:external_exports.literal(ProvingRequestType.BLOCK_ROOT_SINGLE_TX_ROLLUP),inputs:BlockRootSingleTxRollupPrivateInputs.schema}),external_exports.object({type:external_exports.literal(ProvingRequestType.BLOCK_MERGE_ROLLUP),inputs:BlockMergeRollupPrivateInputs.schema}),external_exports.object({type:external_exports.literal(ProvingRequestType.CHECKPOINT_ROOT_ROLLUP),inputs:CheckpointRootRollupPrivateInputs.schema}),external_exports.object({type:external_exports.literal(ProvingRequestType.CHECKPOINT_ROOT_SINGLE_BLOCK_ROLLUP),inputs:CheckpointRootSingleBlockRollupPrivateInputs.schema}),external_exports.object({type:external_exports.literal(ProvingRequestType.CHECKPOINT_PADDING_ROLLUP),inputs:CheckpointPaddingRollupPrivateInputs.schema}),external_exports.object({type:external_exports.literal(ProvingRequestType.CHECKPOINT_MERGE_ROLLUP),inputs:CheckpointMergeRollupPrivateInputs.schema}),external_exports.object({type:external_exports.literal(ProvingRequestType.ROOT_ROLLUP),inputs:RootRollupPrivateInputs.schema})]);var ProvingJobResult=external_exports.discriminatedUnion("type",[external_exports.object({type:external_exports.literal(ProvingRequestType.PUBLIC_VM),result:RecursiveProof.schemaFor(16400)}),external_exports.object({type:external_exports.literal(ProvingRequestType.PUBLIC_CHONK_VERIFIER),result:schemaForPublicInputsAndRecursiveProof(PublicChonkVerifierPublicInputs.schema,480)}),external_exports.object({type:external_exports.literal(ProvingRequestType.PRIVATE_TX_BASE_ROLLUP),result:schemaForPublicInputsAndRecursiveProof(TxRollupPublicInputs.schema,480)}),external_exports.object({type:external_exports.literal(ProvingRequestType.PUBLIC_TX_BASE_ROLLUP),result:schemaForPublicInputsAndRecursiveProof(TxRollupPublicInputs.schema,480)}),external_exports.object({type:external_exports.literal(ProvingRequestType.TX_MERGE_ROLLUP),result:schemaForPublicInputsAndRecursiveProof(TxRollupPublicInputs.schema,480)}),external_exports.object({type:external_exports.literal(ProvingRequestType.BLOCK_ROOT_FIRST_ROLLUP),result:schemaForPublicInputsAndRecursiveProof(BlockRollupPublicInputs.schema,480)}),external_exports.object({type:external_exports.literal(ProvingRequestType.BLOCK_ROOT_SINGLE_TX_FIRST_ROLLUP),result:schemaForPublicInputsAndRecursiveProof(BlockRollupPublicInputs.schema,480)}),external_exports.object({type:external_exports.literal(ProvingRequestType.BLOCK_ROOT_EMPTY_TX_FIRST_ROLLUP),result:schemaForPublicInputsAndRecursiveProof(BlockRollupPublicInputs.schema,480)}),external_exports.object({type:external_exports.literal(ProvingRequestType.BLOCK_ROOT_ROLLUP),result:schemaForPublicInputsAndRecursiveProof(BlockRollupPublicInputs.schema,480)}),external_exports.object({type:external_exports.literal(ProvingRequestType.BLOCK_ROOT_SINGLE_TX_ROLLUP),result:schemaForPublicInputsAndRecursiveProof(BlockRollupPublicInputs.schema,480)}),external_exports.object({type:external_exports.literal(ProvingRequestType.BLOCK_MERGE_ROLLUP),result:schemaForPublicInputsAndRecursiveProof(BlockRollupPublicInputs.schema,480)}),external_exports.object({type:external_exports.literal(ProvingRequestType.CHECKPOINT_ROOT_ROLLUP),result:schemaForPublicInputsAndRecursiveProof(CheckpointRollupPublicInputs.schema,480)}),external_exports.object({type:external_exports.literal(ProvingRequestType.CHECKPOINT_ROOT_SINGLE_BLOCK_ROLLUP),result:schemaForPublicInputsAndRecursiveProof(CheckpointRollupPublicInputs.schema,480)}),external_exports.object({type:external_exports.literal(ProvingRequestType.CHECKPOINT_PADDING_ROLLUP),result:schemaForPublicInputsAndRecursiveProof(CheckpointRollupPublicInputs.schema,480)}),external_exports.object({type:external_exports.literal(ProvingRequestType.CHECKPOINT_MERGE_ROLLUP),result:schemaForPublicInputsAndRecursiveProof(CheckpointRollupPublicInputs.schema,480)}),external_exports.object({type:external_exports.literal(ProvingRequestType.ROOT_ROLLUP),result:schemaForPublicInputsAndRecursiveProof(RootRollupPublicInputs.schema,410)}),external_exports.object({type:external_exports.literal(ProvingRequestType.PARITY_BASE),result:schemaForPublicInputsAndRecursiveProof(ParityPublicInputs.schema,410)}),external_exports.object({type:external_exports.literal(ProvingRequestType.PARITY_ROOT),result:schemaForPublicInputsAndRecursiveProof(ParityPublicInputs.schema,410)})]),ProvingJobId=external_exports.string(),ProofUri=external_exports.string().transform(value=>value),ProvingJob=external_exports.object({id:ProvingJobId,type:external_exports.nativeEnum(ProvingRequestType),epochNumber:EpochNumberSchema,inputsUri:ProofUri});var ProvingJobFulfilledResult=external_exports.object({status:external_exports.literal("fulfilled"),value:ProofUri}),ProvingJobRejectedResult=external_exports.object({status:external_exports.literal("rejected"),reason:external_exports.string()}),ProvingJobSettledResult=external_exports.discriminatedUnion("status",[ProvingJobFulfilledResult,ProvingJobRejectedResult]),ProvingJobStatus=external_exports.discriminatedUnion("status",[external_exports.object({status:external_exports.literal("in-queue")}),external_exports.object({status:external_exports.literal("in-progress")}),external_exports.object({status:external_exports.literal("not-found")}),ProvingJobFulfilledResult,ProvingJobRejectedResult]);var ProvingJobSourceSchema={getProvingJob:external_exports.function({input:external_exports.tuple([]),output:ProvingJob.optional()}),heartbeat:external_exports.function({input:external_exports.tuple([ProvingJobId]),output:external_exports.void()}),resolveProvingJob:external_exports.function({input:external_exports.tuple([ProvingJobId,ProvingJobResult]),output:external_exports.void()}),rejectProvingJob:external_exports.function({input:external_exports.tuple([ProvingJobId,external_exports.string()]),output:external_exports.void()})};async function tryStop(service,logger3){try{return typeof service=="object"&&service&&"stop"in service&&typeof service.stop=="function"?await service.stop():Promise.resolve()}catch(err){logger3?.error(`Error stopping service ${service.constructor?.name}: ${err}`)}}__name(tryStop,"tryStop");var BBCircuitVerifier=class{static{__name(this,"BBCircuitVerifier")}constructor(..._args){throwStub("BBCircuitVerifier")}},BatchChonkVerifier=class{static{__name(this,"BatchChonkVerifier")}constructor(..._args){throwStub("BatchChonkVerifier")}},QueuedIVCVerifier=class{static{__name(this,"QueuedIVCVerifier")}constructor(..._args){throwStub("QueuedIVCVerifier")}};var TestCircuitVerifier=class{static{__name(this,"TestCircuitVerifier")}verificationDelayMs;constructor(verificationDelayMs){this.verificationDelayMs=verificationDelayMs}verifyProof(_tx){return this.verificationDelayMs!==void 0&&this.verificationDelayMs>0?new Promise(resolve=>{setTimeout(()=>{resolve({valid:!0,durationMs:this.verificationDelayMs,totalDurationMs:this.verificationDelayMs})},this.verificationDelayMs)}):Promise.resolve({valid:!0,durationMs:0,totalDurationMs:0})}stop(){return Promise.resolve()}};import{pickL1ContractAddresses}from"@aztec/ethereum/l1-contract-addresses";var import_node_keystore2=__toESM(require_empty_stub(),1),import_actions=__toESM(require_empty_stub(),1),import_p2p2=__toESM(require_empty_stub(),1);var import_validator_client=__toESM(require_empty_stub(),1);async function blockResponseFromL2Block(block,options,context2){let response={header:block.header,archive:block.archive,hash:await block.hash(),checkpointNumber:block.checkpointNumber,indexWithinCheckpoint:block.indexWithinCheckpoint,number:block.number};return options.includeTransactions&&(response.body=block.body),options.includeL1PublishInfo&&(response.l1=l1PublishInfoFromL1PublishedData(context2?.l1)),options.includeAttestations&&(response.attestations=context2?.attestations??[]),response}__name(blockResponseFromL2Block,"blockResponseFromL2Block");function blockResponseFromBlockData(data,options,context2){let response={header:data.header,archive:data.archive,hash:data.blockHash,checkpointNumber:data.checkpointNumber,indexWithinCheckpoint:data.indexWithinCheckpoint,number:data.header.getBlockNumber()};return options.includeL1PublishInfo&&(response.l1=l1PublishInfoFromL1PublishedData(context2?.l1)),options.includeAttestations&&(response.attestations=context2?.attestations??[]),response}__name(blockResponseFromBlockData,"blockResponseFromBlockData");async function checkpointResponseFromPublishedCheckpoint(pc,options){let response={number:pc.checkpoint.number,header:pc.checkpoint.header,archive:pc.checkpoint.archive,checkpointOutHash:pc.checkpoint.getCheckpointOutHash(),startBlock:pc.checkpoint.blocks[0]?.number??BlockNumber.ZERO,blockCount:pc.checkpoint.blocks.length,feeAssetPriceModifier:pc.checkpoint.feeAssetPriceModifier};return options.includeBlocks&&(response.blocks=await Promise.all(pc.checkpoint.blocks.map(block=>blockResponseFromL2Block(block,{includeTransactions:options.includeTransactions,includeL1PublishInfo:!1,includeAttestations:!1})))),options.includeL1PublishInfo&&(response.l1=l1PublishInfoFromL1PublishedData(pc.l1)),options.includeAttestations&&(response.attestations=pc.attestations),response}__name(checkpointResponseFromPublishedCheckpoint,"checkpointResponseFromPublishedCheckpoint");function checkpointResponseFromCheckpointData(cd,options){let response={number:cd.checkpointNumber,header:cd.header,archive:cd.archive,checkpointOutHash:cd.checkpointOutHash,startBlock:cd.startBlock,blockCount:cd.blockCount,feeAssetPriceModifier:cd.feeAssetPriceModifier};return options.includeL1PublishInfo&&(response.l1=l1PublishInfoFromL1PublishedData(cd.l1)),options.includeAttestations&&(response.attestations=cd.attestations),response}__name(checkpointResponseFromCheckpointData,"checkpointResponseFromCheckpointData");async function projectProposedToCheckpointResponse(proposed,options,blocks){if(options.includeL1PublishInfo||options.includeAttestations)throw new Error("Proposed checkpoints have no L1 publish info or attestations");let response={number:proposed.checkpointNumber,header:proposed.header,archive:proposed.archive,checkpointOutHash:proposed.checkpointOutHash,startBlock:proposed.startBlock,blockCount:proposed.blockCount,feeAssetPriceModifier:proposed.feeAssetPriceModifier};if(options.includeBlocks){if(!blocks)throw new Error("Blocks must be supplied when includeBlocks is true");response.blocks=await Promise.all(blocks.map(block=>blockResponseFromL2Block(block,{includeTransactions:options.includeTransactions,includeL1PublishInfo:!1,includeAttestations:!1})))}return response}__name(projectProposedToCheckpointResponse,"projectProposedToCheckpointResponse");function isBlockTag(value){return BlockTag.includes(value)}__name(isBlockTag,"isBlockTag");function isCheckpointTag(value){return value==="checkpointed"||value==="proven"||value==="finalized"}__name(isCheckpointTag,"isCheckpointTag");function normalizeBlockParameter(param){if(BlockHash.isBlockHash(param))return{hash:param};if(typeof param=="number")return{number:param};if(typeof param=="string"){if(isBlockTag(param))return{tag:param==="latest"?"proposed":param};throw new BadRequestError(`Invalid BlockParameter tag: ${param}`)}if(typeof param=="object"&¶m!==null){if("number"in param)return{number:param.number};if("hash"in param)return{hash:param.hash};if("archive"in param)return{archive:param.archive};if("tag"in param){if(isBlockTag(param.tag))return{tag:param.tag};throw new BadRequestError(`Invalid BlockParameter tag: ${param.tag}`)}}throw new BadRequestError(`Invalid BlockParameter: ${JSON.stringify(param)}`)}__name(normalizeBlockParameter,"normalizeBlockParameter");async function resolveCheckpointParameter(param,blockSource){if(typeof param=="number")return{number:param};if(isCheckpointTag(param)){let tips=await blockSource.getL2Tips();switch(param){case"checkpointed":return{number:tips.checkpointed.checkpoint.number};case"proven":return{number:tips.proven.checkpoint.number};case"finalized":return{number:tips.finalized.checkpoint.number}}}if(typeof param=="object"&¶m!==null){if("number"in param)return{number:param.number};if("slot"in param)return{slot:param.slot}}throw new BadRequestError(`Invalid CheckpointParameter: ${JSON.stringify(param)}`)}__name(resolveCheckpointParameter,"resolveCheckpointParameter");var NodeBlockProvider=class{static{__name(this,"NodeBlockProvider")}blockSource;constructor(blockSource){this.blockSource=blockSource}async getBlock(param,options={}){let query=normalizeBlockParameter(param),wantTxs=!!options.includeTransactions,wantContext=!!options.includeL1PublishInfo||!!options.includeAttestations;if(wantTxs){let block=await this.blockSource.getBlock(query);if(!block)return;let ctx2=wantContext?await this.#getCheckpointContext(block.checkpointNumber):void 0;return await blockResponseFromL2Block(block,options,ctx2)}let data=await this.blockSource.getBlockData(query);if(!data)return;let ctx=wantContext?await this.#getCheckpointContext(data.checkpointNumber):void 0;return blockResponseFromBlockData(data,options,ctx)}getBlockData(param){let query=normalizeBlockParameter(param);return this.blockSource.getBlockData(query)}async getBlocks(from,limit,options={}){let wantTxs=!!options.includeTransactions,wantContext=!!options.includeL1PublishInfo||!!options.includeAttestations,onlyCheckpointed=!!options.onlyCheckpointed;if(wantTxs){let blocks=await this.blockSource.getBlocks({from,limit,onlyCheckpointed}),ctxByCheckpoint2=await this.#getCheckpointContextsForBlocks(wantContext?blocks:[]);return await Promise.all(blocks.map(block=>blockResponseFromL2Block(block,options,ctxByCheckpoint2.get(block.checkpointNumber))))}let dataItems=await this.blockSource.getBlocksData({from,limit,onlyCheckpointed}),ctxByCheckpoint=await this.#getCheckpointContextsForBlocks(wantContext?dataItems:[]);return await Promise.all(dataItems.map(data=>blockResponseFromBlockData(data,options,ctxByCheckpoint.get(data.checkpointNumber))))}async getCheckpoint(param,options={}){let query=await resolveCheckpointParameter(param,this.blockSource),confirmed=options.includeBlocks?await this.blockSource.getCheckpoint(query):await this.blockSource.getCheckpointData(query);if(confirmed)return await(options.includeBlocks?checkpointResponseFromPublishedCheckpoint(confirmed,options):checkpointResponseFromCheckpointData(confirmed,options));let proposed=await this.blockSource.getProposedCheckpointData(query);if(proposed){if(options.includeAttestations||options.includeL1PublishInfo)throw new BadRequestError("Options includeL1PublishInfo or includeAttestations cannot be satisfied for a proposed checkpoint");let blocks=options.includeBlocks?await this.blockSource.getBlocks({from:proposed.startBlock,limit:proposed.blockCount}):void 0;return await projectProposedToCheckpointResponse(proposed,options,blocks)}}async getCheckpoints(from,limit,options={}){if(options.includeBlocks){let checkpoints=await this.blockSource.getCheckpoints({from,limit});return await Promise.all(checkpoints.map(cp=>checkpointResponseFromPublishedCheckpoint(cp,options)))}return(await this.blockSource.getCheckpointsData({from,limit})).map(d=>checkpointResponseFromCheckpointData(d,options))}async#getCheckpointContext(checkpointNumber){let checkpoint=await this.blockSource.getCheckpointData({number:checkpointNumber});if(checkpoint)return{l1:checkpoint.l1,attestations:checkpoint.attestations}}async#getCheckpointContextsForBlocks(blocks){let unique2=Array.from(new Set(blocks.map(b=>b.checkpointNumber))),entries=await Promise.all(unique2.map(async n=>[n,await this.#getCheckpointContext(n)]));return new Map(entries)}};var NodeTxReceiptBuilder=class{static{__name(this,"NodeTxReceiptBuilder")}p2pClient;blockSource;debugLogStore;constructor(deps){this.p2pClient=deps.p2pClient,this.blockSource=deps.blockSource,this.debugLogStore=deps.debugLogStore}async getTxReceipt(txHash,options){let txPoolStatus=await this.p2pClient.getTxStatus(txHash),isKnownToPool=txPoolStatus==="pending"||txPoolStatus==="mined",indexed=await this.blockSource.getTxEffect(txHash),receipt;if(indexed)receipt=await this.#assembleMinedReceipt(indexed,options);else if(isKnownToPool){let tx;options?.includePendingTx&&(tx=await this.p2pClient.getTxByHashFromPool(txHash,{includeProof:!!options.includeProof})),receipt=new PendingTxReceipt(txHash,tx)}else receipt=new DroppedTxReceipt(txHash,"Tx dropped by P2P node");return this.debugLogStore.decorateReceiptWithLogs(txHash.toString(),receipt),receipt}async#assembleMinedReceipt(indexed,options){let blockNumber=indexed.l2BlockNumber,[tips,l1Constants]=await Promise.all([this.blockSource.getL2Tips(),this.blockSource.getL1Constants()]),status=this.#deriveMinedStatus(blockNumber,tips),epochNumber=getEpochAtSlot(indexed.slotNumber,l1Constants);return new MinedTxReceipt(indexed.data.txHash,status,MinedTxReceipt.executionResultFromRevertCode(indexed.data.revertCode),indexed.data.transactionFee.toBigInt(),indexed.l2BlockHash,blockNumber,indexed.slotNumber,indexed.txIndexInBlock,epochNumber,options?.includeTxEffect?indexed.data:void 0,void 0)}#deriveMinedStatus(blockNumber,tips){return blockNumber<=tips.finalized.block.number?TxStatus.FINALIZED:blockNumber<=tips.proven.block.number?TxStatus.PROVEN:blockNumber<=tips.checkpointed.block.number?TxStatus.CHECKPOINTED:TxStatus.PROPOSED}};var NodeWorldStateQueries=class{static{__name(this,"NodeWorldStateQueries")}worldStateSynchronizer;blockSource;l1ToL2MessageSource;log;constructor(deps){this.worldStateSynchronizer=deps.worldStateSynchronizer,this.blockSource=deps.blockSource,this.l1ToL2MessageSource=deps.l1ToL2MessageSource,this.log=deps.log??createLogger("node:world-state-queries")}async findLeavesIndexes(referenceBlock,treeId,leafValues){let committedDb=await this.getWorldState(referenceBlock),maybeIndices=await committedDb.findLeafIndices(treeId,leafValues.map(x=>x.toBuffer())),definedIndices=maybeIndices.filter(x=>x!==void 0),blockNumbers=await committedDb.getBlockNumbersForLeafIndices(treeId,definedIndices),indexToBlockNumber=new Map;for(let i=0;i<definedIndices.length;i++){let blockNumber=blockNumbers[i];if(blockNumber===void 0)throw new Error(`Block number is undefined for leaf index ${definedIndices[i]} in tree ${MerkleTreeId[treeId]}`);indexToBlockNumber.set(definedIndices[i],blockNumber)}let uniqueBlockNumbers=[...new Set(indexToBlockNumber.values())],blockHashes=await Promise.all(uniqueBlockNumbers.map(blockNumber=>committedDb.getLeafValue(MerkleTreeId.ARCHIVE,BigInt(blockNumber)))),blockNumberToHash=new Map;for(let i=0;i<uniqueBlockNumbers.length;i++){let blockHash=blockHashes[i];if(blockHash===void 0)throw new Error(`Block hash is undefined for block number ${uniqueBlockNumbers[i]}`);blockNumberToHash.set(uniqueBlockNumbers[i],blockHash)}return maybeIndices.map(index=>{if(index===void 0)return;let blockNumber=indexToBlockNumber.get(index);if(blockNumber===void 0)throw new Error(`Block number not found for leaf index ${index} in tree ${MerkleTreeId[treeId]}`);let l2BlockHash=blockNumberToHash.get(blockNumber);if(l2BlockHash===void 0)throw new Error(`Block hash not found for block number ${blockNumber}`);return{l2BlockNumber:blockNumber,l2BlockHash,data:index}})}async getBlockHashMembershipWitness(referenceBlock,blockHash){let referenceBlockNumber=await this.resolveBlockNumber(referenceBlock);if(referenceBlockNumber===BlockNumber.ZERO)return;let committedDb=await this.getWorldState(BlockNumber(referenceBlockNumber-1)),[pathAndIndex]=await committedDb.findSiblingPaths(MerkleTreeId.ARCHIVE,[blockHash]);return pathAndIndex===void 0?void 0:MembershipWitness.fromSiblingPath(pathAndIndex.index,pathAndIndex.path)}async getNoteHashMembershipWitness(referenceBlock,noteHash){let committedDb=await this.getWorldState(referenceBlock),[pathAndIndex]=await committedDb.findSiblingPaths(MerkleTreeId.NOTE_HASH_TREE,[noteHash]);return pathAndIndex===void 0?void 0:MembershipWitness.fromSiblingPath(pathAndIndex.index,pathAndIndex.path)}async getL1ToL2MessageMembershipWitness(referenceBlock,l1ToL2Message){let db=await this.getWorldState(referenceBlock),[witness]=await db.findSiblingPaths(MerkleTreeId.L1_TO_L2_MESSAGE_TREE,[l1ToL2Message]);if(witness)return[witness.index,witness.path]}async getL1ToL2MessageCheckpoint(l1ToL2Message){let messageIndex=await this.l1ToL2MessageSource.getL1ToL2MessageIndex(l1ToL2Message);return messageIndex!==void 0?InboxLeaf.checkpointNumberFromIndex(messageIndex):void 0}async getL2ToL1Messages(epoch){let blocks=await this.blockSource.getBlocks({epoch,onlyCheckpointed:!0});return chunkBy(blocks,block=>block.header.globalVariables.slotNumber).map(slotBlocks=>slotBlocks.map(block=>block.body.txEffects.map(txEffect=>txEffect.l2ToL1Msgs)))}getL2ToL1MembershipWitness(txHash,message,messageIndexInTx){return this.blockSource.getL2ToL1MembershipWitness(txHash,message,messageIndexInTx)}async getNullifierMembershipWitness(referenceBlock,nullifier){let db=await this.getWorldState(referenceBlock),[witness]=await db.findSiblingPaths(MerkleTreeId.NULLIFIER_TREE,[nullifier.toBuffer()]);if(!witness)return;let{index,path}=witness,leafPreimage=await db.getLeafPreimage(MerkleTreeId.NULLIFIER_TREE,index);if(leafPreimage)return new NullifierMembershipWitness(index,leafPreimage,path)}async getLowNullifierMembershipWitness(referenceBlock,nullifier){let committedDb=await this.getWorldState(referenceBlock),findResult=await committedDb.getPreviousValueIndex(MerkleTreeId.NULLIFIER_TREE,nullifier.toBigInt());if(!findResult)return;let{index,alreadyPresent}=findResult;if(alreadyPresent)throw new Error(`Cannot prove nullifier non-inclusion: nullifier ${nullifier.toBigInt()} already exists in the tree`);let preimageData=await committedDb.getLeafPreimage(MerkleTreeId.NULLIFIER_TREE,index),siblingPath=await committedDb.getSiblingPath(MerkleTreeId.NULLIFIER_TREE,BigInt(index));return new NullifierMembershipWitness(BigInt(index),preimageData,siblingPath)}async getPublicDataWitness(referenceBlock,leafSlot){let committedDb=await this.getWorldState(referenceBlock),lowLeafResult=await committedDb.getPreviousValueIndex(MerkleTreeId.PUBLIC_DATA_TREE,leafSlot.toBigInt());if(lowLeafResult){let preimage=await committedDb.getLeafPreimage(MerkleTreeId.PUBLIC_DATA_TREE,lowLeafResult.index),path=await committedDb.getSiblingPath(MerkleTreeId.PUBLIC_DATA_TREE,lowLeafResult.index);return new PublicDataWitness(lowLeafResult.index,preimage,path)}else return}async getPublicStorageAt(referenceBlock,contract,slot){let committedDb=await this.getWorldState(referenceBlock),leafSlot=await computePublicDataTreeLeafSlot(contract,slot),lowLeafResult=await committedDb.getPreviousValueIndex(MerkleTreeId.PUBLIC_DATA_TREE,leafSlot.toBigInt());return!lowLeafResult||!lowLeafResult.alreadyPresent?Fr.ZERO:(await committedDb.getLeafPreimage(MerkleTreeId.PUBLIC_DATA_TREE,lowLeafResult.index)).leaf.value}async getWorldState(block){let query=normalizeBlockParameter(block),requestedHash="hash"in query?query.hash:void 0,anchorBlockNumber=requestedHash!==void 0?await this.resolveBlockNumber(query):void 0,blockSyncedTo=BlockNumber.ZERO;try{blockSyncedTo=await this.#syncWorldState(anchorBlockNumber,requestedHash)}catch(err){this.log.error(`Error getting world state: ${err}`)}if("tag"in query&&query.tag==="proposed")return this.log.debug(`Using committed db for latest block, world state synced upto ${blockSyncedTo}`),this.worldStateSynchronizer.getCommitted();let blockNumber=anchorBlockNumber??await this.resolveBlockNumber(query);if(blockNumber>blockSyncedTo)throw new Error(`Queried block ${inspectBlockParameter(block)} not yet synced by the node (node is synced upto ${blockSyncedTo}).`);this.log.debug(`Using snapshot for block ${blockNumber}, world state synced upto ${blockSyncedTo}`);let snapshot=this.worldStateSynchronizer.getSnapshot(blockNumber);if(requestedHash!==void 0&&blockNumber!==BlockNumber.ZERO){let blockHash=await snapshot.getLeafValue(MerkleTreeId.ARCHIVE,BigInt(blockNumber));if(!blockHash||!requestedHash.equals(blockHash))throw new Error(`Block hash ${requestedHash.toString()} not found in world state at block number ${blockNumber} (world state has ${blockHash?.toString()??"no hash"} at that index, genesis header hash is ${this.blockSource.getGenesisBlockHash().toString()}). If the node API has been queried with anchor block hash possibly a reorg has occurred.`)}return snapshot}async resolveBlockNumber(block){let query=normalizeBlockParameter(block),blockNumber=await this.blockSource.getBlockNumber(query);if(blockNumber===void 0)throw"hash"in query?new Error(`Block hash ${query.hash.toString()} not found when querying world state. If the node API has been queried with anchor block hash possibly a reorg has occurred.`):"archive"in query?new Error(`Block with archive ${query.archive.toString()} not found.`):new Error(`Block not found for ${inspectBlockParameter(block)}.`);return blockNumber}async#syncWorldState(targetBlockNumber,blockHash){let target2=targetBlockNumber??await this.blockSource.getBlockNumber();return await this.worldStateSynchronizer.syncImmediate(target2,blockHash)}};var NodeMetrics=class{static{__name(this,"NodeMetrics")}constructor(_client,_name){}receivedTx(_durationMs,_isAccepted){throwStub("NodeMetrics.receivedTx")}recordSnapshot(_durationMs){throwStub("NodeMetrics.recordSnapshot")}recordSnapshotError(){throwStub("NodeMetrics.recordSnapshotError")}};var import_epoch_cache=__toESM(require_empty_stub(),1);import{SimulationOverridesBuilder as SimulationOverridesBuilder2}from"@aztec/ethereum/contracts";async function applyPublicDataOverrides(fork,publicStorage){if(!publicStorage?.length)return;let writes=await Promise.all(publicStorage.map(async o=>{let leafSlot=await computePublicDataTreeLeafSlot(o.contract,o.slot);return new PublicDataWrite(leafSlot,o.value)}));await fork.sequentialInsert(MerkleTreeId.PUBLIC_DATA_TREE,writes.map(w=>w.toBuffer()))}__name(applyPublicDataOverrides,"applyPublicDataOverrides");function _ts_add_disposable_resource(env2,value,async){if(value!=null){if(typeof value!="object"&&typeof value!="function")throw new TypeError("Object expected.");var dispose,inner;if(async){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");dispose=value[Symbol.asyncDispose]}if(dispose===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");dispose=value[Symbol.dispose],async&&(inner=dispose)}if(typeof dispose!="function")throw new TypeError("Object not disposable.");inner&&(dispose=__name(function(){try{inner.call(this)}catch(e2){return Promise.reject(e2)}},"dispose")),env2.stack.push({value,dispose,async})}else async&&env2.stack.push({async:!0});return value}__name(_ts_add_disposable_resource,"_ts_add_disposable_resource");function _ts_dispose_resources(env2){var _SuppressedError=typeof SuppressedError=="function"?SuppressedError:function(error2,suppressed,message){var e2=new Error(message);return e2.name="SuppressedError",e2.error=error2,e2.suppressed=suppressed,e2};return(_ts_dispose_resources=__name(function(env3){function fail(e2){env3.error=env3.hasError?new _SuppressedError(e2,env3.error,"An error was suppressed during disposal."):e2,env3.hasError=!0}__name(fail,"fail");var r2,s2=0;function next(){for(;r2=env3.stack.pop();)try{if(!r2.async&&s2===1)return s2=0,env3.stack.push(r2),Promise.resolve().then(next);if(r2.dispose){var result=r2.dispose.call(r2.value);if(r2.async)return s2|=2,Promise.resolve(result).then(next,function(e2){return fail(e2),next()})}else s2|=1}catch(e2){fail(e2)}if(s2===1)return env3.hasError?Promise.reject(env3.error):Promise.resolve();if(env3.hasError)throw env3.error}return __name(next,"next"),next()},"_ts_dispose_resources"))(env2)}__name(_ts_dispose_resources,"_ts_dispose_resources");var NodePublicCallsSimulator=class{static{__name(this,"NodePublicCallsSimulator")}blockSource;worldStateSynchronizer;l1ToL2MessageSource;contractDataSource;globalVariableBuilder;rollupContract;epochCache;signatureContext;config;telemetry;log;constructor(deps){this.blockSource=deps.blockSource,this.worldStateSynchronizer=deps.worldStateSynchronizer,this.l1ToL2MessageSource=deps.l1ToL2MessageSource,this.contractDataSource=deps.contractDataSource,this.globalVariableBuilder=deps.globalVariableBuilder,this.rollupContract=deps.rollupContract,this.epochCache=deps.epochCache,this.signatureContext=deps.signatureContext,this.config=deps.config,this.telemetry=deps.telemetry??getTelemetryClient(),this.log=deps.log??createLogger("node:public-calls-simulator")}async simulate(tx,skipFeeEnforcement=!1,overrides){let env2={stack:[],error:void 0,hasError:!1};try{let gasSettings=tx.data.constants.txContext.gasSettings,txGasLimit=gasSettings.gasLimits.l2Gas,teardownGasLimit=gasSettings.teardownGasLimits.l2Gas;if(txGasLimit+teardownGasLimit>this.config.rpcSimulatePublicMaxGasLimit)throw new BadRequestError(`Transaction total gas limit ${txGasLimit+teardownGasLimit} (${txGasLimit} + ${teardownGasLimit}) exceeds maximum gas limit ${this.config.rpcSimulatePublicMaxGasLimit} for simulation`);let txHash=tx.getTxHash(),[l2Tips,proposedCheckpointData]=await Promise.all([this.blockSource.getL2Tips(),this.blockSource.getProposedCheckpointData()]),latestBlockNumber=l2Tips.proposed.number,blockNumber=BlockNumber.add(latestBlockNumber,1),atCheckpointBoundary=(proposedCheckpointData?BlockNumber.add(proposedCheckpointData.startBlock,proposedCheckpointData.blockCount-1):l2Tips.checkpointed.block.number)===l2Tips.proposed.number,{globalVariables:newGlobalVariables,targetCheckpoint}=atCheckpointBoundary?await this.buildGlobalVariablesForNewCheckpoint(l2Tips,proposedCheckpointData,blockNumber):{globalVariables:await this.copyGlobalVariablesFromLatestProposedBlock(latestBlockNumber,blockNumber)},publicProcessorFactory=new PublicProcessorFactory(this.contractDataSource,new DateProvider,this.telemetry,this.log.getBindings());this.log.verbose(`Simulating public calls for tx ${txHash}`,{globalVariables:newGlobalVariables.toInspect(),txHash,blockNumber,atCheckpointBoundary}),await this.worldStateSynchronizer.syncImmediate(latestBlockNumber);let nextCheckpointMessages=await this.getNextCheckpointMessages(targetCheckpoint),merkleTreeFork=_ts_add_disposable_resource(env2,await this.worldStateSynchronizer.fork(latestBlockNumber),!0);nextCheckpointMessages!==void 0&&(this.log.debug(`Appending ${nextCheckpointMessages.length} L1-to-L2 messages to the world state tree for the next checkpoint`,{checkpointNumber:targetCheckpoint}),await appendL1ToL2MessagesToTree(merkleTreeFork,nextCheckpointMessages)),await applyPublicDataOverrides(merkleTreeFork,overrides?.publicStorage);let config2=PublicSimulatorConfig.from({skipFeeEnforcement,collectDebugLogs:!0,collectHints:!1,collectCallMetadata:!0,collectStatistics:!1,collectionLimits:CollectionLimitsConfig.from({maxDebugLogMemoryReads:this.config.rpcSimulatePublicMaxDebugLogMemoryReads})}),contractsDB=new PublicContractsDB(this.contractDataSource,this.log.getBindings());overrides?.contracts&&contractsDB.addContracts(Object.values(overrides.contracts).map(({instance})=>instance));let processor=publicProcessorFactory.create(merkleTreeFork,newGlobalVariables,config2,contractsDB),[processedTxs,failedTxs,_usedTxs,returns,debugLogs]=await processor.process([tx]);if(failedTxs.length)throw this.log.warn(`Simulated tx ${txHash} fails: ${failedTxs[0].error}`,{txHash}),failedTxs[0].error;let[processedTx]=processedTxs;return new PublicSimulationOutput(processedTx.revertReason,processedTx.globalVariables,processedTx.txEffect,returns,processedTx.gasUsed,debugLogs)}catch(e2){env2.error=e2,env2.hasError=!0}finally{let result=_ts_dispose_resources(env2);result&&await result}}async getNextCheckpointMessages(targetCheckpoint){if(targetCheckpoint!==void 0)try{return await this.l1ToL2MessageSource.getL1ToL2Messages(targetCheckpoint)}catch(err){isErrorClass(err,L1ToL2MessagesNotReadyError2)?this.log.warn(`L1-to-L2 messages for checkpoint ${targetCheckpoint} are not ready yet (simulating without them)`,{checkpointNumber:targetCheckpoint}):this.log.error(`Failed to get L1-to-L2 messages for checkpoint ${targetCheckpoint} (simulating without them)`,err,{checkpointNumber:targetCheckpoint});return}}async copyGlobalVariablesFromLatestProposedBlock(latestBlockNumber,blockNumber){let latestBlockData=await this.blockSource.getBlockData({number:latestBlockNumber});if(!latestBlockData)throw new Error(`Cannot simulate public calls: latest proposed block ${latestBlockNumber} has no header on this node (torn archiver snapshot); retry`);return GlobalVariables.from({...latestBlockData.header.globalVariables,blockNumber})}async buildGlobalVariablesForNewCheckpoint(l2Tips,proposedCheckpointData,blockNumber){let checkpointedCheckpointNumber=l2Tips.checkpointed.checkpoint.number,proposedCheckpointNumber=proposedCheckpointData?.checkpointNumber??checkpointedCheckpointNumber,targetSlot=this.computeTargetSlot(proposedCheckpointData),plan=await this.buildSimulationOverridesPlan(proposedCheckpointData,checkpointedCheckpointNumber),checkpointGlobalVariables=await this.globalVariableBuilder.buildCheckpointGlobalVariables(EthAddress.ZERO,AztecAddress.ZERO,targetSlot,plan);return{globalVariables:GlobalVariables.from({blockNumber,...checkpointGlobalVariables}),targetCheckpoint:CheckpointNumber(proposedCheckpointNumber+1)}}computeTargetSlot(proposedCheckpointData){let slotFromNextL1Timestamp=this.epochCache.getEpochAndSlotInNextL1Slot().slot+import_epoch_cache.PROPOSER_PIPELINING_SLOT_OFFSET,slotAfterProposedCheckpoint=proposedCheckpointData?proposedCheckpointData.header.slotNumber+1:void 0;return SlotNumber(Math.max(...compactArray([slotFromNextL1Timestamp,slotAfterProposedCheckpoint])))}async buildSimulationOverridesPlan(proposedCheckpointData,checkpointedCheckpointNumber){let rollup=this.rollupContract;if(rollup){if(proposedCheckpointData)return buildCheckpointSimulationOverridesPlan({checkpointNumber:CheckpointNumber(proposedCheckpointData.checkpointNumber+1),proposedCheckpointData,checkpointedCheckpointNumber,rollup,signatureContext:this.signatureContext,log:this.log});let validationStatus=await this.blockSource.getPendingChainValidationStatus();if(!validationStatus.valid)return buildCheckpointSimulationOverridesPlan({checkpointNumber:CheckpointNumber(checkpointedCheckpointNumber+1),invalidateToPendingCheckpointNumber:CheckpointNumber(validationStatus.checkpoint.checkpointNumber-1),checkpointedCheckpointNumber,rollup,signatureContext:this.signatureContext,log:this.log})}return new SimulationOverridesBuilder2().withChainTips({pending:checkpointedCheckpointNumber,proven:checkpointedCheckpointNumber}).build()}};function applyDecs2203RFactory3(){function createAddInitializerMethod(initializers,decoratorFinishedRef){return __name(function(initializer3){assertNotFinished(decoratorFinishedRef,"addInitializer"),assertCallable(initializer3,"An initializer"),initializers.push(initializer3)},"addInitializer")}__name(createAddInitializerMethod,"createAddInitializerMethod");function memberDec(dec,name,desc,initializers,kind,isStatic,isPrivate,metadata,value){var kindStr;switch(kind){case 1:kindStr="accessor";break;case 2:kindStr="method";break;case 3:kindStr="getter";break;case 4:kindStr="setter";break;default:kindStr="field"}var ctx={kind:kindStr,name:isPrivate?"#"+name:name,static:isStatic,private:isPrivate,metadata},decoratorFinishedRef={v:!1};ctx.addInitializer=createAddInitializerMethod(initializers,decoratorFinishedRef);var get,set2;kind===0?isPrivate?(get=desc.get,set2=desc.set):(get=__name(function(){return this[name]},"get"),set2=__name(function(v){this[name]=v},"set")):kind===2?get=__name(function(){return desc.value},"get"):((kind===1||kind===3)&&(get=__name(function(){return desc.get.call(this)},"get")),(kind===1||kind===4)&&(set2=__name(function(v){desc.set.call(this,v)},"set"))),ctx.access=get&&set2?{get,set:set2}:get?{get}:{set:set2};try{return dec(value,ctx)}finally{decoratorFinishedRef.v=!0}}__name(memberDec,"memberDec");function assertNotFinished(decoratorFinishedRef,fnName){if(decoratorFinishedRef.v)throw new Error("attempted to call "+fnName+" after decoration was finished")}__name(assertNotFinished,"assertNotFinished");function assertCallable(fn,hint){if(typeof fn!="function")throw new TypeError(hint+" must be a function")}__name(assertCallable,"assertCallable");function assertValidReturnValue(kind,value){var type=typeof value;if(kind===1){if(type!=="object"||value===null)throw new TypeError("accessor decorators must return an object with get, set, or init properties or void 0");value.get!==void 0&&assertCallable(value.get,"accessor.get"),value.set!==void 0&&assertCallable(value.set,"accessor.set"),value.init!==void 0&&assertCallable(value.init,"accessor.init")}else if(type!=="function"){var hint;throw kind===0?hint="field":kind===10?hint="class":hint="method",new TypeError(hint+" decorators must return a function or void 0")}}__name(assertValidReturnValue,"assertValidReturnValue");function applyMemberDec(ret2,base,decInfo,name,kind,isStatic,isPrivate,initializers,metadata){var decs=decInfo[0],desc,init2,value;isPrivate?kind===0||kind===1?desc={get:decInfo[3],set:decInfo[4]}:kind===3?desc={get:decInfo[3]}:kind===4?desc={set:decInfo[3]}:desc={value:decInfo[3]}:kind!==0&&(desc=Object.getOwnPropertyDescriptor(base,name)),kind===1?value={get:desc.get,set:desc.set}:kind===2?value=desc.value:kind===3?value=desc.get:kind===4&&(value=desc.set);var newValue,get,set2;if(typeof decs=="function")newValue=memberDec(decs,name,desc,initializers,kind,isStatic,isPrivate,metadata,value),newValue!==void 0&&(assertValidReturnValue(kind,newValue),kind===0?init2=newValue:kind===1?(init2=newValue.init,get=newValue.get||value.get,set2=newValue.set||value.set,value={get,set:set2}):value=newValue);else for(var i=decs.length-1;i>=0;i--){var dec=decs[i];if(newValue=memberDec(dec,name,desc,initializers,kind,isStatic,isPrivate,metadata,value),newValue!==void 0){assertValidReturnValue(kind,newValue);var newInit;kind===0?newInit=newValue:kind===1?(newInit=newValue.init,get=newValue.get||value.get,set2=newValue.set||value.set,value={get,set:set2}):value=newValue,newInit!==void 0&&(init2===void 0?init2=newInit:typeof init2=="function"?init2=[init2,newInit]:init2.push(newInit))}}if(kind===0||kind===1){if(init2===void 0)init2=__name(function(instance,init3){return init3},"init");else if(typeof init2!="function"){var ownInitializers=init2;init2=__name(function(instance,init3){for(var value2=init3,i2=0;i2<ownInitializers.length;i2++)value2=ownInitializers[i2].call(instance,value2);return value2},"init")}else{var originalInitializer=init2;init2=__name(function(instance,init3){return originalInitializer.call(instance,init3)},"init")}ret2.push(init2)}kind!==0&&(kind===1?(desc.get=value.get,desc.set=value.set):kind===2?desc.value=value:kind===3?desc.get=value:kind===4&&(desc.set=value),isPrivate?kind===1?(ret2.push(function(instance,args){return value.get.call(instance,args)}),ret2.push(function(instance,args){return value.set.call(instance,args)})):kind===2?ret2.push(value):ret2.push(function(instance,args){return value.call(instance,args)}):Object.defineProperty(base,name,desc))}__name(applyMemberDec,"applyMemberDec");function applyMemberDecs(Class2,decInfos,metadata){for(var ret2=[],protoInitializers,staticInitializers,existingProtoNonFields=new Map,existingStaticNonFields=new Map,i=0;i<decInfos.length;i++){var decInfo=decInfos[i];if(Array.isArray(decInfo)){var kind=decInfo[1],name=decInfo[2],isPrivate=decInfo.length>3,isStatic=kind>=5,base,initializers;if(isStatic?(base=Class2,kind=kind-5,staticInitializers=staticInitializers||[],initializers=staticInitializers):(base=Class2.prototype,protoInitializers=protoInitializers||[],initializers=protoInitializers),kind!==0&&!isPrivate){var existingNonFields=isStatic?existingStaticNonFields:existingProtoNonFields,existingKind=existingNonFields.get(name)||0;if(existingKind===!0||existingKind===3&&kind!==4||existingKind===4&&kind!==3)throw new Error("Attempted to decorate a public method/accessor that has the same name as a previously decorated public method/accessor. This is not currently supported by the decorators plugin. Property name was: "+name);!existingKind&&kind>2?existingNonFields.set(name,kind):existingNonFields.set(name,!0)}applyMemberDec(ret2,base,decInfo,name,kind,isStatic,isPrivate,initializers,metadata)}}return pushInitializers(ret2,protoInitializers),pushInitializers(ret2,staticInitializers),ret2}__name(applyMemberDecs,"applyMemberDecs");function pushInitializers(ret2,initializers){initializers&&ret2.push(function(instance){for(var i=0;i<initializers.length;i++)initializers[i].call(instance);return instance})}__name(pushInitializers,"pushInitializers");function applyClassDecs(targetClass,classDecs,metadata){if(classDecs.length>0){for(var initializers=[],newClass=targetClass,name=targetClass.name,i=classDecs.length-1;i>=0;i--){var decoratorFinishedRef={v:!1};try{var nextNewClass=classDecs[i](newClass,{kind:"class",name,addInitializer:createAddInitializerMethod(initializers,decoratorFinishedRef),metadata})}finally{decoratorFinishedRef.v=!0}nextNewClass!==void 0&&(assertValidReturnValue(10,nextNewClass),newClass=nextNewClass)}return[defineMetadata(newClass,metadata),function(){for(var i2=0;i2<initializers.length;i2++)initializers[i2].call(newClass)}]}}__name(applyClassDecs,"applyClassDecs");function defineMetadata(Class2,metadata){return Object.defineProperty(Class2,Symbol.metadata||Symbol.for("Symbol.metadata"),{configurable:!0,enumerable:!0,value:metadata})}return __name(defineMetadata,"defineMetadata"),__name(function(targetClass,memberDecs,classDecs,parentClass){if(parentClass!==void 0)var parentMetadata=parentClass[Symbol.metadata||Symbol.for("Symbol.metadata")];var metadata=Object.create(parentMetadata===void 0?null:parentMetadata),e2=applyMemberDecs(targetClass,memberDecs,metadata);return classDecs.length||defineMetadata(targetClass,metadata),{e:e2,get c(){return applyClassDecs(targetClass,classDecs,metadata)}}},"applyDecs2203R")}__name(applyDecs2203RFactory3,"applyDecs2203RFactory");function _apply_decs_2203_r3(targetClass,memberDecs,classDecs,parentClass){return(_apply_decs_2203_r3=applyDecs2203RFactory3())(targetClass,memberDecs,classDecs,parentClass)}__name(_apply_decs_2203_r3,"_apply_decs_2203_r");var _dec3,_initProto3;_dec3=trackSpan("AztecNodeService.simulatePublicCalls",tx=>({[Attributes.TX_HASH]:tx.getTxHash().toString()}));var AztecNodeService=class{static{__name(this,"AztecNodeService")}static{({e:[_initProto3]}=_apply_decs_2203_r3(this,[[_dec3,2,"simulatePublicCalls"]],[]))}metrics;isUploadingSnapshot=(_initProto3(this),!1);sequencerPausedMinTxsPerBlock;nodePublicCallsSimulator;worldStateQueries;blockProvider;txReceiptBuilder;tracer;config;p2pClient;blockSource;logsSource;contractDataSource;l1ToL2MessageSource;worldStateSynchronizer;sequencer;proverNode;slasherClient;validatorsSentinel;stopStartedWatchers;l1ChainId;version;globalVariableBuilder;rollupContract;feeProvider;epochCache;packageVersion;peerProofVerifier;rpcProofVerifier;telemetry;log;blobClient;validatorClient;keyStoreManager;debugLogStore;automineSequencer;constructor(deps){if(this.config=deps.config,this.p2pClient=deps.p2pClient,this.blockSource=deps.blockSource,this.logsSource=deps.logsSource,this.contractDataSource=deps.contractDataSource,this.l1ToL2MessageSource=deps.l1ToL2MessageSource,this.worldStateSynchronizer=deps.worldStateSynchronizer,this.sequencer=deps.sequencer,this.proverNode=deps.proverNode,this.slasherClient=deps.slasherClient,this.validatorsSentinel=deps.validatorsSentinel,this.stopStartedWatchers=deps.stopStartedWatchers,this.l1ChainId=deps.l1ChainId,this.version=deps.version,this.globalVariableBuilder=deps.globalVariableBuilder,this.rollupContract=deps.rollupContract,this.feeProvider=deps.feeProvider,this.epochCache=deps.epochCache,this.packageVersion=deps.packageVersion,this.peerProofVerifier=deps.peerProofVerifier,this.rpcProofVerifier=deps.rpcProofVerifier,this.telemetry=deps.telemetry??getTelemetryClient(),this.log=deps.log??createLogger("node"),this.blobClient=deps.blobClient,this.validatorClient=deps.validatorClient,this.keyStoreManager=deps.keyStoreManager,this.debugLogStore=deps.debugLogStore??new NullDebugLogStore,this.automineSequencer=deps.automineSequencer,this.metrics=new NodeMetrics(this.telemetry,"AztecNodeService"),this.tracer=this.telemetry.getTracer("AztecNodeService"),this.nodePublicCallsSimulator=new NodePublicCallsSimulator({blockSource:this.blockSource,worldStateSynchronizer:this.worldStateSynchronizer,l1ToL2MessageSource:this.l1ToL2MessageSource,contractDataSource:this.contractDataSource,globalVariableBuilder:this.globalVariableBuilder,rollupContract:this.rollupContract,epochCache:this.epochCache,signatureContext:{chainId:this.l1ChainId,rollupAddress:this.config.rollupAddress},config:this.config,telemetry:this.telemetry,log:this.log.createChild("public-calls-simulator")}),this.worldStateQueries=new NodeWorldStateQueries({worldStateSynchronizer:this.worldStateSynchronizer,blockSource:this.blockSource,l1ToL2MessageSource:this.l1ToL2MessageSource,log:this.log.createChild("world-state-queries")}),this.blockProvider=new NodeBlockProvider(this.blockSource),this.txReceiptBuilder=new NodeTxReceiptBuilder({p2pClient:this.p2pClient,blockSource:this.blockSource,debugLogStore:this.debugLogStore}),this.log.info(`Aztec Node version: ${this.packageVersion}`),this.log.info(`Aztec Node started on chain 0x${this.l1ChainId.toString(16)}`,pickL1ContractAddresses(this.config)),this.debugLogStore.isEnabled&&this.config.realProofs)throw new Error("debugLogStore should never be enabled when realProofs are set")}getProofVerifier(){return this.rpcProofVerifier}async getWorldStateSyncStatus(){return(await this.worldStateSynchronizer.status()).syncSummary}getChainTips(){return this.blockSource.getL2Tips()}getL1Constants(){return this.blockSource.getL1Constants()}getSyncedL2SlotNumber(){return this.blockSource.getSyncedL2SlotNumber()}getSyncedL2EpochNumber(){return this.blockSource.getSyncedL2EpochNumber()}getSyncedL1Timestamp(){return this.blockSource.getL1Timestamp()}getCheckpointsData(query){return this.blockSource.getCheckpointsData(query)}async getBlockNumber(tip){return tip===void 0||tip==="proposed"?this.blockSource.getBlockNumber():await this.blockSource.getBlockNumber({tag:tip})??BlockNumber.ZERO}async getCheckpointNumber(tip){let tips=await this.blockSource.getL2Tips();switch(tip){case void 0:case"checkpointed":return tips.checkpointed.checkpoint.number;case"proven":return tips.proven.checkpoint.number;case"finalized":return tips.finalized.checkpoint.number}}getBlock(param,options={}){return this.blockProvider.getBlock(param,options)}getBlockData(param){return this.blockProvider.getBlockData(param)}getBlocks(from,limit,options={}){return this.blockProvider.getBlocks(from,limit,options)}getCheckpoint(param,options={}){return this.blockProvider.getCheckpoint(param,options)}getCheckpoints(from,limit,options={}){return this.blockProvider.getCheckpoints(from,limit,options)}getSequencer(){return this.sequencer}getAutomineSequencer(){return this.automineSequencer}getProverNode(){return this.proverNode}getBlockSource(){return this.blockSource}getContractDataSource(){return this.contractDataSource}getP2P(){return this.p2pClient}getL1ContractAddresses(){return Promise.resolve(pickL1ContractAddresses(this.config))}getEncodedEnr(){return Promise.resolve(this.p2pClient.getEnr()?.encodeTxt())}async getAllowedPublicSetup(){return[...await(0,import_p2p2.getDefaultAllowedSetupFunctions)(),...this.config.txPublicSetupAllowListExtend??[]]}isReady(){return Promise.resolve(this.p2pClient.isReady()??!1)}async getNodeInfo(){let[nodeVersion,rollupVersion,chainId,enr,contractAddresses,protocolContractAddresses,l1Constants]=await Promise.all([this.getNodeVersion(),this.getVersion(),this.getChainId(),this.getEncodedEnr(),this.getL1ContractAddresses(),this.getProtocolContractAddresses(),this.blockSource.getL1Constants()]),maxTxGas=getNetworkTxGasLimits(this.config,l1Constants);return{nodeVersion,l1ChainId:chainId,rollupVersion,enr,l1ContractAddresses:contractAddresses,protocolContractAddresses,realProofs:!!this.config.realProofs,txsLimits:{gas:{daGas:maxTxGas.daGas,l2Gas:maxTxGas.l2Gas}}}}async getCurrentMinFees(){return await this.feeProvider.getCurrentMinFees()}async getPredictedMinFees(manaUsage){return await this.feeProvider.getPredictedMinFees(manaUsage)}async getMaxPriorityFees(){for await(let tx of this.p2pClient.iteratePendingTxs({includeProof:!1}))return tx.getGasSettings().maxPriorityFeesPerGas;return GasFees.from({feePerDaGas:0n,feePerL2Gas:0n})}getNodeVersion(){return Promise.resolve(this.packageVersion)}getVersion(){return Promise.resolve(this.version)}getChainId(){return Promise.resolve(this.l1ChainId)}getContractClass(id){return this.contractDataSource.getContractClass(id)}async getContract(address,referenceBlock="latest"){let blockData=await this.getBlockData(referenceBlock);if(!blockData)throw new Error(`Reference block ${inspectBlockParameter(referenceBlock)} not found when querying contract ${address}. If the node API has been queried with an anchor block hash, possibly a reorg has occurred.`);return this.contractDataSource.getContract(address,blockData.header.globalVariables.timestamp)}getPrivateLogsByTags(query){return this.logsSource.getPrivateLogsByTags(query)}getPublicLogsByTags(query){return this.logsSource.getPublicLogsByTags(query)}async sendTx(tx){await this.#sendTx(tx)}async#sendTx(tx){let timer=new Timer,txHash=tx.getTxHash().toString(),valid=await this.isValidTx(tx);if(valid.result!=="valid"){let reason=valid.reason.join(", ");throw this.metrics.receivedTx(timer.ms(),!1),this.log.warn(`Received invalid tx ${txHash}: ${reason}`,{txHash}),new Error(`Invalid tx: ${reason}`)}try{await this.p2pClient.sendTx(tx)}catch(err){throw this.metrics.receivedTx(timer.ms(),!1),this.log.warn(`Mempool rejected tx ${txHash}: ${err.message}`,{txHash}),err}let duration3=timer.ms();this.metrics.receivedTx(duration3,!0),this.log.info(`Received tx ${txHash} in ${duration3}ms`,{txHash})}getTxReceipt(txHash,options){return this.txReceiptBuilder.getTxReceipt(txHash,options)}getTxEffect(txHash){return this.blockSource.getTxEffect(txHash)}async stop(){this.log.info("Stopping Aztec Node"),await this.stopStartedWatchers(),await tryStop(this.slasherClient),await Promise.all([tryStop(this.peerProofVerifier),tryStop(this.rpcProofVerifier)]),await tryStop(this.sequencer),await tryStop(this.automineSequencer),await tryStop(this.proverNode),await tryStop(this.p2pClient),await tryStop(this.worldStateSynchronizer),await tryStop(this.blockSource),await tryStop(this.blobClient),await tryStop(this.telemetry),this.log.info("Stopped Aztec Node")}getBlobClient(){return this.blobClient}getPendingTxs(limit,after,options){return this.p2pClient.getPendingTxs(limit,after,options)}getPendingTxCount(){return this.p2pClient.getPendingTxCount()}getPeers(includePending){return this.p2pClient.getPeers(includePending)}getCheckpointAttestationsForSlot(slot,proposalPayloadHash){return this.p2pClient.getCheckpointAttestationsForSlot(slot,proposalPayloadHash)}getProposalsForSlot(slot){return this.p2pClient.getProposalsForSlot(slot)}getTxByHash(txHash,options){return this.p2pClient.getTxByHashFromPool(txHash,{includeProof:!!options?.includeProof})}async getTxsByHash(txHashes,options){let txs=await this.p2pClient.getTxsByHashFromPool(txHashes,{includeProof:!!options?.includeProof});return compactArray(txs)}findLeavesIndexes(referenceBlock,treeId,leafValues){return this.worldStateQueries.findLeavesIndexes(referenceBlock,treeId,leafValues)}getBlockHashMembershipWitness(referenceBlock,blockHash){return this.worldStateQueries.getBlockHashMembershipWitness(referenceBlock,blockHash)}getNoteHashMembershipWitness(referenceBlock,noteHash){return this.worldStateQueries.getNoteHashMembershipWitness(referenceBlock,noteHash)}getL1ToL2MessageMembershipWitness(referenceBlock,l1ToL2Message){return this.worldStateQueries.getL1ToL2MessageMembershipWitness(referenceBlock,l1ToL2Message)}getL1ToL2MessageCheckpoint(l1ToL2Message){return this.worldStateQueries.getL1ToL2MessageCheckpoint(l1ToL2Message)}getL2ToL1Messages(epoch){return this.worldStateQueries.getL2ToL1Messages(epoch)}getL2ToL1MembershipWitness(txHash,message,messageIndexInTx){return this.worldStateQueries.getL2ToL1MembershipWitness(txHash,message,messageIndexInTx)}getNullifierMembershipWitness(referenceBlock,nullifier){return this.worldStateQueries.getNullifierMembershipWitness(referenceBlock,nullifier)}getLowNullifierMembershipWitness(referenceBlock,nullifier){return this.worldStateQueries.getLowNullifierMembershipWitness(referenceBlock,nullifier)}getPublicDataWitness(referenceBlock,leafSlot){return this.worldStateQueries.getPublicDataWitness(referenceBlock,leafSlot)}getPublicStorageAt(referenceBlock,contract,slot){return this.worldStateQueries.getPublicStorageAt(referenceBlock,contract,slot)}simulatePublicCalls(tx,skipFeeEnforcement=!1,overrides){return this.nodePublicCallsSimulator.simulate(tx,skipFeeEnforcement,overrides)}async isValidTx(tx,{isSimulation,skipFeeEnforcement}={}){let db=this.worldStateSynchronizer.getCommitted(),verifier=isSimulation?void 0:this.rpcProofVerifier,{ts:nextSlotTimestamp}=this.epochCache.getEpochAndSlotInNextL1Slot(),blockNumber=BlockNumber(await this.blockSource.getBlockNumber()+1),l1Constants=await this.blockSource.getL1Constants(),networkTxGasLimits=getNetworkTxGasLimits(this.config,l1Constants);return await(0,import_p2p2.createTxValidatorForAcceptingTxsOverRPC)(db,this.contractDataSource,verifier,{timestamp:nextSlotTimestamp,blockNumber,l1ChainId:this.l1ChainId,rollupVersion:this.version,setupAllowList:[...await(0,import_p2p2.getDefaultAllowedSetupFunctions)(),...this.config.txPublicSetupAllowListExtend??[]],gasFees:await this.getCurrentMinFees(),skipFeeEnforcement,isSimulation,txsPermitted:!this.config.disableTransactions,maxTxL2Gas:networkTxGasLimits.l2Gas,maxTxDAGas:networkTxGasLimits.daGas},this.log.getBindings()).validateTx(tx)}getConfig(){let keys=AztecNodeAdminConfigSchema.keyof().options;return Promise.resolve(pick2(this.config,...keys))}async setConfig(config2){let newConfig={...this.config,...config2},sequencerUpdate={...config2};this.sequencerPausedMinTxsPerBlock!==void 0&&sequencerUpdate.minTxsPerBlock!==void 0&&(this.sequencerPausedMinTxsPerBlock=sequencerUpdate.minTxsPerBlock,delete sequencerUpdate.minTxsPerBlock),this.sequencer?.updateConfig(sequencerUpdate),this.automineSequencer?.updateConfig(sequencerUpdate),this.slasherClient?.updateConfig(config2),this.validatorsSentinel?.updateConfig(config2),await this.p2pClient.updateP2PConfig(config2);let archiver=this.blockSource;if("updateConfig"in archiver&&archiver.updateConfig(config2),newConfig.realProofs!==this.config.realProofs)if(await Promise.all([tryStop(this.peerProofVerifier),tryStop(this.rpcProofVerifier)]),newConfig.realProofs){this.peerProofVerifier=await BatchChonkVerifier.new(newConfig,newConfig.bbChonkVerifyMaxBatch,"peer");let rpcVerifier=await BBCircuitVerifier.new(newConfig);this.rpcProofVerifier=new QueuedIVCVerifier(rpcVerifier,newConfig.numConcurrentIVCVerifiers)}else this.peerProofVerifier=new TestCircuitVerifier,this.rpcProofVerifier=new TestCircuitVerifier;this.config=newConfig}getProtocolContractAddresses(){return Promise.resolve({classRegistry:ProtocolContractAddress.ContractClassRegistry,feeJuice:ProtocolContractAddress.FeeJuice,instanceRegistry:ProtocolContractAddress.ContractInstanceRegistry,multiCallEntrypoint:STANDARD_MULTI_CALL_ENTRYPOINT_ADDRESS})}registerContractFunctionSignatures(signatures){return this.contractDataSource.registerContractFunctionSignatures(signatures)}getValidatorsStats(){return this.validatorsSentinel?.computeStats()??Promise.resolve({stats:{},slotWindow:0})}getValidatorStats(validatorAddress,fromSlot,toSlot){return this.validatorsSentinel?.getValidatorStats(validatorAddress,fromSlot,toSlot)??Promise.resolve(void 0)}async startSnapshotUpload(location){let archiver=this.blockSource;if(!("backupTo"in archiver))throw this.metrics.recordSnapshotError(),new Error("Archiver implementation does not support backups. Cannot generate snapshot.");if(!archiver.isInitialSyncComplete())throw this.metrics.recordSnapshotError(),new Error("Archiver initial sync not complete. Cannot start snapshot.");if(!await archiver.getL2Tips().then(tips=>tips.proposed.hash))throw this.metrics.recordSnapshotError(),new Error("Archiver has no latest L2 block hash downloaded. Cannot start snapshot.");if(this.isUploadingSnapshot)throw this.metrics.recordSnapshotError(),new Error("Snapshot upload already in progress. Cannot start another one until complete.");this.isUploadingSnapshot=!0;let timer=new Timer;return(0,import_actions.uploadSnapshot)(location,this.blockSource,this.worldStateSynchronizer,this.config,this.log).then(()=>{this.isUploadingSnapshot=!1,this.metrics.recordSnapshot(timer.ms())}).catch(err=>{this.isUploadingSnapshot=!1,this.metrics.recordSnapshotError(),this.log.error(`Error uploading snapshot: ${err}`)}),Promise.resolve()}async rollbackTo(targetBlock,force,resumeSync=!0){let archiver=this.blockSource;if(!("rollbackTo"in archiver))throw new Error("Archiver implementation does not support rollbacks.");let finalizedBlock=await archiver.getL2Tips().then(tips=>tips.finalized.block.number);if(targetBlock<finalizedBlock)if(force)this.log.warn(`Clearing world state database to allow rolling back behind finalized block ${finalizedBlock}`),await this.worldStateSynchronizer.clear(),await this.p2pClient.clear();else throw new Error(`Cannot rollback to block ${targetBlock} as it is before finalized ${finalizedBlock}`);try{this.log.info("Pausing archiver and world state sync to start rollback"),await archiver.stop(),await this.worldStateSynchronizer.stopSync();let currentBlock=await archiver.getBlockNumber(),blocksToUnwind=currentBlock-targetBlock;this.log.info(`Unwinding ${count(blocksToUnwind,"block")} from L2 block ${currentBlock} to ${targetBlock}`),await archiver.rollbackTo(targetBlock),this.log.info("Unwinding complete.")}catch(err){throw this.log.error("Error during rollback",err),err}finally{resumeSync?(this.log.info("Resuming world state and archiver sync."),this.worldStateSynchronizer.resumeSync(),archiver.resume()):this.log.info("Sync left paused after rollback (resumeSync=false).")}}async pauseSync(){this.log.info("Pausing archiver and world state sync"),await this.blockSource.stop(),await this.worldStateSynchronizer.stopSync()}resumeSync(){return this.log.info("Resuming world state and archiver sync."),this.worldStateSynchronizer.resumeSync(),this.blockSource.resume(),Promise.resolve()}pauseSequencer(){if(this.automineSequencer)return this.automineSequencer.pause(),Promise.resolve();if(this.sequencer)return this.sequencerPausedMinTxsPerBlock===void 0&&(this.sequencerPausedMinTxsPerBlock=this.sequencer.getSequencer().getConfig().minTxsPerBlock??0,this.sequencer.updateConfig({minTxsPerBlock:Number.MAX_SAFE_INTEGER}),this.log.info("Sequencer paused (minTxsPerBlock set to MAX_SAFE_INTEGER)",{previousMinTxsPerBlock:this.sequencerPausedMinTxsPerBlock})),Promise.resolve();throw new BadRequestError("Cannot pause sequencer: no sequencer is running")}resumeSequencer(){if(this.automineSequencer)return this.automineSequencer.resume(),Promise.resolve();if(this.sequencer){if(this.sequencerPausedMinTxsPerBlock!==void 0){let restored=this.sequencerPausedMinTxsPerBlock;this.sequencerPausedMinTxsPerBlock=void 0,this.sequencer.updateConfig({minTxsPerBlock:restored}),this.log.info("Sequencer resumed (minTxsPerBlock restored)",{minTxsPerBlock:restored})}return Promise.resolve()}throw new BadRequestError("Cannot resume sequencer: no sequencer is running")}getSlashOffenses(round){if(!this.slasherClient)throw new Error("Slasher client not enabled");return round==="all"?this.slasherClient.getOffenses():this.slasherClient.gatherOffensesForRound(round==="current"?void 0:BigInt(round))}async reloadKeystore(){if(!this.config.keyStoreDirectory?.length)throw new BadRequestError("Cannot reload keystore: node is not using a file-based keystore. Set KEY_STORE_DIRECTORY to use file-based keystores.");if(!this.validatorClient)throw new BadRequestError("Cannot reload keystore: validator is not enabled.");this.log.info("Reloading keystore from disk");let keyStores=(0,import_node_keystore2.loadKeystores)(this.config.keyStoreDirectory),newManager=new import_node_keystore2.KeystoreManager((0,import_node_keystore2.mergeKeystores)(keyStores));if(await newManager.validateSigners(),import_validator_client.ValidatorClient.validateKeyStoreConfiguration(newManager,this.log),this.keyStoreManager&&this.sequencer){let oldAdapter=import_validator_client.NodeKeystoreAdapter.fromKeyStoreManager(this.keyStoreManager),availablePublishers=new Set(oldAdapter.getAttesterAddresses().flatMap(a=>oldAdapter.getPublisherAddresses(a).map(p=>p.toString().toLowerCase()))),newAdapter2=import_validator_client.NodeKeystoreAdapter.fromKeyStoreManager(newManager);for(let attester of newAdapter2.getAttesterAddresses()){let pubs=newAdapter2.getPublisherAddresses(attester);if(pubs.length>0&&!pubs.some(p=>availablePublishers.has(p.toString().toLowerCase())))throw new BadRequestError(`Cannot reload keystore: validator ${attester} has publisher keys [${pubs.map(p=>p.toString()).join(", ")}] but none match the L1 signers initialized at startup [${[...availablePublishers].join(", ")}]. Publishers cannot be hot-reloaded \u2014 use an existing publisher key or restart the node.`)}}let newAdapter=import_validator_client.NodeKeystoreAdapter.fromKeyStoreManager(newManager),newAddresses=newAdapter.getAttesterAddresses(),oldAddresses=this.keyStoreManager?import_validator_client.NodeKeystoreAdapter.fromKeyStoreManager(this.keyStoreManager).getAttesterAddresses():[],oldSet=new Set(oldAddresses.map(a=>a.toString())),newSet=new Set(newAddresses.map(a=>a.toString())),added=newAddresses.filter(a=>!oldSet.has(a.toString())),removed=oldAddresses.filter(a=>!newSet.has(a.toString()));if(added.length>0&&this.log.info(`Keystore reload: adding attester keys: ${added.map(a=>a.toString()).join(", ")}`),removed.length>0&&this.log.info(`Keystore reload: removing attester keys: ${removed.map(a=>a.toString()).join(", ")}`),added.length===0&&removed.length===0&&this.log.info("Keystore reload: attester keys unchanged"),this.validatorClient.reloadKeystore(newManager),this.sequencer&&this.sequencer.updatePublisherNodeKeyStore(newAdapter),this.slasherClient&&!this.config.slashSelfAllowed){let slashValidatorsNever=unique([...this.config.slashValidatorsNever??[],...newAddresses].map(a=>a.toString())).map(EthAddress.fromString);this.slasherClient.updateConfig({slashValidatorsNever})}this.keyStoreManager=newManager,this.log.info("Keystore reloaded: coinbase, feeRecipient, and attester keys updated")}async mineBlock(){if(this.automineSequencer){await this.automineSequencer.buildEmptyBlock();return}if(!this.sequencer)throw new BadRequestError("Cannot mine block: no sequencer is running");let currentBlockNumber=await this.getBlockNumber(),{slotDuration}=await this.blockSource.getL1Constants(),timeoutSeconds=Math.ceil(slotDuration*1.5),originalMinTxsPerBlock=this.sequencer.getSequencer().getConfig().minTxsPerBlock;this.sequencer.updateConfig({minTxsPerBlock:0});try{this.sequencer.trigger(),await retryUntil(async()=>await this.getBlockNumber()>currentBlockNumber?!0:void 0,"mineBlock",timeoutSeconds,.1)}finally{this.sequencer.updateConfig({minTxsPerBlock:originalMinTxsPerBlock})}}async prove(upToCheckpoint){if(!this.automineSequencer)throw new BadRequestError("Cannot prove checkpoint: no automine sequencer is running");return await this.automineSequencer.prove(upToCheckpoint)}async warpL2TimeAtLeastTo(targetTimestamp){if(!this.automineSequencer)throw new BadRequestError("Cannot warp L2 time: no automine sequencer is running");await this.automineSequencer.warpTo(targetTimestamp)}async warpL2TimeAtLeastBy(duration3){if(!this.automineSequencer)throw new BadRequestError("Cannot warp L2 time: no automine sequencer is running");await this.automineSequencer.warpBy(duration3)}getWorldState(block){return this.worldStateQueries.getWorldState(block)}};var import_client22=__toESM(require_empty_stub(),1);var import_epoch_cache2=__toESM(require_empty_stub(),1);import{createEthereumChain}from"@aztec/ethereum/chain";import{getPublicClient,makeL1HttpTransport}from"@aztec/ethereum/client";import{RegistryContract,RollupContract as RollupContract2}from"@aztec/ethereum/contracts";import{pickL1ContractAddresses as pickL1ContractAddresses2}from"@aztec/ethereum/l1-contract-addresses";var import_node_keystore3=__toESM(require_empty_stub(),1),import_actions2=__toESM(require_empty_stub(),1),import_factories3=__toESM(require_empty_stub(),1),import_p2p4=__toESM(require_empty_stub(),1),import_prover_node=__toESM(require_empty_stub(),1),import_config33=__toESM(require_empty_stub(),1),import_sequencer_client=__toESM(require_empty_stub(),1),import_automine=__toESM(require_empty_stub(),1),import_slasher4=__toESM(require_empty_stub(),1);var import_validator_client2=__toESM(require_empty_stub(),1);import{createPublicClient}from"viem";var import_slasher3=__toESM(require_empty_stub(),1);var DummyP2P=class{static{__name(this,"DummyP2P")}validateTxsReceivedInBlockProposal(_txs){return Promise.resolve()}clear(){throw new Error('DummyP2P does not implement "clear".')}getPendingTxs(){throw new Error('DummyP2P does not implement "getPendingTxs"')}getEncodedEnr(){throw new Error('DummyP2P does not implement "getEncodedEnr"')}getPeers(_includePending){throw new Error('DummyP2P does not implement "getPeers"')}getGossipMeshPeerCount(_topicType){return Promise.resolve(0)}broadcastProposal(_proposal){throw new Error('DummyP2P does not implement "broadcastProposal"')}broadcastCheckpointProposal(_proposal){throw new Error('DummyP2P does not implement "broadcastCheckpointProposal"')}broadcastCheckpointAttestations(_attestations){throw new Error('DummyP2P does not implement "broadcastCheckpointAttestations"')}registerBlockProposalHandler(_handler){throw new Error('DummyP2P does not implement "registerBlockProposalHandler"')}registerValidatorCheckpointProposalHandler(_handler){throw new Error('DummyP2P does not implement "registerValidatorCheckpointProposalHandler"')}registerAllNodesCheckpointProposalHandler(_handler){throw new Error('DummyP2P does not implement "registerAllNodesCheckpointProposalHandler"')}requestTxs(_txHashes){throw new Error('DummyP2P does not implement "requestTxs"')}requestTxByHash(_txHash){throw new Error('DummyP2P does not implement "requestTxByHash"')}sendTx(_tx){throw new Error('DummyP2P does not implement "sendTx"')}handleFailedExecution(_txHashes){throw new Error('DummyP2P does not implement "handleFailedExecution"')}getTxByHashFromPool(_txHash){throw new Error('DummyP2P does not implement "getTxByHashFromPool"')}getTxByHash(_txHash){throw new Error('DummyP2P does not implement "getTxByHash"')}getArchivedTxByHash(_txHash){throw new Error('DummyP2P does not implement "getArchivedTxByHash"')}getTxStatus(_txHash){return Promise.resolve("mined")}iteratePendingTxs(){throw new Error('DummyP2P does not implement "iteratePendingTxs"')}iterateEligiblePendingTxs(){throw new Error('DummyP2P does not implement "iterateEligiblePendingTxs"')}getPendingTxCount(){throw new Error('DummyP2P does not implement "getPendingTxCount"')}hasEligiblePendingTxs(_minCount){throw new Error('DummyP2P does not implement "hasEligiblePendingTxs"')}start(){throw new Error('DummyP2P does not implement "start"')}stop(){throw new Error('DummyP2P does not implement "stop"')}isReady(){throw new Error('DummyP2P does not implement "isReady"')}getStatus(){throw new Error('DummyP2P does not implement "getStatus"')}getEnr(){throw new Error('DummyP2P does not implement "getEnr"')}isP2PClient(){throw new Error('DummyP2P does not implement "isP2PClient"')}getTxProvider(){throw new Error('DummyP2P does not implement "getTxProvider"')}getTxsByHash(_txHashes){throw new Error('DummyP2P does not implement "getTxsByHash"')}getCheckpointAttestationsForSlot(_slot,_proposalPayloadHash){throw new Error('DummyP2P does not implement "getCheckpointAttestationsForSlot"')}addOwnCheckpointAttestations(_attestations){throw new Error('DummyP2P does not implement "addOwnCheckpointAttestations"')}getProposalsForSlot(_slot){return Promise.resolve({blockProposals:[],checkpointProposals:[]})}hasCheckpointProposalForSlot(_slot){return Promise.resolve(!1)}getL2BlockHash(_number2){throw new Error('DummyP2P does not implement "getL2BlockHash"')}updateP2PConfig(_config){throw new Error('DummyP2P does not implement "updateP2PConfig"')}getL2Tips(){throw new Error('DummyP2P does not implement "getL2Tips"')}handleBlockStreamEvent(_event){throw new Error('DummyP2P does not implement "handleBlockStreamEvent"')}sync(){throw new Error('DummyP2P does not implement "sync"')}getTxsByHashFromPool(_txHashes){throw new Error('DummyP2P does not implement "getTxsByHashFromPool"')}hasTxsInPool(_txHashes){throw new Error('DummyP2P does not implement "hasTxsInPool"')}getSyncedLatestBlockNum(){throw new Error('DummyP2P does not implement "getSyncedLatestBlockNum"')}getSyncedProvenBlockNum(){throw new Error('DummyP2P does not implement "getSyncedProvenBlockNum"')}getSyncedLatestSlot(){throw new Error('DummyP2P does not implement "getSyncedLatestSlot"')}protectTxs(_txHashes,_blockHeader){throw new Error('DummyP2P does not implement "protectTxs".')}prepareForSlot(_slotNumber){return Promise.resolve()}addReqRespSubProtocol(_subProtocol,_handler){throw new Error('DummyP2P does not implement "addReqRespSubProtocol".')}handleAuthRequestFromPeer(_authRequest,_peerId){throw new Error('DummyP2P does not implement "handleAuthRequestFromPeer".')}registerThisValidatorAddresses(_address){}registerDuplicateProposalCallback(_callback){throw new Error('DummyP2P does not implement "registerDuplicateProposalCallback"')}registerOversizedProposalCallback(_callback){throw new Error('DummyP2P does not implement "registerOversizedProposalCallback"')}registerDuplicateAttestationCallback(_callback){throw new Error('DummyP2P does not implement "registerDuplicateAttestationCallback"')}registerCheckpointAttestationCallback(_callback){throw new Error('DummyP2P does not implement "registerCheckpointAttestationCallback"')}hasBlockProposalsForSlot(_slot){throw new Error('DummyP2P does not implement "hasBlockProposalsForSlot"')}};var TXEFeeProvider=class{static{__name(this,"TXEFeeProvider")}getCurrentMinFees(){return Promise.resolve(new GasFees(0,0))}getPredictedMinFees(){return Promise.resolve(times(FEE_ORACLE_LAG,()=>new GasFees(0,0)))}},TXEGlobalVariablesBuilder=class{static{__name(this,"TXEGlobalVariablesBuilder")}buildCheckpointGlobalVariables(_coinbase,_feeRecipient,_slotNumber,_simulationOverridesPlan){let vars=makeGlobalVariables();return Promise.resolve({chainId:vars.chainId,version:vars.version,slotNumber:vars.slotNumber,timestamp:vars.timestamp,coinbase:vars.coinbase,feeRecipient:vars.feeRecipient,gasFees:vars.gasFees})}};var MockEpochCache=class{static{__name(this,"MockEpochCache")}getCommittee(_slot="now"){return Promise.resolve({committee:void 0,seed:0n,epoch:EpochNumber.ZERO,isEscapeHatchOpen:!1})}getSlotNow(){return SlotNumber(0)}getTargetSlot(){return SlotNumber(0)}getEpochNow(){return EpochNumber.ZERO}getTargetEpoch(){return EpochNumber.ZERO}getEpochAndSlotNow(){return{epoch:EpochNumber.ZERO,slot:SlotNumber(0),ts:0n,nowMs:0n}}getEpochAndSlotInNextL1Slot(){return{epoch:EpochNumber.ZERO,slot:SlotNumber(0),ts:0n,nowSeconds:0n}}getTargetEpochAndSlotInNextL1Slot(){return this.getEpochAndSlotInNextL1Slot()}getProposerIndexEncoding(_epoch,_slot,_seed){return"0x00"}computeProposerIndex(_slot,_epoch,_seed,_size2){return 0n}getCurrentAndNextSlot(){return{currentSlot:SlotNumber(0),nextSlot:SlotNumber(0)}}getTargetAndNextSlot(){return{targetSlot:SlotNumber(0),nextSlot:SlotNumber(0)}}getProposerAttesterAddressInSlot(_slot){return Promise.resolve(void 0)}isInCommittee(_slot,_validator){return Promise.resolve(!1)}getRegisteredValidators(){return Promise.resolve([])}filterInCommittee(_slot,_validators){return Promise.resolve([])}isEscapeHatchOpen(_epoch){return Promise.resolve(!1)}isEscapeHatchOpenAtSlot(_slot){return Promise.resolve(!1)}getL1Constants(){return EmptyL1RollupConstants}};var TXESynchronizer=class{constructor(nativeWorldStateService){this.nativeWorldStateService=nativeWorldStateService}static{__name(this,"TXESynchronizer")}blockNumber=BlockNumber.ZERO;static async create(){let nativeWorldStateService=await NativeWorldStateService.ephemeral();return new this(nativeWorldStateService)}async handleL2Block(block,l1ToL2Messages=[]){await this.nativeWorldStateService.handleL2BlockAndMessages(block,padArrayEnd(l1ToL2Messages,Fr.ZERO,1024)),this.blockNumber=block.header.globalVariables.blockNumber}syncImmediate(_minBlockNumber,_blockHash){return Promise.resolve(this.blockNumber)}getCommitted(){return this.nativeWorldStateService.getCommitted()}fork(block){return this.nativeWorldStateService.fork(block?BlockNumber(block):void 0)}getSnapshot(blockNumber){return this.nativeWorldStateService.getSnapshot(BlockNumber(blockNumber))}backupTo(dstPath,compact2){return this.nativeWorldStateService.backupTo(dstPath,compact2)}start(){throw new Error('TXE Synchronizer does not implement "start"')}status(){throw new Error('TXE Synchronizer does not implement "status"')}stop(){throw new Error('TXE Synchronizer does not implement "stop"')}stopSync(){throw new Error('TXE Synchronizer does not implement "stopSync"')}resumeSync(){throw new Error('TXE Synchronizer does not implement "resumeSync"')}clear(){throw new Error('TXE Synchronizer does not implement "clear"')}};var VERSION7=1,CHAIN_ID=1,PACKAGE_VERSION="txe",TXEStateMachine=class{constructor(node,synchronizer,archiver,anchorBlockStore,contractSyncService,contractClassService,txResolver){this.node=node;this.synchronizer=synchronizer;this.archiver=archiver;this.anchorBlockStore=anchorBlockStore;this.contractSyncService=contractSyncService;this.contractClassService=contractClassService;this.txResolver=txResolver}static{__name(this,"TXEStateMachine")}static async create(archiver,anchorBlockStore,contractStore,noteStore){let synchronizer=await TXESynchronizer.create(),aztecNodeConfig={},log2=createLogger("txe_node"),node=new AztecNodeService({config:aztecNodeConfig,p2pClient:new DummyP2P,blockSource:archiver,logsSource:archiver,contractDataSource:archiver,l1ToL2MessageSource:archiver,worldStateSynchronizer:synchronizer,sequencer:void 0,proverNode:void 0,slasherClient:void 0,validatorsSentinel:void 0,stopStartedWatchers:__name(async()=>{},"stopStartedWatchers"),l1ChainId:CHAIN_ID,version:VERSION7,globalVariableBuilder:new TXEGlobalVariablesBuilder,rollupContract:void 0,feeProvider:new TXEFeeProvider,epochCache:new MockEpochCache,packageVersion:PACKAGE_VERSION,peerProofVerifier:new TestCircuitVerifier,rpcProofVerifier:new TestCircuitVerifier,telemetry:void 0,log:log2}),contractClassService=new ContractClassService(node,contractStore),contractSyncService=new ContractSyncService(node,contractStore,contractClassService,noteStore,createLogger("txe:contract_sync")),txResolver=new TxResolverService(node);return new this(node,synchronizer,archiver,anchorBlockStore,contractSyncService,contractClassService,txResolver)}get l2TipsProvider(){let node=this.node;return{getL2Tips:__name(()=>node.getChainTips(),"getL2Tips")}}async handleL2Block(block,l1ToL2Messages=[]){let checkpointNumber=CheckpointNumber.fromBlockNumber(block.number),checkpoint=new Checkpoint(block.archive,CheckpointHeader.from({lastArchiveRoot:block.header.lastArchive.root,inHash:Fr.ZERO,blobsHash:Fr.ZERO,blockHeadersHash:Fr.ZERO,epochOutHash:Fr.ZERO,slotNumber:block.header.globalVariables.slotNumber,timestamp:block.header.globalVariables.timestamp,coinbase:block.header.globalVariables.coinbase,feeRecipient:block.header.globalVariables.feeRecipient,gasFees:block.header.globalVariables.gasFees,totalManaUsed:block.header.totalManaUsed,accumulatedFees:block.header.totalFees}),[block],checkpointNumber),publishedCheckpoint=new PublishedCheckpoint(checkpoint,new L1PublishedData(BigInt(block.header.globalVariables.blockNumber),block.header.globalVariables.timestamp,block.header.globalVariables.blockNumber.toString()),[]);this.contractSyncService.wipe(),await Promise.all([this.synchronizer.handleL2Block(block,l1ToL2Messages),this.archiver.addCheckpoints([publishedCheckpoint],void 0),this.anchorBlockStore.setHeader(block.header)])}};async function makeTxEffect(noteCache,txBlockNumber){let txEffect=TxEffect.empty();noteCache.finish();let nonceGenerator=noteCache.getNonceGenerator();return txEffect.noteHashes=await Promise.all(noteCache.getAllNotes().map(async(pendingNote,i)=>computeUniqueNoteHash(await computeNoteHashNonce(nonceGenerator,i),await siloNoteHash(pendingNote.note.contractAddress,pendingNote.noteHashForConsumption)))),txEffect.nullifiers=noteCache.getAllNullifiers(),txEffect.txHash=new TxHash(new Fr(txBlockNumber)),txEffect}__name(makeTxEffect,"makeTxEffect");var TXEAccountStore=class{static{__name(this,"TXEAccountStore")}#accounts;constructor(store){this.#accounts=store.openMap("accounts")}async getAccount(key){let completeAddress=await this.#accounts.getAsync(key.toString());if(!completeAddress)throw new Error(`Account not found: ${key.toString()}`);return CompleteAddress.fromBuffer(completeAddress)}async setAccount(key,value){await this.#accounts.set(key.toString(),value.toBuffer())}};function emptyLastCallState(){return{offchainEffects:[],queried:!1,txHash:Fr.ZERO,anchorBlockTimestamp:0n}}__name(emptyLastCallState,"emptyLastCallState");var TXESession=class _TXESession{constructor(logger3,sessionStore,stateMachine,oracleHandler,contractStore,noteStore,keyStore,addressStore,accountStore,senderTaggingStore,recipientTaggingStore,taggingSecretSourcesStore,capsuleStore,factStore,privateEventStore,jobCoordinator,currentJobId,chainId,version2,nextBlockTimestamp,artifactResolver,rootPath,packageName){this.logger=logger3;this.sessionStore=sessionStore;this.stateMachine=stateMachine;this.oracleHandler=oracleHandler;this.contractStore=contractStore;this.noteStore=noteStore;this.keyStore=keyStore;this.addressStore=addressStore;this.accountStore=accountStore;this.senderTaggingStore=senderTaggingStore;this.recipientTaggingStore=recipientTaggingStore;this.taggingSecretSourcesStore=taggingSecretSourcesStore;this.capsuleStore=capsuleStore;this.factStore=factStore;this.privateEventStore=privateEventStore;this.jobCoordinator=jobCoordinator;this.currentJobId=currentJobId;this.chainId=chainId;this.version=version2;this.nextBlockTimestamp=nextBlockTimestamp;this.artifactResolver=artifactResolver;this.rootPath=rootPath;this.packageName=packageName}static{__name(this,"TXESession")}state={name:"TOP_LEVEL"};authwits=new Map;taggingSecretStrategy=void 0;lastCallInfo=emptyLastCallState();txeOracleVersion;disposed=!1;async dispose(){if(!this.disposed){this.disposed=!0;try{await this.stateMachine.synchronizer.nativeWorldStateService.close()}catch(err){this.logger.warn("Error closing native world state during session dispose",err)}try{await this.sessionStore.close()}catch(err){this.logger.warn("Error closing session LMDB during dispose",err)}}}static async init(contractStore,artifactResolver,rootPath,packageName){let store=await openEphemeralStore("txe-session",void 0,2),addressStore=new AddressStore(store),privateEventStore=new PrivateEventStore(store),noteStore=new NoteStore(store),senderTaggingStore=new SenderTaggingStore(store),recipientTaggingStore=new RecipientTaggingStore(store),taggingSecretSourcesStore=new TaggingSecretSourcesStore(store),capsuleStore=new CapsuleStore(store),factStore=new FactStore(store),keyStore=new KeyStore(store),accountStore=new TXEAccountStore(store),jobCoordinator=new JobCoordinator(store);jobCoordinator.registerStores([capsuleStore,factStore,senderTaggingStore,recipientTaggingStore,privateEventStore,noteStore]);let archiver=new TXEArchiver(store),anchorBlockStore=new AnchorBlockStore(store),stateMachine=await TXEStateMachine.create(archiver,anchorBlockStore,contractStore,noteStore),nextBlockTimestamp=BigInt(Math.floor(new Date().getTime()/1e3)),version2=new Fr(await stateMachine.node.getVersion()),chainId=new Fr(await stateMachine.node.getChainId()),initialJobId=jobCoordinator.beginJob(),logger3=createLogger("txe:session"),topLevelOracleHandler=new TXEOracleTopLevelContext(stateMachine,contractStore,noteStore,keyStore,addressStore,accountStore,senderTaggingStore,recipientTaggingStore,taggingSecretSourcesStore,capsuleStore,factStore,privateEventStore,nextBlockTimestamp,version2,chainId,new Map,void 0,artifactResolver,rootPath,packageName);return await topLevelOracleHandler.mineDeploymentNullifiers([STANDARD_AUTH_REGISTRY_ADDRESS]),new _TXESession(logger3,store,stateMachine,topLevelOracleHandler,contractStore,noteStore,keyStore,addressStore,accountStore,senderTaggingStore,recipientTaggingStore,taggingSecretSourcesStore,capsuleStore,factStore,privateEventStore,jobCoordinator,initialJobId,version2,chainId,nextBlockTimestamp,artifactResolver,rootPath,packageName)}processFunction(functionName,inputs){try{if(Object.hasOwn(LEGACY_ORACLE_REGISTRY,functionName))return callTxeLegacyHandler(functionName,inputs,this.oracleHandler);let translator=new RPCTranslator(this,this.oracleHandler),validatedFunctionName=external_exports.string().refine(fn=>typeof translator[fn]=="function"&&!fn.startsWith("handlerAs")&&fn!=="constructor").parse(functionName);return translator[validatedFunctionName](...inputs)}catch(error2){if(error2 instanceof external_exports.ZodError){let versionHint;throw this.txeOracleVersion?this.txeOracleVersion.minor>2?versionHint=` The test uses Aztec.nr test oracle version ${this.txeOracleVersion.major}.${this.txeOracleVersion.minor}, but this test environment only supports up to ${2}.${2}. Upgrade the Aztec CLI to a compatible version. See https://docs.aztec.network/errors/12`:versionHint=` The test's oracle version (${this.txeOracleVersion.major}.${this.txeOracleVersion.minor}) is compatible with this test environment (${2}.${2}), so this oracle should be available. This is an unexpected error, please report it. See https://docs.aztec.network/errors/13`:versionHint=" The test appears to use an older version of Aztec.nr that does not support test environment oracle versioning. Update Aztec.nr to a compatible version. See https://docs.aztec.network/errors/12",new Error(`Unknown oracle '${functionName}'.${versionHint}`)}else throw error2 instanceof Error?new Error(`Execution error while processing function ${functionName} in state ${this.state.name}: ${error2.message}`):new Error(`Unknown execution error while processing function ${functionName} in state ${this.state.name}`)}}async cycleJob(){return await this.jobCoordinator.commitJob(this.currentJobId),this.currentJobId=this.jobCoordinator.beginJob(),this.currentJobId}resetLastCall(){let notQueriedMessageCount=this.lastCallInfo.queried?0:this.lastCallInfo.offchainEffects.filter(payload=>payload[0]?.equals(OFFCHAIN_MESSAGE_IDENTIFIER)).length;notQueriedMessageCount>0&&this.logger.warn(`Dropping ${notQueriedMessageCount} unqueried offchain message(s) from the previous top-level call. To deliver them, call \`env.offchain_messages()\` and forward the result to the recipient contract's \`offchain_receive\` utility before issuing another top-level call. To intentionally discard, assign to \`let _ = env.offchain_messages()\` to silence this warning.`),this.lastCallInfo=emptyLastCallState()}recordOffchainEffect(data){this.lastCallInfo.offchainEffects.push(data)}setLastCallContext(txHash,anchorBlockTimestamp){this.lastCallInfo.txHash=txHash,this.lastCallInfo.anchorBlockTimestamp=anchorBlockTimestamp}async withTopLevelCallTracking(work){this.resetLastCall();let anchorBlockTimestamp=(await this.stateMachine.node.getBlockData("latest")).header.globalVariables.timestamp,{result,txHash}=await work();return this.setLastCallContext(txHash??Fr.ZERO,anchorBlockTimestamp),result}getLastCallOffchainEffects(){this.lastCallInfo.queried=!0;let effects=this.lastCallInfo.offchainEffects;if(effects.length>MAX_OFFCHAIN_EFFECTS_PER_TXE_QUERY)throw new Error(`${effects.length} offchain effects exceed max ${MAX_OFFCHAIN_EFFECTS_PER_TXE_QUERY}`);if(effects.some(e2=>e2.length>MAX_OFFCHAIN_EFFECT_LEN))throw new Error(`Some offchain effect has length larger than max ${MAX_OFFCHAIN_EFFECT_LEN}`);return{effects}}getLastCallContext(){let{txHash,anchorBlockTimestamp}=this.lastCallInfo;return{txHash,anchorBlockTimestamp}}async executePrivateCall(from,targetContractAddress,functionSelector,args,argsHash,isStaticCall,additionalScopes,authorizedUtilityCallTargets,gasSettings){let handler=this.handlerAsTxe();return await this.withTopLevelCallTracking(async()=>{let{returnValues,offchainEffects}=await handler.privateCallNewFlow(from?.value,targetContractAddress,functionSelector,args,argsHash,isStaticCall,additionalScopes,this.currentJobId,authorizedUtilityCallTargets,gasSettings);for(let data of offchainEffects)this.recordOffchainEffect(data);if(await this.cycleJob(),isStaticCall)return{result:returnValues};let{txHash}=await handler.getLastTxEffects();return{result:returnValues,txHash:txHash.hash}})}async executeUtilityFunction(from,targetContractAddress,functionSelector,args,authorizedUtilityCallTargets){let handler=this.handlerAsTxe();return await this.withTopLevelCallTracking(async()=>{let returnValues=await handler.executeUtilityFunction(from?.value,targetContractAddress,functionSelector,args,this.currentJobId,authorizedUtilityCallTargets);return await this.cycleJob(),{result:returnValues}})}async executePublicCall(from,targetContractAddress,calldata,isStaticCall,gasSettings){let handler=this.handlerAsTxe();return await this.withTopLevelCallTracking(async()=>{let returnValues=await handler.publicCallNewFlow(from?.value,targetContractAddress,calldata,isStaticCall,gasSettings);if(await this.cycleJob(),isStaticCall)return{result:returnValues};let{txHash}=await handler.getLastTxEffects();return{result:returnValues,txHash:txHash.hash}})}async getPrivateEvents(selector,contractAddress,scope){let handler=this.handlerAsTxe();return await handler.syncContractNonOracleMethod(contractAddress,scope,this.currentJobId),await this.cycleJob(),handler.getPrivateEvents(selector,contractAddress,scope)}handlerAsTxe(){if(!("isTxe"in this.oracleHandler))throw new UnavailableOracleError2("Txe");return this.oracleHandler}setTxeOracleVersion(major2,minor){if(major2!==2){let hint=major2>2?"The test was compiled with a newer version of Aztec.nr than your test environment supports. Upgrade your test environment to a compatible version.":"The test was compiled with an older version of Aztec.nr than your test environment supports. Recompile the test with a compatible version of Aztec.nr.";throw new Error(`Incompatible test environment version: ${hint} See https://docs.aztec.network/errors/12 (expected test oracle major version ${2}, got ${major2})`)}this.txeOracleVersion={major:major2,minor},this.logger.debug(`Test compiled with test oracle version ${major2}.${minor}`)}async enterTopLevelState(){switch(this.state.name){case"PRIVATE":{await this.exitPrivateState();break}case"PUBLIC":{await this.exitPublicState();break}case"UTILITY":{this.exitUtilityContext();break}case"TOP_LEVEL":throw new Error("Expected to be in state other than TOP_LEVEL");default:this.state}await this.cycleJob(),this.oracleHandler=new TXEOracleTopLevelContext(this.stateMachine,this.contractStore,this.noteStore,this.keyStore,this.addressStore,this.accountStore,this.senderTaggingStore,this.recipientTaggingStore,this.taggingSecretSourcesStore,this.capsuleStore,this.factStore,this.privateEventStore,this.nextBlockTimestamp,this.version,this.chainId,this.authwits,this.taggingSecretStrategy,this.artifactResolver,this.rootPath,this.packageName),this.state={name:"TOP_LEVEL"},this.logger.debug(`Entered state ${this.state.name}`)}async enterPrivateState(contractAddressOpt,anchorBlockNumberOpt,gasSettings){let contractAddress=contractAddressOpt?.value??DEFAULT_ADDRESS,anchorBlockNumber=anchorBlockNumberOpt?.value;this.exitTopLevelState(),this.resetLastCall();let anchorBlock=await this.stateMachine.node.getBlock(anchorBlockNumber??"latest").then(b=>b?.header);await new NoteService(this.noteStore,this.stateMachine.node,anchorBlock,this.currentJobId).syncNoteNullifiers(contractAddress,await this.keyStore.getAccounts());let latestBlock=await this.stateMachine.node.getBlock("latest").then(b=>b?.header),nextBlockGlobalVariables=makeGlobalVariables(void 0,{blockNumber:BlockNumber(latestBlock.globalVariables.blockNumber+1),timestamp:this.nextBlockTimestamp,version:this.version,chainId:this.chainId}),txRequestHash=getSingleTxBlockRequestHash(nextBlockGlobalVariables.blockNumber),protocolNullifier=await computeProtocolNullifier(txRequestHash),noteCache=new ExecutionNoteCache(protocolNullifier),taggingIndexCache=new ExecutionTaggingIndexCache,utilityExecutor=this.utilityExecutorForContractSync(anchorBlock),transientArrayService=new TransientArrayService,anchoredContractData=new AnchoredContractData(this.contractStore,this.stateMachine.contractClassService,anchorBlock),taggingSecretStrategy=this.taggingSecretStrategy;return this.oracleHandler=new TXEPrivateExecutionOracle({argsHash:Fr.ZERO,txContext:new TxContext(this.chainId,this.version,gasSettings),callContext:new CallContext(AztecAddress.ZERO,contractAddress,FunctionSelector.empty(),!1),anchorBlockHeader:anchorBlock,utilityExecutor,authWitnesses:[],capsules:[],executionCache:new HashedValuesCache,noteCache,taggingIndexCache,anchoredContractData,noteStore:this.noteStore,keyStore:this.keyStore,addressStore:this.addressStore,aztecNode:this.stateMachine.node,senderTaggingStore:this.senderTaggingStore,recipientTaggingStore:this.recipientTaggingStore,taggingSecretSourcesStore:this.taggingSecretSourcesStore,capsuleService:new CapsuleService(this.capsuleStore,await this.keyStore.getAccounts()),factService:new FactService(this.factStore,await this.keyStore.getAccounts()),privateEventStore:this.privateEventStore,contractSyncService:this.stateMachine.contractSyncService,l2TipsStore:this.stateMachine.l2TipsProvider,jobId:this.currentJobId,scopes:await this.keyStore.getAccounts(),txResolver:this.stateMachine.txResolver,simulator:new WASMSimulator,hooks:composeHooks({resolveTaggingSecretStrategy:taggingSecretStrategy?()=>Promise.resolve(taggingSecretStrategy):void 0}),transientArrayService}),this.state={name:"PRIVATE",nextBlockGlobalVariables,noteCache,taggingIndexCache},this.logger.debug(`Entered state ${this.state.name}`),this.setLastCallContext(Fr.ZERO,anchorBlock.globalVariables.timestamp),this.oracleHandler.getPrivateContextInputs()}async enterPublicState(contractAddressOpt){let contractAddress=contractAddressOpt?.value??DEFAULT_ADDRESS;this.exitTopLevelState(),this.resetLastCall();let latestHeader=(await this.stateMachine.node.getBlockData("latest")).header,globalVariables=makeGlobalVariables(void 0,{blockNumber:BlockNumber(latestHeader.globalVariables.blockNumber+1),timestamp:this.nextBlockTimestamp,version:this.version,chainId:this.chainId});this.oracleHandler=new TXEOraclePublicContext(contractAddress,await this.stateMachine.synchronizer.nativeWorldStateService.fork(),getSingleTxBlockRequestHash(globalVariables.blockNumber),globalVariables,this.contractStore),this.state={name:"PUBLIC"},this.logger.debug(`Entered state ${this.state.name}`),this.setLastCallContext(Fr.ZERO,latestHeader.globalVariables.timestamp)}async enterUtilityState(contractAddressOpt){let contractAddress=contractAddressOpt?.value??DEFAULT_ADDRESS;this.exitTopLevelState(),this.resetLastCall();let anchorBlockHeader=await this.stateMachine.anchorBlockStore.getBlockHeader();await new NoteService(this.noteStore,this.stateMachine.node,anchorBlockHeader,this.currentJobId).syncNoteNullifiers(contractAddress,await this.keyStore.getAccounts()),this.oracleHandler=new UtilityExecutionOracle({callContext:CallContext.from({msgSender:AztecAddress.NULL_MSG_SENDER,contractAddress,functionSelector:FunctionSelector.empty(),isStaticCall:!0}),authWitnesses:[],capsules:[],anchorBlockHeader,anchoredContractData:new AnchoredContractData(this.contractStore,this.stateMachine.contractClassService,anchorBlockHeader),noteStore:this.noteStore,keyStore:this.keyStore,addressStore:this.addressStore,aztecNode:this.stateMachine.node,recipientTaggingStore:this.recipientTaggingStore,taggingSecretSourcesStore:this.taggingSecretSourcesStore,capsuleService:new CapsuleService(this.capsuleStore,await this.keyStore.getAccounts()),factService:new FactService(this.factStore,await this.keyStore.getAccounts()),privateEventStore:this.privateEventStore,txResolver:this.stateMachine.txResolver,contractSyncService:this.stateMachine.contractSyncService,l2TipsStore:this.stateMachine.l2TipsProvider,jobId:this.currentJobId,scopes:await this.keyStore.getAccounts(),simulator:new WASMSimulator,utilityExecutor:this.utilityExecutorForContractSync(anchorBlockHeader),transientArrayService:new TransientArrayService}),this.state={name:"UTILITY"},this.logger.debug(`Entered state ${this.state.name}`),this.setLastCallContext(Fr.ZERO,anchorBlockHeader.globalVariables.timestamp)}exitTopLevelState(){if(this.state.name!="TOP_LEVEL")throw new Error(`Expected to be in state 'TOP_LEVEL', but got '${this.state.name}' instead`);[this.nextBlockTimestamp,this.authwits,this.taggingSecretStrategy]=this.oracleHandler.close()}async exitPrivateState(){if(this.state.name!="PRIVATE")throw new Error(`Expected to be in state 'PRIVATE', but got '${this.state.name}' instead`);this.logger.debug("Exiting Private state, building block with collected side effects",{blockNumber:this.state.nextBlockGlobalVariables.blockNumber});let txEffect=await makeTxEffect(this.state.noteCache,this.state.nextBlockGlobalVariables.blockNumber),forkedWorldTrees=await this.stateMachine.synchronizer.nativeWorldStateService.fork();await insertTxEffectIntoWorldTrees(txEffect,forkedWorldTrees);let block=await makeTXEBlock(forkedWorldTrees,this.state.nextBlockGlobalVariables,[txEffect]);await this.stateMachine.handleL2Block(block),await forkedWorldTrees.close(),this.logger.debug("Exited PublicContext with built block",{blockNumber:block.number,txEffects:block.body.txEffects})}async exitPublicState(){if(this.state.name!="PUBLIC")throw new Error(`Expected to be in state 'PUBLIC', but got '${this.state.name}' instead`);let block=await this.oracleHandler.close();await this.stateMachine.handleL2Block(block)}exitUtilityContext(){if(this.state.name!="UTILITY")throw new Error(`Expected to be in state 'UTILITY', but got '${this.state.name}' instead`)}utilityExecutorForContractSync(anchorBlock){return async(call,scopes)=>{let anchoredContractData=new AnchoredContractData(this.contractStore,this.stateMachine.contractClassService,anchorBlock),entryPointArtifact=await anchoredContractData.getFunctionArtifactWithDebugMetadata(call.to,call.selector);if(!entryPointArtifact)throw new Error(`Cannot run function ${call.selector} on ${call.to}: the contract is not registered.`);if(entryPointArtifact.functionType!==FunctionType.UTILITY)throw new Error(`Cannot run ${entryPointArtifact.functionType} function as utility`);try{let simulator=new WASMSimulator,oracle=new UtilityExecutionOracle({callContext:CallContext.from({msgSender:AztecAddress.NULL_MSG_SENDER,contractAddress:call.to,functionSelector:call.selector,isStaticCall:!0}),authWitnesses:[],capsules:[],anchorBlockHeader:anchorBlock,anchoredContractData,noteStore:this.noteStore,keyStore:this.keyStore,addressStore:this.addressStore,aztecNode:this.stateMachine.node,recipientTaggingStore:this.recipientTaggingStore,taggingSecretSourcesStore:this.taggingSecretSourcesStore,capsuleService:new CapsuleService(this.capsuleStore,scopes),factService:new FactService(this.factStore,scopes),privateEventStore:this.privateEventStore,txResolver:this.stateMachine.txResolver,contractSyncService:this.stateMachine.contractSyncService,l2TipsStore:this.stateMachine.l2TipsProvider,jobId:this.currentJobId,scopes,simulator,utilityExecutor:this.utilityExecutorForContractSync(anchorBlock),transientArrayService:new TransientArrayService});await simulator.executeUserCircuit(toACVMWitness(0,call.args),entryPointArtifact,buildACIRCallback(oracle)).catch(err=>{throw err.message=resolveAssertionMessageFromError(err,entryPointArtifact),new ExecutionError(err.message,{contractAddress:call.to,functionSelector:call.selector},extractCallStack(err,entryPointArtifact.debug),{cause:err})})}catch(err){throw createSimulationError(err instanceof Error?err:new Error("Unknown error contract data sync"))}}}};var ForeignCallSingleSchema=external_exports.string(),ForeignCallArraySchema=external_exports.array(external_exports.string()),ForeignCallArgsSchema=external_exports.array(external_exports.union([ForeignCallSingleSchema,ForeignCallArraySchema,ContractArtifactSchema,ContractInstanceWithAddressSchema])),ForeignCallResultSchema=external_exports.object({values:external_exports.array(external_exports.union([ForeignCallSingleSchema,ForeignCallArraySchema]))});var ContractClassRegistryContractArtifact={name:"ContractClassRegistry",aztecVersion:"dev",functions:[{functionType:FunctionType.PRIVATE,name:"publish",isOnlySelf:!1,isStatic:!1,isInitializer:!1,parameters:[{name:"artifact_hash",type:{kind:"field"},visibility:"private"},{name:"private_functions_root",type:{kind:"field"},visibility:"private"},{name:"public_bytecode_commitment",type:{kind:"field"},visibility:"private"}],returnTypes:[],errorTypes:{"10965409165809799877":{error_kind:"string",string:"Given in_len to absorb is larger than the input array len"},"12469291177396340830":{error_kind:"string",string:"call to assert_max_bit_size"},"14990209321349310352":{error_kind:"string",string:"attempt to add with overflow"},"15669273164684982983":{error_kind:"string",string:"num_permutations is greater than MAX_PERMUTATIONS"},"15835548349546956319":{error_kind:"string",string:"Field failed to decompose into specified 32 limbs"},"16431471497789672479":{error_kind:"string",string:"Index out of bounds"},"16450579948625159707":{error_kind:"string",string:"Sponge must be in cache_size=1"},"17655676068928457687":{error_kind:"string",string:"Reader did not read all data"},"1998584279744703196":{error_kind:"string",string:"attempt to subtract with overflow"},"361444214588792908":{error_kind:"string",string:"attempt to multiply with overflow"},"922421554006670918":{error_kind:"string",string:"num_items is greater than MAX_ITEMS"},"9475115977882098926":{error_kind:"string",string:"Extra bytes in the last field of the bytecode"}},bytecode:Buffer.from([]),debugSymbols:""},{functionType:FunctionType.PUBLIC,name:"public_dispatch",isOnlySelf:!1,isStatic:!1,isInitializer:!1,parameters:[{name:"selector",type:{kind:"field"},visibility:"private"}],returnTypes:[],errorTypes:{"1335198680857977525":{error_kind:"string",string:"No public functions"}},bytecode:Buffer.from([]),debugSymbols:""}],nonDispatchPublicFunctions:[],outputs:{structs:{},globals:{}},storageLayout:{},fileMap:{}};var ContractInstanceRegistryContractArtifact={name:"ContractInstanceRegistry",aztecVersion:"dev",functions:[{functionType:FunctionType.PUBLIC,name:"public_dispatch",isOnlySelf:!1,isStatic:!1,isInitializer:!1,parameters:[{name:"selector",type:{kind:"field"},visibility:"private"}],returnTypes:[],errorTypes:{"11194752367584870169":{error_kind:"fmtstring",length:27,item_types:[{kind:"field"}]},"12579274401768182412":{error_kind:"string",string:"New contract class is not registered"},"13455385521185560676":{error_kind:"string",string:"Storage slot 0 not allowed. Storage slots must start from 1."},"14990209321349310352":{error_kind:"string",string:"attempt to add with overflow"},"15353471697975175405":{error_kind:"string",string:"msg.sender is not deployed"},"16431471497789672479":{error_kind:"string",string:"Index out of bounds"},"1998584279744703196":{error_kind:"string",string:"attempt to subtract with overflow"},"5755400808989454547":{error_kind:"string",string:"Function get_update_delay can only be called statically"},"6804164082532189961":{error_kind:"string",string:"New update delay is too low"}},bytecode:Buffer.from([]),debugSymbols:""},{functionType:FunctionType.PRIVATE,name:"publish_for_public_execution",isOnlySelf:!1,isStatic:!1,isInitializer:!1,parameters:[{name:"salt",type:{kind:"field"},visibility:"private"},{name:"contract_class_id",type:{kind:"struct",fields:[{name:"inner",type:{kind:"field"}}],path:"aztec::protocol_types::contract_class_id::ContractClassId"},visibility:"private"},{name:"initialization_hash",type:{kind:"field"},visibility:"private"},{name:"immutables_hash",type:{kind:"field"},visibility:"private"},{name:"public_keys",type:{kind:"struct",fields:[{name:"npk_m_hash",type:{kind:"field"}},{name:"ivpk_m",type:{kind:"struct",fields:[{name:"inner",type:{kind:"struct",fields:[{name:"x",type:{kind:"field"}},{name:"y",type:{kind:"field"}}],path:"std::embedded_curve_ops::EmbeddedCurvePoint"}}],path:"aztec::protocol_types::public_keys::IvpkM"}},{name:"ovpk_m_hash",type:{kind:"field"}},{name:"tpk_m_hash",type:{kind:"field"}},{name:"mspk_m_hash",type:{kind:"field"}},{name:"fbpk_m_hash",type:{kind:"field"}}],path:"aztec::protocol_types::public_keys::PublicKeys"},visibility:"private"},{name:"universal_deploy",type:{kind:"boolean"},visibility:"private"}],returnTypes:[],errorTypes:{"12469291177396340830":{error_kind:"string",string:"call to assert_max_bit_size"},"14483585040754951598":{error_kind:"string",string:"IvpkM is the point at infinity"},"14990209321349310352":{error_kind:"string",string:"attempt to add with overflow"},"718532354304118388":{error_kind:"string",string:"Point not on curve"}},bytecode:Buffer.from([]),debugSymbols:""}],nonDispatchPublicFunctions:[{functionType:FunctionType.PUBLIC,name:"get_update_delay",isOnlySelf:!1,isStatic:!0,isInitializer:!1,parameters:[],returnTypes:[{kind:"integer",sign:"unsigned",width:64}],errorTypes:{"13455385521185560676":{error_kind:"string",string:"Storage slot 0 not allowed. Storage slots must start from 1."},"5755400808989454547":{error_kind:"string",string:"Function get_update_delay can only be called statically"}}},{functionType:FunctionType.PUBLIC,name:"set_update_delay",isOnlySelf:!1,isStatic:!1,isInitializer:!1,parameters:[{name:"new_update_delay",type:{kind:"integer",sign:"unsigned",width:64},visibility:"private"}],returnTypes:[],errorTypes:{"13455385521185560676":{error_kind:"string",string:"Storage slot 0 not allowed. Storage slots must start from 1."},"14990209321349310352":{error_kind:"string",string:"attempt to add with overflow"},"15353471697975175405":{error_kind:"string",string:"msg.sender is not deployed"},"16431471497789672479":{error_kind:"string",string:"Index out of bounds"},"1998584279744703196":{error_kind:"string",string:"attempt to subtract with overflow"},"6804164082532189961":{error_kind:"string",string:"New update delay is too low"}}},{functionType:FunctionType.PUBLIC,name:"update",isOnlySelf:!1,isStatic:!1,isInitializer:!1,parameters:[{name:"new_contract_class_id",type:{kind:"struct",fields:[{name:"inner",type:{kind:"field"}}],path:"aztec::protocol_types::contract_class_id::ContractClassId"},visibility:"private"}],returnTypes:[],errorTypes:{"12579274401768182412":{error_kind:"string",string:"New contract class is not registered"},"13455385521185560676":{error_kind:"string",string:"Storage slot 0 not allowed. Storage slots must start from 1."},"14990209321349310352":{error_kind:"string",string:"attempt to add with overflow"},"15353471697975175405":{error_kind:"string",string:"msg.sender is not deployed"},"16431471497789672479":{error_kind:"string",string:"Index out of bounds"},"1998584279744703196":{error_kind:"string",string:"attempt to subtract with overflow"}}}],outputs:{structs:{},globals:{}},storageLayout:{},fileMap:{}};var DefaultWaitOpts={ignoreDroppedReceiptsFor:5,timeout:300,interval:1};var DefaultWaitForProvenOpts={provenTimeout:600,interval:DefaultWaitOpts.interval};import{createHash as createHash2}from"crypto";import{createReadStream}from"fs";import{readFile,readdir}from"fs/promises";import{join as join4,parse as parse3}from"path";var AsyncCache=class{static{__name(this,"AsyncCache")}#cache=new Map;#inFlight=new Map;getOrCompute(key,compute){let cached2=this.#cache.get(key);if(cached2!==void 0)return Promise.resolve(cached2);let pending=this.#inFlight.get(key);return pending||(pending=(async()=>{try{let value=await compute();return this.#cache.set(key,value),value}finally{this.#inFlight.delete(key)}})(),this.#inFlight.set(key,pending)),pending}},TXEArtifactResolver=class{constructor(contractStore,schnorrClassId){this.contractStore=contractStore;this.schnorrClassId=schnorrClassId}static{__name(this,"TXEArtifactResolver")}#deployments=new AsyncCache;#artifacts=new AsyncCache;#logger=createLogger("txe:artifact_resolver");resolveAccountArtifact(secret){return this.#deployments.getOrCompute(`SchnorrAccountContract-${secret}`,()=>this.#computeAccountArtifact(secret))}async resolveDeployArtifact({rootPath,packageName,contractPath,initializer:initializer3,args,secret,salt,deployer}){let publicKeys=secret.equals(Fr.ZERO)?PublicKeys.default():(await deriveKeys(secret)).publicKeys,publicKeysHash=await publicKeys.hash(),artifactPath=await this.#resolveArtifactPath(rootPath,packageName,contractPath),fileHash=await this.#fastHashFile(artifactPath),{dir:contractDirectory,base:contractFilename}=parse3(contractPath),cacheKey=`${contractDirectory??""}-${contractFilename}-${initializer3}-${args.map(arg=>arg.toString()).join("-")}-${publicKeysHash}-${salt}-${deployer}-${fileHash}`;return this.#deployments.getOrCompute(cacheKey,()=>this.#computeDeployArtifact(artifactPath,fileHash,initializer3,args,salt,publicKeys,publicKeysHash,deployer))}async#resolveArtifactPath(rootPath,packageName,contractPath){let{dir:contractDirectory,base:contractFilename}=parse3(contractPath);if(contractDirectory)if(contractDirectory.includes("@")){let[workspace,pkg]=contractDirectory.split("@"),targetPath=join4(rootPath,workspace,"/target");return this.#logger.debug(`Looking for compiled artifact in workspace ${targetPath}`),join4(targetPath,`${pkg}-${contractFilename}.json`)}else{let targetPath=join4(rootPath,contractDirectory,"/target");this.#logger.debug(`Looking for compiled artifact in ${targetPath}`);let[artifactPath]=(await readdir(targetPath)).filter(file2=>file2.endsWith(`-${contractFilename}.json`));return artifactPath}else return join4(rootPath,"./target",`${packageName}-${contractFilename}.json`)}async#computeAccountArtifact(secret){let[artifactFromStore,classWithPreimage]=await Promise.all([this.contractStore.getContractArtifact(this.schnorrClassId),this.contractStore.getContractClassWithPreimage(this.schnorrClassId)]);if(!artifactFromStore||!classWithPreimage)throw new Error(`SchnorrAccount not found in shared contract store at class id ${this.schnorrClassId.toString()}`);let artifact={...artifactFromStore,artifactHash:classWithPreimage.artifactHash},keys=await deriveKeys(secret),args=[keys.publicKeys.ivpkM.x,keys.publicKeys.ivpkM.y],instance=await getContractInstanceFromInstantiationParams(artifact,{constructorArgs:args,skipArgsDecoding:!0,salt:Fr.ONE,publicKeys:keys.publicKeys,constructorArtifact:"constructor",deployer:AztecAddress.ZERO});return{artifact,instance}}async#computeDeployArtifact(artifactPath,fileHash,initializer3,args,salt,publicKeys,publicKeysHash,deployer){let artifact=await this.#artifacts.getOrCompute(fileHash,async()=>{this.#logger.debug(`Loading compiled artifact ${artifactPath}`);let artifactJSON=JSON.parse(await readFile(artifactPath,"utf-8")),artifactWithoutHash=loadContractArtifact(artifactJSON);return{...artifactWithoutHash,artifactHash:await computeArtifactHash(artifactWithoutHash)}});this.#logger.debug(`Deploy ${artifact.name} with initializer ${initializer3}(${args}) and public keys hash ${publicKeysHash}`);let instance=await getContractInstanceFromInstantiationParams(artifact,{constructorArgs:args,skipArgsDecoding:!0,salt,publicKeys,constructorArtifact:initializer3||void 0,deployer});return{artifact,instance}}#fastHashFile(path){return new Promise(resolve=>{let fd=createReadStream(path),hash5=createHash2("sha1");hash5.setEncoding("hex"),fd.on("end",function(){hash5.end(),resolve(hash5.read())}),fd.pipe(hash5)})}};var TXE_REQUIRED_PROTOCOL_CONTRACTS=[],sessions=new Map,TXEForeignCallInputSchema=zodFor()(external_exports.object({session_id:external_exports.number().nonnegative(),function:external_exports.string(),root_path:external_exports.string(),package_name:external_exports.string(),inputs:ForeignCallArgsSchema})),TXEDispatcher=class{constructor(logger3,opts){this.logger=logger3;this.contractStoreSourceDir=opts.contractStoreSourceDir,this.schnorrClassId=Fr.fromString(opts.schnorrClassId)}static{__name(this,"TXEDispatcher")}contractStore;artifactResolver;contractStoreSourceDir;schnorrClassId;async warmUp(){if(this.contractStore)return;let t0=Date.now(),kvStore=await cloneEphemeralStoreFrom(join5(this.contractStoreSourceDir,"data.mdb"),"txe-contracts",void 0,2);this.contractStore=new ContractStore(kvStore),this.artifactResolver=new TXEArtifactResolver(this.contractStore,this.schnorrClassId),this.logger.debug("Cloned shared protocol-contracts store",{totalMs:Date.now()-t0})}async resolve_foreign_call(callData){let{session_id:sessionId,function:functionName,inputs,root_path:rootPath,package_name:packageName}=callData;return this.logger.debug(`Calling ${functionName} on session ${sessionId}`),sessions.has(sessionId)||(this.logger.debug(`Creating new session ${sessionId}`),await this.warmUp(),sessions.set(sessionId,await TXESession.init(this.contractStore,this.artifactResolver,rootPath,packageName))),await sessions.get(sessionId).processFunction(functionName,inputs)}async disposeSession(sessionId){let session=sessions.get(sessionId);session&&(sessions.delete(sessionId),await session.dispose())}};function activeSessionCount(){return sessions.size}__name(activeSessionCount,"activeSessionCount");var TXEDispatcherApiSchema={resolve_foreign_call:external_exports.function({input:external_exports.tuple([TXEForeignCallInputSchema]),output:ForeignCallResultSchema}),disposeSession:external_exports.function({input:external_exports.tuple([external_exports.number().nonnegative()]),output:external_exports.void()})};export{createLogger,ZodError,external_exports,Fr,schemaHasMethod,getSchemaParameters,parseWithOptionals,require_inherits,promiseWithResolvers,jsonStringify,loadContractArtifact,getContractClassFromArtifact,openEphemeralStore,LazyProtocolContractsProvider,ContractStore,getStandardAuthRegistry,getStandardHandshakeRegistry,TXE_REQUIRED_PROTOCOL_CONTRACTS,TXEDispatcher,activeSessionCount,TXEDispatcherApiSchema};
|
|
268
|
+
}`}};var FinalBlobBatchingChallenges=class _FinalBlobBatchingChallenges{static{__name(this,"FinalBlobBatchingChallenges")}z;gamma;constructor(z2,gamma){this.z=z2,this.gamma=gamma}equals(other){return this.z.equals(other.z)&&this.gamma.equals(other.gamma)}static empty(){return new _FinalBlobBatchingChallenges(Fr.ZERO,BLS12Fr.ZERO)}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _FinalBlobBatchingChallenges(Fr.fromBuffer(reader),reader.readObject(BLS12Fr))}toBuffer(){return serializeToBuffer(this.z,this.gamma)}};var ParityBasePrivateInputs=class _ParityBasePrivateInputs{static{__name(this,"ParityBasePrivateInputs")}msgs;vkTreeRoot;proverId;constructor(msgs,vkTreeRoot,proverId){this.msgs=msgs,this.vkTreeRoot=vkTreeRoot,this.proverId=proverId}static fromSlice(array2,index,vkTreeRoot,proverId){if(array2.length!==1024)throw new Error(`Msgs array length must be NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP=${1024}`);let start=index*256,end=start+256,msgs=array2.slice(start,end);return new _ParityBasePrivateInputs(msgs,vkTreeRoot,proverId)}toBuffer(){return serializeToBuffer(this.msgs,this.vkTreeRoot,this.proverId)}toString(){return bufferToHex(this.toBuffer())}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _ParityBasePrivateInputs(reader.readArray(256,Fr),Fr.fromBuffer(reader),Fr.fromBuffer(reader))}static fromString(str){return _ParityBasePrivateInputs.fromBuffer(hexToBuffer(str))}toJSON(){return this.toBuffer()}static get schema(){return bufferSchemaFor(_ParityBasePrivateInputs)}};var ParityPublicInputs=class _ParityPublicInputs{static{__name(this,"ParityPublicInputs")}shaRoot;convertedRoot;vkTreeRoot;proverId;constructor(shaRoot,convertedRoot,vkTreeRoot,proverId){if(this.shaRoot=shaRoot,this.convertedRoot=convertedRoot,this.vkTreeRoot=vkTreeRoot,this.proverId=proverId,shaRoot.toBuffer()[0]!=0)throw new Error("shaRoot buffer must be 31 bytes. Got 32 bytes")}toBuffer(){return serializeToBuffer(..._ParityPublicInputs.getFields(this))}toString(){return bufferToHex(this.toBuffer())}toJSON(){return this.toBuffer()}static from(fields){return new _ParityPublicInputs(..._ParityPublicInputs.getFields(fields))}static getFields(fields){return[fields.shaRoot,fields.convertedRoot,fields.vkTreeRoot,fields.proverId]}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _ParityPublicInputs(reader.readObject(Fr),reader.readObject(Fr),Fr.fromBuffer(reader),Fr.fromBuffer(reader))}static fromString(str){return _ParityPublicInputs.fromBuffer(hexToBuffer(str))}static get schema(){return bufferSchemaFor(_ParityPublicInputs)}};var ParityRootPrivateInputs=class _ParityRootPrivateInputs{static{__name(this,"ParityRootPrivateInputs")}children;constructor(children){this.children=children}toBuffer(){return serializeToBuffer(this.children)}toString(){return bufferToHex(this.toBuffer())}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _ParityRootPrivateInputs(makeTuple(4,()=>ProofData.fromBuffer(reader,ParityPublicInputs)))}static fromString(str){return _ParityRootPrivateInputs.fromBuffer(hexToBuffer(str))}toJSON(){return this.toBuffer()}static get schema(){return bufferSchemaFor(_ParityRootPrivateInputs)}};var BlockConstantData=class _BlockConstantData{static{__name(this,"BlockConstantData")}lastArchive;l1ToL2TreeSnapshot;vkTreeRoot;protocolContractsHash;globalVariables;proverId;constructor(lastArchive,l1ToL2TreeSnapshot,vkTreeRoot,protocolContractsHash2,globalVariables,proverId){this.lastArchive=lastArchive,this.l1ToL2TreeSnapshot=l1ToL2TreeSnapshot,this.vkTreeRoot=vkTreeRoot,this.protocolContractsHash=protocolContractsHash2,this.globalVariables=globalVariables,this.proverId=proverId}static from(fields){return new _BlockConstantData(..._BlockConstantData.getFields(fields))}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _BlockConstantData(reader.readObject(AppendOnlyTreeSnapshot),reader.readObject(AppendOnlyTreeSnapshot),Fr.fromBuffer(reader),Fr.fromBuffer(reader),reader.readObject(GlobalVariables),Fr.fromBuffer(reader))}static getFields(fields){return[fields.lastArchive,fields.l1ToL2TreeSnapshot,fields.vkTreeRoot,fields.protocolContractsHash,fields.globalVariables,fields.proverId]}static empty(){return new _BlockConstantData(AppendOnlyTreeSnapshot.empty(),AppendOnlyTreeSnapshot.empty(),Fr.ZERO,Fr.ZERO,GlobalVariables.empty(),Fr.ZERO)}toBuffer(){return serializeToBuffer(..._BlockConstantData.getFields(this))}};var TreeSnapshotDiffHints=class _TreeSnapshotDiffHints{static{__name(this,"TreeSnapshotDiffHints")}noteHashSubtreeRootSiblingPath;nullifierPredecessorPreimages;nullifierPredecessorMembershipWitnesses;sortedNullifiers;sortedNullifierIndexes;nullifierSubtreeRootSiblingPath;feePayerBalanceMembershipWitness;constructor(noteHashSubtreeRootSiblingPath,nullifierPredecessorPreimages,nullifierPredecessorMembershipWitnesses,sortedNullifiers,sortedNullifierIndexes,nullifierSubtreeRootSiblingPath,feePayerBalanceMembershipWitness){this.noteHashSubtreeRootSiblingPath=noteHashSubtreeRootSiblingPath,this.nullifierPredecessorPreimages=nullifierPredecessorPreimages,this.nullifierPredecessorMembershipWitnesses=nullifierPredecessorMembershipWitnesses,this.sortedNullifiers=sortedNullifiers,this.sortedNullifierIndexes=sortedNullifierIndexes,this.nullifierSubtreeRootSiblingPath=nullifierSubtreeRootSiblingPath,this.feePayerBalanceMembershipWitness=feePayerBalanceMembershipWitness}static from(fields){return new _TreeSnapshotDiffHints(..._TreeSnapshotDiffHints.getFields(fields))}static getFields(fields){return[fields.noteHashSubtreeRootSiblingPath,fields.nullifierPredecessorPreimages,fields.nullifierPredecessorMembershipWitnesses,fields.sortedNullifiers,fields.sortedNullifierIndexes,fields.nullifierSubtreeRootSiblingPath,fields.feePayerBalanceMembershipWitness]}toBuffer(){return serializeToBuffer(..._TreeSnapshotDiffHints.getFields(this))}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _TreeSnapshotDiffHints(reader.readArray(36,Fr),reader.readArray(64,NullifierLeafPreimage),reader.readArray(64,{fromBuffer:__name(buffer2=>MembershipWitness.fromBuffer(buffer2,42),"fromBuffer")}),reader.readArray(64,Fr),reader.readNumbers(64),reader.readArray(36,Fr),MembershipWitness.fromBuffer(reader,40))}static empty(){return new _TreeSnapshotDiffHints(makeTuple(36,Fr.zero),makeTuple(64,NullifierLeafPreimage.empty),makeTuple(64,()=>MembershipWitness.empty(42)),makeTuple(64,Fr.zero),makeTuple(64,()=>0),makeTuple(36,Fr.zero),MembershipWitness.empty(40))}};var PrivateBaseRollupHints=class _PrivateBaseRollupHints{static{__name(this,"PrivateBaseRollupHints")}start;startSpongeBlob;treeSnapshotDiffHints;feePayerBalanceLeafPreimage;anchorBlockArchiveSiblingPath;contractClassLogsFields;constants;constructor(start,startSpongeBlob,treeSnapshotDiffHints,feePayerBalanceLeafPreimage,anchorBlockArchiveSiblingPath,contractClassLogsFields,constants){this.start=start,this.startSpongeBlob=startSpongeBlob,this.treeSnapshotDiffHints=treeSnapshotDiffHints,this.feePayerBalanceLeafPreimage=feePayerBalanceLeafPreimage,this.anchorBlockArchiveSiblingPath=anchorBlockArchiveSiblingPath,this.contractClassLogsFields=contractClassLogsFields,this.constants=constants}static from(fields){return new _PrivateBaseRollupHints(..._PrivateBaseRollupHints.getFields(fields))}static getFields(fields){return[fields.start,fields.startSpongeBlob,fields.treeSnapshotDiffHints,fields.feePayerBalanceLeafPreimage,fields.anchorBlockArchiveSiblingPath,fields.contractClassLogsFields,fields.constants]}toBuffer(){return serializeToBuffer(..._PrivateBaseRollupHints.getFields(this))}toString(){return bufferToHex(this.toBuffer())}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _PrivateBaseRollupHints(reader.readObject(PartialStateReference),reader.readObject(SpongeBlob),reader.readObject(TreeSnapshotDiffHints),reader.readObject(PublicDataTreeLeafPreimage),reader.readArray(30,Fr),makeTuple(1,()=>reader.readObject(ContractClassLogFields)),reader.readObject(BlockConstantData))}static fromString(str){return _PrivateBaseRollupHints.fromBuffer(hexToBuffer(str))}static empty(){return new _PrivateBaseRollupHints(PartialStateReference.empty(),SpongeBlob.empty(),TreeSnapshotDiffHints.empty(),PublicDataTreeLeafPreimage.empty(),makeTuple(30,Fr.zero),makeTuple(1,ContractClassLogFields.empty),BlockConstantData.empty())}},PublicBaseRollupHints=class _PublicBaseRollupHints{static{__name(this,"PublicBaseRollupHints")}startSpongeBlob;lastArchive;anchorBlockArchiveSiblingPath;contractClassLogsFields;constructor(startSpongeBlob,lastArchive,anchorBlockArchiveSiblingPath,contractClassLogsFields){this.startSpongeBlob=startSpongeBlob,this.lastArchive=lastArchive,this.anchorBlockArchiveSiblingPath=anchorBlockArchiveSiblingPath,this.contractClassLogsFields=contractClassLogsFields}static from(fields){return new _PublicBaseRollupHints(..._PublicBaseRollupHints.getFields(fields))}static getFields(fields){return[fields.startSpongeBlob,fields.lastArchive,fields.anchorBlockArchiveSiblingPath,fields.contractClassLogsFields]}toBuffer(){return serializeToBuffer(..._PublicBaseRollupHints.getFields(this))}toString(){return bufferToHex(this.toBuffer())}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _PublicBaseRollupHints(reader.readObject(SpongeBlob),reader.readObject(AppendOnlyTreeSnapshot),reader.readArray(30,Fr),makeTuple(1,()=>reader.readObject(ContractClassLogFields)))}static fromString(str){return _PublicBaseRollupHints.fromBuffer(hexToBuffer(str))}static empty(){return new _PublicBaseRollupHints(SpongeBlob.empty(),AppendOnlyTreeSnapshot.empty(),makeTuple(30,Fr.zero),makeTuple(1,ContractClassLogFields.empty))}};import{inspect as inspect45}from"util";var _computedKey47;_computedKey47=inspect45.custom;var CheckpointConstantData=class _CheckpointConstantData{static{__name(this,"CheckpointConstantData")}chainId;version;vkTreeRoot;protocolContractsHash;proverId;slotNumber;coinbase;feeRecipient;gasFees;constructor(chainId,version2,vkTreeRoot,protocolContractsHash2,proverId,slotNumber,coinbase,feeRecipient,gasFees){this.chainId=chainId,this.version=version2,this.vkTreeRoot=vkTreeRoot,this.protocolContractsHash=protocolContractsHash2,this.proverId=proverId,this.slotNumber=slotNumber,this.coinbase=coinbase,this.feeRecipient=feeRecipient,this.gasFees=gasFees}static from(fields){return new _CheckpointConstantData(..._CheckpointConstantData.getFields(fields))}static getFields(fields){return[fields.chainId,fields.version,fields.vkTreeRoot,fields.protocolContractsHash,fields.proverId,fields.slotNumber,fields.coinbase,fields.feeRecipient,fields.gasFees]}static empty(){return new _CheckpointConstantData(Fr.ZERO,Fr.ZERO,Fr.ZERO,Fr.ZERO,Fr.ZERO,SlotNumber.ZERO,EthAddress.ZERO,AztecAddress.ZERO,GasFees.empty())}toBuffer(){return serializeToBuffer(this.chainId,this.version,this.vkTreeRoot,this.protocolContractsHash,this.proverId,new Fr(this.slotNumber),this.coinbase,this.feeRecipient,this.gasFees)}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _CheckpointConstantData(Fr.fromBuffer(reader),Fr.fromBuffer(reader),Fr.fromBuffer(reader),Fr.fromBuffer(reader),Fr.fromBuffer(reader),SlotNumber(Fr.fromBuffer(reader).toNumber()),reader.readObject(EthAddress),reader.readObject(AztecAddress),reader.readObject(GasFees))}getSlotNumber(){return this.slotNumber}toInspect(){return{chainId:this.chainId.toNumber(),version:this.version.toNumber(),vkTreeRoot:this.vkTreeRoot.toString(),protocolContractsHash:this.protocolContractsHash.toString(),proverId:this.proverId.toString(),slotNumber:this.slotNumber,coinbase:this.coinbase.toString(),feeRecipient:this.feeRecipient.toString(),gasFees:this.gasFees.toInspect()}}[_computedKey47](){return`CheckpointConstantData ${inspect45(this.toInspect())}`}};var BlockRollupPublicInputs=class _BlockRollupPublicInputs{static{__name(this,"BlockRollupPublicInputs")}constants;previousArchive;newArchive;startState;endState;startSpongeBlob;endSpongeBlob;timestamp;blockHeadersHash;inHash;outHash;accumulatedFees;accumulatedManaUsed;constructor(constants,previousArchive,newArchive,startState,endState,startSpongeBlob,endSpongeBlob,timestamp,blockHeadersHash,inHash,outHash,accumulatedFees,accumulatedManaUsed){this.constants=constants,this.previousArchive=previousArchive,this.newArchive=newArchive,this.startState=startState,this.endState=endState,this.startSpongeBlob=startSpongeBlob,this.endSpongeBlob=endSpongeBlob,this.timestamp=timestamp,this.blockHeadersHash=blockHeadersHash,this.inHash=inHash,this.outHash=outHash,this.accumulatedFees=accumulatedFees,this.accumulatedManaUsed=accumulatedManaUsed}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _BlockRollupPublicInputs(reader.readObject(CheckpointConstantData),reader.readObject(AppendOnlyTreeSnapshot),reader.readObject(AppendOnlyTreeSnapshot),reader.readObject(StateReference),reader.readObject(StateReference),reader.readObject(SpongeBlob),reader.readObject(SpongeBlob),reader.readUInt64(),Fr.fromBuffer(reader),Fr.fromBuffer(reader),Fr.fromBuffer(reader),Fr.fromBuffer(reader),Fr.fromBuffer(reader))}toBuffer(){return serializeToBuffer(this.constants,this.previousArchive,this.newArchive,this.startState,this.endState,this.startSpongeBlob,this.endSpongeBlob,bigintToUInt64BE(this.timestamp),this.blockHeadersHash,this.inHash,this.outHash,this.accumulatedFees,this.accumulatedManaUsed)}toString(){return bufferToHex(this.toBuffer())}static fromString(str){return _BlockRollupPublicInputs.fromBuffer(hexToBuffer(str))}toJSON(){return this.toBuffer()}toInspect(){return{previousArchiveRoot:this.previousArchive.root.toString(),newArchiveRoot:this.newArchive.root.toString(),blockHeadersHash:this.blockHeadersHash.toString(),inHash:this.inHash.toString(),outHash:this.outHash.toString(),timestamp:this.timestamp.toString(),accumulatedFees:this.accumulatedFees.toString(),accumulatedManaUsed:this.accumulatedManaUsed.toString()}}static get schema(){return bufferSchemaFor(_BlockRollupPublicInputs)}};var BlockMergeRollupPrivateInputs=class _BlockMergeRollupPrivateInputs{static{__name(this,"BlockMergeRollupPrivateInputs")}previousRollups;constructor(previousRollups){this.previousRollups=previousRollups}toBuffer(){return serializeToBuffer(this.previousRollups)}toString(){return bufferToHex(this.toBuffer())}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _BlockMergeRollupPrivateInputs([ProofData.fromBuffer(reader,BlockRollupPublicInputs),ProofData.fromBuffer(reader,BlockRollupPublicInputs)])}static fromString(str){return _BlockMergeRollupPrivateInputs.fromBuffer(hexToBuffer(str))}toJSON(){return this.toBuffer()}static get schema(){return bufferSchemaFor(_BlockMergeRollupPrivateInputs)}};var TxRollupPublicInputs=class _TxRollupPublicInputs{static{__name(this,"TxRollupPublicInputs")}numTxs;constants;startTreeSnapshots;endTreeSnapshots;startSpongeBlob;endSpongeBlob;outHash;accumulatedFees;accumulatedManaUsed;constructor(numTxs,constants,startTreeSnapshots,endTreeSnapshots,startSpongeBlob,endSpongeBlob,outHash,accumulatedFees,accumulatedManaUsed){this.numTxs=numTxs,this.constants=constants,this.startTreeSnapshots=startTreeSnapshots,this.endTreeSnapshots=endTreeSnapshots,this.startSpongeBlob=startSpongeBlob,this.endSpongeBlob=endSpongeBlob,this.outHash=outHash,this.accumulatedFees=accumulatedFees,this.accumulatedManaUsed=accumulatedManaUsed}static empty(){return new _TxRollupPublicInputs(0,BlockConstantData.empty(),PartialStateReference.empty(),PartialStateReference.empty(),SpongeBlob.empty(),SpongeBlob.empty(),Fr.zero(),Fr.zero(),Fr.zero())}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _TxRollupPublicInputs(reader.readNumber(),reader.readObject(BlockConstantData),reader.readObject(PartialStateReference),reader.readObject(PartialStateReference),reader.readObject(SpongeBlob),reader.readObject(SpongeBlob),Fr.fromBuffer(reader),Fr.fromBuffer(reader),Fr.fromBuffer(reader))}toBuffer(){return serializeToBuffer(this.numTxs,this.constants,this.startTreeSnapshots,this.endTreeSnapshots,this.startSpongeBlob,this.endSpongeBlob,this.outHash,this.accumulatedFees,this.accumulatedManaUsed)}toString(){return bufferToHex(this.toBuffer())}static fromString(str){return _TxRollupPublicInputs.fromBuffer(hexToBuffer(str))}toJSON(){return this.toBuffer()}static get schema(){return bufferSchemaFor(_TxRollupPublicInputs)}};var BlockRootFirstRollupPrivateInputs=class _BlockRootFirstRollupPrivateInputs{static{__name(this,"BlockRootFirstRollupPrivateInputs")}l1ToL2Roots;previousRollups;previousL1ToL2;newL1ToL2MessageSubtreeRootSiblingPath;newArchiveSiblingPath;constructor(l1ToL2Roots,previousRollups,previousL1ToL2,newL1ToL2MessageSubtreeRootSiblingPath,newArchiveSiblingPath){this.l1ToL2Roots=l1ToL2Roots,this.previousRollups=previousRollups,this.previousL1ToL2=previousL1ToL2,this.newL1ToL2MessageSubtreeRootSiblingPath=newL1ToL2MessageSubtreeRootSiblingPath,this.newArchiveSiblingPath=newArchiveSiblingPath}static from(fields){return new _BlockRootFirstRollupPrivateInputs(..._BlockRootFirstRollupPrivateInputs.getFields(fields))}static getFields(fields){return[fields.l1ToL2Roots,fields.previousRollups,fields.previousL1ToL2,fields.newL1ToL2MessageSubtreeRootSiblingPath,fields.newArchiveSiblingPath]}toBuffer(){return serializeToBuffer(..._BlockRootFirstRollupPrivateInputs.getFields(this))}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _BlockRootFirstRollupPrivateInputs(ProofData.fromBuffer(reader,ParityPublicInputs),[ProofData.fromBuffer(reader,TxRollupPublicInputs),ProofData.fromBuffer(reader,TxRollupPublicInputs)],AppendOnlyTreeSnapshot.fromBuffer(reader),reader.readArray(26,Fr),reader.readArray(30,Fr))}toJSON(){return this.toBuffer()}static get schema(){return bufferSchemaFor(_BlockRootFirstRollupPrivateInputs)}},BlockRootSingleTxFirstRollupPrivateInputs=class _BlockRootSingleTxFirstRollupPrivateInputs{static{__name(this,"BlockRootSingleTxFirstRollupPrivateInputs")}l1ToL2Roots;previousRollup;previousL1ToL2;newL1ToL2MessageSubtreeRootSiblingPath;newArchiveSiblingPath;constructor(l1ToL2Roots,previousRollup,previousL1ToL2,newL1ToL2MessageSubtreeRootSiblingPath,newArchiveSiblingPath){this.l1ToL2Roots=l1ToL2Roots,this.previousRollup=previousRollup,this.previousL1ToL2=previousL1ToL2,this.newL1ToL2MessageSubtreeRootSiblingPath=newL1ToL2MessageSubtreeRootSiblingPath,this.newArchiveSiblingPath=newArchiveSiblingPath}static from(fields){return new _BlockRootSingleTxFirstRollupPrivateInputs(..._BlockRootSingleTxFirstRollupPrivateInputs.getFields(fields))}static getFields(fields){return[fields.l1ToL2Roots,fields.previousRollup,fields.previousL1ToL2,fields.newL1ToL2MessageSubtreeRootSiblingPath,fields.newArchiveSiblingPath]}toBuffer(){return serializeToBuffer(..._BlockRootSingleTxFirstRollupPrivateInputs.getFields(this))}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _BlockRootSingleTxFirstRollupPrivateInputs(ProofData.fromBuffer(reader,ParityPublicInputs),ProofData.fromBuffer(reader,TxRollupPublicInputs),AppendOnlyTreeSnapshot.fromBuffer(reader),reader.readArray(26,Fr),reader.readArray(30,Fr))}toJSON(){return this.toBuffer()}static get schema(){return bufferSchemaFor(_BlockRootSingleTxFirstRollupPrivateInputs)}},BlockRootEmptyTxFirstRollupPrivateInputs=class _BlockRootEmptyTxFirstRollupPrivateInputs{static{__name(this,"BlockRootEmptyTxFirstRollupPrivateInputs")}l1ToL2Roots;previousArchive;previousState;constants;timestamp;newL1ToL2MessageSubtreeRootSiblingPath;newArchiveSiblingPath;constructor(l1ToL2Roots,previousArchive,previousState,constants,timestamp,newL1ToL2MessageSubtreeRootSiblingPath,newArchiveSiblingPath){this.l1ToL2Roots=l1ToL2Roots,this.previousArchive=previousArchive,this.previousState=previousState,this.constants=constants,this.timestamp=timestamp,this.newL1ToL2MessageSubtreeRootSiblingPath=newL1ToL2MessageSubtreeRootSiblingPath,this.newArchiveSiblingPath=newArchiveSiblingPath}static from(fields){return new _BlockRootEmptyTxFirstRollupPrivateInputs(..._BlockRootEmptyTxFirstRollupPrivateInputs.getFields(fields))}static getFields(fields){return[fields.l1ToL2Roots,fields.previousArchive,fields.previousState,fields.constants,fields.timestamp,fields.newL1ToL2MessageSubtreeRootSiblingPath,fields.newArchiveSiblingPath]}toBuffer(){return serializeToBuffer([this.l1ToL2Roots,this.previousArchive,this.previousState,this.constants,bigintToUInt64BE(this.timestamp),this.newL1ToL2MessageSubtreeRootSiblingPath,this.newArchiveSiblingPath])}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _BlockRootEmptyTxFirstRollupPrivateInputs(ProofData.fromBuffer(reader,ParityPublicInputs),AppendOnlyTreeSnapshot.fromBuffer(reader),StateReference.fromBuffer(reader),CheckpointConstantData.fromBuffer(reader),reader.readUInt64(),reader.readArray(26,Fr),reader.readArray(30,Fr))}toJSON(){return this.toBuffer()}static get schema(){return bufferSchemaFor(_BlockRootEmptyTxFirstRollupPrivateInputs)}},BlockRootRollupPrivateInputs=class _BlockRootRollupPrivateInputs{static{__name(this,"BlockRootRollupPrivateInputs")}previousRollups;newArchiveSiblingPath;constructor(previousRollups,newArchiveSiblingPath){this.previousRollups=previousRollups,this.newArchiveSiblingPath=newArchiveSiblingPath}static from(fields){return new _BlockRootRollupPrivateInputs(..._BlockRootRollupPrivateInputs.getFields(fields))}static getFields(fields){return[fields.previousRollups,fields.newArchiveSiblingPath]}toBuffer(){return serializeToBuffer(..._BlockRootRollupPrivateInputs.getFields(this))}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _BlockRootRollupPrivateInputs([ProofData.fromBuffer(reader,TxRollupPublicInputs),ProofData.fromBuffer(reader,TxRollupPublicInputs)],reader.readArray(30,Fr))}toJSON(){return this.toBuffer()}static get schema(){return bufferSchemaFor(_BlockRootRollupPrivateInputs)}},BlockRootSingleTxRollupPrivateInputs=class _BlockRootSingleTxRollupPrivateInputs{static{__name(this,"BlockRootSingleTxRollupPrivateInputs")}previousRollup;newArchiveSiblingPath;constructor(previousRollup,newArchiveSiblingPath){this.previousRollup=previousRollup,this.newArchiveSiblingPath=newArchiveSiblingPath}static from(fields){return new _BlockRootSingleTxRollupPrivateInputs(..._BlockRootSingleTxRollupPrivateInputs.getFields(fields))}static getFields(fields){return[fields.previousRollup,fields.newArchiveSiblingPath]}toBuffer(){return serializeToBuffer(..._BlockRootSingleTxRollupPrivateInputs.getFields(this))}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _BlockRootSingleTxRollupPrivateInputs(ProofData.fromBuffer(reader,TxRollupPublicInputs),reader.readArray(30,Fr))}toJSON(){return this.toBuffer()}static get schema(){return bufferSchemaFor(_BlockRootSingleTxRollupPrivateInputs)}};var EpochConstantData=class _EpochConstantData{static{__name(this,"EpochConstantData")}chainId;version;vkTreeRoot;protocolContractsHash;proverId;constructor(chainId,version2,vkTreeRoot,protocolContractsHash2,proverId){this.chainId=chainId,this.version=version2,this.vkTreeRoot=vkTreeRoot,this.protocolContractsHash=protocolContractsHash2,this.proverId=proverId}static from(fields){return new _EpochConstantData(..._EpochConstantData.getFields(fields))}static getFields(fields){return[fields.chainId,fields.version,fields.vkTreeRoot,fields.protocolContractsHash,fields.proverId]}toFields(){return serializeToFields(..._EpochConstantData.getFields(this))}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _EpochConstantData(Fr.fromBuffer(reader),Fr.fromBuffer(reader),Fr.fromBuffer(reader),Fr.fromBuffer(reader),Fr.fromBuffer(reader))}toBuffer(){return serializeToBuffer(..._EpochConstantData.getFields(this))}static empty(){return new _EpochConstantData(Fr.ZERO,Fr.ZERO,Fr.ZERO,Fr.ZERO,Fr.ZERO)}};var CheckpointRollupPublicInputs=class _CheckpointRollupPublicInputs{static{__name(this,"CheckpointRollupPublicInputs")}constants;previousArchive;newArchive;previousOutHash;newOutHash;checkpointHeaderHashes;fees;startBlobAccumulator;endBlobAccumulator;finalBlobChallenges;constructor(constants,previousArchive,newArchive,previousOutHash,newOutHash,checkpointHeaderHashes,fees,startBlobAccumulator,endBlobAccumulator,finalBlobChallenges){this.constants=constants,this.previousArchive=previousArchive,this.newArchive=newArchive,this.previousOutHash=previousOutHash,this.newOutHash=newOutHash,this.checkpointHeaderHashes=checkpointHeaderHashes,this.fees=fees,this.startBlobAccumulator=startBlobAccumulator,this.endBlobAccumulator=endBlobAccumulator,this.finalBlobChallenges=finalBlobChallenges}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _CheckpointRollupPublicInputs(reader.readObject(EpochConstantData),reader.readObject(AppendOnlyTreeSnapshot),reader.readObject(AppendOnlyTreeSnapshot),reader.readObject(AppendOnlyTreeSnapshot),reader.readObject(AppendOnlyTreeSnapshot),reader.readArray(32,Fr),reader.readArray(32,FeeRecipient),reader.readObject(BlobAccumulator),reader.readObject(BlobAccumulator),reader.readObject(FinalBlobBatchingChallenges))}toBuffer(){return serializeToBuffer(this.constants,this.previousArchive,this.newArchive,this.previousOutHash,this.newOutHash,this.checkpointHeaderHashes,this.fees,this.startBlobAccumulator,this.endBlobAccumulator,this.finalBlobChallenges)}toString(){return bufferToHex(this.toBuffer())}static fromString(str){return _CheckpointRollupPublicInputs.fromBuffer(hexToBuffer(str))}toJSON(){return this.toBuffer()}toInspect(){return{checkpointHeaderHash:this.checkpointHeaderHashes[0].toString(),previousArchiveRoot:this.previousArchive.root.toString(),newArchiveRoot:this.newArchive.root.toString(),previousOutHashRoot:this.previousOutHash.root.toString(),newOutHashRoot:this.newOutHash.root.toString()}}static get schema(){return bufferSchemaFor(_CheckpointRollupPublicInputs)}},FeeRecipient=class _FeeRecipient{static{__name(this,"FeeRecipient")}recipient;value;constructor(recipient,value){this.recipient=recipient,this.value=value}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _FeeRecipient(reader.readObject(EthAddress),Fr.fromBuffer(reader))}toBuffer(){return serializeToBuffer(this.recipient,this.value)}static getFields(fields){return[fields.recipient,fields.value]}toFields(){return serializeToFields(..._FeeRecipient.getFields(this))}static empty(){return new _FeeRecipient(EthAddress.ZERO,Fr.ZERO)}isEmpty(){return this.value.isZero()&&this.recipient.isZero()}toFriendlyJSON(){return this.isEmpty()?{}:{recipient:this.recipient.toString(),value:this.value.toString()}}static random(){return new _FeeRecipient(EthAddress.random(),Fr.random())}};var PrivateTxBaseRollupPrivateInputs=class _PrivateTxBaseRollupPrivateInputs{static{__name(this,"PrivateTxBaseRollupPrivateInputs")}hidingKernelProofData;hints;constructor(hidingKernelProofData,hints){this.hidingKernelProofData=hidingKernelProofData,this.hints=hints}static from(fields){return new _PrivateTxBaseRollupPrivateInputs(..._PrivateTxBaseRollupPrivateInputs.getFields(fields))}static getFields(fields){return[fields.hidingKernelProofData,fields.hints]}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _PrivateTxBaseRollupPrivateInputs(ProofData.fromBuffer(reader,PrivateToRollupKernelCircuitPublicInputs),reader.readObject(PrivateBaseRollupHints))}toBuffer(){return serializeToBuffer(..._PrivateTxBaseRollupPrivateInputs.getFields(this))}static fromString(str){return _PrivateTxBaseRollupPrivateInputs.fromBuffer(hexToBuffer(str))}toString(){return bufferToHex(this.toBuffer())}toJSON(){return this.toBuffer()}static get schema(){return bufferSchemaFor(_PrivateTxBaseRollupPrivateInputs)}};var PublicChonkVerifierPublicInputs=class _PublicChonkVerifierPublicInputs{static{__name(this,"PublicChonkVerifierPublicInputs")}privateTail;proverId;constructor(privateTail,proverId){this.privateTail=privateTail,this.proverId=proverId}static from(fields){return new _PublicChonkVerifierPublicInputs(..._PublicChonkVerifierPublicInputs.getFields(fields))}static getFields(fields){return[fields.privateTail,fields.proverId]}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _PublicChonkVerifierPublicInputs(reader.readObject(PrivateToPublicKernelCircuitPublicInputs),reader.readObject(Fr))}toBuffer(){return serializeToBuffer(..._PublicChonkVerifierPublicInputs.getFields(this))}static fromString(str){return _PublicChonkVerifierPublicInputs.fromBuffer(hexToBuffer(str))}toString(){return bufferToHex(this.toBuffer())}toJSON(){return this.toBuffer()}static get schema(){return bufferSchemaFor(_PublicChonkVerifierPublicInputs)}};var PublicTxBaseRollupPrivateInputs=class _PublicTxBaseRollupPrivateInputs{static{__name(this,"PublicTxBaseRollupPrivateInputs")}publicChonkVerifierProofData;avmProofData;hints;constructor(publicChonkVerifierProofData,avmProofData,hints){this.publicChonkVerifierProofData=publicChonkVerifierProofData,this.avmProofData=avmProofData,this.hints=hints}static from(fields){return new _PublicTxBaseRollupPrivateInputs(..._PublicTxBaseRollupPrivateInputs.getFields(fields))}static getFields(fields){return[fields.publicChonkVerifierProofData,fields.avmProofData,fields.hints]}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _PublicTxBaseRollupPrivateInputs(ProofData.fromBuffer(reader,PublicChonkVerifierPublicInputs),ProofDataForFixedVk.fromBuffer(reader,AvmCircuitPublicInputs),reader.readObject(PublicBaseRollupHints))}toBuffer(){return serializeToBuffer(..._PublicTxBaseRollupPrivateInputs.getFields(this))}static fromString(str){return _PublicTxBaseRollupPrivateInputs.fromBuffer(hexToBuffer(str))}toString(){return bufferToHex(this.toBuffer())}toJSON(){return this.toBuffer()}static get schema(){return bufferSchemaFor(_PublicTxBaseRollupPrivateInputs)}};var RootRollupPublicInputs=class _RootRollupPublicInputs{static{__name(this,"RootRollupPublicInputs")}previousArchiveRoot;endArchiveRoot;outHash;checkpointHeaderHashes;fees;constants;blobPublicInputs;constructor(previousArchiveRoot,endArchiveRoot,outHash,checkpointHeaderHashes,fees,constants,blobPublicInputs){this.previousArchiveRoot=previousArchiveRoot,this.endArchiveRoot=endArchiveRoot,this.outHash=outHash,this.checkpointHeaderHashes=checkpointHeaderHashes,this.fees=fees,this.constants=constants,this.blobPublicInputs=blobPublicInputs}static getFields(fields){return[fields.previousArchiveRoot,fields.endArchiveRoot,fields.outHash,fields.checkpointHeaderHashes,fields.fees,fields.constants,fields.blobPublicInputs]}toBuffer(){return serializeToBuffer(..._RootRollupPublicInputs.getFields(this))}toFields(){return serializeToFields(..._RootRollupPublicInputs.getFields(this))}static from(fields){return new _RootRollupPublicInputs(..._RootRollupPublicInputs.getFields(fields))}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _RootRollupPublicInputs(Fr.fromBuffer(reader),Fr.fromBuffer(reader),Fr.fromBuffer(reader),reader.readArray(32,Fr),reader.readArray(32,FeeRecipient),EpochConstantData.fromBuffer(reader),reader.readObject(FinalBlobAccumulator))}toString(){return bufferToHex(this.toBuffer())}static fromString(str){return _RootRollupPublicInputs.fromBuffer(hexToBuffer(str))}toJSON(){return this.toBuffer()}static get schema(){return bufferSchemaFor(_RootRollupPublicInputs)}static random(){return new _RootRollupPublicInputs(Fr.random(),Fr.random(),Fr.random(),makeTuple(32,Fr.random),makeTuple(32,FeeRecipient.random),new EpochConstantData(Fr.random(),Fr.random(),Fr.random(),Fr.random(),Fr.random()),FinalBlobAccumulator.random())}};var TxMergeRollupPrivateInputs=class _TxMergeRollupPrivateInputs{static{__name(this,"TxMergeRollupPrivateInputs")}previousRollups;constructor(previousRollups){this.previousRollups=previousRollups}toBuffer(){return serializeToBuffer(this.previousRollups)}toString(){return bufferToHex(this.toBuffer())}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _TxMergeRollupPrivateInputs([ProofData.fromBuffer(reader,TxRollupPublicInputs),ProofData.fromBuffer(reader,TxRollupPublicInputs)])}static fromString(str){return _TxMergeRollupPrivateInputs.fromBuffer(hexToBuffer(str))}toJSON(){return this.toBuffer()}static get schema(){return bufferSchemaFor(_TxMergeRollupPrivateInputs)}};function makeGlobalVariables(seed=1,overrides={}){return GlobalVariables.from({chainId:new Fr(seed),version:new Fr(seed+1),blockNumber:BlockNumber(seed+2),slotNumber:SlotNumber(seed+3),timestamp:BigInt(seed+4),coinbase:EthAddress.fromField(new Fr(seed+5)),feeRecipient:AztecAddress.fromFieldUnsafe(new Fr(seed+6)),gasFees:new GasFees(seed+7,seed+8),...compact(overrides)})}__name(makeGlobalVariables,"makeGlobalVariables");import{hashTypedData as hashTypedData2}from"viem";var TEST_COORDINATION_SIGNATURE_CONTEXT={chainId:31337,rollupAddress:EthAddress.fromNumber(1)};var DEFAULT_ADDRESS=AztecAddress.fromNumberUnsafe(42),MAX_PRIVATE_EVENT_LEN=10,MAX_PRIVATE_EVENTS_PER_TXE_QUERY=5,MAX_OFFCHAIN_EFFECTS_PER_TXE_QUERY=64,MAX_OFFCHAIN_EFFECT_LEN=17;function getSingleTxBlockRequestHash(blockNumber){return new Fr(blockNumber+9999)}__name(getSingleTxBlockRequestHash,"getSingleTxBlockRequestHash");async function insertTxEffectIntoWorldTrees(txEffect,worldTrees,l1ToL2Messages=[]){await worldTrees.appendLeaves(MerkleTreeId.NOTE_HASH_TREE,padArrayEnd(txEffect.noteHashes,Fr.ZERO,64)),await worldTrees.batchInsert(MerkleTreeId.NULLIFIER_TREE,padArrayEnd(txEffect.nullifiers,Fr.ZERO,64).map(nullifier=>nullifier.toBuffer()),6),await worldTrees.appendLeaves(MerkleTreeId.L1_TO_L2_MESSAGE_TREE,padArrayEnd(l1ToL2Messages,Fr.ZERO,1024))}__name(insertTxEffectIntoWorldTrees,"insertTxEffectIntoWorldTrees");async function makeTXEBlockHeader(worldTrees,globalVariables){let stateReference=await worldTrees.getStateReference(),archiveInfo=await worldTrees.getTreeInfo(MerkleTreeId.ARCHIVE);return BlockHeader.from({lastArchive:new AppendOnlyTreeSnapshot(new Fr(archiveInfo.root),Number(archiveInfo.size)),spongeBlobHash:Fr.ZERO,state:stateReference,globalVariables,totalFees:Fr.ZERO,totalManaUsed:Fr.ZERO})}__name(makeTXEBlockHeader,"makeTXEBlockHeader");async function makeTXEBlock(worldTrees,globalVariables,txEffects){let header=await makeTXEBlockHeader(worldTrees,globalVariables);await worldTrees.updateArchive(header);let newArchiveInfo=await worldTrees.getTreeInfo(MerkleTreeId.ARCHIVE),newArchive=new AppendOnlyTreeSnapshot(new Fr(newArchiveInfo.root),Number(newArchiveInfo.size)),checkpointNumber=CheckpointNumber.fromBlockNumber(globalVariables.blockNumber),indexWithinCheckpoint=IndexWithinCheckpoint(0);return new L2Block(newArchive,header,new Body(txEffects),checkpointNumber,indexWithinCheckpoint)}__name(makeTXEBlock,"makeTXEBlock");var TXEOraclePublicContext=class{constructor(contractAddress,forkedWorldTrees,txRequestHash,globalVariables,contractStore){this.contractAddress=contractAddress;this.forkedWorldTrees=forkedWorldTrees;this.txRequestHash=txRequestHash;this.globalVariables=globalVariables;this.contractStore=contractStore;this.logger=createLogger("txe:public_context"),this.logger.debug("Entering Public Context",{contractAddress,blockNumber:globalVariables.blockNumber,timestamp:globalVariables.timestamp})}static{__name(this,"TXEOraclePublicContext")}isAvm=!0;logger;transientUniqueNoteHashes=[];transientSiloedNullifiers=[];publicDataWrites=[];address(){return Promise.resolve(this.contractAddress)}sender(){return Promise.resolve(AztecAddress.ZERO)}blockNumber(){return Promise.resolve(this.globalVariables.blockNumber)}timestamp(){return Promise.resolve(this.globalVariables.timestamp)}isStaticCall(){return Promise.resolve(!1)}chainId(){return Promise.resolve(this.globalVariables.chainId)}version(){return Promise.resolve(this.globalVariables.version)}async emitNullifier(nullifier){let siloedNullifier=await siloNullifier(this.contractAddress,nullifier);this.transientSiloedNullifiers.push(siloedNullifier)}async emitNoteHash(noteHash){let siloedNoteHash=await siloNoteHash(this.contractAddress,noteHash);this.transientUniqueNoteHashes.push(siloedNoteHash)}async nullifierExists(siloedNullifier){let treeIndex=(await this.forkedWorldTrees.findLeafIndices(MerkleTreeId.NULLIFIER_TREE,[siloedNullifier.toBuffer()]))[0],transientIndex=this.transientSiloedNullifiers.find(n=>n.equals(siloedNullifier));return treeIndex!==void 0||transientIndex!==void 0}async storageWrite(slot,value){this.logger.debug("AVM storage write",{slot,value});let dataWrite=new PublicDataWrite(await computePublicDataTreeLeafSlot(this.contractAddress,slot),value);this.publicDataWrites.push(dataWrite),await this.forkedWorldTrees.sequentialInsert(MerkleTreeId.PUBLIC_DATA_TREE,[new PublicDataTreeLeaf(dataWrite.leafSlot,dataWrite.value).toBuffer()])}async storageRead(slot,contractAddress){let leafSlot=await computePublicDataTreeLeafSlot(contractAddress,slot),lowLeafResult=await this.forkedWorldTrees.getPreviousValueIndex(MerkleTreeId.PUBLIC_DATA_TREE,leafSlot.toBigInt()),value=!lowLeafResult||!lowLeafResult.alreadyPresent?Fr.ZERO:(await this.forkedWorldTrees.getLeafPreimage(MerkleTreeId.PUBLIC_DATA_TREE,lowLeafResult.index)).leaf.value;return this.logger.debug("AVM storage read",{slot,contractAddress,value}),value}getContractInstanceDeployer(address){return this.getContractInstanceMember(address,i=>i.deployer.toField())}getContractInstanceClassId(address){return this.getContractInstanceMember(address,i=>i.originalContractClassId)}getContractInstanceInitializationHash(address){return this.getContractInstanceMember(address,i=>i.initializationHash)}getContractInstanceImmutablesHash(address){return this.getContractInstanceMember(address,i=>i.immutablesHash)}async getContractInstanceMember(address,accessor){let instance=await this.contractStore.getContractInstance(address);return instance?[{member:accessor(instance),exists:!0}]:[{member:Fr.ZERO,exists:!1}]}returndataSize(){throw new Error("Contract calls are forbidden inside a `TestEnvironment::public_context`, use `public_call` instead")}returndataCopy(_rdOffset,_copySize){throw new Error("Contract calls are forbidden inside a `TestEnvironment::public_context`, use `public_call` instead")}call(_l2Gas,_daGas,_address,_argsLength,_args){throw new Error("Contract calls are forbidden inside a `TestEnvironment::public_context`, use `public_call` instead")}staticCall(_l2Gas,_daGas,_address,_argsLength,_args){throw new Error("Contract calls are forbidden inside a `TestEnvironment::public_context`, use `public_call` instead")}successCopy(){throw new Error("Contract calls are forbidden inside a `TestEnvironment::public_context`, use `public_call` instead")}async close(){this.logger.debug("Exiting Public Context, building block with collected side effects",{blockNumber:this.globalVariables.blockNumber});let txEffect=this.makeTxEffect();await insertTxEffectIntoWorldTrees(txEffect,this.forkedWorldTrees);let block=await makeTXEBlock(this.forkedWorldTrees,this.globalVariables,[txEffect]);return await this.forkedWorldTrees.close(),this.logger.debug("Exited PublicContext with built block",{blockNumber:block.number,txEffects:block.body.txEffects}),block}makeTxEffect(){let txEffect=TxEffect.empty();return txEffect.noteHashes=this.transientUniqueNoteHashes,txEffect.nullifiers=[this.txRequestHash,...this.transientSiloedNullifiers],txEffect.publicDataWrites=this.publicDataWrites,txEffect.txHash=new TxHash(new Fr(this.globalVariables.blockNumber)),txEffect}};var GAS_SETTINGS={deserialization:{fn:__name(([reader])=>GasSettings.fromFields(reader.readFieldArray(8)),"fn")},shape:[{len:8}]},STRATEGY_NON_INTERACTIVE_HANDSHAKE=1,STRATEGY_ARBITRARY_SECRET=2,STRATEGY_ADDRESS_DERIVED=3,STRATEGY_INTERACTIVE_HANDSHAKE=4,TAGGING_SECRET_STRATEGY={serialization:{fn:__name(strategy=>{switch(strategy.type){case"non-interactive-handshake":return[new Fr(STRATEGY_NON_INTERACTIVE_HANDSHAKE),Fr.ZERO,Fr.ZERO];case"interactive-handshake":return[new Fr(STRATEGY_INTERACTIVE_HANDSHAKE),Fr.ZERO,Fr.ZERO];case"address-derived":return[new Fr(STRATEGY_ADDRESS_DERIVED),Fr.ZERO,Fr.ZERO];case"arbitrary-secret":return[new Fr(STRATEGY_ARBITRARY_SECRET),strategy.secret.x,strategy.secret.y]}},"fn")},deserialization:{fn:__name(([kindReader,xReader,yReader])=>{let kind=kindReader.readField().toNumber(),[x,y]=[xReader.readField(),yReader.readField()];switch(kind){case STRATEGY_NON_INTERACTIVE_HANDSHAKE:return{type:"non-interactive-handshake"};case STRATEGY_INTERACTIVE_HANDSHAKE:return{type:"interactive-handshake"};case STRATEGY_ADDRESS_DERIVED:return{type:"address-derived"};case STRATEGY_ARBITRARY_SECRET:return{type:"arbitrary-secret",secret:Point.fromFields([x,y])};default:throw new Error(`Unrecognized tagging secret strategy kind: ${kind}`)}},"fn")},shape:["scalar","scalar","scalar"]},PRIVATE_CONTEXT_INPUTS={serialization:{fn:__name(v=>v.toFields(),"fn")},shape:Array(37).fill("scalar")},COMPLETE_ADDRESS={serialization:{fn:__name(v=>[v.address.toField(),...v.publicKeys.toFields()],"fn")},shape:Array(8).fill("scalar")},TXE_TX_EFFECTS={serialization:{fn:__name(({txHash,noteHashes,nullifiers,privateLogs})=>{let emittedLogs=privateLogs.map(log2=>log2.getEmittedFields()),rawLogStorage=emittedLogs.map(fields=>fields.concat(Array(16-fields.length).fill(Fr.ZERO))).concat(Array(64-emittedLogs.length).fill(Array(16).fill(Fr.ZERO))).flat(),logLengths=emittedLogs.map(fields=>new Fr(fields.length)).concat(Array(64-emittedLogs.length).fill(Fr.ZERO)),paddedNoteHashes=noteHashes.concat(Array(64-noteHashes.length).fill(Fr.ZERO)),paddedNullifiers=nullifiers.concat(Array(64-nullifiers.length).fill(Fr.ZERO));return[txHash.hash,paddedNoteHashes,new Fr(noteHashes.length),paddedNullifiers,new Fr(nullifiers.length),rawLogStorage,logLengths,new Fr(emittedLogs.length)]},"fn")},shape:["scalar",{len:64},"scalar",{len:64},"scalar",{len:1024},{len:64},"scalar"]},TXE_OFFCHAIN_EFFECTS={serialization:{fn:__name(({effects})=>{let rawArrayStorage=effects.map(e2=>e2.concat(Array(MAX_OFFCHAIN_EFFECT_LEN-e2.length).fill(Fr.ZERO))).concat(Array(MAX_OFFCHAIN_EFFECTS_PER_TXE_QUERY-effects.length).fill(Array(MAX_OFFCHAIN_EFFECT_LEN).fill(Fr.ZERO))).flat(),effectLengths=effects.map(e2=>new Fr(e2.length)).concat(Array(MAX_OFFCHAIN_EFFECTS_PER_TXE_QUERY-effects.length).fill(Fr.ZERO));return[rawArrayStorage,effectLengths,new Fr(effects.length)]},"fn")},shape:[{len:MAX_OFFCHAIN_EFFECTS_PER_TXE_QUERY*MAX_OFFCHAIN_EFFECT_LEN},{len:MAX_OFFCHAIN_EFFECTS_PER_TXE_QUERY},"scalar"]},TXE_CALL_CONTEXT={serialization:{fn:__name(({txHash,anchorBlockTimestamp})=>{let isSome=txHash.isZero()?0:1;return[new Fr(isSome),txHash,new Fr(anchorBlockTimestamp)]},"fn")},shape:["scalar","scalar","scalar"]},CONTRACT_INSTANCE_MEMBER=FIXED_ARRAY(STRUCT([{name:"exists",type:BOOL},{name:"member",type:FIELD}]),1),EVENT_SELECTOR={serialization:{fn:__name(v=>[v.toField()],"fn")},deserialization:{fn:__name(([reader])=>EventSelector.fromField(reader.readField()),"fn")},shape:["scalar"]},TXE_PRIVATE_EVENTS={serialization:{fn:__name(events=>{let rawArrayStorage=events.map(e2=>e2.concat(Array(MAX_PRIVATE_EVENT_LEN-e2.length).fill(Fr.ZERO))).concat(Array(MAX_PRIVATE_EVENTS_PER_TXE_QUERY-events.length).fill(Array(MAX_PRIVATE_EVENT_LEN).fill(Fr.ZERO))).flat(),eventLengths=events.map(e2=>new Fr(e2.length)).concat(Array(MAX_PRIVATE_EVENTS_PER_TXE_QUERY-events.length).fill(Fr.ZERO));return[rawArrayStorage,eventLengths,new Fr(events.length)]},"fn")},shape:[{len:MAX_PRIVATE_EVENTS_PER_TXE_QUERY*MAX_PRIVATE_EVENT_LEN},{len:MAX_PRIVATE_EVENTS_PER_TXE_QUERY},"scalar"]},TXE_ORACLE_REGISTRY={...ORACLE_REGISTRY,aztec_txe_assertCompatibleOracleVersion:makeEntry({params:[{name:"major",type:U32},{name:"minor",type:U32}]}),aztec_txe_setTopLevelTXEContext:makeEntry(),aztec_txe_setPrivateTXEContext:makeEntry({params:[{name:"contractAddress",type:OPTION(AZTEC_ADDRESS)},{name:"anchorBlockNumber",type:OPTION(BLOCK_NUMBER)},{name:"gasSettings",type:GAS_SETTINGS}],returnType:PRIVATE_CONTEXT_INPUTS}),aztec_txe_setPublicTXEContext:makeEntry({params:[{name:"contractAddress",type:OPTION(AZTEC_ADDRESS)}]}),aztec_txe_setUtilityTXEContext:makeEntry({params:[{name:"contractAddress",type:OPTION(AZTEC_ADDRESS)}]}),aztec_txe_getDefaultAddress:makeEntry({returnType:AZTEC_ADDRESS}),aztec_txe_getNextBlockNumber:makeEntry({returnType:BLOCK_NUMBER}),aztec_txe_getNextBlockTimestamp:makeEntry({returnType:BIGINT}),aztec_txe_advanceBlocksBy:makeEntry({params:[{name:"blocks",type:U32}]}),aztec_txe_advanceTimestampBy:makeEntry({params:[{name:"duration",type:BIGINT}]}),aztec_txe_deploy:makeEntry({params:[{name:"contractPath",type:STR},{name:"initializer",type:STR},{name:"argsLength",type:U32},{name:"args",type:ARRAY(FIELD)},{name:"secret",type:FIELD},{name:"salt",type:FIELD},{name:"deployer",type:AZTEC_ADDRESS}],returnType:ARRAY(FIELD)}),aztec_txe_createAccount:makeEntry({params:[{name:"secret",type:FIELD}],returnType:COMPLETE_ADDRESS}),aztec_txe_addAccount:makeEntry({params:[{name:"secret",type:FIELD}],returnType:COMPLETE_ADDRESS}),aztec_txe_addAuthWitness:makeEntry({params:[{name:"address",type:AZTEC_ADDRESS},{name:"messageHash",type:FIELD}]}),aztec_txe_sendL1ToL2Message:makeEntry({params:[{name:"content",type:FIELD},{name:"secretHash",type:FIELD},{name:"sender",type:ETH_ADDRESS},{name:"recipient",type:AZTEC_ADDRESS}],returnType:FIELD}),aztec_txe_setTaggingSecretStrategy:makeEntry({params:[{name:"strategy",type:OPTION(TAGGING_SECRET_STRATEGY)}]}),aztec_txe_getLastBlockTimestamp:makeEntry({returnType:BIGINT}),aztec_txe_getLastTxEffects:makeEntry({returnType:TXE_TX_EFFECTS}),aztec_txe_getLastCallOffchainEffects:makeEntry({returnType:TXE_OFFCHAIN_EFFECTS}),aztec_txe_getLastCallContext:makeEntry({returnType:TXE_CALL_CONTEXT}),aztec_txe_getPrivateEvents:makeEntry({params:[{name:"selector",type:EVENT_SELECTOR},{name:"contractAddress",type:AZTEC_ADDRESS},{name:"scope",type:AZTEC_ADDRESS}],returnType:TXE_PRIVATE_EVENTS}),aztec_txe_privateCallNewFlow:makeEntry({params:[{name:"from",type:OPTION(AZTEC_ADDRESS)},{name:"targetContractAddress",type:AZTEC_ADDRESS},{name:"functionSelector",type:FUNCTION_SELECTOR},{name:"args",type:ARRAY(FIELD)},{name:"argsHash",type:FIELD},{name:"isStaticCall",type:BOOL},{name:"additionalScopes",type:ARRAY(AZTEC_ADDRESS)},{name:"authorizedUtilityCallTargets",type:ARRAY(AZTEC_ADDRESS)},{name:"gasSettings",type:GAS_SETTINGS}],returnType:ARRAY(FIELD)}),aztec_txe_executeUtilityFunction:makeEntry({params:[{name:"from",type:OPTION(AZTEC_ADDRESS)},{name:"targetContractAddress",type:AZTEC_ADDRESS},{name:"functionSelector",type:FUNCTION_SELECTOR},{name:"args",type:ARRAY(FIELD)},{name:"authorizedUtilityCallTargets",type:ARRAY(AZTEC_ADDRESS)}],returnType:ARRAY(FIELD)}),aztec_txe_publicCallNewFlow:makeEntry({params:[{name:"from",type:OPTION(AZTEC_ADDRESS)},{name:"address",type:AZTEC_ADDRESS},{name:"calldata",type:ARRAY(FIELD)},{name:"isStaticCall",type:BOOL},{name:"gasSettings",type:GAS_SETTINGS}],returnType:ARRAY(FIELD)}),aztec_avm_address:makeEntry({returnType:AZTEC_ADDRESS}),aztec_avm_sender:makeEntry({returnType:AZTEC_ADDRESS}),aztec_avm_blockNumber:makeEntry({returnType:BLOCK_NUMBER}),aztec_avm_timestamp:makeEntry({returnType:BIGINT}),aztec_avm_isStaticCall:makeEntry({returnType:BOOL}),aztec_avm_chainId:makeEntry({returnType:FIELD}),aztec_avm_version:makeEntry({returnType:FIELD}),aztec_avm_emitNullifier:makeEntry({params:[{name:"nullifier",type:FIELD}]}),aztec_avm_emitNoteHash:makeEntry({params:[{name:"noteHash",type:FIELD}]}),aztec_avm_nullifierExists:makeEntry({params:[{name:"siloedNullifier",type:FIELD}],returnType:BOOL}),aztec_avm_storageRead:makeEntry({params:[{name:"slot",type:FIELD},{name:"contractAddress",type:AZTEC_ADDRESS}],returnType:FIELD}),aztec_avm_storageWrite:makeEntry({params:[{name:"slot",type:FIELD},{name:"value",type:FIELD}]}),aztec_avm_emitPublicLog:makeEntry({params:[{name:"message",type:ARRAY(FIELD)}]}),aztec_avm_returndataSize:makeEntry({returnType:U32}),aztec_avm_returndataCopy:makeEntry({params:[{name:"rdOffset",type:U32},{name:"copySize",type:U32}],returnType:ARRAY(FIELD)}),aztec_avm_call:makeEntry({params:[{name:"l2Gas",type:U32},{name:"daGas",type:U32},{name:"address",type:AZTEC_ADDRESS},{name:"argsLength",type:U32},{name:"args",type:ARRAY(FIELD)}]}),aztec_avm_staticCall:makeEntry({params:[{name:"l2Gas",type:U32},{name:"daGas",type:U32},{name:"address",type:AZTEC_ADDRESS},{name:"argsLength",type:U32},{name:"args",type:ARRAY(FIELD)}]}),aztec_avm_successCopy:makeEntry({returnType:BOOL}),aztec_avm_getContractInstanceDeployer:makeEntry({params:[{name:"address",type:AZTEC_ADDRESS}],returnType:CONTRACT_INSTANCE_MEMBER}),aztec_avm_getContractInstanceClassId:makeEntry({params:[{name:"address",type:AZTEC_ADDRESS}],returnType:CONTRACT_INSTANCE_MEMBER}),aztec_avm_getContractInstanceInitializationHash:makeEntry({params:[{name:"address",type:AZTEC_ADDRESS}],returnType:CONTRACT_INSTANCE_MEMBER}),aztec_avm_getContractInstanceImmutablesHash:makeEntry({params:[{name:"address",type:AZTEC_ADDRESS}],returnType:CONTRACT_INSTANCE_MEMBER})};function toInputSlots(inputs){return inputs.map(v=>Array.isArray(v)?v.map(withHexPrefix):[withHexPrefix(v)])}__name(toInputSlots,"toInputSlots");async function callTxeHandler({oracle,inputs,handler}){let entry=TXE_ORACLE_REGISTRY[oracle],positional=entry.deserializeParams(toInputSlots(inputs)).map(p=>p.value),result=await handler(positional);return outputSlotsToForeignCallResult(entry.serializeReturn(result))}__name(callTxeHandler,"callTxeHandler");var legacyCallbacksByHandler=new WeakMap;async function callTxeLegacyHandler(oracle,inputs,oracleHandler){let callback=legacyCallbacksByHandler.get(oracleHandler);callback||(callback=buildACIRCallback(oracleHandler),legacyCallbacksByHandler.set(oracleHandler,callback));let outputSlots=await callback[oracle](...toInputSlots(inputs));return outputSlotsToForeignCallResult(outputSlots)}__name(callTxeLegacyHandler,"callTxeLegacyHandler");function outputSlotsToForeignCallResult(outputSlots){return{values:outputSlots.map(slot=>Array.isArray(slot)?slot.map(withoutHexPrefix):withoutHexPrefix(slot))}}__name(outputSlotsToForeignCallResult,"outputSlotsToForeignCallResult");import{BarretenbergSync as BarretenbergSync8}from"@aztec/bb.js";var SchnorrSignature=class _SchnorrSignature{static{__name(this,"SchnorrSignature")}buffer;static SIZE=64;constructor(buffer){if(this.buffer=buffer,buffer.length!==_SchnorrSignature.SIZE)throw new Error(`Invalid signature buffer of length ${buffer.length}.`)}get s(){return this.buffer.subarray(0,32)}get e(){return this.buffer.subarray(32)}toBuffer(){return this.buffer}toString(){return`0x${this.buffer.toString("hex")}`}toFields(){let sig=this.toBuffer(),buf1=Buffer.alloc(32),buf2=Buffer.alloc(32),buf3=Buffer.alloc(32);return sig.copy(buf1,1,0,31),sig.copy(buf2,1,31,62),sig.copy(buf3,1,62,64),mapTuple([buf1,buf2,buf3],Fr.fromBuffer)}toLimbFields(){let limb=__name(start=>{let buf=Buffer.alloc(32);return this.buffer.copy(buf,16,start,start+16),Fr.fromBuffer(buf)},"limb");return[limb(16),limb(0),limb(48),limb(32)]}};var Schnorr=class{static{__name(this,"Schnorr")}async computePublicKey(privateKey){await BarretenbergSync8.initSingleton();let response=BarretenbergSync8.getSingleton().schnorrComputePublicKey({privateKey:privateKey.toBuffer()});return Point.fromBuffer(Buffer.concat([Buffer.from(response.publicKey.x),Buffer.from(response.publicKey.y)]))}async constructSignature(msg,privateKey){await BarretenbergSync8.initSingleton();let response=BarretenbergSync8.getSingleton().schnorrConstructSignature({messageField:msg.toBuffer(),privateKey:privateKey.toBuffer()});return new SchnorrSignature(Buffer.from([...response.s,...response.e]))}async verifySignature(msg,pubKey,sig){return await BarretenbergSync8.initSingleton(),BarretenbergSync8.getSingleton().schnorrVerifySignature({messageField:msg.toBuffer(),publicKey:{x:pubKey.x.toBuffer(),y:pubKey.y.toBuffer()},s:sig.s,e:sig.e}).verified}};var TXEPublicContractDataSource=class{constructor(blockNumber,contractStore){this.blockNumber=blockNumber;this.contractStore=contractStore}static{__name(this,"TXEPublicContractDataSource")}getBlockNumber(){return Promise.resolve(this.blockNumber)}async getContractClass(id){let contractClass=await this.contractStore.getContractClassWithPreimage(id);if(contractClass)return{id:contractClass.id,artifactHash:contractClass.artifactHash,packedBytecode:contractClass.packedBytecode,privateFunctionsRoot:contractClass.privateFunctionsRoot,version:contractClass.version}}async getBytecodeCommitment(id){return(await this.contractStore.getContractClassWithPreimage(id))?.publicBytecodeCommitment}async getContract(address){let instance=await this.contractStore.getContractInstance(address);return instance&&{...instance,address,currentContractClassId:instance.originalContractClassId}}getContractClassIds(){throw new Error("Method not implemented.")}async getContractArtifact(address){let instance=await this.getContract(address);return instance&&this.contractStore.getContractArtifact(instance.originalContractClassId)}async getDebugFunctionName(address,selector){let instance=await this.getContract(address);return instance&&this.contractStore.getDebugFunctionName(instance.originalContractClassId,selector)}registerContractFunctionSignatures(_signatures){return Promise.resolve()}};var TXEOracleTopLevelContext=class{constructor(stateMachine,contractStore,noteStore,keyStore,addressStore,accountStore,senderTaggingStore,recipientTaggingStore,taggingSecretSourcesStore,capsuleStore,factStore,privateEventStore,nextBlockTimestamp,version2,chainId,authwits,taggingSecretStrategy,artifactResolver,rootPath,packageName){this.stateMachine=stateMachine;this.contractStore=contractStore;this.noteStore=noteStore;this.keyStore=keyStore;this.addressStore=addressStore;this.accountStore=accountStore;this.senderTaggingStore=senderTaggingStore;this.recipientTaggingStore=recipientTaggingStore;this.taggingSecretSourcesStore=taggingSecretSourcesStore;this.capsuleStore=capsuleStore;this.factStore=factStore;this.privateEventStore=privateEventStore;this.nextBlockTimestamp=nextBlockTimestamp;this.version=version2;this.chainId=chainId;this.authwits=authwits;this.taggingSecretStrategy=taggingSecretStrategy;this.artifactResolver=artifactResolver;this.rootPath=rootPath;this.packageName=packageName;this.logger=createLogger("txe:top_level_context"),this.logger.debug("Entering Top Level Context")}static{__name(this,"TXEOracleTopLevelContext")}isMisc=!0;isTxe=!0;logger;contractOracleVersion;assertCompatibleOracleVersion(major2,minor){if(major2!==30){let hint=major2>30?"The contract was compiled with a newer version of Aztec.nr than this aztec cli version supports. Upgrade your aztec cli version to a compatible version.":"The contract was compiled with an older version of Aztec.nr than this aztec cli version supports. Recompile the contract with a compatible version of Aztec.nr.";throw new Error(`Incompatible aztec cli version: ${hint} See https://docs.aztec.network/errors/8 (expected oracle major version ${30}, got ${major2})`)}this.contractOracleVersion={major:major2,minor}}nonOracleFunctionGetContractOracleVersion(){return this.contractOracleVersion}getRandomField(){return Fr.random()}log(level,message,_fieldsSize,fields){if(!LogLevels[level])throw new Error(`Invalid log level: ${level}`);let levelName=LogLevels[level];return this.logger[levelName](`${applyStringFormatting(message,fields)}`,{module:`${this.logger.module}:debug_log`}),Promise.resolve()}getDefaultAddress(){return DEFAULT_ADDRESS}async getNextBlockNumber(){return BlockNumber(await this.getLastBlockNumber()+1)}getNextBlockTimestamp(){return Promise.resolve(this.nextBlockTimestamp)}async getLastBlockTimestamp(){return(await this.stateMachine.node.getBlockData("latest")).header.globalVariables.timestamp}async getLastTxEffects(){let latestBlockNumber=await this.stateMachine.archiver.getBlockNumber(),block=await this.stateMachine.archiver.getBlock({number:latestBlockNumber});if(block.body.txEffects.length!=1)throw new Error(`Expected a single transaction in the last block, found ${block.body.txEffects.length}`);let txEffects=block.body.txEffects[0],privateLogs=txEffects.privateLogs;if(privateLogs.length>64)throw new Error(`${privateLogs.length} private logs exceed max ${64}`);return{txHash:txEffects.txHash,noteHashes:txEffects.noteHashes,nullifiers:txEffects.nullifiers,privateLogs}}async syncContractNonOracleMethod(contractAddress,scope,jobId){if(contractAddress.equals(DEFAULT_ADDRESS)){this.logger.debug("Skipping sync in getPrivateEvents because the events correspond to the default address.");return}let blockHeader=await this.stateMachine.anchorBlockStore.getBlockHeader();await this.stateMachine.contractSyncService.ensureContractSynced(contractAddress,null,async(call,execScopes)=>{await this.executeUtilityCall(call,{scopes:execScopes,jobId})},blockHeader,jobId,[scope])}async getPrivateEvents(selector,contractAddress,scope){let events=(await this.privateEventStore.getPrivateEvents(selector,{contractAddress,scopes:[scope],fromBlock:0,toBlock:await this.getLastBlockNumber()+1})).map(e2=>e2.packedEvent);if(events.length>MAX_PRIVATE_EVENTS_PER_TXE_QUERY)throw new Error(`Array of length ${events.length} larger than maxLen ${MAX_PRIVATE_EVENTS_PER_TXE_QUERY}`);if(events.some(e2=>e2.length>MAX_PRIVATE_EVENT_LEN))throw new Error(`Some private event has length larger than maxLen ${MAX_PRIVATE_EVENT_LEN}`);return events}async advanceBlocksBy(blocks){this.logger.debug(`time traveling ${blocks} blocks`);for(let i=0;i<blocks;i++)await this.mineBlock()}advanceTimestampBy(duration3){this.logger.debug(`time traveling ${duration3} seconds`),this.nextBlockTimestamp+=duration3}deploymentNullifier(address){return siloNullifier(AztecAddress.fromNumberUnsafe(2),address.toField())}async deploy(contractPath,initializer3,args,secret,salt,deployer){let{artifact,instance}=await this.artifactResolver.resolveDeployArtifact({rootPath:this.rootPath,packageName:this.packageName,contractPath,initializer:initializer3,args,secret,salt,deployer});return await this.mineBlock({nullifiers:[await this.deploymentNullifier(instance.address)]}),secret.equals(Fr.ZERO)?(await this.contractStore.addContractInstance(instance),await this.contractStore.addContractArtifact(artifact),this.logger.debug(`Deployed ${artifact.name} at ${instance.address}`)):await this.registerContractAndAddAccount(artifact,instance,secret),CONTRACT_INSTANCE.serialization.fn(instance).flat()}async mineDeploymentNullifiers(addresses){await this.mineBlock({nullifiers:await Promise.all(addresses.map(address=>this.deploymentNullifier(address)))})}async addAccount(secret){let{artifact,instance}=await this.artifactResolver.resolveAccountArtifact(secret);return this.registerContractAndAddAccount(artifact,instance,secret)}async registerContractAndAddAccount(artifact,instance,secret){let partialAddress=await computePartialAddress(instance);this.logger.debug(`Deployed ${artifact.name} at ${instance.address}`),await this.contractStore.addContractInstance(instance),await this.contractStore.addContractArtifact(artifact);let completeAddress=await this.keyStore.addAccount(await deriveKeys(secret),partialAddress);return await this.accountStore.setAccount(completeAddress.address,completeAddress),await this.addressStore.addCompleteAddress(completeAddress),this.logger.debug(`Created account ${completeAddress.address}`),completeAddress}async createAccount(secret){let completeAddress=await this.keyStore.addAccount(await deriveKeys(secret),secret);return await this.accountStore.setAccount(completeAddress.address,completeAddress),await this.addressStore.addCompleteAddress(completeAddress),this.logger.debug(`Created account ${completeAddress.address}`),completeAddress}async addAuthWitness(address,messageHash){let account=await this.accountStore.getAccount(address),ivpkMHash=await hashPublicKey(account.publicKeys.ivpkM),privateKey=await this.keyStore.getMasterSecretKey(ivpkMHash),signature=await new Schnorr().constructSignature(messageHash,privateKey),authWitness=new AuthWitness(messageHash,signature.toLimbFields());this.authwits.set(authWitness.requestHash.toString(),authWitness)}setTaggingSecretStrategy(strategy){this.taggingSecretStrategy=strategy.value}async sendL1ToL2Message(content,secretHash,sender,recipient){let{size}=await this.stateMachine.synchronizer.getCommitted().getTreeInfo(MerkleTreeId.L1_TO_L2_MESSAGE_TREE),leafIndex=new Fr(size),message=new L1ToL2Message(new L1Actor(sender,this.chainId.toNumber()),new L2Actor(recipient,this.version.toNumber()),content,secretHash,leafIndex);return await this.mineBlock({l1ToL2Messages:[message.hash()]}),leafIndex}async mineBlock(options={}){let blockNumber=await this.getNextBlockNumber(),txEffect=TxEffect.empty();txEffect.nullifiers=[getSingleTxBlockRequestHash(blockNumber),...options.nullifiers??[]],txEffect.txHash=new TxHash(new Fr(blockNumber));let forkedWorldTrees=await this.stateMachine.synchronizer.nativeWorldStateService.fork();await insertTxEffectIntoWorldTrees(txEffect,forkedWorldTrees,options.l1ToL2Messages??[]);let globals=makeGlobalVariables(void 0,{blockNumber,timestamp:this.nextBlockTimestamp,version:this.version,chainId:this.chainId}),block=await makeTXEBlock(forkedWorldTrees,globals,[txEffect]);await forkedWorldTrees.close(),this.logger.info(`Created block ${blockNumber} with timestamp ${block.header.globalVariables.timestamp}`),await this.stateMachine.handleL2Block(block,options.l1ToL2Messages??[])}async privateCallNewFlow(from,targetContractAddress=AztecAddress.zero(),functionSelector=FunctionSelector.empty(),args,argsHash=Fr.zero(),isStaticCall=!1,additionalScopes=[],jobId,authorizedUtilityCallTargets,gasSettings){let blockHeader=await this.stateMachine.anchorBlockStore.getBlockHeader(),anchoredContractData=new AnchoredContractData(this.contractStore,this.stateMachine.contractClassService,blockHeader);this.logger.verbose(`Executing external function ${await anchoredContractData.getDebugFunctionName(targetContractAddress,functionSelector)}@${targetContractAddress} isStaticCall=${isStaticCall}`);let artifact=await anchoredContractData.getFunctionArtifact(targetContractAddress,functionSelector);if(!artifact){let message=functionSelector.equals(await FunctionSelector.fromSignature("verify_private_authwit(Field)"))?"Found no account contract artifact for a private authwit check - use `create_contract_account` instead of `create_light_account` for authwit support.":"Function Artifact does not exist";throw new Error(message)}let scopes=from===void 0?additionalScopes:[from,...additionalScopes],utilityExecutor=__name(async(call,execScopes)=>{await this.executeUtilityCall(call,{scopes:execScopes,jobId})},"utilityExecutor");await this.stateMachine.contractSyncService.ensureContractSynced(targetContractAddress,functionSelector,utilityExecutor,blockHeader,jobId,scopes);let blockNumber=await this.getNextBlockNumber(),msgSender=from??AztecAddress.NULL_MSG_SENDER,callContext=new CallContext(msgSender,targetContractAddress,functionSelector,isStaticCall),txContext=new TxContext(this.chainId,this.version,gasSettings),protocolNullifier=await computeProtocolNullifier(getSingleTxBlockRequestHash(blockNumber)),noteCache=new ExecutionNoteCache(protocolNullifier),minRevertibleSideEffectCounter=1;await noteCache.setMinRevertibleSideEffectCounter(minRevertibleSideEffectCounter);let taggingIndexCache=new ExecutionTaggingIndexCache,simulator=new WASMSimulator,transientArrayService=new TransientArrayService,taggingSecretStrategy=this.taggingSecretStrategy,privateExecutionOracle=new PrivateExecutionOracle({argsHash,txContext,callContext,anchorBlockHeader:blockHeader,utilityExecutor,authWitnesses:Array.from(this.authwits.values()),capsules:[],executionCache:HashedValuesCache.create([new HashedValues(args,argsHash)]),noteCache,taggingIndexCache,anchoredContractData,noteStore:this.noteStore,keyStore:this.keyStore,addressStore:this.addressStore,aztecNode:this.stateMachine.node,senderTaggingStore:this.senderTaggingStore,recipientTaggingStore:this.recipientTaggingStore,taggingSecretSourcesStore:this.taggingSecretSourcesStore,capsuleService:new CapsuleService(this.capsuleStore,scopes),factService:new FactService(this.factStore,scopes),privateEventStore:this.privateEventStore,contractSyncService:this.stateMachine.contractSyncService,jobId,totalPublicCalldataCount:0,sideEffectCounter:minRevertibleSideEffectCounter,scopes,senderForTags:from,simulator,txResolver:this.stateMachine.txResolver,l2TipsStore:this.stateMachine.l2TipsProvider,hooks:composeHooks({authorizeUtilityCall:this.buildAuthorizeUtilityCallHook(isStaticCall?"private view":"private",authorizedUtilityCallTargets),resolveTaggingSecretStrategy:taggingSecretStrategy?()=>Promise.resolve(taggingSecretStrategy):void 0}),transientArrayService}),result,executionResult;try{executionResult=await executePrivateFunction(simulator,privateExecutionOracle,artifact,targetContractAddress,functionSelector);let publicCallRequests=collectNested([executionResult],r2=>r2.publicInputs.publicCallRequests.getActiveItems().map(r3=>r3.inner).concat(r2.publicInputs.publicTeardownCallRequest.isEmpty()?[]:[r2.publicInputs.publicTeardownCallRequest])),publicFunctionsCalldata=await Promise.all(publicCallRequests.map(async r2=>{let calldata=await privateExecutionOracle.getHashPreimage(r2.calldataHash);return new HashedValues(calldata,r2.calldataHash)}));noteCache.finish();let nonceGenerator=noteCache.getNonceGenerator();result=new PrivateExecutionResult(executionResult,nonceGenerator,publicFunctionsCalldata)}catch(err){throw createSimulationError(err instanceof Error?err:new Error("Unknown error during private execution"))}let{publicInputs}=await generateSimulatedProvingResult(result,(addr,sel)=>anchoredContractData.getDebugFunctionName(addr,sel),this.stateMachine.node,minRevertibleSideEffectCounter),globals=makeGlobalVariables();globals.blockNumber=blockNumber,globals.timestamp=this.nextBlockTimestamp,globals.chainId=this.chainId,globals.version=this.version,globals.gasFees=GasFees.empty();let forkedWorldTrees=await this.stateMachine.synchronizer.nativeWorldStateService.fork(),bindings=this.logger.getBindings(),contractsDB=new PublicContractsDB(new TXEPublicContractDataSource(blockNumber,this.contractStore),bindings),guardedMerkleTrees=new GuardedMerkleTreeOperations(forkedWorldTrees),config2=PublicSimulatorConfig.from({skipFeeEnforcement:!0,collectDebugLogs:!0,collectHints:!1,collectStatistics:!1,collectCallMetadata:!0}),processor=new PublicProcessor(globals,guardedMerkleTrees,contractsDB,new CppPublicTxSimulator(guardedMerkleTrees,contractsDB,globals,config2,bindings),new TestDateProvider,void 0,createLogger("simulator:public-processor",bindings)),tx=await Tx.create({data:publicInputs,chonkProof:ChonkProof.empty(),contractClassLogFields:[],publicFunctionCalldata:result.publicFunctionCalldata}),checkpoint;isStaticCall&&(checkpoint=await ForkCheckpoint.new(forkedWorldTrees));let results=await processor.process([tx]),[processedTx]=results[0],failedTxs=results[1];if(failedTxs.length!==0)throw new Error(`Public execution has failed: ${failedTxs[0].error}`);if(!processedTx.revertCode.isOK())if(processedTx.revertReason){try{await enrichPublicSimulationError(processedTx.revertReason,this.contractStore,this.stateMachine.contractClassService,await this.stateMachine.anchorBlockStore.getBlockHeader(),this.logger)}catch{}throw new Error(`Contract execution has reverted: ${processedTx.revertReason.getMessage()}`)}else throw new Error("Contract execution has reverted");let offchainEffects=collectNested([executionResult],r2=>r2.offchainEffects.map(e2=>e2.data));if(isStaticCall)return await checkpoint.revert(),await forkedWorldTrees.close(),{returnValues:executionResult.returnValues??[],offchainEffects};let txEffect=TxEffect.empty();txEffect.noteHashes=processedTx.txEffect.noteHashes,txEffect.nullifiers=processedTx.txEffect.nullifiers,txEffect.privateLogs=processedTx.txEffect.privateLogs,txEffect.publicLogs=processedTx.txEffect.publicLogs,txEffect.publicDataWrites=processedTx.txEffect.publicDataWrites,txEffect.txHash=new TxHash(new Fr(blockNumber));let l1ToL2Messages=Array(1024).fill(0).map(Fr.zero);await forkedWorldTrees.appendLeaves(MerkleTreeId.L1_TO_L2_MESSAGE_TREE,l1ToL2Messages);let l2Block=await makeTXEBlock(forkedWorldTrees,globals,[txEffect]);return await this.stateMachine.handleL2Block(l2Block),await forkedWorldTrees.close(),{returnValues:executionResult.returnValues??[],offchainEffects}}async publicCallNewFlow(from,targetContractAddress,calldata,isStaticCall,gasSettings){let anchorBlockHeader=await this.stateMachine.anchorBlockStore.getBlockHeader(),anchoredContractData=new AnchoredContractData(this.contractStore,this.stateMachine.contractClassService,anchorBlockHeader);this.logger.verbose(`Executing public function ${await anchoredContractData.getDebugFunctionName(targetContractAddress,FunctionSelector.fromField(calldata[0]))}@${targetContractAddress} isStaticCall=${isStaticCall}`);let blockNumber=await this.getNextBlockNumber(),txContext=new TxContext(this.chainId,this.version,gasSettings),calldataHash=await computeCalldataHash(calldata),calldataHashedValues=new HashedValues(calldata,calldataHash),globals=makeGlobalVariables();globals.blockNumber=blockNumber,globals.timestamp=this.nextBlockTimestamp,globals.chainId=this.chainId,globals.version=this.version,globals.gasFees=GasFees.empty();let forkedWorldTrees=await this.stateMachine.synchronizer.nativeWorldStateService.fork(),bindings2=this.logger.getBindings(),contractsDB=new PublicContractsDB(new TXEPublicContractDataSource(blockNumber,this.contractStore),bindings2),guardedMerkleTrees=new GuardedMerkleTreeOperations(forkedWorldTrees),config2=PublicSimulatorConfig.from({skipFeeEnforcement:!0,collectDebugLogs:!0,collectHints:!1,collectStatistics:!1,collectCallMetadata:!0}),simulator=new CppPublicTxSimulator(guardedMerkleTrees,contractsDB,globals,config2,bindings2),processor=new PublicProcessor(globals,guardedMerkleTrees,contractsDB,simulator,new TestDateProvider,void 0,createLogger("simulator:public-processor",bindings2)),nonRevertibleAccumulatedData=PrivateToPublicAccumulatedData.empty();nonRevertibleAccumulatedData.nullifiers[0]=getSingleTxBlockRequestHash(blockNumber);let revertibleAccumulatedData=PrivateToPublicAccumulatedData.empty();revertibleAccumulatedData.publicCallRequests[0]=new PublicCallRequest(from??AztecAddress.NULL_MSG_SENDER,targetContractAddress,isStaticCall,calldataHash);let inputsForPublic=new PartialPrivateTailPublicInputsForPublic(nonRevertibleAccumulatedData,revertibleAccumulatedData,PublicCallRequest.empty()),constantData=new TxConstantData(anchorBlockHeader,txContext,Fr.zero(),Fr.zero()),txData=new PrivateKernelTailCircuitPublicInputs(constantData,new Gas(0,0),AztecAddress.zero(),0n,inputsForPublic,void 0),tx=await Tx.create({data:txData,chonkProof:ChonkProof.empty(),contractClassLogFields:[],publicFunctionCalldata:[calldataHashedValues]}),checkpoint;isStaticCall&&(checkpoint=await ForkCheckpoint.new(forkedWorldTrees));let results=await processor.process([tx]),[processedTx]=results[0],failedTxs=results[1];if(failedTxs.length!==0)throw new Error(`Public execution has failed: ${failedTxs[0].error}`);if(!processedTx.revertCode.isOK())if(processedTx.revertReason){try{await enrichPublicSimulationError(processedTx.revertReason,this.contractStore,this.stateMachine.contractClassService,anchorBlockHeader,this.logger)}catch{}throw new Error(`Contract execution has reverted: ${processedTx.revertReason.getMessage()}`)}else throw new Error("Contract execution has reverted");let returnValues=results[3][0].values;if(isStaticCall)return await checkpoint.revert(),await forkedWorldTrees.close(),returnValues??[];let txEffect=TxEffect.empty();txEffect.noteHashes=processedTx.txEffect.noteHashes,txEffect.nullifiers=processedTx.txEffect.nullifiers,txEffect.privateLogs=processedTx.txEffect.privateLogs,txEffect.publicLogs=processedTx.txEffect.publicLogs,txEffect.publicDataWrites=processedTx.txEffect.publicDataWrites,txEffect.txHash=new TxHash(new Fr(blockNumber));let l1ToL2Messages=Array(1024).fill(0).map(Fr.zero);await forkedWorldTrees.appendLeaves(MerkleTreeId.L1_TO_L2_MESSAGE_TREE,l1ToL2Messages);let l2Block=await makeTXEBlock(forkedWorldTrees,globals,[txEffect]);return await this.stateMachine.handleL2Block(l2Block),await forkedWorldTrees.close(),returnValues??[]}async executeUtilityFunction(from,targetContractAddress,functionSelector,args,jobId,authorizedUtilityCallTargets){let blockHeader=await this.stateMachine.anchorBlockStore.getBlockHeader(),artifact=await new AnchoredContractData(this.contractStore,this.stateMachine.contractClassService,blockHeader).getFunctionArtifact(targetContractAddress,functionSelector);if(!artifact)throw new Error(`Cannot call ${functionSelector} as there is no artifact found at ${targetContractAddress}.`);await this.stateMachine.contractSyncService.ensureContractSynced(targetContractAddress,functionSelector,async(call2,execScopes)=>{await this.executeUtilityCall(call2,{scopes:execScopes,jobId})},blockHeader,jobId,await this.keyStore.getAccounts());let call=FunctionCall.from({name:artifact.name,to:targetContractAddress,selector:functionSelector,type:FunctionType.UTILITY,hideMsgSender:!1,isStatic:!1,args,returnTypes:[]});return this.executeUtilityCall(call,{from,scopes:await this.keyStore.getAccounts(),jobId,authorizedUtilityCallTargets})}async executeUtilityCall(call,{from=AztecAddress.NULL_MSG_SENDER,scopes,jobId,authorizedUtilityCallTargets=[]}){let anchorBlockHeader=await this.stateMachine.anchorBlockStore.getBlockHeader(),anchoredContractData=new AnchoredContractData(this.contractStore,this.stateMachine.contractClassService,anchorBlockHeader),entryPointArtifact=await anchoredContractData.getFunctionArtifactWithDebugMetadata(call.to,call.selector);if(!entryPointArtifact)throw new Error(`Cannot run function ${call.selector} on ${call.to}: the contract is not registered.`);if(entryPointArtifact.functionType!==FunctionType.UTILITY)throw new Error(`Cannot run ${entryPointArtifact.functionType} function as utility`);this.logger.verbose(`Executing utility function ${entryPointArtifact.name}`,{contract:call.to,selector:call.selector});try{let simulator=new WASMSimulator,utilityExecutor=__name(async(syncCall,execScopes)=>{await this.executeUtilityCall(syncCall,{scopes:execScopes,jobId})},"utilityExecutor"),oracle=new UtilityExecutionOracle({callContext:CallContext.from({msgSender:from,contractAddress:call.to,functionSelector:call.selector,isStaticCall:!0}),authWitnesses:[],capsules:[],anchorBlockHeader,anchoredContractData,noteStore:this.noteStore,keyStore:this.keyStore,addressStore:this.addressStore,aztecNode:this.stateMachine.node,recipientTaggingStore:this.recipientTaggingStore,taggingSecretSourcesStore:this.taggingSecretSourcesStore,capsuleService:new CapsuleService(this.capsuleStore,scopes),factService:new FactService(this.factStore,scopes),privateEventStore:this.privateEventStore,txResolver:this.stateMachine.txResolver,contractSyncService:this.stateMachine.contractSyncService,l2TipsStore:this.stateMachine.l2TipsProvider,jobId,scopes,simulator,hooks:composeHooks({authorizeUtilityCall:this.buildAuthorizeUtilityCallHook("utility",authorizedUtilityCallTargets)}),utilityExecutor,transientArrayService:new TransientArrayService}),acirExecutionResult=await simulator.executeUserCircuit(toACVMWitness(0,call.args),entryPointArtifact,buildACIRCallback(oracle)).catch(err=>{throw err.message=resolveAssertionMessageFromError(err,entryPointArtifact),new ExecutionError(err.message,{contractAddress:call.to,functionSelector:call.selector},extractCallStack(err,entryPointArtifact.debug),{cause:err})});return this.logger.verbose(`Utility execution for ${call.to}.${call.selector} completed`),witnessMapToFields(acirExecutionResult.returnWitness)}catch(err){throw createSimulationError(err instanceof Error?err:new Error("Unknown error during utility execution"))}}close(){return this.logger.debug("Exiting Top Level Context"),[this.nextBlockTimestamp,this.authwits,this.taggingSecretStrategy]}async getLastBlockNumber(){let block=await this.stateMachine.node.getBlock("latest");return block?block.header.globalVariables.blockNumber:BlockNumber.ZERO}buildAuthorizeUtilityCallHook(callerContext,authorizedTargets){if(authorizedTargets.length!==0)return req=>Promise.resolve({authorized:req.callerContext===callerContext&&authorizedTargets.some(t=>t.equals(req.target))})}};var TXEPrivateExecutionOracle=class extends PrivateExecutionOracle{static{__name(this,"TXEPrivateExecutionOracle")}callPrivateFunction(_targetContractAddress,_functionSelector,_argsHash,_sideEffectCounter,_isStaticCall){throw new Error("Contract calls are forbidden inside a `TestEnvironment::private_context`, use `private_call` instead")}assertValidPublicCalldata(_calldataHash){throw new Error("Enqueueing public calls is not supported in TestEnvironment::private_context")}notifyRevertiblePhaseStart(_minRevertibleSideEffectCounter){throw new Error("Enqueueing public calls is not supported in TestEnvironment::private_context")}};var UnavailableOracleError2=class extends Error{static{__name(this,"UnavailableOracleError")}constructor(oracleName){super(`${oracleName} oracles not available with the current handler`)}},RPCTranslator=class{constructor(stateHandler,oracleHandler){this.stateHandler=stateHandler;this.oracleHandler=oracleHandler}static{__name(this,"RPCTranslator")}handlerAsMisc(){if(!("isMisc"in this.oracleHandler))throw new UnavailableOracleError2("Misc");return this.oracleHandler}handlerAsUtility(){if(!("isUtility"in this.oracleHandler))throw new UnavailableOracleError2("Utility");return this.oracleHandler}handlerAsPrivate(){if(!("isPrivate"in this.oracleHandler))throw new UnavailableOracleError2("Private");return this.oracleHandler}handlerAsAvm(){if(!("isAvm"in this.oracleHandler))throw new UnavailableOracleError2("Avm");return this.oracleHandler}handlerAsTxe(){if(!("isTxe"in this.oracleHandler))throw new UnavailableOracleError2("Txe");return this.oracleHandler}aztec_txe_assertCompatibleOracleVersion(...inputs){return callTxeHandler({oracle:"aztec_txe_assertCompatibleOracleVersion",inputs,handler:__name(([major2,minor])=>{this.stateHandler.setTxeOracleVersion(major2,minor)},"handler")})}aztec_txe_setTopLevelTXEContext(){return callTxeHandler({oracle:"aztec_txe_setTopLevelTXEContext",inputs:[],handler:__name(()=>this.stateHandler.enterTopLevelState(),"handler")})}aztec_txe_setPrivateTXEContext(...inputs){return callTxeHandler({oracle:"aztec_txe_setPrivateTXEContext",inputs,handler:__name(([contractAddress,anchorBlockNumber,gasSettings])=>this.stateHandler.enterPrivateState(contractAddress,anchorBlockNumber,gasSettings),"handler")})}aztec_txe_setPublicTXEContext(...inputs){return callTxeHandler({oracle:"aztec_txe_setPublicTXEContext",inputs,handler:__name(([contractAddress])=>this.stateHandler.enterPublicState(contractAddress),"handler")})}aztec_txe_setUtilityTXEContext(...inputs){return callTxeHandler({oracle:"aztec_txe_setUtilityTXEContext",inputs,handler:__name(([contractAddress])=>this.stateHandler.enterUtilityState(contractAddress),"handler")})}aztec_txe_getDefaultAddress(){return callTxeHandler({oracle:"aztec_txe_getDefaultAddress",inputs:[],handler:__name(()=>this.handlerAsTxe().getDefaultAddress(),"handler")})}aztec_txe_getNextBlockNumber(){return callTxeHandler({oracle:"aztec_txe_getNextBlockNumber",inputs:[],handler:__name(()=>this.handlerAsTxe().getNextBlockNumber(),"handler")})}aztec_txe_getNextBlockTimestamp(){return callTxeHandler({oracle:"aztec_txe_getNextBlockTimestamp",inputs:[],handler:__name(()=>this.handlerAsTxe().getNextBlockTimestamp(),"handler")})}aztec_txe_advanceBlocksBy(...inputs){return callTxeHandler({oracle:"aztec_txe_advanceBlocksBy",inputs,handler:__name(([blocks])=>this.handlerAsTxe().advanceBlocksBy(blocks),"handler")})}aztec_txe_advanceTimestampBy(...inputs){return callTxeHandler({oracle:"aztec_txe_advanceTimestampBy",inputs,handler:__name(([duration3])=>this.handlerAsTxe().advanceTimestampBy(duration3),"handler")})}aztec_txe_deploy(...inputs){return callTxeHandler({oracle:"aztec_txe_deploy",inputs,handler:__name(([contractPath,initializer3,_,args,secret,salt,deployer])=>this.handlerAsTxe().deploy(contractPath,initializer3,args,secret,salt,deployer),"handler")})}aztec_txe_createAccount(...inputs){return callTxeHandler({oracle:"aztec_txe_createAccount",inputs,handler:__name(([secret])=>this.handlerAsTxe().createAccount(secret),"handler")})}aztec_txe_addAccount(...inputs){return callTxeHandler({oracle:"aztec_txe_addAccount",inputs,handler:__name(([secret])=>this.handlerAsTxe().addAccount(secret),"handler")})}aztec_txe_addAuthWitness(...inputs){return callTxeHandler({oracle:"aztec_txe_addAuthWitness",inputs,handler:__name(([address,messageHash])=>this.handlerAsTxe().addAuthWitness(address,messageHash),"handler")})}aztec_txe_sendL1ToL2Message(...inputs){return callTxeHandler({oracle:"aztec_txe_sendL1ToL2Message",inputs,handler:__name(([content,secretHash,sender,recipient])=>this.handlerAsTxe().sendL1ToL2Message(content,secretHash,sender,recipient),"handler")})}aztec_txe_setTaggingSecretStrategy(...inputs){return callTxeHandler({oracle:"aztec_txe_setTaggingSecretStrategy",inputs,handler:__name(([strategy])=>this.handlerAsTxe().setTaggingSecretStrategy(strategy),"handler")})}aztec_misc_assertCompatibleOracleVersion(...inputs){return callTxeHandler({oracle:"aztec_misc_assertCompatibleOracleVersion",inputs,handler:__name(([major2,minor])=>this.handlerAsMisc().assertCompatibleOracleVersion(major2,minor),"handler")})}aztec_misc_getRandomField(){return callTxeHandler({oracle:"aztec_misc_getRandomField",inputs:[],handler:__name(()=>this.handlerAsMisc().getRandomField(),"handler")})}aztec_txe_getLastBlockTimestamp(){return callTxeHandler({oracle:"aztec_txe_getLastBlockTimestamp",inputs:[],handler:__name(()=>this.handlerAsTxe().getLastBlockTimestamp(),"handler")})}aztec_txe_getLastTxEffects(){return callTxeHandler({oracle:"aztec_txe_getLastTxEffects",inputs:[],handler:__name(()=>this.handlerAsTxe().getLastTxEffects(),"handler")})}aztec_txe_getLastCallOffchainEffects(){return callTxeHandler({oracle:"aztec_txe_getLastCallOffchainEffects",inputs:[],handler:__name(()=>this.stateHandler.getLastCallOffchainEffects(),"handler")})}aztec_txe_getLastCallContext(){return callTxeHandler({oracle:"aztec_txe_getLastCallContext",inputs:[],handler:__name(()=>this.stateHandler.getLastCallContext(),"handler")})}aztec_txe_getPrivateEvents(...inputs){return callTxeHandler({oracle:"aztec_txe_getPrivateEvents",inputs,handler:__name(([selector,contractAddress,scope])=>this.stateHandler.getPrivateEvents(selector,contractAddress,scope),"handler")})}aztec_prv_setHashPreimage(...inputs){return callTxeHandler({oracle:"aztec_prv_setHashPreimage",inputs,handler:__name(([values,hash5])=>this.handlerAsPrivate().setHashPreimage(values,hash5),"handler")})}aztec_prv_getHashPreimage(...inputs){return callTxeHandler({oracle:"aztec_prv_getHashPreimage",inputs,handler:__name(([hash5])=>this.handlerAsPrivate().getHashPreimage(hash5),"handler")})}aztec_misc_log(...inputs){return callTxeHandler({oracle:"aztec_misc_log",inputs,handler:__name(([level,message,fieldsSize,fields])=>this.handlerAsMisc().log(level,message,fieldsSize,fields),"handler")})}aztec_utl_getFromPublicStorage(...inputs){return callTxeHandler({oracle:"aztec_utl_getFromPublicStorage",inputs,handler:__name(([blockHash,contractAddress,startStorageSlot,numberOfElements])=>this.handlerAsUtility().getFromPublicStorage(blockHash,contractAddress,startStorageSlot,numberOfElements),"handler")})}aztec_utl_getPublicDataWitness(...inputs){return callTxeHandler({oracle:"aztec_utl_getPublicDataWitness",inputs,handler:__name(([blockHash,leafSlot])=>this.handlerAsUtility().getPublicDataWitness(blockHash,leafSlot),"handler")})}aztec_utl_getNotes(...inputs){return callTxeHandler({oracle:"aztec_utl_getNotes",inputs,handler:__name(([owner,storageSlot,numSelects,selectByIndexes,selectByOffsets,selectByLengths,selectValues,selectComparators,sortByIndexes,sortByOffsets,sortByLengths,sortOrder,limit,offset,status,maxNotes,packedHintedNoteLength])=>this.handlerAsUtility().getNotes(owner,storageSlot,numSelects,selectByIndexes,selectByOffsets,selectByLengths,selectValues,selectComparators,sortByIndexes,sortByOffsets,sortByLengths,sortOrder,limit,offset,status,maxNotes,packedHintedNoteLength),"handler")})}aztec_prv_notifyCreatedNote(...inputs){return callTxeHandler({oracle:"aztec_prv_notifyCreatedNote",inputs,handler:__name(([owner,storageSlot,randomness,noteTypeId,note,noteHash,counter])=>this.handlerAsPrivate().notifyCreatedNote(owner,storageSlot,randomness,noteTypeId,note,noteHash,counter),"handler")})}aztec_prv_notifyNullifiedNote(...inputs){return callTxeHandler({oracle:"aztec_prv_notifyNullifiedNote",inputs,handler:__name(([innerNullifier,noteHash,counter])=>this.handlerAsPrivate().notifyNullifiedNote(innerNullifier,noteHash,counter),"handler")})}aztec_prv_notifyCreatedNullifier(...inputs){return callTxeHandler({oracle:"aztec_prv_notifyCreatedNullifier",inputs,handler:__name(([innerNullifier])=>this.handlerAsPrivate().notifyCreatedNullifier(innerNullifier),"handler")})}aztec_prv_isNullifierPending(...inputs){return callTxeHandler({oracle:"aztec_prv_isNullifierPending",inputs,handler:__name(([innerNullifier,contractAddress])=>this.handlerAsPrivate().isNullifierPending(innerNullifier,contractAddress),"handler")})}aztec_utl_doesNullifierExist(...inputs){return callTxeHandler({oracle:"aztec_utl_doesNullifierExist",inputs,handler:__name(([innerNullifier])=>this.handlerAsUtility().doesNullifierExist(innerNullifier),"handler")})}aztec_utl_getContractInstance(...inputs){return callTxeHandler({oracle:"aztec_utl_getContractInstance",inputs,handler:__name(([address])=>this.handlerAsUtility().getContractInstance(address),"handler")})}aztec_utl_getPublicKeysAndPartialAddress(...inputs){return callTxeHandler({oracle:"aztec_utl_getPublicKeysAndPartialAddress",inputs,handler:__name(([address])=>this.handlerAsUtility().getPublicKeysAndPartialAddress(address),"handler")})}aztec_utl_getKeyValidationRequest(...inputs){return callTxeHandler({oracle:"aztec_utl_getKeyValidationRequest",inputs,handler:__name(([pkMHash,keyIndex])=>this.handlerAsUtility().getKeyValidationRequest(pkMHash,keyIndex),"handler")})}aztec_prv_callPrivateFunction(...inputs){return callTxeHandler({oracle:"aztec_prv_callPrivateFunction",inputs,handler:__name(([contractAddress,functionSelector,argsHash,sideEffectCounter,isStaticCall])=>this.handlerAsPrivate().callPrivateFunction(contractAddress,functionSelector,argsHash,sideEffectCounter,isStaticCall),"handler")})}aztec_utl_getNullifierMembershipWitness(...inputs){return callTxeHandler({oracle:"aztec_utl_getNullifierMembershipWitness",inputs,handler:__name(([blockHash,nullifier])=>this.handlerAsUtility().getNullifierMembershipWitness(blockHash,nullifier),"handler")})}aztec_utl_getL1ToL2MembershipWitness(...inputs){return callTxeHandler({oracle:"aztec_utl_getL1ToL2MembershipWitness",inputs,handler:__name(([contractAddress,messageHash,secret])=>this.handlerAsUtility().getL1ToL2MembershipWitness(contractAddress,messageHash,secret),"handler")})}aztec_utl_getAuthWitness(...inputs){return callTxeHandler({oracle:"aztec_utl_getAuthWitness",inputs,handler:__name(([messageHash])=>this.handlerAsUtility().getAuthWitness(messageHash),"handler")})}aztec_prv_assertValidPublicCalldata(...inputs){return callTxeHandler({oracle:"aztec_prv_assertValidPublicCalldata",inputs,handler:__name(([calldataHash])=>this.handlerAsPrivate().assertValidPublicCalldata(calldataHash),"handler")})}aztec_prv_notifyRevertiblePhaseStart(...inputs){return callTxeHandler({oracle:"aztec_prv_notifyRevertiblePhaseStart",inputs,handler:__name(([minRevertibleSideEffectCounter])=>this.handlerAsPrivate().notifyRevertiblePhaseStart(minRevertibleSideEffectCounter),"handler")})}aztec_prv_isExecutionInRevertiblePhase(...inputs){return callTxeHandler({oracle:"aztec_prv_isExecutionInRevertiblePhase",inputs,handler:__name(([sideEffectCounter])=>this.handlerAsPrivate().isExecutionInRevertiblePhase(sideEffectCounter),"handler")})}aztec_utl_getUtilityContext(){return callTxeHandler({oracle:"aztec_utl_getUtilityContext",inputs:[],handler:__name(()=>this.handlerAsUtility().getUtilityContext(),"handler")})}aztec_utl_getBlockHeader(...inputs){return callTxeHandler({oracle:"aztec_utl_getBlockHeader",inputs,handler:__name(([blockNumber])=>this.handlerAsUtility().getBlockHeader(blockNumber),"handler")})}aztec_utl_getNoteHashMembershipWitness(...inputs){return callTxeHandler({oracle:"aztec_utl_getNoteHashMembershipWitness",inputs,handler:__name(([blockHash,noteHash])=>this.handlerAsUtility().getNoteHashMembershipWitness(blockHash,noteHash),"handler")})}aztec_utl_getBlockHashMembershipWitness(...inputs){return callTxeHandler({oracle:"aztec_utl_getBlockHashMembershipWitness",inputs,handler:__name(([anchorBlockHash,blockHash])=>this.handlerAsUtility().getBlockHashMembershipWitness(anchorBlockHash,blockHash),"handler")})}aztec_utl_getLowNullifierMembershipWitness(...inputs){return callTxeHandler({oracle:"aztec_utl_getLowNullifierMembershipWitness",inputs,handler:__name(([blockHash,nullifier])=>this.handlerAsUtility().getLowNullifierMembershipWitness(blockHash,nullifier),"handler")})}aztec_utl_getPendingTaggedLogsV2(...inputs){return callTxeHandler({oracle:"aztec_utl_getPendingTaggedLogsV2",inputs,handler:__name(([scope,providedSecrets])=>this.handlerAsUtility().getPendingTaggedLogsV2(scope,providedSecrets),"handler")})}aztec_utl_validateAndStoreEnqueuedNotesAndEvents(...inputs){return callTxeHandler({oracle:"aztec_utl_validateAndStoreEnqueuedNotesAndEvents",inputs,handler:__name(([noteValidationRequests,eventValidationRequests,scope])=>this.handlerAsUtility().validateAndStoreEnqueuedNotesAndEvents(noteValidationRequests,eventValidationRequests,scope),"handler")})}aztec_utl_getLogsByTagV2(...inputs){return callTxeHandler({oracle:"aztec_utl_getLogsByTagV2",inputs,handler:__name(([requestArrayBaseSlot])=>this.handlerAsUtility().getLogsByTagV2(requestArrayBaseSlot),"handler")})}aztec_utl_getResolvedTxs(...inputs){return callTxeHandler({oracle:"aztec_utl_getResolvedTxs",inputs,handler:__name(([requestArrayBaseSlot])=>this.handlerAsUtility().getResolvedTxs(requestArrayBaseSlot),"handler")})}aztec_utl_setCapsule(...inputs){return callTxeHandler({oracle:"aztec_utl_setCapsule",inputs,handler:__name(([contractAddress,slot,capsule,scope])=>this.handlerAsUtility().setCapsule(contractAddress,slot,capsule,scope),"handler")})}aztec_utl_getCapsule(...inputs){return callTxeHandler({oracle:"aztec_utl_getCapsule",inputs,handler:__name(([contractAddress,slot,tSize,scope])=>this.handlerAsUtility().getCapsule(contractAddress,slot,tSize,scope),"handler")})}aztec_utl_deleteCapsule(...inputs){return callTxeHandler({oracle:"aztec_utl_deleteCapsule",inputs,handler:__name(([contractAddress,slot,scope])=>this.handlerAsUtility().deleteCapsule(contractAddress,slot,scope),"handler")})}aztec_utl_copyCapsule(...inputs){return callTxeHandler({oracle:"aztec_utl_copyCapsule",inputs,handler:__name(([contractAddress,srcSlot,dstSlot,numEntries,scope])=>this.handlerAsUtility().copyCapsule(contractAddress,srcSlot,dstSlot,numEntries,scope),"handler")})}aztec_utl_pushEphemeral(...inputs){return callTxeHandler({oracle:"aztec_utl_pushEphemeral",inputs,handler:__name(([slot,elements])=>this.handlerAsUtility().pushEphemeral(slot,elements),"handler")})}aztec_utl_popEphemeral(...inputs){return callTxeHandler({oracle:"aztec_utl_popEphemeral",inputs,handler:__name(([slot])=>this.handlerAsUtility().popEphemeral(slot),"handler")})}aztec_utl_getEphemeral(...inputs){return callTxeHandler({oracle:"aztec_utl_getEphemeral",inputs,handler:__name(([slot,index])=>this.handlerAsUtility().getEphemeral(slot,index),"handler")})}aztec_utl_setEphemeral(...inputs){return callTxeHandler({oracle:"aztec_utl_setEphemeral",inputs,handler:__name(([slot,index,elements])=>this.handlerAsUtility().setEphemeral(slot,index,elements),"handler")})}aztec_utl_getEphemeralLen(...inputs){return callTxeHandler({oracle:"aztec_utl_getEphemeralLen",inputs,handler:__name(([slot])=>this.handlerAsUtility().getEphemeralLen(slot),"handler")})}aztec_utl_removeEphemeral(...inputs){return callTxeHandler({oracle:"aztec_utl_removeEphemeral",inputs,handler:__name(([slot,index])=>this.handlerAsUtility().removeEphemeral(slot,index),"handler")})}aztec_utl_clearEphemeral(...inputs){return callTxeHandler({oracle:"aztec_utl_clearEphemeral",inputs,handler:__name(([slot])=>this.handlerAsUtility().clearEphemeral(slot),"handler")})}aztec_utl_pushTransient(...inputs){return callTxeHandler({oracle:"aztec_utl_pushTransient",inputs,handler:__name(([slot,elements])=>this.handlerAsUtility().pushTransient(slot,elements),"handler")})}aztec_utl_popTransient(...inputs){return callTxeHandler({oracle:"aztec_utl_popTransient",inputs,handler:__name(([slot])=>this.handlerAsUtility().popTransient(slot),"handler")})}aztec_utl_getTransient(...inputs){return callTxeHandler({oracle:"aztec_utl_getTransient",inputs,handler:__name(([slot,index])=>this.handlerAsUtility().getTransient(slot,index),"handler")})}aztec_utl_setTransient(...inputs){return callTxeHandler({oracle:"aztec_utl_setTransient",inputs,handler:__name(([slot,index,elements])=>this.handlerAsUtility().setTransient(slot,index,elements),"handler")})}aztec_utl_getTransientLen(...inputs){return callTxeHandler({oracle:"aztec_utl_getTransientLen",inputs,handler:__name(([slot])=>this.handlerAsUtility().getTransientLen(slot),"handler")})}aztec_utl_removeTransient(...inputs){return callTxeHandler({oracle:"aztec_utl_removeTransient",inputs,handler:__name(([slot,index])=>this.handlerAsUtility().removeTransient(slot,index),"handler")})}aztec_utl_clearTransient(...inputs){return callTxeHandler({oracle:"aztec_utl_clearTransient",inputs,handler:__name(([slot])=>this.handlerAsUtility().clearTransient(slot),"handler")})}aztec_utl_decryptAes128(...inputs){return callTxeHandler({oracle:"aztec_utl_decryptAes128",inputs,handler:__name(([ciphertext,iv,symKey])=>this.handlerAsUtility().decryptAes128(ciphertext,iv,symKey),"handler")})}aztec_utl_getSharedSecrets(...inputs){return callTxeHandler({oracle:"aztec_utl_getSharedSecrets",inputs,handler:__name(([address,ephPksSlot,contractAddress])=>this.handlerAsUtility().getSharedSecrets(address,ephPksSlot,contractAddress),"handler")})}aztec_utl_setContractSyncCacheInvalid(...inputs){return callTxeHandler({oracle:"aztec_utl_setContractSyncCacheInvalid",inputs,handler:__name(([contractAddress,scopes])=>this.handlerAsUtility().setContractSyncCacheInvalid(contractAddress,scopes),"handler")})}aztec_utl_emitOffchainEffect(...inputs){return callTxeHandler({oracle:"aztec_utl_emitOffchainEffect",inputs,handler:__name(([data])=>{this.stateHandler.recordOffchainEffect(data)},"handler")})}aztec_utl_recordFact(...inputs){return callTxeHandler({oracle:"aztec_utl_recordFact",inputs,handler:__name(([contractAddress,scope,factCollectionTypeId,factCollectionId,factTypeId,payload,originBlock])=>this.handlerAsUtility().recordFact(contractAddress,scope,factCollectionTypeId,factCollectionId,factTypeId,payload,originBlock),"handler")})}aztec_utl_deleteFactCollection(...inputs){return callTxeHandler({oracle:"aztec_utl_deleteFactCollection",inputs,handler:__name(([contractAddress,scope,factCollectionTypeId,factCollectionId])=>this.handlerAsUtility().deleteFactCollection(contractAddress,scope,factCollectionTypeId,factCollectionId),"handler")})}aztec_utl_getFactCollection(...inputs){return callTxeHandler({oracle:"aztec_utl_getFactCollection",inputs,handler:__name(([contractAddress,scope,factCollectionTypeId,factCollectionId])=>this.handlerAsUtility().getFactCollection(contractAddress,scope,factCollectionTypeId,factCollectionId),"handler")})}aztec_utl_getFactCollectionsByType(...inputs){return callTxeHandler({oracle:"aztec_utl_getFactCollectionsByType",inputs,handler:__name(([contractAddress,scope,factCollectionTypeId])=>this.handlerAsUtility().getFactCollectionsByType(contractAddress,scope,factCollectionTypeId),"handler")})}aztec_avm_emitPublicLog(){return callTxeHandler({oracle:"aztec_avm_emitPublicLog",inputs:[],handler:__name(()=>{},"handler")})}aztec_avm_storageRead(...inputs){return callTxeHandler({oracle:"aztec_avm_storageRead",inputs,handler:__name(([slot,contractAddress])=>this.handlerAsAvm().storageRead(slot,contractAddress),"handler")})}aztec_avm_storageWrite(...inputs){return callTxeHandler({oracle:"aztec_avm_storageWrite",inputs,handler:__name(([slot,value])=>this.handlerAsAvm().storageWrite(slot,value),"handler")})}aztec_avm_getContractInstanceDeployer(...inputs){return callTxeHandler({oracle:"aztec_avm_getContractInstanceDeployer",inputs,handler:__name(([address])=>this.handlerAsAvm().getContractInstanceDeployer(address),"handler")})}aztec_avm_getContractInstanceClassId(...inputs){return callTxeHandler({oracle:"aztec_avm_getContractInstanceClassId",inputs,handler:__name(([address])=>this.handlerAsAvm().getContractInstanceClassId(address),"handler")})}aztec_avm_getContractInstanceInitializationHash(...inputs){return callTxeHandler({oracle:"aztec_avm_getContractInstanceInitializationHash",inputs,handler:__name(([address])=>this.handlerAsAvm().getContractInstanceInitializationHash(address),"handler")})}aztec_avm_getContractInstanceImmutablesHash(...inputs){return callTxeHandler({oracle:"aztec_avm_getContractInstanceImmutablesHash",inputs,handler:__name(([address])=>this.handlerAsAvm().getContractInstanceImmutablesHash(address),"handler")})}aztec_avm_sender(){return callTxeHandler({oracle:"aztec_avm_sender",inputs:[],handler:__name(()=>this.handlerAsAvm().sender(),"handler")})}aztec_avm_emitNullifier(...inputs){return callTxeHandler({oracle:"aztec_avm_emitNullifier",inputs,handler:__name(([nullifier])=>this.handlerAsAvm().emitNullifier(nullifier),"handler")})}aztec_avm_emitNoteHash(...inputs){return callTxeHandler({oracle:"aztec_avm_emitNoteHash",inputs,handler:__name(([noteHash])=>this.handlerAsAvm().emitNoteHash(noteHash),"handler")})}aztec_avm_nullifierExists(...inputs){return callTxeHandler({oracle:"aztec_avm_nullifierExists",inputs,handler:__name(([siloedNullifier])=>this.handlerAsAvm().nullifierExists(siloedNullifier),"handler")})}aztec_avm_address(){return callTxeHandler({oracle:"aztec_avm_address",inputs:[],handler:__name(()=>this.handlerAsAvm().address(),"handler")})}aztec_avm_blockNumber(){return callTxeHandler({oracle:"aztec_avm_blockNumber",inputs:[],handler:__name(()=>this.handlerAsAvm().blockNumber(),"handler")})}aztec_avm_timestamp(){return callTxeHandler({oracle:"aztec_avm_timestamp",inputs:[],handler:__name(()=>this.handlerAsAvm().timestamp(),"handler")})}aztec_avm_isStaticCall(){return callTxeHandler({oracle:"aztec_avm_isStaticCall",inputs:[],handler:__name(()=>this.handlerAsAvm().isStaticCall(),"handler")})}aztec_avm_chainId(){return callTxeHandler({oracle:"aztec_avm_chainId",inputs:[],handler:__name(()=>this.handlerAsAvm().chainId(),"handler")})}aztec_avm_version(){return callTxeHandler({oracle:"aztec_avm_version",inputs:[],handler:__name(()=>this.handlerAsAvm().version(),"handler")})}aztec_avm_returndataSize(){return callTxeHandler({oracle:"aztec_avm_returndataSize",inputs:[],handler:__name(()=>this.handlerAsAvm().returndataSize(),"handler")})}aztec_avm_returndataCopy(...inputs){return callTxeHandler({oracle:"aztec_avm_returndataCopy",inputs,handler:__name(([rdOffset,copySize])=>this.handlerAsAvm().returndataCopy(rdOffset,copySize),"handler")})}aztec_avm_call(...inputs){return callTxeHandler({oracle:"aztec_avm_call",inputs,handler:__name(([l2Gas,daGas,address,argsLength,args])=>this.handlerAsAvm().call(l2Gas,daGas,address,argsLength,args),"handler")})}aztec_avm_staticCall(...inputs){return callTxeHandler({oracle:"aztec_avm_staticCall",inputs,handler:__name(([l2Gas,daGas,address,argsLength,args])=>this.handlerAsAvm().staticCall(l2Gas,daGas,address,argsLength,args),"handler")})}aztec_avm_successCopy(){return callTxeHandler({oracle:"aztec_avm_successCopy",inputs:[],handler:__name(()=>this.handlerAsAvm().successCopy(),"handler")})}aztec_txe_privateCallNewFlow(...inputs){return callTxeHandler({oracle:"aztec_txe_privateCallNewFlow",inputs,handler:__name(([from,targetContractAddress,functionSelector,args,argsHash,isStaticCall,additionalScopes,authorizedUtilityCallTargets,gasSettings])=>this.stateHandler.executePrivateCall(from,targetContractAddress,functionSelector,args,argsHash,isStaticCall,additionalScopes,authorizedUtilityCallTargets,gasSettings),"handler")})}aztec_txe_executeUtilityFunction(...inputs){return callTxeHandler({oracle:"aztec_txe_executeUtilityFunction",inputs,handler:__name(([from,targetContractAddress,functionSelector,args,authorizedUtilityCallTargets])=>this.stateHandler.executeUtilityFunction(from,targetContractAddress,functionSelector,args,authorizedUtilityCallTargets),"handler")})}aztec_txe_publicCallNewFlow(...inputs){return callTxeHandler({oracle:"aztec_txe_publicCallNewFlow",inputs,handler:__name(([from,address,calldata,isStaticCall,gasSettings])=>this.stateHandler.executePublicCall(from,address,calldata,isStaticCall,gasSettings),"handler")})}aztec_prv_getSenderForTags(){return callTxeHandler({oracle:"aztec_prv_getSenderForTags",inputs:[],handler:__name(()=>this.handlerAsPrivate().getSenderForTags(),"handler")})}aztec_prv_resolveTaggingStrategy(...inputs){return callTxeHandler({oracle:"aztec_prv_resolveTaggingStrategy",inputs,handler:__name(([sender,recipient,deliveryMode])=>this.handlerAsPrivate().resolveTaggingStrategy(sender,recipient,deliveryMode),"handler")})}aztec_prv_resolveCustomRequest(...inputs){return callTxeHandler({oracle:"aztec_prv_resolveCustomRequest",inputs,handler:__name(([kind,payload])=>this.handlerAsPrivate().resolveCustomRequest(kind,payload),"handler")})}aztec_prv_getAppTaggingSecret(...inputs){return callTxeHandler({oracle:"aztec_prv_getAppTaggingSecret",inputs,handler:__name(([sender,recipient])=>this.handlerAsPrivate().getAppTaggingSecret(sender,recipient),"handler")})}aztec_prv_getNextTaggingIndex(...inputs){return callTxeHandler({oracle:"aztec_prv_getNextTaggingIndex",inputs,handler:__name(([secret,deliveryMode])=>this.handlerAsPrivate().getNextTaggingIndex(secret,deliveryMode),"handler")})}};function computeCheckpointPayloadDigest(args){let consensusPayload=new ConsensusPayload(args.header,args.archiveRoot,args.feeAssetPriceModifier,args.signatureContext);return getHashedSignaturePayloadTypedData(consensusPayload)}__name(computeCheckpointPayloadDigest,"computeCheckpointPayloadDigest");import{RollupContract,SimulationOverridesBuilder}from"@aztec/ethereum/contracts";async function buildCheckpointSimulationOverridesPlan(input){if(input.proposedCheckpointData&&input.invalidateToPendingCheckpointNumber!==void 0)throw new Error("Error in buildCheckpointSimulationOverridesPlan: proposedCheckpointData and invalidateToPendingCheckpointNumber are mutually exclusive");let builder=new SimulationOverridesBuilder,overridenChainTip=derivePendingCheckpointNumber(input)??input.checkpointedCheckpointNumber;if(builder.withChainTips({pending:overridenChainTip,proven:overridenChainTip}),input.proposedCheckpointData){let{header,archive,checkpointOutHash,feeAssetPriceModifier}=input.proposedCheckpointData;builder.withPendingArchive(archive.root),builder.withPendingTempCheckpointLogFields({headerHash:header.hash(),outHash:checkpointOutHash,slotNumber:header.slotNumber,payloadDigest:computeCheckpointPayloadDigest({header,archiveRoot:archive.root,feeAssetPriceModifier,signatureContext:input.signatureContext})});let feeHeader=await computePipelinedParentFeeHeader({checkpointNumber:input.checkpointNumber,proposedCheckpointData:input.proposedCheckpointData,rollup:input.rollup,log:input.log});feeHeader&&builder.withPendingFeeHeader(feeHeader)}return builder.build()}__name(buildCheckpointSimulationOverridesPlan,"buildCheckpointSimulationOverridesPlan");function derivePendingCheckpointNumber(input){if(input.invalidateToPendingCheckpointNumber!==void 0)return input.invalidateToPendingCheckpointNumber;if(!input.proposedCheckpointData)return;if(input.checkpointNumber<1)throw new Error(`Cannot build simulation override for checkpoint ${input.checkpointNumber}: no parent exists`);let expectedParent=CheckpointNumber(input.checkpointNumber-1);if(input.proposedCheckpointData.checkpointNumber!==expectedParent)throw new Error(`Cannot build simulation override for checkpoint ${input.checkpointNumber}: proposedCheckpointData.checkpointNumber (${input.proposedCheckpointData.checkpointNumber}) does not match expected parent ${expectedParent}`);return expectedParent}__name(derivePendingCheckpointNumber,"derivePendingCheckpointNumber");async function computePipelinedParentFeeHeader(input){if(input.checkpointNumber<2)return;let grandparentCheckpointNumber=CheckpointNumber(input.checkpointNumber-2),[grandparentCheckpoint,manaTarget]=await Promise.all([input.rollup.getCheckpoint(grandparentCheckpointNumber),input.rollup.getManaTarget()]);if(!grandparentCheckpoint?.feeHeader)throw new Error(`Grandparent checkpoint or feeHeader missing for checkpoint ${grandparentCheckpointNumber.toString()}`);return RollupContract.computeChildFeeHeader(grandparentCheckpoint.feeHeader,input.proposedCheckpointData.totalManaUsed,input.proposedCheckpointData.feeAssetPriceModifier,manaTarget)}__name(computePipelinedParentFeeHeader,"computePipelinedParentFeeHeader");var CheckpointValidationError=class extends Error{static{__name(this,"CheckpointValidationError")}checkpointNumber;slot;constructor(message,checkpointNumber,slot){super(message),this.checkpointNumber=checkpointNumber,this.slot=slot,this.name="CheckpointValidationError"}};function validateCheckpoint(checkpoint,opts){validateCheckpointStructure(checkpoint,{maxBlocksPerCheckpoint:opts.maxBlocksPerCheckpoint}),validateCheckpointLimits(checkpoint,opts),validateCheckpointBlocksLimits(checkpoint,opts)}__name(validateCheckpoint,"validateCheckpoint");function validateCheckpointStructure(checkpoint,opts={}){let{maxBlocksPerCheckpoint=MAX_ATTESTABLE_BLOCKS_PER_CHECKPOINT}=opts,{blocks,number:number4,slot}=checkpoint;if(blocks.length===0)throw new CheckpointValidationError("Checkpoint has no blocks",number4,slot);if(blocks.length>maxBlocksPerCheckpoint)throw new CheckpointValidationError(`Checkpoint has ${blocks.length} blocks, exceeding limit of ${maxBlocksPerCheckpoint}`,number4,slot);let firstBlock=blocks[0];if(!checkpoint.header.lastArchiveRoot.equals(firstBlock.header.lastArchive.root))throw new CheckpointValidationError("Checkpoint lastArchiveRoot does not match first block's lastArchive root",number4,slot);for(let i=0;i<blocks.length;i++){let block=blocks[i];if(block.indexWithinCheckpoint!==i)throw new CheckpointValidationError(`Block at index ${i} has indexWithinCheckpoint ${block.indexWithinCheckpoint}, expected ${i}`,number4,slot);if(block.slot!==slot)throw new CheckpointValidationError(`Block ${block.number} has slot ${block.slot}, expected ${slot} (all blocks must share the same slot)`,number4,slot);if(!checkpoint.header.matchesGlobalVariables(block.header.globalVariables))throw new CheckpointValidationError(`Block ${block.number} global variables (slot, timestamp, coinbase, feeRecipient, gasFees) do not match checkpoint header`,number4,slot);if(i>0){let prev=blocks[i-1];if(block.number!==prev.number+1)throw new CheckpointValidationError(`Block numbers are not sequential: block at index ${i-1} has number ${prev.number}, block at index ${i} has number ${block.number}`,number4,slot);if(!block.header.lastArchive.root.equals(prev.archive.root))throw new CheckpointValidationError(`Block ${block.number} lastArchive root does not match archive root of block ${prev.number}`,number4,slot)}}}__name(validateCheckpointStructure,"validateCheckpointStructure");function validateCheckpointBlocksLimits(checkpoint,opts){let{maxL2BlockGas,maxDABlockGas,maxTxsPerBlock}=opts;if(maxL2BlockGas!==void 0)for(let block of checkpoint.blocks){let blockL2Gas=block.header.totalManaUsed.toNumber();if(blockL2Gas>maxL2BlockGas)throw new CheckpointValidationError(`Block ${block.number} in checkpoint has L2 gas used ${blockL2Gas} exceeding limit of ${maxL2BlockGas}`,checkpoint.number,checkpoint.slot)}if(maxDABlockGas!==void 0)for(let block of checkpoint.blocks){let blockDAGas=block.computeDAGasUsed();if(blockDAGas>maxDABlockGas)throw new CheckpointValidationError(`Block ${block.number} in checkpoint has DA gas used ${blockDAGas} exceeding limit of ${maxDABlockGas}`,checkpoint.number,checkpoint.slot)}if(maxTxsPerBlock!==void 0)for(let block of checkpoint.blocks){let blockTxCount=block.body.txEffects.length;if(blockTxCount>maxTxsPerBlock)throw new CheckpointValidationError(`Block ${block.number} in checkpoint has ${blockTxCount} txs exceeding limit of ${maxTxsPerBlock}`,checkpoint.number,checkpoint.slot)}}__name(validateCheckpointBlocksLimits,"validateCheckpointBlocksLimits");function validateCheckpointLimits(checkpoint,opts){let{rollupManaLimit,maxTxsPerCheckpoint}=opts,maxBlobFields=6*4096,maxDAGas=MAX_PROCESSABLE_DA_GAS_PER_CHECKPOINT2;if(rollupManaLimit!==void 0){let checkpointMana=sum(checkpoint.blocks.map(block=>block.header.totalManaUsed.toNumber()));if(checkpointMana>rollupManaLimit)throw new CheckpointValidationError(`Checkpoint mana cost ${checkpointMana} exceeds rollup limit of ${rollupManaLimit}`,checkpoint.number,checkpoint.slot)}let checkpointDAGas=sum(checkpoint.blocks.map(block=>block.computeDAGasUsed()));if(checkpointDAGas>maxDAGas)throw new CheckpointValidationError(`Checkpoint DA gas cost ${checkpointDAGas} exceeds limit of ${maxDAGas}`,checkpoint.number,checkpoint.slot);let checkpointBlobFields=checkpoint.toBlobFields().length;if(checkpointBlobFields>maxBlobFields)throw new CheckpointValidationError(`Checkpoint blob field count ${checkpointBlobFields} exceeds limit of ${maxBlobFields}`,checkpoint.number,checkpoint.slot);if(maxTxsPerCheckpoint!==void 0){let checkpointTxCount=sum(checkpoint.blocks.map(block=>block.body.txEffects.length));if(checkpointTxCount>maxTxsPerCheckpoint)throw new CheckpointValidationError(`Checkpoint tx count ${checkpointTxCount} exceeds limit of ${maxTxsPerCheckpoint}`,checkpoint.number,checkpoint.slot)}}__name(validateCheckpointLimits,"validateCheckpointLimits");var ArchiverDataSourceBase=class{static{__name(this,"ArchiverDataSourceBase")}stores;l1Constants;initialHeader;initialBlockHash;genesisArchiveRoot;genesisBlock;genesisBlockData;constructor(stores,l1Constants,initialHeader,initialBlockHash,genesisArchiveRoot){this.stores=stores,this.l1Constants=l1Constants,this.initialHeader=initialHeader,this.initialBlockHash=initialBlockHash,this.genesisArchiveRoot=genesisArchiveRoot;let genesisArchive=new AppendOnlyTreeSnapshot(genesisArchiveRoot,1);this.genesisBlock=new L2Block(genesisArchive,initialHeader,Body.empty(),CheckpointNumber.ZERO,IndexWithinCheckpoint(0)),this.genesisBlockData={header:initialHeader,archive:genesisArchive,blockHash:initialBlockHash,checkpointNumber:CheckpointNumber.ZERO,indexWithinCheckpoint:IndexWithinCheckpoint(0)}}getGenesisBlockHash(){return this.initialBlockHash}getGenesisBlock(){return this.genesisBlock}getGenesisBlockData(){return this.genesisBlockData}isGenesisBlockQuery(query){return"genesis"in query}async isPruneDueAtSlot(slot){if(!this.l1Constants)throw new Error("isPruneDueAtSlot requires l1Constants");let tips=await this.getL2Tips(),proven=tips.proven.checkpoint.number;if(tips.checkpointed.checkpoint.number===proven)return!1;let oldestUnproven=await this.getCheckpointData({number:CheckpointNumber(Number(proven)+1)});if(!oldestUnproven)return!1;let slotTs=getLastL1SlotTimestampForL2Slot(slot,this.l1Constants),slotEpoch=getEpochNumberAtTimestamp(slotTs,this.l1Constants),oldestUnprovenEpoch=getEpochAtSlot(oldestUnproven.header.slotNumber,this.l1Constants),deadlineEpoch=getProofSubmissionDeadlineEpoch(oldestUnprovenEpoch,this.l1Constants);return slotEpoch>=deadlineEpoch}getCheckpointNumber(){return this.stores.blocks.getLatestCheckpointNumber()}getProvenCheckpointNumber(){return this.stores.blocks.getProvenCheckpointNumber()}async getBlockNumber(query){if(!query)return this.stores.blocks.getLatestL2BlockNumber();let resolved=await this.resolveBlockQuery(query);if(resolved!==void 0)return this.isGenesisBlockQuery(resolved)?BlockNumber.ZERO:this.stores.blocks.getBlockNumber(resolved)}resolveCheckpointQuery(query){if("number"in query)return Promise.resolve(query.number);if("slot"in query)return this.stores.blocks.getCheckpointNumberBySlot(query.slot);switch(query.tag){case"checkpointed":return this.stores.blocks.getLatestCheckpointNumber();case"proven":return this.stores.blocks.getProvenCheckpointNumber();case"finalized":return this.stores.blocks.getFinalizedCheckpointNumber()}}async getCheckpoint(query){let number4=await this.resolveCheckpointQuery(query);if(number4===void 0||number4===0)return;let data=await this.stores.blocks.getCheckpointData(number4);if(data)return this.getPublishedCheckpointFromCheckpointData(data)}async getCheckpoints(query){let checkpoints=await this.getCheckpointsData(query);return Promise.all(checkpoints.map(ch=>this.getPublishedCheckpointFromCheckpointData(ch)))}async getCheckpointData(query){let number4=await this.resolveCheckpointQuery(query);if(!(number4===void 0||number4===0))return this.stores.blocks.getCheckpointData(number4)}async getCheckpointsData(query){if("fromSlot"in query)return this.stores.blocks.getCheckpointsBySlot(query.fromSlot,query.limit,query.reverse??!1);if("from"in query)return this.stores.blocks.getRangeOfCheckpoints(query.from,query.limit);let numbers=await this.getCheckpointNumbersForEpoch(query.epoch);return numbers.length>0?this.stores.blocks.getRangeOfCheckpoints(numbers[0],numbers.length):[]}getProposedCheckpointData(query){return!query||"tag"in query?this.stores.blocks.getLastProposedCheckpoint():"number"in query?this.stores.blocks.getProposedCheckpointByNumber(query.number):this.stores.blocks.getProposedCheckpointBySlot(query.slot)}getTxEffect(txHash){return this.stores.blocks.getTxEffect(txHash)}isPendingChainInvalid(){return this.getPendingChainValidationStatus().then(status=>!status.valid)}async getPendingChainValidationStatus(){return await this.stores.blocks.getPendingChainValidationStatus()??{valid:!0}}getPrivateLogsByTags(query){return this.stores.logs.getPrivateLogsByTags(query)}getPublicLogsByTags(query){return this.stores.logs.getPublicLogsByTags(query)}getContractClass(id){return this.stores.contractClasses.getContractClass(id)}getBytecodeCommitment(id){return this.stores.contractClasses.getBytecodeCommitment(id)}getContract(address,timestamp){return this.stores.contractInstances.getContractInstance(address,timestamp)}getContractClassIds(){return this.stores.contractClasses.getContractClassIds()}getDebugFunctionName(_address,selector){return Promise.resolve(this.stores.functionNames.get(selector))}registerContractFunctionSignatures(signatures){return this.stores.functionNames.register(signatures)}getL1ToL2Messages(checkpointNumber){return this.stores.messages.getL1ToL2Messages(checkpointNumber)}getL1ToL2MessageIndex(l1ToL2Message){return this.stores.messages.getL1ToL2MessageIndex(l1ToL2Message)}async getPublishedCheckpointFromCheckpointData(checkpoint){let blocksForCheckpoint=await this.stores.blocks.getBlocksForCheckpoint(checkpoint.checkpointNumber);if(!blocksForCheckpoint)throw new Error(`Blocks for checkpoint ${checkpoint.checkpointNumber} not found`);let fullCheckpoint=new Checkpoint(checkpoint.archive,checkpoint.header,blocksForCheckpoint,checkpoint.checkpointNumber,checkpoint.feeAssetPriceModifier);return new PublishedCheckpoint(fullCheckpoint,checkpoint.l1,checkpoint.attestations)}getBlocksForSlot(slotNumber){return this.stores.blocks.getBlocksForSlot(slotNumber)}getCheckpointNumbersForEpoch(epochNumber){if(!this.l1Constants)throw new Error("L1 constants not set");let[start,end]=getSlotRangeForEpoch(epochNumber,this.l1Constants);return this.stores.blocks.getCheckpointNumbersForSlotRange(start,end)}async getBlock(query){let resolved=await this.resolveBlockQuery(query);if(resolved!==void 0)return this.isGenesisBlockQuery(resolved)?this.getGenesisBlock():this.stores.blocks.getBlock(resolved)}async getBlocks(query){let resolved=await this.resolveBlocksQuery(query);return resolved?this.stores.blocks.getBlocks(resolved):[]}async getBlockData(query){let resolved=await this.resolveBlockQuery(query);if(resolved!==void 0)return this.isGenesisBlockQuery(resolved)?this.getGenesisBlockData():this.stores.blocks.getBlockData(resolved)}async getBlocksData(query){let resolved=await this.resolveBlocksQuery(query);return resolved?this.stores.blocks.getBlocksData(resolved):[]}async resolveBlockQuery(query){if("number"in query)return query.number===BlockNumber.ZERO?{genesis:!0}:query;if("hash"in query)return query.hash.equals(this.initialBlockHash)?{genesis:!0}:query;if("archive"in query)return query.archive.equals(this.genesisArchiveRoot)?{genesis:!0}:query;let number4=await this.resolveBlockTag(query.tag);return number4===BlockNumber.ZERO?{genesis:!0}:{number:number4}}resolveBlockTag(tag){switch(tag){case"latest":case"proposed":return this.stores.blocks.getLatestL2BlockNumber();case"checkpointed":return this.stores.blocks.getCheckpointedL2BlockNumber();case"proven":return this.stores.blocks.getProvenBlockNumber();case"finalized":return this.stores.blocks.getFinalizedL2BlockNumber()}}async resolveBlocksQuery(query){if(!("epoch"in query)){if(query.from<INITIAL_L2_BLOCK_NUM2)throw new Error(`getBlocks/getBlocksData: 'from' must be >= ${INITIAL_L2_BLOCK_NUM2}, got ${query.from}. Use getBlock({number:0})/getBlockData({number:0}) for genesis-aware single-block lookups.`);return query}let checkpointNumbers=await this.getCheckpointNumbersForEpoch(query.epoch);if(checkpointNumbers.length===0)return;let firstNumber=checkpointNumbers[0],lastNumber=checkpointNumbers[checkpointNumbers.length-1],first=await this.stores.blocks.getCheckpointData(firstNumber);if(!first)return;let last=firstNumber===lastNumber?first:await this.stores.blocks.getCheckpointData(lastNumber);if(!last)return;let from=BlockNumber(first.startBlock),limit=last.startBlock+last.blockCount-first.startBlock;return{from,limit,onlyCheckpointed:!0}}};var Operation=(function(Operation2){return Operation2[Operation2.Store=0]="Store",Operation2[Operation2.Delete=1]="Delete",Operation2})(Operation||{}),ArchiverDataStoreUpdater=class{static{__name(this,"ArchiverDataStoreUpdater")}stores;l2TipsCache;opts;log;constructor(stores,l2TipsCache,opts={}){this.stores=stores,this.l2TipsCache=l2TipsCache,this.opts=opts,this.log=createLogger("archiver:store_updater")}async addProposedBlock(block,pendingChainValidationStatus){let result=await this.stores.db.transactionAsync(async()=>(await this.stores.blocks.addProposedBlock(block),(await Promise.all([pendingChainValidationStatus&&this.stores.blocks.setPendingChainValidationStatus(pendingChainValidationStatus),this.stores.logs.addLogs([block]),this.addContractDataToDb(block)])).every(Boolean)));return await this.l2TipsCache?.refresh(),result}async addCheckpoints(checkpoints,pendingChainValidationStatus,promoteProposed,evictProposedFrom){for(let checkpoint of checkpoints)validateCheckpoint(checkpoint.checkpoint,{rollupManaLimit:this.opts?.rollupManaLimit,maxBlocksPerCheckpoint:MAX_CAPACITY_BLOCKS_PER_CHECKPOINT});promoteProposed&&validateCheckpoint(promoteProposed.checkpoint.checkpoint,{rollupManaLimit:this.opts?.rollupManaLimit,maxBlocksPerCheckpoint:MAX_CAPACITY_BLOCKS_PER_CHECKPOINT});let result=await this.stores.db.transactionAsync(async()=>{let{prunedBlocks,lastAlreadyInsertedBlockNumber}=await this.pruneMismatchingLocalBlocks(checkpoints),newBlocks=(await this.stores.blocks.addCheckpoints(checkpoints)).flatMap(ch=>ch.checkpoint.blocks).filter(b=>lastAlreadyInsertedBlockNumber===void 0||b.number>lastAlreadyInsertedBlockNumber);return await Promise.all([pendingChainValidationStatus&&this.stores.blocks.setPendingChainValidationStatus(pendingChainValidationStatus),this.stores.logs.addLogs(newBlocks),...newBlocks.map(block=>this.addContractDataToDb(block)),promoteProposed?this.stores.blocks.promoteProposedToCheckpointed(promoteProposed.checkpoint.checkpoint.number,promoteProposed.l1,promoteProposed.attestations,promoteProposed.checkpoint.checkpoint.archive.root):void 0,evictProposedFrom!==void 0?this.stores.blocks.evictProposedCheckpointsFrom(evictProposedFrom):void 0]),{prunedBlocks,lastAlreadyInsertedBlockNumber}});return await this.l2TipsCache?.refresh(),result}async addProposedCheckpoint(proposedCheckpoint){let result=await this.stores.db.transactionAsync(async()=>{await this.stores.blocks.addProposedCheckpoint(proposedCheckpoint)});return await this.l2TipsCache?.refresh(),result}async pruneMismatchingLocalBlocks(checkpoints){let[lastCheckpointedBlockNumber,lastBlockNumber]=await Promise.all([this.stores.blocks.getCheckpointedL2BlockNumber(),this.stores.blocks.getLatestL2BlockNumber()]);if(lastBlockNumber===lastCheckpointedBlockNumber)return{prunedBlocks:void 0,lastAlreadyInsertedBlockNumber:void 0};let uncheckpointedLocalBlocks=await this.stores.blocks.getBlocksData({from:BlockNumber.add(lastCheckpointedBlockNumber,1),limit:lastBlockNumber-lastCheckpointedBlockNumber}),lastAlreadyInsertedBlockNumber;for(let publishedCheckpoint of checkpoints){let checkpointBlocks=publishedCheckpoint.checkpoint.blocks,slot=publishedCheckpoint.checkpoint.slot;if(checkpointBlocks.length===0){this.log.warn(`Checkpoint ${publishedCheckpoint.checkpoint.number} for slot ${slot} has no blocks`);continue}for(let checkpointBlock of checkpointBlocks){let blockNumber=checkpointBlock.number,existingBlock=uncheckpointedLocalBlocks.find(b=>b.header.getBlockNumber()===blockNumber),blockInfos={existingBlock:existingBlock?.header.toInspect(),checkpointBlock:checkpointBlock.toBlockInfo()};if(!existingBlock)this.log.verbose(`No local block found for checkpointed block number ${blockNumber}`,blockInfos);else if(existingBlock.archive.root.equals(checkpointBlock.archive.root))this.log.verbose(`Block number ${blockNumber} already inserted and matches checkpoint`,blockInfos),lastAlreadyInsertedBlockNumber=blockNumber;else{this.log.info(`Conflict detected at block ${blockNumber} between checkpointed and local block`,blockInfos);let prunedBlocks=await this.removeBlocksAfter(BlockNumber(blockNumber-1));return await this.evictProposedCheckpointsForPrunedBlocks(prunedBlocks),{prunedBlocks,lastAlreadyInsertedBlockNumber}}}let lastCheckpointBlockNumber=checkpointBlocks.at(-1).number,lastLocalBlockNumber=uncheckpointedLocalBlocks.filter(b=>b.header.getSlot()===slot).at(-1)?.header.getBlockNumber();if(lastLocalBlockNumber!==void 0&&lastLocalBlockNumber>lastCheckpointBlockNumber){this.log.warn(`Local chain for slot ${slot} ends at block ${lastLocalBlockNumber} but checkpoint ends at ${lastCheckpointBlockNumber}. Pruning blocks after block ${lastCheckpointBlockNumber}.`);let prunedBlocks=await this.removeBlocksAfter(lastCheckpointBlockNumber);return await this.evictProposedCheckpointsForPrunedBlocks(prunedBlocks),{prunedBlocks,lastAlreadyInsertedBlockNumber}}}return{prunedBlocks:void 0,lastAlreadyInsertedBlockNumber}}async removeUncheckpointedBlocksAfter(blockNumber){let result=await this.stores.db.transactionAsync(async()=>{let lastCheckpointedBlockNumber=await this.stores.blocks.getCheckpointedL2BlockNumber();if(blockNumber<lastCheckpointedBlockNumber)throw new Error(`Cannot remove blocks after ${blockNumber} because checkpointed blocks exist up to ${lastCheckpointedBlockNumber}`);let prunedBlocks=await this.removeBlocksAfter(blockNumber);return await this.evictProposedCheckpointsForPrunedBlocks(prunedBlocks),prunedBlocks});return await this.l2TipsCache?.refresh(),result}async removeBlocksWithoutProposedCheckpointAfter(blockNumber){let result=await this.stores.db.transactionAsync(async()=>{let lastCheckpointedBlockNumber=await this.stores.blocks.getProposedCheckpointL2BlockNumber();if(blockNumber<lastCheckpointedBlockNumber)throw new Error(`Cannot remove blocks after ${blockNumber} because proposed checkpointed blocks exist up to ${lastCheckpointedBlockNumber}`);return await this.removeBlocksAfter(blockNumber)});return await this.l2TipsCache?.refresh(),result}async evictProposedCheckpointsForPrunedBlocks(prunedBlocks){if(prunedBlocks.length===0)return;let fromCheckpointNumber=prunedBlocks[0].checkpointNumber;await this.stores.blocks.evictProposedCheckpointsFrom(fromCheckpointNumber)}async removeBlocksAfter(blockNumber){let removedBlocks=await this.stores.blocks.removeBlocksAfter(blockNumber);return await Promise.all([this.stores.logs.deleteLogs(removedBlocks),...removedBlocks.map(block=>this.removeContractDataFromDb(block))]),removedBlocks}async removeCheckpointsAfter(checkpointNumber){let result=await this.stores.db.transactionAsync(async()=>{let{blocksRemoved=[]}=await this.stores.blocks.removeCheckpointsAfter(checkpointNumber);return(await Promise.all([this.stores.blocks.setPendingChainValidationStatus({valid:!0}),...blocksRemoved.map(block=>this.removeContractDataFromDb(block)),this.stores.logs.deleteLogs(blocksRemoved)])).every(Boolean)});return await this.l2TipsCache?.refresh(),result}async setProvenCheckpointNumber(checkpointNumber){await this.stores.db.transactionAsync(async()=>{await this.stores.blocks.setProvenCheckpointNumber(checkpointNumber)}),await this.l2TipsCache?.refresh()}async setFinalizedCheckpointNumber(checkpointNumber){await this.stores.db.transactionAsync(async()=>{await this.stores.blocks.setFinalizedCheckpointNumber(checkpointNumber)}),await this.l2TipsCache?.refresh()}addContractDataToDb(block){return this.updateContractDataOnDb(block,0)}removeContractDataFromDb(block){return this.updateContractDataOnDb(block,1)}async updateContractDataOnDb(block,operation){let contractClassLogs=block.body.txEffects.flatMap(txEffect=>txEffect.contractClassLogs),privateLogs=block.body.txEffects.flatMap(txEffect=>txEffect.privateLogs),publicLogs=block.body.txEffects.flatMap(txEffect=>txEffect.publicLogs);return(await Promise.all([this.updatePublishedContractClasses(contractClassLogs,block.number,operation),this.updateDeployedContractInstances(privateLogs,block.number,operation),this.updateUpdatedContractInstances(publicLogs,block.header.globalVariables.timestamp,operation)])).every(Boolean)}async updatePublishedContractClasses(allLogs,blockNum,operation){let contractClassPublishedEvents=allLogs.filter(log2=>ContractClassPublishedEvent.isContractClassPublishedEvent(log2)).map(log2=>ContractClassPublishedEvent.fromLog(log2));if(operation==1){let contractClasses2=contractClassPublishedEvents.map(e2=>e2.toContractClassPublic());return contractClasses2.length>0?(contractClasses2.forEach(c2=>this.log.verbose(`${Operation[operation]} contract class ${c2.id.toString()}`)),await this.stores.contractClasses.deleteContractClasses(contractClasses2,blockNum)):!0}let contractClasses=[];for(let event of contractClassPublishedEvents){let contractClass=await event.toContractClassPublicWithBytecodeCommitment(),computedClassId=await computeContractClassId({artifactHash:contractClass.artifactHash,privateFunctionsRoot:contractClass.privateFunctionsRoot,publicBytecodeCommitment:contractClass.publicBytecodeCommitment});if(!computedClassId.equals(contractClass.id)){this.log.warn(`Skipping contract class with mismatched id at block ${blockNum}. Claimed ${contractClass.id}, computed ${computedClassId}`,{blockNum,contractClassId:event.contractClassId.toString()});continue}contractClasses.push(contractClass)}return contractClasses.length>0?(contractClasses.forEach(c2=>this.log.verbose(`${Operation[operation]} contract class ${c2.id.toString()}`)),await this.stores.contractClasses.addContractClasses(contractClasses,blockNum)):!0}async updateDeployedContractInstances(allLogs,blockNum,operation){let allInstances=allLogs.filter(log2=>ContractInstancePublishedEvent.isContractInstancePublishedEvent(log2)).map(log2=>ContractInstancePublishedEvent.fromLog(log2)).map(e2=>e2.toContractInstance()),contractInstances=operation===1?allInstances:await filterAsync(allInstances,async instance=>{let computedAddress=await computeContractAddressFromInstance(instance);return computedAddress.equals(instance.address)?!0:(this.log.warn(`Found contract instance with mismatched address at block ${blockNum}. Claimed ${instance.address} but computed ${computedAddress}.`,{instanceAddress:instance.address.toString(),computedAddress:computedAddress.toString(),blockNum}),!1)});if(contractInstances.length>0){if(contractInstances.forEach(c2=>this.log.verbose(`${Operation[operation]} contract instance at ${c2.address.toString()}`)),operation==0)return await this.stores.contractInstances.addContractInstances(contractInstances,blockNum);if(operation==1)return await this.stores.contractInstances.deleteContractInstances(contractInstances)}return!0}async updateUpdatedContractInstances(allLogs,timestamp,operation){let contractUpdates=allLogs.filter(log2=>ContractInstanceUpdatedEvent.isContractInstanceUpdatedEvent(log2)).map(log2=>ContractInstanceUpdatedEvent.fromLog(log2)).map(e2=>e2.toContractInstanceUpdate());if(contractUpdates.length>0){if(contractUpdates.forEach(c2=>this.log.verbose(`${Operation[operation]} contract instance update at ${c2.address.toString()}`)),operation==0)return await this.stores.contractInstances.addContractInstanceUpdates(contractUpdates,timestamp);if(operation==1)return await this.stores.contractInstances.deleteContractInstanceUpdates(contractUpdates,timestamp)}return!0}};var CheckpointMergeRollupPrivateInputs=class _CheckpointMergeRollupPrivateInputs{static{__name(this,"CheckpointMergeRollupPrivateInputs")}previousRollups;constructor(previousRollups){this.previousRollups=previousRollups}toBuffer(){return serializeToBuffer(this.previousRollups)}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _CheckpointMergeRollupPrivateInputs([ProofData.fromBuffer(reader,CheckpointRollupPublicInputs),ProofData.fromBuffer(reader,CheckpointRollupPublicInputs)])}toString(){return bufferToHex(this.toBuffer())}static fromString(str){return _CheckpointMergeRollupPrivateInputs.fromBuffer(hexToBuffer(str))}toJSON(){return this.toBuffer()}static get schema(){return bufferSchemaFor(_CheckpointMergeRollupPrivateInputs)}};var CheckpointRootRollupHints=class _CheckpointRootRollupHints{static{__name(this,"CheckpointRootRollupHints")}previousBlockHeader;previousArchiveSiblingPath;previousOutHash;newOutHashSiblingPath;startBlobAccumulator;finalBlobChallenges;blobFields;blobCommitments;blobsHash;constructor(previousBlockHeader,previousArchiveSiblingPath,previousOutHash,newOutHashSiblingPath,startBlobAccumulator,finalBlobChallenges,blobFields,blobCommitments,blobsHash){this.previousBlockHeader=previousBlockHeader,this.previousArchiveSiblingPath=previousArchiveSiblingPath,this.previousOutHash=previousOutHash,this.newOutHashSiblingPath=newOutHashSiblingPath,this.startBlobAccumulator=startBlobAccumulator,this.finalBlobChallenges=finalBlobChallenges,this.blobFields=blobFields,this.blobCommitments=blobCommitments,this.blobsHash=blobsHash}static from(fields){return new _CheckpointRootRollupHints(..._CheckpointRootRollupHints.getFields(fields))}static getFields(fields){return[fields.previousBlockHeader,fields.previousArchiveSiblingPath,fields.previousOutHash,fields.newOutHashSiblingPath,fields.startBlobAccumulator,fields.finalBlobChallenges,fields.blobFields,fields.blobCommitments,fields.blobsHash]}toBuffer(){return serializeToBuffer(..._CheckpointRootRollupHints.getFields(this))}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _CheckpointRootRollupHints(BlockHeader.fromBuffer(reader),reader.readArray(30,Fr),reader.readObject(AppendOnlyTreeSnapshot),reader.readArray(5,Fr),reader.readObject(BlobAccumulator),reader.readObject(FinalBlobBatchingChallenges),Array.from({length:4096*6},()=>Fr.fromBuffer(reader)),reader.readArray(6,BLS12Point),Fr.fromBuffer(reader))}toString(){return bufferToHex(this.toBuffer())}static fromString(str){return _CheckpointRootRollupHints.fromBuffer(hexToBuffer(str))}toJSON(){return this.toBuffer()}static get schema(){return bufferSchemaFor(_CheckpointRootRollupHints)}},CheckpointRootRollupPrivateInputs=class _CheckpointRootRollupPrivateInputs{static{__name(this,"CheckpointRootRollupPrivateInputs")}previousRollups;hints;constructor(previousRollups,hints){this.previousRollups=previousRollups,this.hints=hints}static from(fields){return new _CheckpointRootRollupPrivateInputs(..._CheckpointRootRollupPrivateInputs.getFields(fields))}static getFields(fields){return[fields.previousRollups,fields.hints]}toBuffer(){return serializeToBuffer(..._CheckpointRootRollupPrivateInputs.getFields(this))}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _CheckpointRootRollupPrivateInputs([ProofData.fromBuffer(reader,BlockRollupPublicInputs),ProofData.fromBuffer(reader,BlockRollupPublicInputs)],CheckpointRootRollupHints.fromBuffer(reader))}toString(){return bufferToHex(this.toBuffer())}static fromString(str){return _CheckpointRootRollupPrivateInputs.fromBuffer(hexToBuffer(str))}toJSON(){return this.toBuffer()}static get schema(){return bufferSchemaFor(_CheckpointRootRollupPrivateInputs)}},CheckpointRootSingleBlockRollupPrivateInputs=class _CheckpointRootSingleBlockRollupPrivateInputs{static{__name(this,"CheckpointRootSingleBlockRollupPrivateInputs")}previousRollup;hints;constructor(previousRollup,hints){this.previousRollup=previousRollup,this.hints=hints}static from(fields){return new _CheckpointRootSingleBlockRollupPrivateInputs(..._CheckpointRootSingleBlockRollupPrivateInputs.getFields(fields))}static getFields(fields){return[fields.previousRollup,fields.hints]}toBuffer(){return serializeToBuffer(..._CheckpointRootSingleBlockRollupPrivateInputs.getFields(this))}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _CheckpointRootSingleBlockRollupPrivateInputs(ProofData.fromBuffer(reader,BlockRollupPublicInputs),CheckpointRootRollupHints.fromBuffer(reader))}toString(){return bufferToHex(this.toBuffer())}static fromString(str){return _CheckpointRootSingleBlockRollupPrivateInputs.fromBuffer(hexToBuffer(str))}toJSON(){return this.toBuffer()}static get schema(){return bufferSchemaFor(_CheckpointRootSingleBlockRollupPrivateInputs)}},CheckpointPaddingRollupPrivateInputs=class _CheckpointPaddingRollupPrivateInputs{static{__name(this,"CheckpointPaddingRollupPrivateInputs")}constructor(){}toBuffer(){return Buffer.alloc(0)}static fromBuffer(_buffer){return new _CheckpointPaddingRollupPrivateInputs}toString(){return"0x"}static fromString(_str){return new _CheckpointPaddingRollupPrivateInputs}toJSON(){return this.toBuffer()}static get schema(){return bufferSchemaFor(_CheckpointPaddingRollupPrivateInputs)}};var PublicChonkVerifierPrivateInputs=class _PublicChonkVerifierPrivateInputs{static{__name(this,"PublicChonkVerifierPrivateInputs")}hidingKernelProofData;proverId;constructor(hidingKernelProofData,proverId){this.hidingKernelProofData=hidingKernelProofData,this.proverId=proverId}static from(fields){return new _PublicChonkVerifierPrivateInputs(..._PublicChonkVerifierPrivateInputs.getFields(fields))}static getFields(fields){return[fields.hidingKernelProofData,fields.proverId]}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _PublicChonkVerifierPrivateInputs(ProofData.fromBuffer(reader,PrivateToPublicKernelCircuitPublicInputs),Fr.fromBuffer(reader))}toBuffer(){return serializeToBuffer(..._PublicChonkVerifierPrivateInputs.getFields(this))}static fromString(str){return _PublicChonkVerifierPrivateInputs.fromBuffer(hexToBuffer(str))}toString(){return bufferToHex(this.toBuffer())}toJSON(){return this.toBuffer()}static get schema(){return bufferSchemaFor(_PublicChonkVerifierPrivateInputs)}};var RootRollupPrivateInputs=class _RootRollupPrivateInputs{static{__name(this,"RootRollupPrivateInputs")}previousRollups;constructor(previousRollups){this.previousRollups=previousRollups}toBuffer(){return serializeToBuffer(..._RootRollupPrivateInputs.getFields(this))}toString(){return bufferToHex(this.toBuffer())}static from(fields){return new _RootRollupPrivateInputs(..._RootRollupPrivateInputs.getFields(fields))}static getFields(fields){return[fields.previousRollups]}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _RootRollupPrivateInputs([ProofData.fromBuffer(reader,CheckpointRollupPublicInputs),ProofData.fromBuffer(reader,CheckpointRollupPublicInputs)])}static fromString(str){return _RootRollupPrivateInputs.fromBuffer(hexToBuffer(str))}toJSON(){return this.toBuffer()}static get schema(){return bufferSchemaFor(_RootRollupPrivateInputs)}};var BlockNumberNotSequentialError=class extends Error{static{__name(this,"BlockNumberNotSequentialError")}constructor(newBlockNumber,previous){super(`Cannot insert new block ${newBlockNumber} given previous block number is ${previous??"undefined"}`),this.name="BlockNumberNotSequentialError"}},InitialCheckpointNumberNotSequentialError=class extends Error{static{__name(this,"InitialCheckpointNumberNotSequentialError")}newCheckpointNumber;previousCheckpointNumber;constructor(newCheckpointNumber,previousCheckpointNumber){super(`Cannot insert new checkpoint ${newCheckpointNumber} given previous checkpoint number in store is ${previousCheckpointNumber??"undefined"}`),this.newCheckpointNumber=newCheckpointNumber,this.previousCheckpointNumber=previousCheckpointNumber,this.name="InitialCheckpointNumberNotSequentialError"}},CheckpointNumberNotSequentialError=class extends Error{static{__name(this,"CheckpointNumberNotSequentialError")}newCheckpointNumber;previousCheckpointNumber;constructor(newCheckpointNumber,previousCheckpointNumber,source){let qualifier=source?`${source} `:"";super(`Cannot insert new checkpoint ${newCheckpointNumber} given previous ${qualifier}checkpoint number is ${previousCheckpointNumber??"undefined"}`),this.newCheckpointNumber=newCheckpointNumber,this.previousCheckpointNumber=previousCheckpointNumber,this.name="CheckpointNumberNotSequentialError"}},BlockCheckpointNumberNotSequentialError=class extends Error{static{__name(this,"BlockCheckpointNumberNotSequentialError")}constructor(blockNumber,blockCheckpointNumber,previous){super(`Cannot insert new block ${blockNumber} for checkpoint ${blockCheckpointNumber} given previous checkpoint number is ${previous??"undefined"}`),this.name="BlockCheckpointNumberNotSequentialError"}},BlockIndexNotSequentialError=class extends Error{static{__name(this,"BlockIndexNotSequentialError")}constructor(newBlockIndex,previousBlockIndex){super(`Cannot insert new block at checkpoint index ${newBlockIndex} given previous block index is ${previousBlockIndex??"undefined"}`),this.name="BlockIndexNotSequentialError"}},BlockArchiveNotConsistentError=class extends Error{static{__name(this,"BlockArchiveNotConsistentError")}constructor(newBlockNumber,previousBlockNumber,newBlockArchive,previousBlockArchive){super(`Cannot insert new block number ${newBlockNumber} with archive ${newBlockArchive.toString()} previous block number is ${previousBlockNumber??"undefined"}, previous archive is ${previousBlockArchive?.toString()??"undefined"}`),this.name="BlockArchiveNotConsistentError"}},CheckpointNotFoundError=class extends Error{static{__name(this,"CheckpointNotFoundError")}constructor(checkpointNumber){super(`Failed to find expected checkpoint number ${checkpointNumber}`),this.name="CheckpointNotFoundError"}},BlockNotFoundError=class extends Error{static{__name(this,"BlockNotFoundError")}constructor(blockNumber){super(`Failed to find expected block number ${blockNumber}`),this.name="BlockNotFoundError"}},BlockAlreadyCheckpointedError=class extends Error{static{__name(this,"BlockAlreadyCheckpointedError")}blockNumber;constructor(blockNumber){super(`Block ${blockNumber} has already been checkpointed with the same content`),this.blockNumber=blockNumber,this.name="BlockAlreadyCheckpointedError"}},L1ToL2MessagesNotReadyError=class extends Error{static{__name(this,"L1ToL2MessagesNotReadyError")}checkpointNumber;inboxTreeInProgress;constructor(checkpointNumber,inboxTreeInProgress){super(`Cannot get L1 to L2 messages for checkpoint ${checkpointNumber}: inbox tree in progress is ${inboxTreeInProgress}, messages not yet sealed`),this.checkpointNumber=checkpointNumber,this.inboxTreeInProgress=inboxTreeInProgress,this.name="L1ToL2MessagesNotReadyError"}};var ProposedCheckpointNotSequentialError=class extends Error{static{__name(this,"ProposedCheckpointNotSequentialError")}proposedCheckpointNumber;latestTipNumber;constructor(proposedCheckpointNumber,latestTipNumber){super(`Proposed checkpoint ${proposedCheckpointNumber} is not sequential: expected ${latestTipNumber+1} (latest tip + 1, where tip is highest of confirmed or pending)`),this.proposedCheckpointNumber=proposedCheckpointNumber,this.latestTipNumber=latestTipNumber,this.name="ProposedCheckpointNotSequentialError"}};var NoProposedCheckpointToPromoteError=class extends Error{static{__name(this,"NoProposedCheckpointToPromoteError")}constructor(){super("Cannot promote proposed checkpoint: no proposed checkpoint exists"),this.name="NoProposedCheckpointToPromoteError"}},ProposedCheckpointArchiveRootMismatchError=class extends Error{static{__name(this,"ProposedCheckpointArchiveRootMismatchError")}expectedArchiveRoot;actualArchiveRoot;constructor(expectedArchiveRoot,actualArchiveRoot){super(`Cannot promote proposed checkpoint: archive root mismatch (expected ${expectedArchiveRoot}, got ${actualArchiveRoot})`),this.expectedArchiveRoot=expectedArchiveRoot,this.actualArchiveRoot=actualArchiveRoot,this.name="ProposedCheckpointArchiveRootMismatchError"}},ProposedCheckpointPromotionNotSequentialError=class extends Error{static{__name(this,"ProposedCheckpointPromotionNotSequentialError")}proposedCheckpointNumber;latestCheckpointNumber;constructor(proposedCheckpointNumber,latestCheckpointNumber){super(`Cannot promote proposed checkpoint: not sequential (latest ${latestCheckpointNumber}, proposed ${proposedCheckpointNumber})`),this.proposedCheckpointNumber=proposedCheckpointNumber,this.latestCheckpointNumber=latestCheckpointNumber,this.name="ProposedCheckpointPromotionNotSequentialError"}},CannotOverwriteCheckpointedBlockError=class extends Error{static{__name(this,"CannotOverwriteCheckpointedBlockError")}blockNumber;lastCheckpointedBlock;constructor(blockNumber,lastCheckpointedBlock){super(`Cannot add block ${blockNumber}: would overwrite checkpointed data (checkpointed up to block ${lastCheckpointedBlock})`),this.blockNumber=blockNumber,this.lastCheckpointedBlock=lastCheckpointedBlock,this.name="CannotOverwriteCheckpointedBlockError"}};var BlockStore=class{static{__name(this,"BlockStore")}db;#blocks;#proposedCheckpoints;#checkpoints;#slotToCheckpoint;#blockTxs;#txEffects;#lastSynchedL1Block;#lastProvenCheckpoint;#lastFinalizedCheckpoint;#pendingChainValidationStatus;#contractIndex;#blockHashIndex;#blockArchiveIndex;#rejectedCheckpoints;#rejectedCheckpointsByNumber;#log;constructor(db){this.db=db,this.#log=createLogger("archiver:block_store"),this.#blocks=db.openMap("archiver_blocks"),this.#blockTxs=db.openMap("archiver_block_txs"),this.#txEffects=db.openMap("archiver_tx_effects"),this.#contractIndex=db.openMap("archiver_contract_index"),this.#blockHashIndex=db.openMap("archiver_block_hash_index"),this.#blockArchiveIndex=db.openMap("archiver_block_archive_index"),this.#lastSynchedL1Block=db.openSingleton("archiver_last_synched_l1_block"),this.#lastProvenCheckpoint=db.openSingleton("archiver_last_proven_l2_checkpoint"),this.#lastFinalizedCheckpoint=db.openSingleton("archiver_last_finalized_l2_checkpoint"),this.#pendingChainValidationStatus=db.openSingleton("archiver_pending_chain_validation_status"),this.#checkpoints=db.openMap("archiver_checkpoints"),this.#slotToCheckpoint=db.openMap("archiver_slot_to_checkpoint"),this.#proposedCheckpoints=db.openMap("archiver_proposed_checkpoints"),this.#rejectedCheckpoints=db.openMap("archiver_rejected_checkpoints"),this.#rejectedCheckpointsByNumber=db.openMap("archiver_rejected_checkpoints_by_number")}async getFinalizedL2BlockNumber(){let finalizedCheckpointNumber=await this.getFinalizedCheckpointNumber();if(finalizedCheckpointNumber===INITIAL_CHECKPOINT_NUMBER2-1)return BlockNumber(INITIAL_L2_BLOCK_NUM2-1);let checkpointStorage=await this.#checkpoints.getAsync(finalizedCheckpointNumber);if(!checkpointStorage)throw new CheckpointNotFoundError(finalizedCheckpointNumber);return BlockNumber(checkpointStorage.startBlock+checkpointStorage.blockCount-1)}async addProposedBlock(block,opts={}){return await this.db.transactionAsync(async()=>{let blockNumber=block.number,blockCheckpointNumber=block.checkpointNumber,blockIndex=block.indexWithinCheckpoint,blockLastArchive=block.header.lastArchive.root,previousBlockNumber=await this.getLatestL2BlockNumber(),latestCheckpointNumber=await this.getLatestCheckpointNumber(),lastCheckpointedBlockNumber=await this.getCheckpointedL2BlockNumber();if(!opts.force&&blockNumber<=lastCheckpointedBlockNumber){let existingBlock=await this.getBlockData({number:BlockNumber(blockNumber)});throw existingBlock&&existingBlock.archive.root.equals(block.archive.root)?new BlockAlreadyCheckpointedError(blockNumber):new CannotOverwriteCheckpointedBlockError(blockNumber,lastCheckpointedBlockNumber)}if(!opts.force&&previousBlockNumber!==blockNumber-1)throw new BlockNumberNotSequentialError(blockNumber,previousBlockNumber);let expectedCheckpointNumber=blockCheckpointNumber-1,hasPendingAtExpected=await this.#proposedCheckpoints.hasAsync(expectedCheckpointNumber);if(!opts.force&&latestCheckpointNumber!==expectedCheckpointNumber&&!hasPendingAtExpected){let[latestPendingKey]=await toArray(this.#proposedCheckpoints.keysAsync({reverse:!0,limit:1})),previous=CheckpointNumber(Math.max(latestCheckpointNumber,latestPendingKey??0));throw new BlockCheckpointNumberNotSequentialError(BlockNumber(blockNumber),blockCheckpointNumber,previous)}let previousBlockResult=await this.getBlockData({number:previousBlockNumber}),expectedBlockIndex=0,previousBlockIndex;if(previousBlockResult!==void 0&&(previousBlockResult.checkpointNumber===blockCheckpointNumber&&(previousBlockIndex=previousBlockResult.indexWithinCheckpoint,expectedBlockIndex=previousBlockIndex+1),!previousBlockResult.archive.root.equals(blockLastArchive)))throw new BlockArchiveNotConsistentError(blockNumber,previousBlockResult.header.globalVariables.blockNumber,blockLastArchive,previousBlockResult.archive.root);if(!opts.force&&expectedBlockIndex!==blockIndex)throw new BlockIndexNotSequentialError(blockIndex,previousBlockIndex);return await this.addBlockToDatabase(block,block.checkpointNumber,block.indexWithinCheckpoint),!0})}async addCheckpoints(checkpoints,opts={}){return checkpoints.length===0?[]:await this.db.transactionAsync(async()=>{let firstCheckpointNumber=checkpoints[0].checkpoint.number,previousCheckpointNumber=await this.getLatestCheckpointNumber();if(!opts.force&&firstCheckpointNumber<=previousCheckpointNumber){if(checkpoints=await this.skipOrUpdateAlreadyStoredCheckpoints(checkpoints,previousCheckpointNumber),checkpoints.length===0)return[];let newFirstNumber=checkpoints[0].checkpoint.number;if(previousCheckpointNumber!==newFirstNumber-1)throw new InitialCheckpointNumberNotSequentialError(newFirstNumber,previousCheckpointNumber)}else if(previousCheckpointNumber!==firstCheckpointNumber-1&&!opts.force)throw new InitialCheckpointNumberNotSequentialError(firstCheckpointNumber,previousCheckpointNumber);let previousBlock=await this.getPreviousCheckpointBlock(checkpoints[0].checkpoint.number),previousCheckpoint;for(let checkpoint of checkpoints){if(!opts.force&&previousCheckpoint&&previousCheckpoint.checkpoint.number+1!==checkpoint.checkpoint.number)throw new CheckpointNumberNotSequentialError(checkpoint.checkpoint.number,previousCheckpoint.checkpoint.number);previousCheckpoint=checkpoint,this.validateCheckpointBlocks(checkpoint.checkpoint.blocks,previousBlock);for(let i=0;i<checkpoint.checkpoint.blocks.length;i++)await this.addBlockToDatabase(checkpoint.checkpoint.blocks[i],checkpoint.checkpoint.number,i);previousBlock=checkpoint.checkpoint.blocks.at(-1),await this.#checkpoints.set(checkpoint.checkpoint.number,{header:checkpoint.checkpoint.header.toBuffer(),archive:checkpoint.checkpoint.archive.toBuffer(),checkpointOutHash:checkpoint.checkpoint.getCheckpointOutHash().toBuffer(),l1:checkpoint.l1.toBuffer(),attestations:checkpoint.attestations.map(attestation=>attestation.toBuffer()),checkpointNumber:checkpoint.checkpoint.number,startBlock:checkpoint.checkpoint.blocks[0].number,blockCount:checkpoint.checkpoint.blocks.length,feeAssetPriceModifier:checkpoint.checkpoint.feeAssetPriceModifier.toString()}),await this.#slotToCheckpoint.set(checkpoint.checkpoint.header.slotNumber,checkpoint.checkpoint.number),await this.#proposedCheckpoints.delete(checkpoint.checkpoint.number),await this.removeRejectedCheckpointByArchiveRoot(checkpoint.checkpoint.archive.root)}return await this.advanceSynchedL1BlockNumber(checkpoints[checkpoints.length-1].l1.blockNumber),checkpoints})}async skipOrUpdateAlreadyStoredCheckpoints(checkpoints,latestStored){let i=0;for(;i<checkpoints.length&&checkpoints[i].checkpoint.number<=latestStored;i++){let incoming=checkpoints[i],stored=await this.getCheckpointData(incoming.checkpoint.number);if(!stored)break;if(!stored.archive.root.equals(incoming.checkpoint.archive.root))throw new Error(`Checkpoint ${incoming.checkpoint.number} already exists in store but with a different archive root. Stored: ${stored.archive.root}, incoming: ${incoming.checkpoint.archive.root}`);this.#log.warn(`Checkpoint ${incoming.checkpoint.number} already stored, updating L1 info (L1 block ${stored.l1.blockNumber} -> ${incoming.l1.blockNumber})`),await this.#checkpoints.set(incoming.checkpoint.number,{header:incoming.checkpoint.header.toBuffer(),archive:incoming.checkpoint.archive.toBuffer(),checkpointOutHash:incoming.checkpoint.getCheckpointOutHash().toBuffer(),l1:incoming.l1.toBuffer(),attestations:incoming.attestations.map(a=>a.toBuffer()),checkpointNumber:incoming.checkpoint.number,startBlock:incoming.checkpoint.blocks[0].number,blockCount:incoming.checkpoint.blocks.length,feeAssetPriceModifier:incoming.checkpoint.feeAssetPriceModifier.toString()}),await this.advanceSynchedL1BlockNumber(incoming.l1.blockNumber)}return checkpoints.slice(i)}async getPreviousCheckpointBlock(checkpointNumber){let previousCheckpointNumber=CheckpointNumber(checkpointNumber-1);if(previousCheckpointNumber===INITIAL_CHECKPOINT_NUMBER2-1)return;let predecessor=await this.getProposedCheckpointByNumber(previousCheckpointNumber)??await this.getCheckpointData(previousCheckpointNumber);if(!predecessor)throw new CheckpointNotFoundError(previousCheckpointNumber);let previousBlockNumber=BlockNumber(predecessor.startBlock+predecessor.blockCount-1),previousBlock=await this.getBlock({number:previousBlockNumber});if(previousBlock===void 0)throw new BlockNotFoundError(previousBlockNumber);return previousBlock}validateCheckpointBlocks(blocks,previousBlock){for(let block of blocks){if(previousBlock){if(previousBlock.number!==block.number-1)throw new BlockNumberNotSequentialError(block.number,previousBlock.number);if(previousBlock.checkpointNumber===block.checkpointNumber){if(previousBlock.indexWithinCheckpoint!==block.indexWithinCheckpoint-1)throw new BlockIndexNotSequentialError(block.indexWithinCheckpoint,previousBlock.indexWithinCheckpoint)}else if(block.indexWithinCheckpoint!==0)throw new BlockIndexNotSequentialError(block.indexWithinCheckpoint,previousBlock.indexWithinCheckpoint);if(!previousBlock.archive.root.equals(block.header.lastArchive.root))throw new BlockArchiveNotConsistentError(block.number,previousBlock.number,block.header.lastArchive.root,previousBlock.archive.root)}else{if(block.indexWithinCheckpoint!==0)throw new BlockIndexNotSequentialError(block.indexWithinCheckpoint,void 0);if(block.number!==INITIAL_L2_BLOCK_NUM2)throw new BlockNumberNotSequentialError(block.number,void 0)}previousBlock=block}}async addBlockToDatabase(block,checkpointNumber,indexWithinCheckpoint){let blockHash=await block.hash();await this.#blocks.set(block.number,{header:block.header.toBuffer(),blockHash:blockHash.toBuffer(),archive:block.archive.toBuffer(),checkpointNumber,indexWithinCheckpoint});for(let i=0;i<block.body.txEffects.length;i++){let txEffect={data:block.body.txEffects[i],l2BlockNumber:block.number,l2BlockHash:blockHash,txIndexInBlock:i,slotNumber:block.header.globalVariables.slotNumber};await this.#txEffects.set(txEffect.data.txHash.toString(),serializeIndexedTxEffect(txEffect))}await this.#blockTxs.set(blockHash.toString(),Buffer.concat(block.body.txEffects.map(tx=>tx.txHash.toBuffer()))),await this.#blockHashIndex.set(blockHash.toString(),block.number),await this.#blockArchiveIndex.set(block.archive.root.toString(),block.number)}async deleteBlock(block){await this.#blocks.delete(block.number),await Promise.all(block.body.txEffects.map(tx=>this.#txEffects.delete(tx.txHash.toString())));let blockHash=(await block.hash()).toString();await this.#blockTxs.delete(blockHash),await this.#blockHashIndex.delete(blockHash),await this.#blockArchiveIndex.delete(block.archive.root.toString())}async removeCheckpointsAfter(checkpointNumber){return await this.db.transactionAsync(async()=>{let latestCheckpointNumber=await this.getLatestCheckpointNumber();if(checkpointNumber>=latestCheckpointNumber)return this.#log.warn(`No checkpoints to remove after ${checkpointNumber} (latest is ${latestCheckpointNumber})`),{blocksRemoved:void 0};let proven=await this.getProvenCheckpointNumber();proven>checkpointNumber&&(this.#log.warn(`Updating proven checkpoint ${proven} to last valid checkpoint ${checkpointNumber}`),await this.setProvenCheckpointNumber(checkpointNumber));let lastBlockToKeep;if(checkpointNumber<=0)lastBlockToKeep=BlockNumber(INITIAL_L2_BLOCK_NUM2-1);else{let targetCheckpoint=await this.#checkpoints.getAsync(checkpointNumber);if(!targetCheckpoint)throw new Error(`Target checkpoint ${checkpointNumber} not found in store`);lastBlockToKeep=BlockNumber(targetCheckpoint.startBlock+targetCheckpoint.blockCount-1)}let blocksRemoved=await this.removeBlocksAfter(lastBlockToKeep);for(let c2=latestCheckpointNumber;c2>checkpointNumber;c2=CheckpointNumber(c2-1)){let checkpointStorage=await this.#checkpoints.getAsync(c2);if(checkpointStorage){let slotNumber=CheckpointHeader.fromBuffer(checkpointStorage.header).slotNumber;await this.#slotToCheckpoint.delete(slotNumber)}await this.#checkpoints.delete(c2),this.#log.debug(`Removed checkpoint ${c2}`)}return await this.evictProposedCheckpointsFrom(CheckpointNumber(checkpointNumber+1)),{blocksRemoved}})}async getCheckpointData(checkpointNumber){let checkpointStorage=await this.#checkpoints.getAsync(checkpointNumber);if(checkpointStorage)return this.checkpointDataFromCheckpointStorage(checkpointStorage)}async getRangeOfCheckpoints(from,limit){let checkpoints=[];for(let checkpointNumber=from;checkpointNumber<from+limit;checkpointNumber++){let checkpoint=await this.#checkpoints.getAsync(checkpointNumber);if(!checkpoint)break;checkpoints.push(this.checkpointDataFromCheckpointStorage(checkpoint))}return checkpoints}async getCheckpointsBySlot(fromSlot,limit,reverse){let range=reverse?{end:fromSlot,reverse:!0,limit}:{start:fromSlot,limit},result=[];for await(let[,checkpointNumber]of this.#slotToCheckpoint.entriesAsync(range)){let checkpointStorage=await this.#checkpoints.getAsync(checkpointNumber);checkpointStorage&&result.push(this.checkpointDataFromCheckpointStorage(checkpointStorage))}return result}async getCheckpointDataForSlotRange(startSlot,endSlot){let result=[];for await(let[,checkpointNumber]of this.#slotToCheckpoint.entriesAsync({start:startSlot,end:endSlot+1})){let checkpointStorage=await this.#checkpoints.getAsync(checkpointNumber);checkpointStorage&&result.push(this.checkpointDataFromCheckpointStorage(checkpointStorage))}return result}async getCheckpointNumbersForSlotRange(startSlot,endSlot){let result=[];for await(let[,checkpointNumber]of this.#slotToCheckpoint.entriesAsync({start:startSlot,end:endSlot+1}))result.push(CheckpointNumber(checkpointNumber));return result}checkpointDataFromCheckpointStorage(checkpointStorage){return{header:CheckpointHeader.fromBuffer(checkpointStorage.header),archive:AppendOnlyTreeSnapshot.fromBuffer(checkpointStorage.archive),checkpointOutHash:Fr.fromBuffer(checkpointStorage.checkpointOutHash),checkpointNumber:CheckpointNumber(checkpointStorage.checkpointNumber),startBlock:BlockNumber(checkpointStorage.startBlock),blockCount:checkpointStorage.blockCount,feeAssetPriceModifier:BigInt(checkpointStorage.feeAssetPriceModifier),l1:L1PublishedData.fromBuffer(checkpointStorage.l1),attestations:checkpointStorage.attestations.map(buf=>CommitteeAttestation.fromBuffer(buf))}}async getBlocksForCheckpoint(checkpointNumber){let checkpoint=await this.#checkpoints.getAsync(checkpointNumber);if(!checkpoint)return;let blocksForCheckpoint=await toArray(this.#blocks.entriesAsync({start:checkpoint.startBlock,end:checkpoint.startBlock+checkpoint.blockCount}));return(await Promise.all(blocksForCheckpoint.map(x=>this.getBlockFromBlockStorage(x[0],x[1])))).filter(isDefined)}async getBlocksForSlot(slotNumber){let blocks=[];for await(let[blockNumber,blockStorage]of this.#blocks.entriesAsync({reverse:!0})){let block=await this.getBlockFromBlockStorage(blockNumber,blockStorage),blockSlot=block?.header.globalVariables.slotNumber;if(block&&blockSlot===slotNumber)blocks.push(block);else if(blockSlot&&blockSlot<slotNumber)break}return blocks.reverse()}async removeBlocksAfter(blockNumber){return await this.db.transactionAsync(async()=>{let removedBlocks=[],latestBlockNumber=await this.getLatestL2BlockNumber();for(let bn=blockNumber+1;bn<=latestBlockNumber;bn++){let block=await this.getBlock({number:BlockNumber(bn)});if(block===void 0){this.#log.warn(`Cannot remove block ${bn} from the store since we don't have it`);continue}removedBlocks.push(block),await this.deleteBlock(block),this.#log.debug(`Removed block ${bn} ${(await block.hash()).toString()}`)}return removedBlocks})}async getProvenBlockNumber(){let provenCheckpointNumber=await this.getProvenCheckpointNumber();if(provenCheckpointNumber===INITIAL_CHECKPOINT_NUMBER2-1)return BlockNumber(INITIAL_L2_BLOCK_NUM2-1);let checkpointStorage=await this.#checkpoints.getAsync(provenCheckpointNumber);if(checkpointStorage)return BlockNumber(checkpointStorage.startBlock+checkpointStorage.blockCount-1);throw new CheckpointNotFoundError(provenCheckpointNumber)}async getLatestCheckpointNumber(){let[latestCheckpointNumber]=await toArray(this.#checkpoints.keysAsync({reverse:!0,limit:1}));return latestCheckpointNumber===void 0?CheckpointNumber(INITIAL_CHECKPOINT_NUMBER2-1):CheckpointNumber(latestCheckpointNumber)}async hasProposedCheckpoint(){let[key]=await toArray(this.#proposedCheckpoints.keysAsync({limit:1}));return key!==void 0}async deleteProposedCheckpoints(){for await(let key of this.#proposedCheckpoints.keysAsync())await this.#proposedCheckpoints.delete(key)}async promoteProposedToCheckpointed(checkpointNumber,l1,attestations,expectedArchiveRoot){return await this.db.transactionAsync(async()=>{let proposed=await this.getProposedCheckpointByNumber(checkpointNumber);if(!proposed)throw new NoProposedCheckpointToPromoteError;if(!proposed.archive.root.equals(expectedArchiveRoot))throw new ProposedCheckpointArchiveRootMismatchError(expectedArchiveRoot,proposed.archive.root);let latestCheckpointNumber=await this.getLatestCheckpointNumber();if(latestCheckpointNumber!==proposed.checkpointNumber-1)throw new ProposedCheckpointPromotionNotSequentialError(proposed.checkpointNumber,latestCheckpointNumber);await this.#checkpoints.set(proposed.checkpointNumber,{header:proposed.header.toBuffer(),archive:proposed.archive.toBuffer(),checkpointOutHash:proposed.checkpointOutHash.toBuffer(),l1:l1.toBuffer(),attestations:attestations.map(attestation=>attestation.toBuffer()),checkpointNumber:proposed.checkpointNumber,startBlock:proposed.startBlock,blockCount:proposed.blockCount,feeAssetPriceModifier:proposed.feeAssetPriceModifier.toString()}),await this.#slotToCheckpoint.set(proposed.header.slotNumber,proposed.checkpointNumber),await this.#proposedCheckpoints.delete(proposed.checkpointNumber),await this.removeRejectedCheckpointByArchiveRoot(proposed.archive.root),await this.advanceSynchedL1BlockNumber(l1.blockNumber)})}async getLastProposedCheckpoint(){let[key]=await toArray(this.#proposedCheckpoints.keysAsync({reverse:!0,limit:1}));if(key===void 0)return;let stored=await this.#proposedCheckpoints.getAsync(key);return stored?this.convertToProposedCheckpointData(stored):void 0}async getProposedCheckpointByNumber(n){let stored=await this.#proposedCheckpoints.getAsync(n);return stored?this.convertToProposedCheckpointData(stored):void 0}async getProposedCheckpointBySlot(slot){for await(let[,stored]of this.#proposedCheckpoints.entriesAsync())if(CheckpointHeader.fromBuffer(stored.header).slotNumber===slot)return this.convertToProposedCheckpointData(stored)}async evictProposedCheckpointsFrom(fromNumber){let keysToDelete=[];for await(let key of this.#proposedCheckpoints.keysAsync())key>=fromNumber&&keysToDelete.push(key);for(let key of keysToDelete)await this.#proposedCheckpoints.delete(key)}async getLastCheckpoint(){let latest=await this.getLastProposedCheckpoint();return latest||this.getCheckpointData(await this.getLatestCheckpointNumber())}convertToProposedCheckpointData(stored){return{checkpointNumber:CheckpointNumber(stored.checkpointNumber),header:CheckpointHeader.fromBuffer(stored.header),archive:AppendOnlyTreeSnapshot.fromBuffer(stored.archive),checkpointOutHash:Fr.fromBuffer(stored.checkpointOutHash),startBlock:BlockNumber(stored.startBlock),blockCount:stored.blockCount,totalManaUsed:BigInt(stored.totalManaUsed),feeAssetPriceModifier:BigInt(stored.feeAssetPriceModifier)}}async getProposedCheckpointNumber(){let proposed=await this.getLastCheckpoint();return proposed?CheckpointNumber(proposed.checkpointNumber):await this.getLatestCheckpointNumber()}async getProposedCheckpointL2BlockNumber(){let proposed=await this.getLastCheckpoint();return proposed?BlockNumber(proposed.startBlock+proposed.blockCount-1):await this.getCheckpointedL2BlockNumber()}async getCheckpointNumberBySlot(slot){let checkpointNumber=await this.#slotToCheckpoint.getAsync(slot);return checkpointNumber===void 0?void 0:CheckpointNumber(checkpointNumber)}async getBlock(query){let blockNumber=await this.getBlockNumber(query);if(blockNumber===void 0)return;let blockStorage=await this.#blocks.getAsync(blockNumber);if(blockStorage)return this.getBlockFromBlockStorage(blockNumber,blockStorage)}getBlocks(query){return toArray(this.iterateBlocks(query))}async getBlockData(query){let blockNumber=await this.getBlockNumber(query);if(blockNumber===void 0)return;let blockStorage=await this.#blocks.getAsync(blockNumber);if(!(!blockStorage||!blockStorage.header))return this.getBlockDataFromBlockStorage(blockStorage)}getBlocksData(query){return toArray(this.iterateBlocksData(query))}async*iterateBlocks(query){let cap=query.onlyCheckpointed?await this.getCheckpointedL2BlockNumber():void 0;for await(let[blockNumber,blockStorage]of this.getBlockStorages(query.from,query.limit)){if(cap!==void 0&&blockNumber>cap)break;let block=await this.getBlockFromBlockStorage(blockNumber,blockStorage);block&&(yield block)}}async*iterateBlocksData(query){let cap=query.onlyCheckpointed?await this.getCheckpointedL2BlockNumber():void 0;for await(let[blockNumber,blockStorage]of this.getBlockStorages(query.from,query.limit)){if(cap!==void 0&&blockNumber>cap)break;yield this.getBlockDataFromBlockStorage(blockStorage)}}async*getBlockStorages(start,limit){let expectedBlockNumber=start;for await(let[blockNumber,blockStorage]of this.#blocks.entriesAsync(this.#computeBlockRange(start,limit))){if(blockNumber!==expectedBlockNumber)throw new Error(`Block number mismatch when iterating blocks from archive (expected ${expectedBlockNumber} but got ${blockNumber})`);expectedBlockNumber++,yield[blockNumber,blockStorage]}}async getBlockNumber(query){let blockNumber;if("number"in query)blockNumber=query.number;else if("hash"in query){let n=await this.#blockHashIndex.getAsync(query.hash.toString());blockNumber=n!==void 0?BlockNumber(n):void 0}else{let n=await this.#blockArchiveIndex.getAsync(query.archive.toString());blockNumber=n!==void 0?BlockNumber(n):void 0}if(blockNumber!==void 0)return blockNumber}getBlockDataFromBlockStorage(blockStorage){return{header:BlockHeader.fromBuffer(blockStorage.header),archive:AppendOnlyTreeSnapshot.fromBuffer(blockStorage.archive),blockHash:BlockHash.fromBuffer(blockStorage.blockHash),checkpointNumber:CheckpointNumber(blockStorage.checkpointNumber),indexWithinCheckpoint:IndexWithinCheckpoint(blockStorage.indexWithinCheckpoint)}}async getBlockFromBlockStorage(blockNumber,blockStorage){let{header,archive,blockHash,checkpointNumber,indexWithinCheckpoint}=this.getBlockDataFromBlockStorage(blockStorage);header.setHash(blockHash);let blockHashString=bufferToHex(blockStorage.blockHash),blockTxsBuffer=await this.#blockTxs.getAsync(blockHashString);if(blockTxsBuffer===void 0){this.#log.warn(`Could not find body for block ${header.globalVariables.blockNumber} ${blockHash}`);return}let txEffects=[],reader=BufferReader.asReader(blockTxsBuffer);for(;!reader.isEmpty();){let txHash=reader.readObject(TxHash),txEffect=await this.#txEffects.getAsync(txHash.toString());if(txEffect===void 0){this.#log.warn(`Could not find tx effect for tx ${txHash} in block ${blockNumber}`);return}txEffects.push(deserializeIndexedTxEffect(txEffect).data)}let body=new Body(txEffects),block=new L2Block(archive,header,body,checkpointNumber,indexWithinCheckpoint);if(block.number!==blockNumber)throw new Error(`Block number mismatch when retrieving block from archive (expected ${blockNumber} but got ${block.number} with hash ${blockHashString})`);return block}async getTxEffect(txHash){let buffer=await this.#txEffects.getAsync(txHash.toString());if(buffer)return deserializeIndexedTxEffect(buffer)}async getTxLocation(txHash){let txEffect=await this.#txEffects.getAsync(txHash.toString());if(!txEffect)return;let view=Buffer.from(txEffect.buffer,txEffect.byteOffset,txEffect.byteLength),l2BlockNumber=view.readUInt32BE(32),txIndexInBlock=view.readUInt32BE(36);return[l2BlockNumber,txIndexInBlock]}getNoteHashesAndNullifiers(txHashes){return Promise.all(txHashes.map(async txHash=>{let buffer=await this.#txEffects.getAsync(txHash.toString());if(!buffer)return[[],[]];let reader=BufferReader.asReader(buffer);reader.readBytes(109);let noteHashes=reader.readVectorUint8Prefix(Fr),nullifiers=reader.readVectorUint8Prefix(Fr);return[noteHashes,nullifiers]}))}getContractLocation(contractAddress){return this.#contractIndex.getAsync(contractAddress.toString())}async getCheckpointedL2BlockNumber(){let latestCheckpointNumber=await this.getLatestCheckpointNumber(),checkpoint=await this.getCheckpointData(latestCheckpointNumber);return checkpoint?BlockNumber(checkpoint.startBlock+checkpoint.blockCount-1):BlockNumber(INITIAL_L2_BLOCK_NUM2-1)}async getLatestL2BlockNumber(){let[lastBlockNumber]=await toArray(this.#blocks.keysAsync({reverse:!0,limit:1}));return typeof lastBlockNumber=="number"?BlockNumber(lastBlockNumber):BlockNumber(INITIAL_L2_BLOCK_NUM2-1)}async getL2TipsData(genesisBlockHash){return await this.db.transactionAsync(async()=>{let genesisBlockNumber=BlockNumber(INITIAL_L2_BLOCK_NUM2-1),genesisCheckpointNumber=CheckpointNumber(INITIAL_CHECKPOINT_NUMBER2-1),genesisBlockId={number:genesisBlockNumber,hash:genesisBlockHash.toString()},genesisCheckpointId={number:genesisCheckpointNumber,hash:GENESIS_CHECKPOINT_HEADER_HASH.toString()},genesisTip={block:genesisBlockId,checkpoint:genesisCheckpointId},[latestBlockEntry]=await toArray(this.#blocks.entriesAsync({reverse:!0,limit:1})),[latestCheckpointEntry]=await toArray(this.#checkpoints.entriesAsync({reverse:!0,limit:1})),latestCheckpointNumber=latestCheckpointEntry?CheckpointNumber(latestCheckpointEntry[0]):genesisCheckpointNumber,[provenRaw,finalizedRaw]=await Promise.all([this.#lastProvenCheckpoint.getAsync(),this.#lastFinalizedCheckpoint.getAsync()]),provenCheckpointNumber=CheckpointNumber(Math.min(provenRaw??0,latestCheckpointNumber)),finalizedCheckpointNumber=CheckpointNumber(Math.min(finalizedRaw??0,provenCheckpointNumber)),checkpointStorageCache=new Map;latestCheckpointEntry&&checkpointStorageCache.set(CheckpointNumber(latestCheckpointEntry[0]),latestCheckpointEntry[1]);let loadCheckpointStorage=__name(async n=>{if(n!==0){if(!checkpointStorageCache.has(n)){let checkpointStorage=await this.#checkpoints.getAsync(n);if(!checkpointStorage)throw new CheckpointNotFoundError(n);checkpointStorageCache.set(n,checkpointStorage)}return checkpointStorageCache.get(n)}},"loadCheckpointStorage"),provenCheckpoint=await loadCheckpointStorage(provenCheckpointNumber),finalizedCheckpoint=await loadCheckpointStorage(finalizedCheckpointNumber),blockHashCache=new Map;blockHashCache.set(genesisBlockNumber,genesisBlockHash.toString()),latestBlockEntry&&blockHashCache.set(latestBlockEntry[0],BlockHash.fromBuffer(latestBlockEntry[1].blockHash).toString());let loadBlockHash=__name(async n=>{if(!blockHashCache.has(n)){let blockStorage=await this.#blocks.getAsync(n);if(!blockStorage)throw new BlockNotFoundError(n);let blockHash=BlockHash.fromBuffer(blockStorage.blockHash).toString();blockHashCache.set(n,blockHash)}return blockHashCache.get(n)},"loadBlockHash"),proposedBlockId=latestBlockEntry===void 0?genesisBlockId:{number:BlockNumber(latestBlockEntry[0]),hash:BlockHash.fromBuffer(latestBlockEntry[1].blockHash).toString()},buildTipFromCheckpoint=__name(async stored=>{if(!stored)return genesisTip;let blockNumber=BlockNumber(stored.startBlock+stored.blockCount-1),blockHash=await loadBlockHash(blockNumber),header=CheckpointHeader.fromBuffer(stored.header);return{block:{number:blockNumber,hash:blockHash},checkpoint:{number:CheckpointNumber(stored.checkpointNumber),hash:header.hash().toString()}}},"buildTipFromCheckpoint"),checkpointedTip=await buildTipFromCheckpoint(latestCheckpointEntry?.[1]),provenTip=await buildTipFromCheckpoint(provenCheckpoint),finalizedTip=await buildTipFromCheckpoint(finalizedCheckpoint);if(proposedBlockId.number<checkpointedTip.block.number)throw new Error(`Inconsistent block store: latest block ${proposedBlockId.number} is behind checkpointed block ${checkpointedTip.block.number}`);if(finalizedTip.checkpoint.number>provenTip.checkpoint.number||provenTip.checkpoint.number>checkpointedTip.checkpoint.number)throw new Error(`Inconsistent checkpoint numbers in chain tips: finalized=${finalizedTip.checkpoint.number} proven=${provenTip.checkpoint.number} checkpointed=${checkpointedTip.checkpoint.number}`);if(finalizedTip.block.number>provenTip.block.number||provenTip.block.number>checkpointedTip.block.number||checkpointedTip.block.number>proposedBlockId.number)throw new Error(`Inconsistent block numbers in chain tips: finalized=${finalizedTip.block.number} proven=${provenTip.block.number} checkpointed=${checkpointedTip.block.number} proposed=${proposedBlockId.number}`);return{proposed:proposedBlockId,checkpointed:checkpointedTip,proven:provenTip,finalized:finalizedTip}})}getSynchedL1BlockNumber(){return this.#lastSynchedL1Block.getAsync()}setSynchedL1BlockNumber(l1BlockNumber){return this.#lastSynchedL1Block.set(l1BlockNumber)}async addProposedCheckpoint(proposed){return await this.db.transactionAsync(async()=>{let confirmed=await this.getLatestCheckpointNumber(),[latestPendingKey]=await toArray(this.#proposedCheckpoints.keysAsync({reverse:!0,limit:1})),latestTip=CheckpointNumber(latestPendingKey!==void 0?Math.max(latestPendingKey,confirmed):confirmed);if(proposed.checkpointNumber!==latestTip+1)throw new ProposedCheckpointNotSequentialError(proposed.checkpointNumber,latestTip);let previousBlock=await this.getPreviousCheckpointBlock(proposed.checkpointNumber),blocks=[];for(let i=0;i<proposed.blockCount;i++){let block=await this.getBlock({number:BlockNumber(proposed.startBlock+i)});if(!block)throw new BlockNotFoundError(proposed.startBlock+i);blocks.push(block)}this.validateCheckpointBlocks(blocks,previousBlock);let archive=blocks[blocks.length-1].archive,checkpointOutHash=Checkpoint.getCheckpointOutHash(blocks);await this.#proposedCheckpoints.set(proposed.checkpointNumber,{header:proposed.header.toBuffer(),archive:archive.toBuffer(),checkpointOutHash:checkpointOutHash.toBuffer(),checkpointNumber:proposed.checkpointNumber,startBlock:proposed.startBlock,blockCount:proposed.blockCount,totalManaUsed:proposed.totalManaUsed.toString(),feeAssetPriceModifier:proposed.feeAssetPriceModifier.toString()})})}async getProvenCheckpointNumber(){return await this.db.transactionAsync(async()=>{let[latestCheckpointNumber,provenCheckpointNumber]=await Promise.all([this.getLatestCheckpointNumber(),this.#lastProvenCheckpoint.getAsync()]);return(provenCheckpointNumber??0)>latestCheckpointNumber?latestCheckpointNumber:CheckpointNumber(provenCheckpointNumber??0)})}async setProvenCheckpointNumber(checkpointNumber){return await this.#lastProvenCheckpoint.set(checkpointNumber)}async getFinalizedCheckpointNumber(){return await this.db.transactionAsync(async()=>{let[provenCheckpointNumber,finalizedCheckpointNumber]=await Promise.all([this.getProvenCheckpointNumber(),this.#lastFinalizedCheckpoint.getAsync()]);return(finalizedCheckpointNumber??0)>provenCheckpointNumber?provenCheckpointNumber:CheckpointNumber(finalizedCheckpointNumber??0)})}setFinalizedCheckpointNumber(checkpointNumber){return this.#lastFinalizedCheckpoint.set(checkpointNumber)}#computeBlockRange(start,limit){if(limit<1)throw new Error(`Invalid limit: ${limit}`);if(start<INITIAL_L2_BLOCK_NUM2)throw new Error(`Invalid start: ${start}`);return{start,limit}}async getPendingChainValidationStatus(){let buffer=await this.#pendingChainValidationStatus.getAsync();if(buffer)return deserializeValidateCheckpointResult(buffer)}async setPendingChainValidationStatus(status){if(status){let buffer=serializeValidateCheckpointResult(status);await this.#pendingChainValidationStatus.set(buffer)}else await this.#pendingChainValidationStatus.delete()}async addRejectedCheckpoint(entry){let archiveRootHex=entry.archiveRoot.toString();await this.#rejectedCheckpoints.set(archiveRootHex,{checkpointNumber:entry.checkpointNumber,archiveRoot:entry.archiveRoot.toBuffer(),parentArchiveRoot:entry.parentArchiveRoot.toBuffer(),slotNumber:entry.slotNumber,l1:entry.l1.toBuffer(),reason:entry.reason}),await this.#rejectedCheckpointsByNumber.set(entry.checkpointNumber,archiveRootHex),await this.advanceSynchedL1BlockNumber(entry.l1.blockNumber)}async getRejectedCheckpointByArchiveRoot(archiveRoot){let stored=await this.#rejectedCheckpoints.getAsync(archiveRoot.toString());return stored?this.rejectedCheckpointFromStorage(stored):void 0}async getRejectedCheckpointByNumber(checkpointNumber){let archiveRootHex=await this.#rejectedCheckpointsByNumber.getAsync(checkpointNumber);if(archiveRootHex===void 0)return;let stored=await this.#rejectedCheckpoints.getAsync(archiveRootHex);return stored?this.rejectedCheckpointFromStorage(stored):void 0}async getLatestRejectedCheckpointNumber(){let[latest]=await toArray(this.#rejectedCheckpointsByNumber.keysAsync({reverse:!0,limit:1}));return CheckpointNumber(latest??INITIAL_CHECKPOINT_NUMBER2-1)}async removeRejectedCheckpointByArchiveRoot(archiveRoot){let archiveRootHex=archiveRoot.toString(),stored=await this.#rejectedCheckpoints.getAsync(archiveRootHex);await this.#rejectedCheckpoints.delete(archiveRootHex),stored&&await this.#rejectedCheckpointsByNumber.getAsync(stored.checkpointNumber)===archiveRootHex&&await this.#rejectedCheckpointsByNumber.delete(stored.checkpointNumber)}async advanceSynchedL1BlockNumber(l1BlockNumber){let current=await this.#lastSynchedL1Block.getAsync();(current===void 0||l1BlockNumber>current)&&await this.#lastSynchedL1Block.set(l1BlockNumber)}rejectedCheckpointFromStorage(stored){return{checkpointNumber:CheckpointNumber(stored.checkpointNumber),archiveRoot:Fr.fromBuffer(stored.archiveRoot),parentArchiveRoot:Fr.fromBuffer(stored.parentArchiveRoot),slotNumber:SlotNumber(stored.slotNumber),l1:L1PublishedData.fromBuffer(stored.l1),reason:stored.reason}}};var ContractClassStore=class{static{__name(this,"ContractClassStore")}db;#contractClasses;#bytecodeCommitments;constructor(db){this.db=db,this.#contractClasses=db.openMap("archiver_contract_classes"),this.#bytecodeCommitments=db.openMap("archiver_bytecode_commitments")}async addContractClasses(data,blockNumber){return(await Promise.all(data.map(c2=>this.addContractClass(c2,c2.publicBytecodeCommitment,blockNumber)))).every(Boolean)}async deleteContractClasses(data,blockNumber){return(await Promise.all(data.map(c2=>this.deleteContractClass(c2,blockNumber)))).every(Boolean)}async addContractClass(contractClass,bytecodeCommitment,blockNumber){await this.db.transactionAsync(async()=>{let key=contractClass.id.toString(),existing=await this.#contractClasses.getAsync(key);if(existing!==void 0){if(isProtocolContractClass(contractClass.id)||deserializeContractClassPublic(existing).l2BlockNumber===blockNumber)return;throw new Error(`Contract class ${key} already exists, cannot add again at block ${blockNumber}`)}await this.#contractClasses.set(key,serializeContractClassPublic({...contractClass,l2BlockNumber:blockNumber})),await this.#bytecodeCommitments.set(key,bytecodeCommitment.toBuffer())})}async deleteContractClass(contractClass,blockNumber){if(isProtocolContractClass(contractClass.id))return;let restoredContractClass=await this.#contractClasses.getAsync(contractClass.id.toString());restoredContractClass&&deserializeContractClassPublic(restoredContractClass).l2BlockNumber>=blockNumber&&await this.db.transactionAsync(async()=>{await this.#contractClasses.delete(contractClass.id.toString()),await this.#bytecodeCommitments.delete(contractClass.id.toString())})}async getContractClass(id){let contractClass=await this.#contractClasses.getAsync(id.toString());return contractClass&&{...deserializeContractClassPublic(contractClass),id}}async getBytecodeCommitment(id){let value=await this.#bytecodeCommitments.getAsync(id.toString());return value===void 0?void 0:Fr.fromBuffer(value)}async getContractClassIds(){return(await toArray(this.#contractClasses.keysAsync())).map(key=>Fr.fromHexString(key))}};function serializeContractClassPublic(contractClass){return serializeToBuffer(contractClass.l2BlockNumber,numToUInt8(contractClass.version),contractClass.artifactHash,contractClass.packedBytecode.length,contractClass.packedBytecode,contractClass.privateFunctionsRoot)}__name(serializeContractClassPublic,"serializeContractClassPublic");function deserializeContractClassPublic(buffer){let reader=BufferReader.asReader(buffer);return{l2BlockNumber:reader.readNumber(),version:reader.readUInt8(),artifactHash:reader.readObject(Fr),packedBytecode:reader.readBuffer(),privateFunctionsRoot:reader.readObject(Fr)}}__name(deserializeContractClassPublic,"deserializeContractClassPublic");var ContractInstanceStore=class{static{__name(this,"ContractInstanceStore")}db;#contractInstances;#contractInstancePublishedAt;#contractInstanceUpdates;constructor(db){this.db=db,this.#contractInstances=db.openMap("archiver_contract_instances"),this.#contractInstancePublishedAt=db.openMap("archiver_contract_instances_publication_block_number"),this.#contractInstanceUpdates=db.openMap("archiver_contract_instance_updates")}async addContractInstances(data,blockNumber){return(await Promise.all(data.map(c2=>this.addContractInstance(c2,blockNumber)))).every(Boolean)}async deleteContractInstances(data){return(await Promise.all(data.map(c2=>this.deleteContractInstance(c2)))).every(Boolean)}async addContractInstanceUpdates(data,timestamp){return(await Promise.all(data.map((update,logIndex)=>this.addContractInstanceUpdate(update,timestamp,logIndex)))).every(Boolean)}async deleteContractInstanceUpdates(data,timestamp){return(await Promise.all(data.map((update,logIndex)=>this.deleteContractInstanceUpdate(update,timestamp,logIndex)))).every(Boolean)}addContractInstance(contractInstance,blockNumber){return this.db.transactionAsync(async()=>{let key=contractInstance.address.toString();if(await this.#contractInstances.hasAsync(key)){if(isProtocolContract(contractInstance.address))return;let existingBlockNumber=await this.#contractInstancePublishedAt.getAsync(key);if(existingBlockNumber===blockNumber)return;throw new Error(`Contract instance at ${key} already exists (deployed at block ${existingBlockNumber}), cannot add again at block ${blockNumber}`)}await this.#contractInstances.set(key,new SerializableContractInstance(contractInstance).toBuffer()),await this.#contractInstancePublishedAt.set(key,blockNumber)})}deleteContractInstance(contractInstance){return isProtocolContract(contractInstance.address)?Promise.resolve():this.db.transactionAsync(async()=>{await this.#contractInstances.delete(contractInstance.address.toString()),await this.#contractInstancePublishedAt.delete(contractInstance.address.toString())})}getUpdateKey(contractAddress,timestamp,logIndex){return logIndex===void 0?[contractAddress.toString(),timestamp.toString()]:[contractAddress.toString(),timestamp.toString(),logIndex]}addContractInstanceUpdate(contractInstanceUpdate,timestamp,logIndex){return this.#contractInstanceUpdates.set(this.getUpdateKey(contractInstanceUpdate.address,timestamp,logIndex),new SerializableContractInstanceUpdate(contractInstanceUpdate).toBuffer())}deleteContractInstanceUpdate(contractInstanceUpdate,timestamp,logIndex){return this.#contractInstanceUpdates.delete(this.getUpdateKey(contractInstanceUpdate.address,timestamp,logIndex))}async getCurrentContractInstanceClassId(address,timestamp,originalClassId){let queryResult=await this.#contractInstanceUpdates.valuesAsync({reverse:!0,start:this.getUpdateKey(address,0n),end:this.getUpdateKey(address,timestamp+1n),limit:1}).next();if(queryResult.done)return originalClassId;let serializedUpdate=queryResult.value,update=SerializableContractInstanceUpdate.fromBuffer(serializedUpdate);return timestamp<update.timestampOfChange?update.prevContractClassId.isZero()?originalClassId:update.prevContractClassId:update.newContractClassId}async getContractInstance(address,timestamp){let contractInstance=await this.#contractInstances.getAsync(address.toString());if(!contractInstance)return;let instance=SerializableContractInstance.fromBuffer(contractInstance).withAddress(address);return instance.currentContractClassId=await this.getCurrentContractInstanceClassId(address,timestamp,instance.originalContractClassId),instance}getContractInstanceDeploymentBlockNumber(address){return this.#contractInstancePublishedAt.getAsync(address.toString())}};var MAX_FUNCTION_SIGNATURES=1e3,MAX_FUNCTION_NAME_LEN=256,FunctionNamesCache=class{static{__name(this,"FunctionNamesCache")}log=createLogger("archiver:data-stores");names=new Map;async register(signatures){for(let sig of signatures){if(this.names.size>MAX_FUNCTION_SIGNATURES)return;try{let selector=await FunctionSelector.fromSignature(sig);this.names.set(selector.toString(),sig.slice(0,sig.indexOf("(")).slice(0,MAX_FUNCTION_NAME_LEN))}catch{this.log.warn(`Failed to parse signature: ${sig}. Ignoring`)}}}get(selector){return this.names.get(selector.toString())}};var NUMERIC_HEX_LEN=8,SEP="-",HEX_SENTINEL="g";function fieldHex(value){return value.toString().slice(2)}__name(fieldHex,"fieldHex");function tagHexForLog(fields){return fields.length>0?fieldHex(fields[0]):""}__name(tagHexForLog,"tagHexForLog");function u32Hex(n){return n.toString(16).padStart(NUMERIC_HEX_LEN,"0")}__name(u32Hex,"u32Hex");function encodeKey(prefix,blockNumber,txIndex,logIndex){return`${prefix}${SEP}${u32Hex(blockNumber)}${SEP}${u32Hex(txIndex)}${SEP}${u32Hex(logIndex)}`}__name(encodeKey,"encodeKey");function decodeKeyTail(key){let parts=key.split(SEP),len=parts.length;return{blockNumber:BlockNumber(parseInt(parts[len-3],16)),txIndexWithinBlock:parseInt(parts[len-2],16),logIndexWithinTx:parseInt(parts[len-1],16)}}__name(decodeKeyTail,"decodeKeyTail");function endOfTagRange(prefix,upperBlockExclusive){return upperBlockExclusive===void 0?`${prefix}${SEP}${HEX_SENTINEL}`:encodeKey(prefix,upperBlockExclusive,0,0)}__name(endOfTagRange,"endOfTagRange");function endOfTxRange(prefix,txBlk,txIdx){return`${prefix}${SEP}${u32Hex(txBlk)}${SEP}${u32Hex(txIdx)}${SEP}${HEX_SENTINEL}`}__name(endOfTxRange,"endOfTxRange");function incKey(key){return key+HEX_SENTINEL}__name(incKey,"incKey");function encodeValue(value){let head=Buffer.allocUnsafe(76);value.txHash.toBuffer().copy(head,0),value.blockHash.toBuffer().copy(head,32),head.writeBigUInt64BE(value.blockTimestamp,64),head.writeUInt32BE(value.logData.length,72);let fieldBufs=value.logData.map(f=>f.toBuffer());return Buffer.concat([head,...fieldBufs])}__name(encodeValue,"encodeValue");function decodeValue(buffer){let buf=Buffer.isBuffer(buffer)?buffer:Buffer.from(buffer.buffer,buffer.byteOffset,buffer.byteLength),off=0,txHash=TxHash.fromBuffer(buf.subarray(off,off+32));off+=32;let blockHash=BlockHash.fromBuffer(buf.subarray(off,off+32));off+=32;let blockTimestamp=buf.readBigUInt64BE(off);off+=8;let logDataLen=buf.readUInt32BE(off);off+=4;let logData=new Array(logDataLen);for(let i=0;i<logDataLen;i++)logData[i]=Fr.fromBuffer(buf.subarray(off,off+32)),off+=32;return{txHash,blockHash,blockTimestamp,logData}}__name(decodeValue,"decodeValue");function encodePublicPrefix(contractHex,tagHex){return`${contractHex}${SEP}${tagHex}`}__name(encodePublicPrefix,"encodePublicPrefix");var LogStore=class _LogStore{static{__name(this,"LogStore")}db;blockStore;genesisBlockHash;#privateLogs;#publicLogs;#privateKeysByBlock;#publicKeysByBlock;#log;constructor(db,blockStore,genesisBlockHash){this.db=db,this.blockStore=blockStore,this.genesisBlockHash=genesisBlockHash,this.#log=createLogger("archiver:log_store"),this.#privateLogs=db.openMap("archiver_private_logs"),this.#publicLogs=db.openMap("archiver_public_logs"),this.#privateKeysByBlock=db.openMap("archiver_private_log_keys_by_block"),this.#publicKeysByBlock=db.openMap("archiver_public_log_keys_by_block")}addLogs(blocks){return this.db.transactionAsync(async()=>{for(let block of blocks){let blockHash=await block.hash(),blockNumber=block.number,blockTimestamp=block.timestamp,privateKeys=[],privateValues=[],publicKeys=[],publicValues=[];for(let txIndexWithinBlock=0;txIndexWithinBlock<block.body.txEffects.length;txIndexWithinBlock++){let txEffect=block.body.txEffects[txIndexWithinBlock],txHash=txEffect.txHash,privateLogIndexWithinTx=0,publicLogIndexWithinTx=0;for(let log2 of txEffect.privateLogs){let tagHex=tagHexForLog(log2.fields),key=encodeKey(tagHex,blockNumber,txIndexWithinBlock,privateLogIndexWithinTx),value=encodeValue({txHash,blockHash,blockTimestamp,logData:log2.getEmittedFields()});privateKeys.push(key),privateValues.push(value),privateLogIndexWithinTx++}for(let log2 of txEffect.publicLogs){let contractHex=fieldHex(log2.contractAddress),tagHex=tagHexForLog(log2.fields),key=encodeKey(encodePublicPrefix(contractHex,tagHex),blockNumber,txIndexWithinBlock,publicLogIndexWithinTx),value=encodeValue({txHash,blockHash,blockTimestamp,logData:log2.getEmittedFields()});publicKeys.push(key),publicValues.push(value),publicLogIndexWithinTx++}}for(let i=0;i<privateKeys.length;i++)await this.#privateLogs.set(privateKeys[i],privateValues[i]);for(let i=0;i<publicKeys.length;i++)await this.#publicLogs.set(publicKeys[i],publicValues[i]);await this.#privateKeysByBlock.set(blockNumber,privateKeys),await this.#publicKeysByBlock.set(blockNumber,publicKeys),this.#log.debug(`Indexed logs for block ${blockNumber}`,{blockNumber,privateCount:privateKeys.length,publicCount:publicKeys.length})}return!0})}deleteLogs(blocks){return this.db.transactionAsync(async()=>{for(let block of blocks){let blockNumber=block.number,[privateKeys,publicKeys]=await Promise.all([this.#privateKeysByBlock.getAsync(blockNumber),this.#publicKeysByBlock.getAsync(blockNumber)]);if(privateKeys){for(let key of privateKeys)await this.#privateLogs.delete(key);await this.#privateKeysByBlock.delete(blockNumber)}if(publicKeys){for(let key of publicKeys)await this.#publicLogs.delete(key);await this.#publicKeysByBlock.delete(blockNumber)}}return!0})}getPrivateLogsByTags(query){return _LogStore.#validateQuery(query),this.db.transactionAsync(()=>this.#runQuery(query,void 0))}getPublicLogsByTags(query){return _LogStore.#validateQuery(query),this.db.transactionAsync(()=>this.#runQuery(query,fieldHex(query.contractAddress)))}static#validateQuery(query){if(query.txHash!==void 0&&(query.fromBlock!==void 0||query.toBlock!==void 0))throw new Error("`txHash` is mutually exclusive with `fromBlock`/`toBlock`")}async#runQuery(query,contractHex){let isPublic=contractHex!==void 0,tags=query.tags??[],primaryMap=isPublic?this.#publicLogs:this.#privateLogs,referenceBlockNumber;if(query.referenceBlock)if(query.referenceBlock.equals(this.genesisBlockHash))referenceBlockNumber=INITIAL_L2_BLOCK_NUM2-1;else{let refBlk=await this.blockStore.getBlockData({hash:query.referenceBlock});if(!refBlk)throw new Error(`Reference block ${query.referenceBlock.toString()} not found in the node. This might indicate a reorg has occurred.`);referenceBlockNumber=refBlk.header.globalVariables.blockNumber}let upperExclusive;if(query.toBlock!==void 0&&(upperExclusive=query.toBlock),referenceBlockNumber!==void 0){let refExclusive=referenceBlockNumber+1;upperExclusive=upperExclusive===void 0?refExclusive:Math.min(upperExclusive,refExclusive)}let txLocation;if(query.txHash){let loc=await this.blockStore.getTxLocation(query.txHash);if(!loc)return tags.map(()=>[]);if(txLocation=loc,upperExclusive!==void 0&&txLocation[0]>=upperExclusive)return tags.map(()=>[])}let fromBlock=query.fromBlock??INITIAL_L2_BLOCK_NUM2,includeEffects=query.includeEffects===!0,perTagResults=[];for(let tagEntry of tags){let{tagHex,afterLog}=normalizeTagEntry(tagEntry),prefix=contractHex!==void 0?encodePublicPrefix(contractHex,tagHex):tagHex,end=txLocation?endOfTxRange(prefix,txLocation[0],txLocation[1]):endOfTagRange(prefix,upperExclusive),start;afterLog?start=incKey(encodeKey(prefix,afterLog.blockNumber,afterLog.txIndexWithinBlock,afterLog.logIndexWithinTx)):txLocation?start=encodeKey(prefix,txLocation[0],txLocation[1],0):start=encodeKey(prefix,fromBlock,0,0);let limit=query.limitPerTag??20,out=[];for await(let[rawKey,rawVal]of primaryMap.entriesAsync({start,end,limit})){let tail=decodeKeyTail(rawKey),value=decodeValue(rawVal);out.push({logData:value.logData,blockNumber:tail.blockNumber,blockHash:value.blockHash,blockTimestamp:value.blockTimestamp,txHash:value.txHash,txIndexWithinBlock:tail.txIndexWithinBlock,logIndexWithinTx:tail.logIndexWithinTx})}perTagResults.push(out)}if(includeEffects){let txHashByKey=new Map;for(let arr of perTagResults)for(let log2 of arr)txHashByKey.set(log2.txHash.toString(),log2.txHash);let uniqueTxs=Array.from(txHashByKey.values());if(uniqueTxs.length>0){let effects=await this.blockStore.getNoteHashesAndNullifiers(uniqueTxs),byTxHash=new Map;uniqueTxs.forEach((tx,i)=>byTxHash.set(tx.toString(),effects[i]));for(let i=0;i<perTagResults.length;i++)perTagResults[i]=perTagResults[i].map(log2=>{let[noteHashes,nullifiers]=byTxHash.get(log2.txHash.toString())??[[],[]];return{...log2,noteHashes,nullifiers}})}}return perTagResults}getPrivateLogsForBlock(blockNumber){return this.db.transactionAsync(()=>this.#readBlockLogs(this.#privateKeysByBlock,this.#privateLogs,blockNumber))}getPublicLogsForBlock(blockNumber){return this.db.transactionAsync(()=>this.#readBlockLogs(this.#publicKeysByBlock,this.#publicLogs,blockNumber))}async#readBlockLogs(keysByBlock,primaryMap,blockNumber){let keys=await keysByBlock.getAsync(blockNumber);if(!keys||keys.length===0)return[];let results=[];for(let key of keys){let raw=await primaryMap.getAsync(key);if(!raw)continue;let tail=decodeKeyTail(key),value=decodeValue(raw);results.push({logData:value.logData,blockNumber:tail.blockNumber,blockHash:value.blockHash,blockTimestamp:value.blockTimestamp,txHash:value.txHash,txIndexWithinBlock:tail.txIndexWithinBlock,logIndexWithinTx:tail.logIndexWithinTx})}return results}};function normalizeTagEntry(entry){return typeof entry=="object"&&entry!==null&&"tag"in entry?{tagHex:fieldHex(entry.tag.value),afterLog:entry.afterLog}:{tagHex:fieldHex(entry.value),afterLog:void 0}}__name(normalizeTagEntry,"normalizeTagEntry");function mapRange(range,mapFn){return{start:range.start?mapFn(range.start):void 0,end:range.end?mapFn(range.end):void 0,reverse:range.reverse,limit:range.limit}}__name(mapRange,"mapRange");function updateRollingHash(currentRollingHash,leaf){let input=Buffer.concat([currentRollingHash.toBuffer(),leaf.toBuffer()]);return Buffer16.fromBuffer(keccak256(input))}__name(updateRollingHash,"updateRollingHash");function serializeInboxMessage(message){return serializeToBuffer([bigintToUInt64BE(message.index),message.leaf,message.l1BlockHash,numToUInt32BE(Number(message.l1BlockNumber)),numToUInt32BE(message.checkpointNumber),message.rollingHash])}__name(serializeInboxMessage,"serializeInboxMessage");function deserializeInboxMessage(buffer){let reader=BufferReader.asReader(buffer),index=reader.readUInt64(),leaf=reader.readObject(Fr),l1BlockHash=reader.readObject(Buffer32),l1BlockNumber=BigInt(reader.readNumber()),checkpointNumber=CheckpointNumber(reader.readNumber()),rollingHash=reader.readObject(Buffer16);return{index,leaf,l1BlockHash,l1BlockNumber,checkpointNumber,rollingHash}}__name(deserializeInboxMessage,"deserializeInboxMessage");var MessageStoreError=class extends Error{static{__name(this,"MessageStoreError")}inboxMessage;constructor(message,inboxMessage){super(message),this.inboxMessage=inboxMessage,this.name="MessageStoreError"}},MessageStore=class{static{__name(this,"MessageStore")}db;#l1ToL2Messages;#l1ToL2MessageIndices;#lastSynchedL1Block;#totalMessageCount;#inboxTreeInProgress;#messagesFinalizedL1Block;#log;constructor(db){this.db=db,this.#log=createLogger("archiver:message_store"),this.#l1ToL2Messages=db.openMap("archiver_l1_to_l2_messages"),this.#l1ToL2MessageIndices=db.openMap("archiver_l1_to_l2_message_indices"),this.#lastSynchedL1Block=db.openSingleton("archiver_last_l1_block_id"),this.#totalMessageCount=db.openSingleton("archiver_l1_to_l2_message_count"),this.#inboxTreeInProgress=db.openSingleton("archiver_inbox_tree_in_progress"),this.#messagesFinalizedL1Block=db.openSingleton("archiver_messages_finalized_l1_block")}async getTotalL1ToL2MessageCount(){return await this.#totalMessageCount.getAsync()??0n}async getSynchedL1Block(){let buffer=await this.#lastSynchedL1Block.getAsync();if(!buffer)return;let reader=BufferReader.asReader(buffer);return{l1BlockNumber:reader.readUInt256(),l1BlockHash:Buffer32.fromBuffer(reader.readBytes(Buffer32.SIZE))}}async setSynchedL1Block(l1Block){let buffer=serializeToBuffer([l1Block.l1BlockNumber,l1Block.l1BlockHash]);await this.#lastSynchedL1Block.set(buffer)}async getMessagesFinalizedL1Block(){let buffer=await this.#messagesFinalizedL1Block.getAsync();if(!buffer)return;let reader=BufferReader.asReader(buffer);return{l1BlockNumber:reader.readUInt256(),l1BlockHash:Buffer32.fromBuffer(reader.readBytes(Buffer32.SIZE))}}async maybeAdvanceFinalizedL1Block(l1Block){let existing=await this.getMessagesFinalizedL1Block();if(existing&&l1Block.l1BlockNumber<=existing.l1BlockNumber)return;let buffer=serializeToBuffer([l1Block.l1BlockNumber,l1Block.l1BlockHash]);await this.#messagesFinalizedL1Block.set(buffer)}addL1ToL2Messages(messages){return messages.length===0?Promise.resolve():this.db.transactionAsync(async()=>{let lastMessage=await this.getLastMessage(),messageCount=0;for(let message of messages){if(lastMessage&&message.index<=lastMessage.index){let existing=await this.#l1ToL2Messages.getAsync(this.indexToKey(message.index));if(existing&&deserializeInboxMessage(existing).rollingHash.equals(message.rollingHash)){this.#log.trace(`Reinserting message with index ${message.index} in the store`),await this.#l1ToL2Messages.set(this.indexToKey(message.index),serializeInboxMessage(message));continue}throw new MessageStoreError(`Cannot insert L1 to L2 message with index ${message.index} before last message with index ${lastMessage.index}`,message)}let previousRollingHash=lastMessage?.rollingHash??Buffer16.ZERO,expectedRollingHash=updateRollingHash(previousRollingHash,message.leaf);if(!expectedRollingHash.equals(message.rollingHash))throw new MessageStoreError(`Invalid rolling hash for incoming L1 to L2 message ${message.leaf.toString()} with index ${message.index} (expected ${expectedRollingHash.toString()} from previous hash ${previousRollingHash} but got ${message.rollingHash.toString()})`,message);let[expectedStart,expectedEnd]=InboxLeaf.indexRangeForCheckpoint(message.checkpointNumber);if(message.index<expectedStart||message.index>=expectedEnd)throw new MessageStoreError(`Invalid index ${message.index} for incoming L1 to L2 message ${message.leaf.toString()} at checkpoint ${message.checkpointNumber} (expected value in range [${expectedStart}, ${expectedEnd}))`,message);if(lastMessage&&message.checkpointNumber===lastMessage.checkpointNumber&&message.index!==lastMessage.index+1n)throw new MessageStoreError(`Missing prior message for incoming L1 to L2 message ${message.leaf.toString()} with index ${message.index}`,message);if((!lastMessage||message.checkpointNumber>lastMessage.checkpointNumber)&&message.index!==expectedStart)throw new MessageStoreError(`Message ${message.leaf.toString()} for checkpoint ${message.checkpointNumber} has wrong index ${message.index} (expected ${expectedStart})`,message);await this.#l1ToL2Messages.set(this.indexToKey(message.index),serializeInboxMessage(message)),await this.#l1ToL2MessageIndices.set(this.leafToIndexKey(message.leaf),message.index),messageCount++,this.#log.trace(`Inserted L1 to L2 message ${message.leaf} with index ${message.index} into the store`),lastMessage=message}await this.increaseTotalMessageCount(messageCount)})}getL1ToL2MessageIndex(l1ToL2Message){return this.#l1ToL2MessageIndices.getAsync(this.leafToIndexKey(l1ToL2Message))}async getLastMessage(){let[msg]=await toArray(this.#l1ToL2Messages.valuesAsync({reverse:!0,limit:1}));return msg?deserializeInboxMessage(msg):void 0}getInboxTreeInProgress(){return this.#inboxTreeInProgress.getAsync()}setMessageSyncState(l1Block,treeInProgress,finalizedL1Block){return this.db.transactionAsync(async()=>{await this.setSynchedL1Block(l1Block),treeInProgress!==void 0?await this.#inboxTreeInProgress.set(treeInProgress):await this.#inboxTreeInProgress.delete(),finalizedL1Block!==void 0&&await this.maybeAdvanceFinalizedL1Block(finalizedL1Block)})}async getL1ToL2Messages(checkpointNumber){let treeInProgress=await this.#inboxTreeInProgress.getAsync();if(treeInProgress!==void 0&&BigInt(checkpointNumber)>=treeInProgress)throw new L1ToL2MessagesNotReadyError(checkpointNumber,treeInProgress);let messages=[],[startIndex,endIndex]=InboxLeaf.indexRangeForCheckpoint(checkpointNumber),lastIndex=startIndex-1n;for await(let msgBuffer of this.#l1ToL2Messages.valuesAsync({start:this.indexToKey(startIndex),end:this.indexToKey(endIndex)})){let msg=deserializeInboxMessage(msgBuffer);if(msg.checkpointNumber!==checkpointNumber)throw new Error(`L1 to L2 message with index ${msg.index} has invalid checkpoint number ${msg.checkpointNumber}`);if(msg.index!==lastIndex+1n)throw new Error(`Expected L1 to L2 message with index ${lastIndex+1n} but got ${msg.index}`);lastIndex=msg.index,messages.push(msg.leaf)}return messages}async*iterateL1ToL2Messages(range={}){let entriesRange=mapRange(range,this.indexToKey);for await(let msgBuffer of this.#l1ToL2Messages.valuesAsync(entriesRange))yield deserializeInboxMessage(msgBuffer)}removeL1ToL2Messages(startIndex){this.#log.debug(`Deleting L1 to L2 messages from index ${startIndex}`);let deleteCount=0;return this.db.transactionAsync(async()=>{for await(let[key,msgBuffer]of this.#l1ToL2Messages.entriesAsync({start:this.indexToKey(startIndex)}))this.#log.trace(`Deleting L1 to L2 message with index ${key-1} from the store`),await this.#l1ToL2Messages.delete(key),await this.#l1ToL2MessageIndices.delete(this.leafToIndexKey(deserializeInboxMessage(msgBuffer).leaf)),deleteCount++;await this.increaseTotalMessageCount(-deleteCount),this.#log.warn(`Deleted ${deleteCount} L1 to L2 messages from index ${startIndex} from the store`)})}rollbackL1ToL2MessagesToCheckpoint(targetCheckpointNumber){this.#log.debug(`Deleting L1 to L2 messages up to target checkpoint ${targetCheckpointNumber}`);let startIndex=InboxLeaf.smallestIndexForCheckpoint(CheckpointNumber(targetCheckpointNumber+1));return this.removeL1ToL2Messages(startIndex)}indexToKey(index){return Number(index)}leafToIndexKey(leaf){return leaf.toString()}async increaseTotalMessageCount(count2){if(count2!==0)return await this.db.transactionAsync(async()=>{let lastTotalMessageCount=await this.getTotalL1ToL2MessageCount();await this.#totalMessageCount.set(lastTotalMessageCount+BigInt(count2))})}};function createArchiverDataStores(db,genesisBlockHash){let blocks=new BlockStore(db);return{db,blocks,logs:new LogStore(db,blocks,genesisBlockHash),messages:new MessageStore(db),contractClasses:new ContractClassStore(db),contractInstances:new ContractInstanceStore(db),functionNames:new FunctionNamesCache}}__name(createArchiverDataStores,"createArchiverDataStores");var L1ToL2MessagesNotReadyError2=class extends Error{static{__name(this,"L1ToL2MessagesNotReadyError")}constructor(message){super(message),this.name="L1ToL2MessagesNotReadyError"}};var TXEArchiver=class extends ArchiverDataSourceBase{static{__name(this,"TXEArchiver")}updater=new ArchiverDataStoreUpdater(this.stores);constructor(db){super(createArchiverDataStores(db,GENESIS_BLOCK_HEADER_HASH3),void 0,BlockHeader.empty(),GENESIS_BLOCK_HEADER_HASH3,new Fr(GENESIS_ARCHIVE_ROOT))}async addCheckpoints(checkpoints,result){await this.updater.addCheckpoints(checkpoints,result)}getRollupAddress(){throw new Error('TXE Archiver does not implement "getRollupAddress"')}getRegistryAddress(){throw new Error('TXE Archiver does not implement "getRegistryAddress"')}getL1Constants(){return Promise.resolve(EmptyL1RollupConstants)}getGenesisValues(){return Promise.resolve({genesisArchiveRoot:new Fr(GENESIS_ARCHIVE_ROOT)})}getL1Timestamp(){throw new Error('TXE Archiver does not implement "getL1Timestamp"')}async getL2Tips(){let latestBlockNumber=await this.stores.blocks.getLatestL2BlockNumber();if(latestBlockNumber===0)throw new Error("L2Tips requested from TXE Archiver but no block found");let latestBlockData=await this.stores.blocks.getBlockData({number:latestBlockNumber});if(!latestBlockData)throw new Error("L2Tips requested from TXE Archiver but no block header found");let number4=latestBlockData.header.globalVariables.blockNumber,hash5=latestBlockData.blockHash.toString(),checkpoint=await this.stores.blocks.getRangeOfCheckpoints(CheckpointNumber.fromBlockNumber(number4),1);if(checkpoint.length===0)throw new Error(`L2Tips requested from TXE Archiver but no checkpoint found for block number ${number4}`);let blockId={number:number4,hash:hash5},checkpointId={number:checkpoint[0].checkpointNumber,hash:checkpoint[0].header.hash().toString()},tipId={block:blockId,checkpoint:checkpointId};return{proposed:blockId,proven:tipId,finalized:tipId,checkpointed:tipId}}getSyncedL2SlotNumber(){throw new Error('TXE Archiver does not implement "getSyncedL2SlotNumber"')}getSyncedL2EpochNumber(){throw new Error('TXE Archiver does not implement "getSyncedL2EpochNumber"')}isEpochComplete(_epochNumber){throw new Error('TXE Archiver does not implement "isEpochComplete"')}syncImmediate(){throw new Error('TXE Archiver does not implement "syncImmediate"')}getL2ToL1MembershipWitness(){return Promise.resolve(void 0)}};var import_config15=__toESM(require_empty_stub(),1);import{l1ContractsConfigMappings as l1ContractsConfigMappings2}from"@aztec/ethereum/config";import{l1ReaderConfigMappings}from"@aztec/ethereum/l1-reader";var archiverConfigMappings={...import_config15.blobClientConfigMapping,archiverPollingIntervalMS:{env:"ARCHIVER_POLLING_INTERVAL_MS",description:"The polling interval in ms for retrieving new L2 blocks and encrypted logs.",...numberConfigHelper(500)},archiverBatchSize:{env:"ARCHIVER_BATCH_SIZE",description:"The number of L2 blocks the archiver will attempt to download at a time.",...numberConfigHelper(100)},archiverStoreMapSizeKb:{env:"ARCHIVER_STORE_MAP_SIZE_KB",...optionalNumberConfigHelper(),description:"The maximum possible size of the archiver DB in KB. Overwrites the general dataStoreMapSizeKb."},blockDurationMs:{env:"SEQ_BLOCK_DURATION_MS",description:"Duration per block in milliseconds when building multiple blocks per slot. Used to derive orphan proposed block pruning timing.",...optionalNumberConfigHelper()},checkpointProposalSyncGraceSeconds:{env:"CHECKPOINT_PROPOSAL_SYNC_GRACE_SECONDS",description:"Consensus grace in seconds for a received checkpoint proposal to materialize into local proposed state.",...optionalNumberConfigHelper()},skipValidateCheckpointAttestations:{description:"Skip validating checkpoint attestations (for testing purposes only)",...booleanConfigHelper(!1)},skipPromoteProposedCheckpointDuringL1Sync:{description:"Skip promoting proposed checkpoints during L1 sync (for testing purposes only)",...booleanConfigHelper(!1)},maxAllowedEthClientDriftSeconds:{env:"MAX_ALLOWED_ETH_CLIENT_DRIFT_SECONDS",description:"Maximum allowed drift in seconds between the Ethereum client and current time.",...numberConfigHelper(300)},ethereumAllowNoDebugHosts:{env:"ETHEREUM_ALLOW_NO_DEBUG_HOSTS",description:"Whether to allow starting the archiver without debug/trace method support on Ethereum hosts",...booleanConfigHelper(!0)},archiverSkipHistoricalLogsCheck:{env:"ARCHIVER_SKIP_HISTORICAL_LOGS_CHECK",description:"Skip the startup check that probes the L1 RPC for historical Rollup contract logs. Set to true to bypass the check when the connected RPC node is known to prune old logs.",...booleanConfigHelper(!1)},orphanPruneNoProposalTolerance:{env:"ARCHIVER_ORPHAN_PRUNE_NO_PROPOSAL_TOLERANCE",description:"Local tolerance in seconds before pruning an orphan block when no checkpoint proposal was received.",...numberConfigHelper(1)},skipOrphanProposedBlockPruning:{env:"ARCHIVER_SKIP_ORPHAN_PROPOSED_BLOCK_PRUNING",description:"Skip pruning orphan proposed blocks that have no matching proposed checkpoint.",...booleanConfigHelper(!1)},...chainConfigMappings,...l1ReaderConfigMappings,viemPollingIntervalMS:{env:"ARCHIVER_VIEM_POLLING_INTERVAL_MS",description:"The polling interval viem uses in ms",...numberConfigHelper(1e3)},...l1ContractsConfigMappings2};import{genesisStateConfigMappings}from"@aztec/ethereum/config";var import_node_keystore=__toESM(require_empty_stub(),1),import_config24=__toESM(require_empty_stub(),1),import_config25=__toESM(require_empty_stub(),1),import_config26=__toESM(require_empty_stub(),1),import_config27=__toESM(require_empty_stub(),1),import_config28=__toESM(require_empty_stub(),1),import_slasher2=__toESM(require_empty_stub(),1);var import_config30=__toESM(require_empty_stub(),1);var worldStateConfigMappings={worldStateBlockCheckIntervalMS:{env:"WS_BLOCK_CHECK_INTERVAL_MS",...numberConfigHelper(100),description:"The frequency in which to check."},worldStateBlockRequestBatchSize:{env:"WS_BLOCK_REQUEST_BATCH_SIZE",...optionalNumberConfigHelper(),description:"Size of the batch for each get-blocks request from the synchronizer to the archiver."},worldStateDbMapSizeKb:{env:"WS_DB_MAP_SIZE_KB",...optionalNumberConfigHelper(),description:"The maximum possible size of the world state DB in KB. Overwrites the general dataStoreMapSizeKb."},archiveTreeMapSizeKb:{env:"ARCHIVE_TREE_MAP_SIZE_KB",...optionalNumberConfigHelper(),description:"The maximum possible size of the world state archive tree in KB. Overwrites the general worldStateDbMapSizeKb."},nullifierTreeMapSizeKb:{env:"NULLIFIER_TREE_MAP_SIZE_KB",...optionalNumberConfigHelper(),description:"The maximum possible size of the world state nullifier tree in KB. Overwrites the general worldStateDbMapSizeKb."},noteHashTreeMapSizeKb:{env:"NOTE_HASH_TREE_MAP_SIZE_KB",...optionalNumberConfigHelper(),description:"The maximum possible size of the world state note hash tree in KB. Overwrites the general worldStateDbMapSizeKb."},messageTreeMapSizeKb:{env:"MESSAGE_TREE_MAP_SIZE_KB",...optionalNumberConfigHelper(),description:"The maximum possible size of the world state message tree in KB. Overwrites the general worldStateDbMapSizeKb."},publicDataTreeMapSizeKb:{env:"PUBLIC_DATA_TREE_MAP_SIZE_KB",...optionalNumberConfigHelper(),description:"The maximum possible size of the world state public data tree in KB. Overwrites the general worldStateDbMapSizeKb."},worldStateDataDirectory:{env:"WS_DATA_DIRECTORY",description:"Optional directory for the world state database"},worldStateCheckpointHistory:{env:"WS_NUM_HISTORIC_CHECKPOINTS",description:"The number of historic checkpoints worth of blocks to maintain. Values less than 1 mean all history is maintained",fallback:["WS_NUM_HISTORIC_BLOCKS"],...numberConfigHelper(64)}};import{privateKeyToAddress}from"viem/accounts";var sentinelConfigMappings={sentinelHistoryLengthInEpochs:{description:"The number of L2 epochs kept of history for each validator for computing their stats.",env:"SENTINEL_HISTORY_LENGTH_IN_EPOCHS",...numberConfigHelper(24)},sentinelHistoricEpochPerformanceLengthInEpochs:{description:"The number of L2 epochs kept of per-epoch performance history for each validator.",env:"SENTINEL_HISTORIC_EPOCH_PERFORMANCE_LENGTH_IN_EPOCHS",...numberConfigHelper(2e3)},sentinelEnabled:{description:"Whether the sentinel is enabled or not.",env:"SENTINEL_ENABLED",...booleanConfigHelper(!1)},sentinelEpochEndBufferSlots:{description:"Number of L2 slots after the end of an epoch before the sentinel evaluates it.",env:"SENTINEL_EPOCH_END_BUFFER_SLOTS",...numberConfigHelper(2)}};var aztecNodeConfigMappings={...dataConfigMappings,...import_node_keystore.keyStoreConfigMappings,...archiverConfigMappings,...import_config28.sequencerClientConfigMappings,...import_config27.proverNodeConfigMappings,...import_config30.validatorClientConfigMappings,...import_config26.proverClientConfigMappings,...worldStateConfigMappings,...import_config25.p2pConfigMappings,...sentinelConfigMappings,...import_config24.sharedNodeConfigMappings,...genesisStateConfigMappings,...nodeRpcConfigMappings,...import_slasher2.slasherConfigMappings,...import_config27.specificProverNodeConfigMappings,disableValidator:{env:"VALIDATOR_DISABLED",description:"Whether the validator is disabled for this node.",...booleanConfigHelper()},skipArchiverInitialSync:{env:"SKIP_ARCHIVER_INITIAL_SYNC",description:"Whether to skip waiting for the archiver to be fully synced before starting other services.",...booleanConfigHelper(!1)},debugForceTxProofVerification:{env:"DEBUG_FORCE_TX_PROOF_VERIFICATION",description:"Whether to skip waiting for the archiver to be fully synced before starting other services.",...booleanConfigHelper(!1)},enableProverNode:{env:"ENABLE_PROVER_NODE",description:"Whether to enable the prover node as a subsystem.",...booleanConfigHelper(!1)},enableOffenseCollection:{env:"OFFENSE_COLLECTION_ENABLED",description:"Whether to run the slashing watchers to collect offenses even if not a validator.",...booleanConfigHelper(!1)},useAutomineSequencer:{env:"USE_AUTOMINE_SEQUENCER",description:"Test-only: use AutomineSequencer instead of the production Sequencer.",...booleanConfigHelper(!1)},automineEnableProveEpoch:{env:"AUTOMINE_ENABLE_PROVE_EPOCH",description:"Test-only: have the AutomineSequencer automatically prove epochs as checkpoints land.",...booleanConfigHelper(!1)}};var P2PBootstrapApiSchema={getEncodedEnr:external_exports.function({input:external_exports.tuple([]),output:external_exports.string()}),getRoutingTable:external_exports.function({input:external_exports.tuple([]),output:external_exports.array(external_exports.string())})};var ProverAgentStatusSchema=external_exports.discriminatedUnion("status",[external_exports.object({status:external_exports.literal("stopped")}),external_exports.object({status:external_exports.literal("running")}),external_exports.object({status:external_exports.literal("proving"),jobId:external_exports.string(),proofType:external_exports.number(),startedAtISO:external_exports.string()})]),ProverAgentApiSchema={getStatus:external_exports.function({input:external_exports.tuple([]),output:ProverAgentStatusSchema})};var EpochProvingJobState=["initialized","awaiting-checkpoints","awaiting-root","awaiting-predecessor","publishing-proof","completed","superseded","failed","stopped","cancelled","timed-out"];var ProverNodeApiSchema={getJobs:external_exports.function({input:external_exports.tuple([]),output:external_exports.array(external_exports.object({uuid:external_exports.string(),status:external_exports.enum(EpochProvingJobState),epochNumber:external_exports.number()}))}),startProof:external_exports.function({input:external_exports.tuple([schemas2.Integer]),output:external_exports.string()})};function schemaForPublicInputsAndRecursiveProof(inputs,proofSize){return external_exports.object({inputs,proof:RecursiveProof.schemaFor(proofSize),verificationKey:VerificationKeyData.schema})}__name(schemaForPublicInputsAndRecursiveProof,"schemaForPublicInputsAndRecursiveProof");var ProvingJobInputs=external_exports.discriminatedUnion("type",[AvmProvingRequestSchema,external_exports.object({type:external_exports.literal(ProvingRequestType.PARITY_BASE),inputs:ParityBasePrivateInputs.schema}),external_exports.object({type:external_exports.literal(ProvingRequestType.PARITY_ROOT),inputs:ParityRootPrivateInputs.schema}),external_exports.object({type:external_exports.literal(ProvingRequestType.PUBLIC_CHONK_VERIFIER),inputs:PublicChonkVerifierPrivateInputs.schema}),external_exports.object({type:external_exports.literal(ProvingRequestType.PRIVATE_TX_BASE_ROLLUP),inputs:PrivateTxBaseRollupPrivateInputs.schema}),external_exports.object({type:external_exports.literal(ProvingRequestType.PUBLIC_TX_BASE_ROLLUP),inputs:PublicTxBaseRollupPrivateInputs.schema}),external_exports.object({type:external_exports.literal(ProvingRequestType.TX_MERGE_ROLLUP),inputs:TxMergeRollupPrivateInputs.schema}),external_exports.object({type:external_exports.literal(ProvingRequestType.BLOCK_ROOT_FIRST_ROLLUP),inputs:BlockRootFirstRollupPrivateInputs.schema}),external_exports.object({type:external_exports.literal(ProvingRequestType.BLOCK_ROOT_SINGLE_TX_FIRST_ROLLUP),inputs:BlockRootSingleTxFirstRollupPrivateInputs.schema}),external_exports.object({type:external_exports.literal(ProvingRequestType.BLOCK_ROOT_EMPTY_TX_FIRST_ROLLUP),inputs:BlockRootEmptyTxFirstRollupPrivateInputs.schema}),external_exports.object({type:external_exports.literal(ProvingRequestType.BLOCK_ROOT_ROLLUP),inputs:BlockRootRollupPrivateInputs.schema}),external_exports.object({type:external_exports.literal(ProvingRequestType.BLOCK_ROOT_SINGLE_TX_ROLLUP),inputs:BlockRootSingleTxRollupPrivateInputs.schema}),external_exports.object({type:external_exports.literal(ProvingRequestType.BLOCK_MERGE_ROLLUP),inputs:BlockMergeRollupPrivateInputs.schema}),external_exports.object({type:external_exports.literal(ProvingRequestType.CHECKPOINT_ROOT_ROLLUP),inputs:CheckpointRootRollupPrivateInputs.schema}),external_exports.object({type:external_exports.literal(ProvingRequestType.CHECKPOINT_ROOT_SINGLE_BLOCK_ROLLUP),inputs:CheckpointRootSingleBlockRollupPrivateInputs.schema}),external_exports.object({type:external_exports.literal(ProvingRequestType.CHECKPOINT_PADDING_ROLLUP),inputs:CheckpointPaddingRollupPrivateInputs.schema}),external_exports.object({type:external_exports.literal(ProvingRequestType.CHECKPOINT_MERGE_ROLLUP),inputs:CheckpointMergeRollupPrivateInputs.schema}),external_exports.object({type:external_exports.literal(ProvingRequestType.ROOT_ROLLUP),inputs:RootRollupPrivateInputs.schema})]);var ProvingJobResult=external_exports.discriminatedUnion("type",[external_exports.object({type:external_exports.literal(ProvingRequestType.PUBLIC_VM),result:RecursiveProof.schemaFor(16400)}),external_exports.object({type:external_exports.literal(ProvingRequestType.PUBLIC_CHONK_VERIFIER),result:schemaForPublicInputsAndRecursiveProof(PublicChonkVerifierPublicInputs.schema,480)}),external_exports.object({type:external_exports.literal(ProvingRequestType.PRIVATE_TX_BASE_ROLLUP),result:schemaForPublicInputsAndRecursiveProof(TxRollupPublicInputs.schema,480)}),external_exports.object({type:external_exports.literal(ProvingRequestType.PUBLIC_TX_BASE_ROLLUP),result:schemaForPublicInputsAndRecursiveProof(TxRollupPublicInputs.schema,480)}),external_exports.object({type:external_exports.literal(ProvingRequestType.TX_MERGE_ROLLUP),result:schemaForPublicInputsAndRecursiveProof(TxRollupPublicInputs.schema,480)}),external_exports.object({type:external_exports.literal(ProvingRequestType.BLOCK_ROOT_FIRST_ROLLUP),result:schemaForPublicInputsAndRecursiveProof(BlockRollupPublicInputs.schema,480)}),external_exports.object({type:external_exports.literal(ProvingRequestType.BLOCK_ROOT_SINGLE_TX_FIRST_ROLLUP),result:schemaForPublicInputsAndRecursiveProof(BlockRollupPublicInputs.schema,480)}),external_exports.object({type:external_exports.literal(ProvingRequestType.BLOCK_ROOT_EMPTY_TX_FIRST_ROLLUP),result:schemaForPublicInputsAndRecursiveProof(BlockRollupPublicInputs.schema,480)}),external_exports.object({type:external_exports.literal(ProvingRequestType.BLOCK_ROOT_ROLLUP),result:schemaForPublicInputsAndRecursiveProof(BlockRollupPublicInputs.schema,480)}),external_exports.object({type:external_exports.literal(ProvingRequestType.BLOCK_ROOT_SINGLE_TX_ROLLUP),result:schemaForPublicInputsAndRecursiveProof(BlockRollupPublicInputs.schema,480)}),external_exports.object({type:external_exports.literal(ProvingRequestType.BLOCK_MERGE_ROLLUP),result:schemaForPublicInputsAndRecursiveProof(BlockRollupPublicInputs.schema,480)}),external_exports.object({type:external_exports.literal(ProvingRequestType.CHECKPOINT_ROOT_ROLLUP),result:schemaForPublicInputsAndRecursiveProof(CheckpointRollupPublicInputs.schema,480)}),external_exports.object({type:external_exports.literal(ProvingRequestType.CHECKPOINT_ROOT_SINGLE_BLOCK_ROLLUP),result:schemaForPublicInputsAndRecursiveProof(CheckpointRollupPublicInputs.schema,480)}),external_exports.object({type:external_exports.literal(ProvingRequestType.CHECKPOINT_PADDING_ROLLUP),result:schemaForPublicInputsAndRecursiveProof(CheckpointRollupPublicInputs.schema,480)}),external_exports.object({type:external_exports.literal(ProvingRequestType.CHECKPOINT_MERGE_ROLLUP),result:schemaForPublicInputsAndRecursiveProof(CheckpointRollupPublicInputs.schema,480)}),external_exports.object({type:external_exports.literal(ProvingRequestType.ROOT_ROLLUP),result:schemaForPublicInputsAndRecursiveProof(RootRollupPublicInputs.schema,410)}),external_exports.object({type:external_exports.literal(ProvingRequestType.PARITY_BASE),result:schemaForPublicInputsAndRecursiveProof(ParityPublicInputs.schema,410)}),external_exports.object({type:external_exports.literal(ProvingRequestType.PARITY_ROOT),result:schemaForPublicInputsAndRecursiveProof(ParityPublicInputs.schema,410)})]),ProvingJobId=external_exports.string(),ProofUri=external_exports.string().transform(value=>value),ProvingJob=external_exports.object({id:ProvingJobId,type:external_exports.nativeEnum(ProvingRequestType),epochNumber:EpochNumberSchema,inputsUri:ProofUri});var ProvingJobFulfilledResult=external_exports.object({status:external_exports.literal("fulfilled"),value:ProofUri}),ProvingJobRejectedResult=external_exports.object({status:external_exports.literal("rejected"),reason:external_exports.string()}),ProvingJobSettledResult=external_exports.discriminatedUnion("status",[ProvingJobFulfilledResult,ProvingJobRejectedResult]),ProvingJobStatus=external_exports.discriminatedUnion("status",[external_exports.object({status:external_exports.literal("in-queue")}),external_exports.object({status:external_exports.literal("in-progress")}),external_exports.object({status:external_exports.literal("not-found")}),ProvingJobFulfilledResult,ProvingJobRejectedResult]);var ProvingJobSourceSchema={getProvingJob:external_exports.function({input:external_exports.tuple([]),output:ProvingJob.optional()}),heartbeat:external_exports.function({input:external_exports.tuple([ProvingJobId]),output:external_exports.void()}),resolveProvingJob:external_exports.function({input:external_exports.tuple([ProvingJobId,ProvingJobResult]),output:external_exports.void()}),rejectProvingJob:external_exports.function({input:external_exports.tuple([ProvingJobId,external_exports.string()]),output:external_exports.void()})};async function tryStop(service,logger3){try{return typeof service=="object"&&service&&"stop"in service&&typeof service.stop=="function"?await service.stop():Promise.resolve()}catch(err){logger3?.error(`Error stopping service ${service.constructor?.name}: ${err}`)}}__name(tryStop,"tryStop");var BBCircuitVerifier=class{static{__name(this,"BBCircuitVerifier")}constructor(..._args){throwStub("BBCircuitVerifier")}},BatchChonkVerifier=class{static{__name(this,"BatchChonkVerifier")}constructor(..._args){throwStub("BatchChonkVerifier")}},QueuedIVCVerifier=class{static{__name(this,"QueuedIVCVerifier")}constructor(..._args){throwStub("QueuedIVCVerifier")}};var TestCircuitVerifier=class{static{__name(this,"TestCircuitVerifier")}verificationDelayMs;constructor(verificationDelayMs){this.verificationDelayMs=verificationDelayMs}verifyProof(_tx){return this.verificationDelayMs!==void 0&&this.verificationDelayMs>0?new Promise(resolve=>{setTimeout(()=>{resolve({valid:!0,durationMs:this.verificationDelayMs,totalDurationMs:this.verificationDelayMs})},this.verificationDelayMs)}):Promise.resolve({valid:!0,durationMs:0,totalDurationMs:0})}stop(){return Promise.resolve()}};import{pickL1ContractAddresses}from"@aztec/ethereum/l1-contract-addresses";var import_node_keystore2=__toESM(require_empty_stub(),1),import_actions=__toESM(require_empty_stub(),1),import_p2p2=__toESM(require_empty_stub(),1);var import_validator_client=__toESM(require_empty_stub(),1);async function blockResponseFromL2Block(block,options,context2){let response={header:block.header,archive:block.archive,hash:await block.hash(),checkpointNumber:block.checkpointNumber,indexWithinCheckpoint:block.indexWithinCheckpoint,number:block.number};return options.includeTransactions&&(response.body=block.body),options.includeL1PublishInfo&&(response.l1=l1PublishInfoFromL1PublishedData(context2?.l1)),options.includeAttestations&&(response.attestations=context2?.attestations??[]),response}__name(blockResponseFromL2Block,"blockResponseFromL2Block");function blockResponseFromBlockData(data,options,context2){let response={header:data.header,archive:data.archive,hash:data.blockHash,checkpointNumber:data.checkpointNumber,indexWithinCheckpoint:data.indexWithinCheckpoint,number:data.header.getBlockNumber()};return options.includeL1PublishInfo&&(response.l1=l1PublishInfoFromL1PublishedData(context2?.l1)),options.includeAttestations&&(response.attestations=context2?.attestations??[]),response}__name(blockResponseFromBlockData,"blockResponseFromBlockData");async function checkpointResponseFromPublishedCheckpoint(pc,options){let response={number:pc.checkpoint.number,header:pc.checkpoint.header,archive:pc.checkpoint.archive,checkpointOutHash:pc.checkpoint.getCheckpointOutHash(),startBlock:pc.checkpoint.blocks[0]?.number??BlockNumber.ZERO,blockCount:pc.checkpoint.blocks.length,feeAssetPriceModifier:pc.checkpoint.feeAssetPriceModifier};return options.includeBlocks&&(response.blocks=await Promise.all(pc.checkpoint.blocks.map(block=>blockResponseFromL2Block(block,{includeTransactions:options.includeTransactions,includeL1PublishInfo:!1,includeAttestations:!1})))),options.includeL1PublishInfo&&(response.l1=l1PublishInfoFromL1PublishedData(pc.l1)),options.includeAttestations&&(response.attestations=pc.attestations),response}__name(checkpointResponseFromPublishedCheckpoint,"checkpointResponseFromPublishedCheckpoint");function checkpointResponseFromCheckpointData(cd,options){let response={number:cd.checkpointNumber,header:cd.header,archive:cd.archive,checkpointOutHash:cd.checkpointOutHash,startBlock:cd.startBlock,blockCount:cd.blockCount,feeAssetPriceModifier:cd.feeAssetPriceModifier};return options.includeL1PublishInfo&&(response.l1=l1PublishInfoFromL1PublishedData(cd.l1)),options.includeAttestations&&(response.attestations=cd.attestations),response}__name(checkpointResponseFromCheckpointData,"checkpointResponseFromCheckpointData");async function projectProposedToCheckpointResponse(proposed,options,blocks){if(options.includeL1PublishInfo||options.includeAttestations)throw new Error("Proposed checkpoints have no L1 publish info or attestations");let response={number:proposed.checkpointNumber,header:proposed.header,archive:proposed.archive,checkpointOutHash:proposed.checkpointOutHash,startBlock:proposed.startBlock,blockCount:proposed.blockCount,feeAssetPriceModifier:proposed.feeAssetPriceModifier};if(options.includeBlocks){if(!blocks)throw new Error("Blocks must be supplied when includeBlocks is true");response.blocks=await Promise.all(blocks.map(block=>blockResponseFromL2Block(block,{includeTransactions:options.includeTransactions,includeL1PublishInfo:!1,includeAttestations:!1})))}return response}__name(projectProposedToCheckpointResponse,"projectProposedToCheckpointResponse");function isBlockTag(value){return BlockTag.includes(value)}__name(isBlockTag,"isBlockTag");function isCheckpointTag(value){return value==="checkpointed"||value==="proven"||value==="finalized"}__name(isCheckpointTag,"isCheckpointTag");function normalizeBlockParameter(param){if(BlockHash.isBlockHash(param))return{hash:param};if(typeof param=="number")return{number:param};if(typeof param=="string"){if(isBlockTag(param))return{tag:param==="latest"?"proposed":param};throw new BadRequestError(`Invalid BlockParameter tag: ${param}`)}if(typeof param=="object"&¶m!==null){if("number"in param)return{number:param.number};if("hash"in param)return{hash:param.hash};if("archive"in param)return{archive:param.archive};if("tag"in param){if(isBlockTag(param.tag))return{tag:param.tag};throw new BadRequestError(`Invalid BlockParameter tag: ${param.tag}`)}}throw new BadRequestError(`Invalid BlockParameter: ${JSON.stringify(param)}`)}__name(normalizeBlockParameter,"normalizeBlockParameter");async function resolveCheckpointParameter(param,blockSource){if(typeof param=="number")return{number:param};if(isCheckpointTag(param)){let tips=await blockSource.getL2Tips();switch(param){case"checkpointed":return{number:tips.checkpointed.checkpoint.number};case"proven":return{number:tips.proven.checkpoint.number};case"finalized":return{number:tips.finalized.checkpoint.number}}}if(typeof param=="object"&¶m!==null){if("number"in param)return{number:param.number};if("slot"in param)return{slot:param.slot}}throw new BadRequestError(`Invalid CheckpointParameter: ${JSON.stringify(param)}`)}__name(resolveCheckpointParameter,"resolveCheckpointParameter");var NodeBlockProvider=class{static{__name(this,"NodeBlockProvider")}blockSource;constructor(blockSource){this.blockSource=blockSource}async getBlock(param,options={}){let query=normalizeBlockParameter(param),wantTxs=!!options.includeTransactions,wantContext=!!options.includeL1PublishInfo||!!options.includeAttestations;if(wantTxs){let block=await this.blockSource.getBlock(query);if(!block)return;let ctx2=wantContext?await this.#getCheckpointContext(block.checkpointNumber):void 0;return await blockResponseFromL2Block(block,options,ctx2)}let data=await this.blockSource.getBlockData(query);if(!data)return;let ctx=wantContext?await this.#getCheckpointContext(data.checkpointNumber):void 0;return blockResponseFromBlockData(data,options,ctx)}getBlockData(param){let query=normalizeBlockParameter(param);return this.blockSource.getBlockData(query)}async getBlocks(from,limit,options={}){let wantTxs=!!options.includeTransactions,wantContext=!!options.includeL1PublishInfo||!!options.includeAttestations,onlyCheckpointed=!!options.onlyCheckpointed;if(wantTxs){let blocks=await this.blockSource.getBlocks({from,limit,onlyCheckpointed}),ctxByCheckpoint2=await this.#getCheckpointContextsForBlocks(wantContext?blocks:[]);return await Promise.all(blocks.map(block=>blockResponseFromL2Block(block,options,ctxByCheckpoint2.get(block.checkpointNumber))))}let dataItems=await this.blockSource.getBlocksData({from,limit,onlyCheckpointed}),ctxByCheckpoint=await this.#getCheckpointContextsForBlocks(wantContext?dataItems:[]);return await Promise.all(dataItems.map(data=>blockResponseFromBlockData(data,options,ctxByCheckpoint.get(data.checkpointNumber))))}async getCheckpoint(param,options={}){let query=await resolveCheckpointParameter(param,this.blockSource),confirmed=options.includeBlocks?await this.blockSource.getCheckpoint(query):await this.blockSource.getCheckpointData(query);if(confirmed)return await(options.includeBlocks?checkpointResponseFromPublishedCheckpoint(confirmed,options):checkpointResponseFromCheckpointData(confirmed,options));let proposed=await this.blockSource.getProposedCheckpointData(query);if(proposed){if(options.includeAttestations||options.includeL1PublishInfo)throw new BadRequestError("Options includeL1PublishInfo or includeAttestations cannot be satisfied for a proposed checkpoint");let blocks=options.includeBlocks?await this.blockSource.getBlocks({from:proposed.startBlock,limit:proposed.blockCount}):void 0;return await projectProposedToCheckpointResponse(proposed,options,blocks)}}async getCheckpoints(from,limit,options={}){if(options.includeBlocks){let checkpoints=await this.blockSource.getCheckpoints({from,limit});return await Promise.all(checkpoints.map(cp=>checkpointResponseFromPublishedCheckpoint(cp,options)))}return(await this.blockSource.getCheckpointsData({from,limit})).map(d=>checkpointResponseFromCheckpointData(d,options))}async#getCheckpointContext(checkpointNumber){let checkpoint=await this.blockSource.getCheckpointData({number:checkpointNumber});if(checkpoint)return{l1:checkpoint.l1,attestations:checkpoint.attestations}}async#getCheckpointContextsForBlocks(blocks){let unique2=Array.from(new Set(blocks.map(b=>b.checkpointNumber))),entries=await Promise.all(unique2.map(async n=>[n,await this.#getCheckpointContext(n)]));return new Map(entries)}};var NodeTxReceiptBuilder=class{static{__name(this,"NodeTxReceiptBuilder")}p2pClient;blockSource;debugLogStore;constructor(deps){this.p2pClient=deps.p2pClient,this.blockSource=deps.blockSource,this.debugLogStore=deps.debugLogStore}async getTxReceipt(txHash,options){let txPoolStatus=await this.p2pClient.getTxStatus(txHash),isKnownToPool=txPoolStatus==="pending"||txPoolStatus==="mined",indexed=await this.blockSource.getTxEffect(txHash),receipt;if(indexed)receipt=await this.#assembleMinedReceipt(indexed,options);else if(isKnownToPool){let tx;options?.includePendingTx&&(tx=await this.p2pClient.getTxByHashFromPool(txHash,{includeProof:!!options.includeProof})),receipt=new PendingTxReceipt(txHash,tx)}else receipt=new DroppedTxReceipt(txHash,"Tx dropped by P2P node");return this.debugLogStore.decorateReceiptWithLogs(txHash.toString(),receipt),receipt}async#assembleMinedReceipt(indexed,options){let blockNumber=indexed.l2BlockNumber,[tips,l1Constants]=await Promise.all([this.blockSource.getL2Tips(),this.blockSource.getL1Constants()]),status=this.#deriveMinedStatus(blockNumber,tips),epochNumber=getEpochAtSlot(indexed.slotNumber,l1Constants);return new MinedTxReceipt(indexed.data.txHash,status,MinedTxReceipt.executionResultFromRevertCode(indexed.data.revertCode),indexed.data.transactionFee.toBigInt(),indexed.l2BlockHash,blockNumber,indexed.slotNumber,indexed.txIndexInBlock,epochNumber,options?.includeTxEffect?indexed.data:void 0,void 0)}#deriveMinedStatus(blockNumber,tips){return blockNumber<=tips.finalized.block.number?TxStatus.FINALIZED:blockNumber<=tips.proven.block.number?TxStatus.PROVEN:blockNumber<=tips.checkpointed.block.number?TxStatus.CHECKPOINTED:TxStatus.PROPOSED}};var WorldStateSynchronizerError=class extends Error{static{__name(this,"WorldStateSynchronizerError")}constructor(message,options){super(message,options),this.name="WorldStateSynchronizerError"}};var WORLD_STATE_SYNC_ATTEMPTS=3,WORLD_STATE_SYNC_RETRY_DELAY_MS=100,NodeWorldStateQueries=class{static{__name(this,"NodeWorldStateQueries")}worldStateSynchronizer;blockSource;l1ToL2MessageSource;log;constructor(deps){this.worldStateSynchronizer=deps.worldStateSynchronizer,this.blockSource=deps.blockSource,this.l1ToL2MessageSource=deps.l1ToL2MessageSource,this.log=deps.log??createLogger("node:world-state-queries")}async findLeavesIndexes(referenceBlock,treeId,leafValues){let committedDb=await this.getWorldState(referenceBlock),maybeIndices=await committedDb.findLeafIndices(treeId,leafValues.map(x=>x.toBuffer())),definedIndices=maybeIndices.filter(x=>x!==void 0),blockNumbers=await committedDb.getBlockNumbersForLeafIndices(treeId,definedIndices),indexToBlockNumber=new Map;for(let i=0;i<definedIndices.length;i++){let blockNumber=blockNumbers[i];if(blockNumber===void 0)throw new Error(`Block number is undefined for leaf index ${definedIndices[i]} in tree ${MerkleTreeId[treeId]}`);indexToBlockNumber.set(definedIndices[i],blockNumber)}let uniqueBlockNumbers=[...new Set(indexToBlockNumber.values())],blockHashes=await Promise.all(uniqueBlockNumbers.map(blockNumber=>committedDb.getLeafValue(MerkleTreeId.ARCHIVE,BigInt(blockNumber)))),blockNumberToHash=new Map;for(let i=0;i<uniqueBlockNumbers.length;i++){let blockHash=blockHashes[i];if(blockHash===void 0)throw new Error(`Block hash is undefined for block number ${uniqueBlockNumbers[i]}`);blockNumberToHash.set(uniqueBlockNumbers[i],blockHash)}return maybeIndices.map(index=>{if(index===void 0)return;let blockNumber=indexToBlockNumber.get(index);if(blockNumber===void 0)throw new Error(`Block number not found for leaf index ${index} in tree ${MerkleTreeId[treeId]}`);let l2BlockHash=blockNumberToHash.get(blockNumber);if(l2BlockHash===void 0)throw new Error(`Block hash not found for block number ${blockNumber}`);return{l2BlockNumber:blockNumber,l2BlockHash,data:index}})}async getBlockHashMembershipWitness(referenceBlock,blockHash){let referenceBlockNumber=await this.#resolveBlockNumber(referenceBlock);if(referenceBlockNumber===BlockNumber.ZERO)return;let committedDb=await this.getWorldState(BlockNumber(referenceBlockNumber-1)),[pathAndIndex]=await committedDb.findSiblingPaths(MerkleTreeId.ARCHIVE,[blockHash]);return pathAndIndex===void 0?void 0:MembershipWitness.fromSiblingPath(pathAndIndex.index,pathAndIndex.path)}async getNoteHashMembershipWitness(referenceBlock,noteHash){let committedDb=await this.getWorldState(referenceBlock),[pathAndIndex]=await committedDb.findSiblingPaths(MerkleTreeId.NOTE_HASH_TREE,[noteHash]);return pathAndIndex===void 0?void 0:MembershipWitness.fromSiblingPath(pathAndIndex.index,pathAndIndex.path)}async getL1ToL2MessageMembershipWitness(referenceBlock,l1ToL2Message){let db=await this.getWorldState(referenceBlock),[witness]=await db.findSiblingPaths(MerkleTreeId.L1_TO_L2_MESSAGE_TREE,[l1ToL2Message]);if(witness)return[witness.index,witness.path]}async getL1ToL2MessageCheckpoint(l1ToL2Message){let messageIndex=await this.l1ToL2MessageSource.getL1ToL2MessageIndex(l1ToL2Message);return messageIndex!==void 0?InboxLeaf.checkpointNumberFromIndex(messageIndex):void 0}async getL2ToL1Messages(epoch){let blocks=await this.blockSource.getBlocks({epoch,onlyCheckpointed:!0});return chunkBy(blocks,block=>block.header.globalVariables.slotNumber).map(slotBlocks=>slotBlocks.map(block=>block.body.txEffects.map(txEffect=>txEffect.l2ToL1Msgs)))}getL2ToL1MembershipWitness(txHash,message,messageIndexInTx){return this.blockSource.getL2ToL1MembershipWitness(txHash,message,messageIndexInTx)}async getNullifierMembershipWitness(referenceBlock,nullifier){let db=await this.getWorldState(referenceBlock),[witness]=await db.findSiblingPaths(MerkleTreeId.NULLIFIER_TREE,[nullifier.toBuffer()]);if(!witness)return;let{index,path}=witness,leafPreimage=await db.getLeafPreimage(MerkleTreeId.NULLIFIER_TREE,index);if(leafPreimage)return new NullifierMembershipWitness(index,leafPreimage,path)}async getLowNullifierMembershipWitness(referenceBlock,nullifier){let committedDb=await this.getWorldState(referenceBlock),findResult=await committedDb.getPreviousValueIndex(MerkleTreeId.NULLIFIER_TREE,nullifier.toBigInt());if(!findResult)return;let{index,alreadyPresent}=findResult;if(alreadyPresent)throw new Error(`Cannot prove nullifier non-inclusion: nullifier ${nullifier.toBigInt()} already exists in the tree`);let preimageData=await committedDb.getLeafPreimage(MerkleTreeId.NULLIFIER_TREE,index),siblingPath=await committedDb.getSiblingPath(MerkleTreeId.NULLIFIER_TREE,BigInt(index));return new NullifierMembershipWitness(BigInt(index),preimageData,siblingPath)}async getPublicDataWitness(referenceBlock,leafSlot){let committedDb=await this.getWorldState(referenceBlock),lowLeafResult=await committedDb.getPreviousValueIndex(MerkleTreeId.PUBLIC_DATA_TREE,leafSlot.toBigInt());if(lowLeafResult){let preimage=await committedDb.getLeafPreimage(MerkleTreeId.PUBLIC_DATA_TREE,lowLeafResult.index),path=await committedDb.getSiblingPath(MerkleTreeId.PUBLIC_DATA_TREE,lowLeafResult.index);return new PublicDataWitness(lowLeafResult.index,preimage,path)}else return}async getPublicStorageAt(referenceBlock,contract,slot){let committedDb=await this.getWorldState(referenceBlock),leafSlot=await computePublicDataTreeLeafSlot(contract,slot),lowLeafResult=await committedDb.getPreviousValueIndex(MerkleTreeId.PUBLIC_DATA_TREE,leafSlot.toBigInt());return!lowLeafResult||!lowLeafResult.alreadyPresent?Fr.ZERO:(await committedDb.getLeafPreimage(MerkleTreeId.PUBLIC_DATA_TREE,lowLeafResult.index)).leaf.value}async getWorldState(block){let query=normalizeBlockParameter(block);for(let attempt=1;;attempt++)try{return await this.#resolveWorldState(query)}catch(err){if(attempt>=WORLD_STATE_SYNC_ATTEMPTS||!(err instanceof WorldStateSynchronizerError))throw err;this.log.verbose(`Retrying world state query after sync failure: ${err.message}`,{attempt,block:inspectBlockParameter(block)}),await sleep(WORLD_STATE_SYNC_RETRY_DELAY_MS)}}async#resolveWorldState(query){if("tag"in query&&query.tag==="proposed")return this.log.debug("Using committed db for latest block"),await this.worldStateSynchronizer.syncImmediate(),this.worldStateSynchronizer.getCommitted();let{blockNumber,blockHash}=await this.#resolveBlockNumberAndHash(query),blockSyncedTo=await this.worldStateSynchronizer.syncImmediate(blockNumber,blockHash);return this.log.debug(`Using verified snapshot for block ${blockNumber}, world state synced upto ${blockSyncedTo}`),await this.worldStateSynchronizer.getVerifiedSnapshot(blockNumber,blockHash)}async#resolveBlockNumberAndHash(query){let blockData=await this.blockSource.getBlockData(query);return blockData===void 0&&this.#throwOnUndefinedBlockData(query),{blockNumber:blockData.header.getBlockNumber(),blockHash:blockData.blockHash}}async#resolveBlockNumber(block){let blockQuery=normalizeBlockParameter(block),blockNumber=await this.blockSource.getBlockNumber(blockQuery);return blockNumber===void 0&&this.#throwOnUndefinedBlockData(blockQuery),blockNumber}#throwOnUndefinedBlockData(query){throw"hash"in query?new Error(`Block hash ${query.hash.toString()} not found when resolving query. If the node API has been queried with anchor block hash possibly a reorg has occurred.`):"archive"in query?new Error(`Block with archive ${query.archive.toString()} not found when resolving query.`):new WorldStateSynchronizerError(`Block not found for ${inspectBlockParameter(query)} when resolving query.`)}};var NodeMetrics=class{static{__name(this,"NodeMetrics")}constructor(_client,_name){}receivedTx(_durationMs,_isAccepted){throwStub("NodeMetrics.receivedTx")}recordSnapshot(_durationMs){throwStub("NodeMetrics.recordSnapshot")}recordSnapshotError(){throwStub("NodeMetrics.recordSnapshotError")}};var import_epoch_cache=__toESM(require_empty_stub(),1);import{SimulationOverridesBuilder as SimulationOverridesBuilder2}from"@aztec/ethereum/contracts";async function applyPublicDataOverrides(fork,publicStorage){if(!publicStorage?.length)return;let writes=await Promise.all(publicStorage.map(async o=>{let leafSlot=await computePublicDataTreeLeafSlot(o.contract,o.slot);return new PublicDataWrite(leafSlot,o.value)}));await fork.sequentialInsert(MerkleTreeId.PUBLIC_DATA_TREE,writes.map(w=>w.toBuffer()))}__name(applyPublicDataOverrides,"applyPublicDataOverrides");function _ts_add_disposable_resource(env2,value,async){if(value!=null){if(typeof value!="object"&&typeof value!="function")throw new TypeError("Object expected.");var dispose,inner;if(async){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");dispose=value[Symbol.asyncDispose]}if(dispose===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");dispose=value[Symbol.dispose],async&&(inner=dispose)}if(typeof dispose!="function")throw new TypeError("Object not disposable.");inner&&(dispose=__name(function(){try{inner.call(this)}catch(e2){return Promise.reject(e2)}},"dispose")),env2.stack.push({value,dispose,async})}else async&&env2.stack.push({async:!0});return value}__name(_ts_add_disposable_resource,"_ts_add_disposable_resource");function _ts_dispose_resources(env2){var _SuppressedError=typeof SuppressedError=="function"?SuppressedError:function(error2,suppressed,message){var e2=new Error(message);return e2.name="SuppressedError",e2.error=error2,e2.suppressed=suppressed,e2};return(_ts_dispose_resources=__name(function(env3){function fail(e2){env3.error=env3.hasError?new _SuppressedError(e2,env3.error,"An error was suppressed during disposal."):e2,env3.hasError=!0}__name(fail,"fail");var r2,s2=0;function next(){for(;r2=env3.stack.pop();)try{if(!r2.async&&s2===1)return s2=0,env3.stack.push(r2),Promise.resolve().then(next);if(r2.dispose){var result=r2.dispose.call(r2.value);if(r2.async)return s2|=2,Promise.resolve(result).then(next,function(e2){return fail(e2),next()})}else s2|=1}catch(e2){fail(e2)}if(s2===1)return env3.hasError?Promise.reject(env3.error):Promise.resolve();if(env3.hasError)throw env3.error}return __name(next,"next"),next()},"_ts_dispose_resources"))(env2)}__name(_ts_dispose_resources,"_ts_dispose_resources");var NodePublicCallsSimulator=class{static{__name(this,"NodePublicCallsSimulator")}blockSource;worldStateSynchronizer;l1ToL2MessageSource;contractDataSource;globalVariableBuilder;rollupContract;epochCache;signatureContext;config;telemetry;log;constructor(deps){this.blockSource=deps.blockSource,this.worldStateSynchronizer=deps.worldStateSynchronizer,this.l1ToL2MessageSource=deps.l1ToL2MessageSource,this.contractDataSource=deps.contractDataSource,this.globalVariableBuilder=deps.globalVariableBuilder,this.rollupContract=deps.rollupContract,this.epochCache=deps.epochCache,this.signatureContext=deps.signatureContext,this.config=deps.config,this.telemetry=deps.telemetry??getTelemetryClient(),this.log=deps.log??createLogger("node:public-calls-simulator")}async simulate(tx,skipFeeEnforcement=!1,overrides){let env2={stack:[],error:void 0,hasError:!1};try{let gasSettings=tx.data.constants.txContext.gasSettings,txGasLimit=gasSettings.gasLimits.l2Gas,teardownGasLimit=gasSettings.teardownGasLimits.l2Gas;if(txGasLimit+teardownGasLimit>this.config.rpcSimulatePublicMaxGasLimit)throw new BadRequestError(`Transaction total gas limit ${txGasLimit+teardownGasLimit} (${txGasLimit} + ${teardownGasLimit}) exceeds maximum gas limit ${this.config.rpcSimulatePublicMaxGasLimit} for simulation`);let txHash=tx.getTxHash(),[l2Tips,proposedCheckpointData]=await Promise.all([this.blockSource.getL2Tips(),this.blockSource.getProposedCheckpointData()]),latestBlockNumber=l2Tips.proposed.number,blockNumber=BlockNumber.add(latestBlockNumber,1),atCheckpointBoundary=(proposedCheckpointData?BlockNumber.add(proposedCheckpointData.startBlock,proposedCheckpointData.blockCount-1):l2Tips.checkpointed.block.number)===l2Tips.proposed.number,{globalVariables:newGlobalVariables,targetCheckpoint}=atCheckpointBoundary?await this.buildGlobalVariablesForNewCheckpoint(l2Tips,proposedCheckpointData,blockNumber):{globalVariables:await this.copyGlobalVariablesFromLatestProposedBlock(latestBlockNumber,blockNumber)},publicProcessorFactory=new PublicProcessorFactory(this.contractDataSource,new DateProvider,this.telemetry,this.log.getBindings());this.log.verbose(`Simulating public calls for tx ${txHash}`,{globalVariables:newGlobalVariables.toInspect(),txHash,blockNumber,atCheckpointBoundary}),await this.worldStateSynchronizer.syncImmediate(latestBlockNumber);let nextCheckpointMessages=await this.getNextCheckpointMessages(targetCheckpoint),merkleTreeFork=_ts_add_disposable_resource(env2,await this.worldStateSynchronizer.fork(latestBlockNumber),!0);nextCheckpointMessages!==void 0&&(this.log.debug(`Appending ${nextCheckpointMessages.length} L1-to-L2 messages to the world state tree for the next checkpoint`,{checkpointNumber:targetCheckpoint}),await appendL1ToL2MessagesToTree(merkleTreeFork,nextCheckpointMessages)),await applyPublicDataOverrides(merkleTreeFork,overrides?.publicStorage);let config2=PublicSimulatorConfig.from({skipFeeEnforcement,collectDebugLogs:!0,collectHints:!1,collectCallMetadata:!0,collectStatistics:!1,collectionLimits:CollectionLimitsConfig.from({maxDebugLogMemoryReads:this.config.rpcSimulatePublicMaxDebugLogMemoryReads})}),contractsDB=new PublicContractsDB(this.contractDataSource,this.log.getBindings());overrides?.contracts&&contractsDB.addContracts(Object.values(overrides.contracts).map(({instance})=>instance));let processor=publicProcessorFactory.create(merkleTreeFork,newGlobalVariables,config2,contractsDB),[processedTxs,failedTxs,_usedTxs,returns,debugLogs]=await processor.process([tx]);if(failedTxs.length)throw this.log.warn(`Simulated tx ${txHash} fails: ${failedTxs[0].error}`,{txHash}),failedTxs[0].error;let[processedTx]=processedTxs;return new PublicSimulationOutput(processedTx.revertReason,processedTx.globalVariables,processedTx.txEffect,returns,processedTx.gasUsed,debugLogs)}catch(e2){env2.error=e2,env2.hasError=!0}finally{let result=_ts_dispose_resources(env2);result&&await result}}async getNextCheckpointMessages(targetCheckpoint){if(targetCheckpoint!==void 0)try{return await this.l1ToL2MessageSource.getL1ToL2Messages(targetCheckpoint)}catch(err){isErrorClass(err,L1ToL2MessagesNotReadyError2)?this.log.warn(`L1-to-L2 messages for checkpoint ${targetCheckpoint} are not ready yet (simulating without them)`,{checkpointNumber:targetCheckpoint}):this.log.error(`Failed to get L1-to-L2 messages for checkpoint ${targetCheckpoint} (simulating without them)`,err,{checkpointNumber:targetCheckpoint});return}}async copyGlobalVariablesFromLatestProposedBlock(latestBlockNumber,blockNumber){let latestBlockData=await this.blockSource.getBlockData({number:latestBlockNumber});if(!latestBlockData)throw new Error(`Cannot simulate public calls: latest proposed block ${latestBlockNumber} has no header on this node (torn archiver snapshot); retry`);return GlobalVariables.from({...latestBlockData.header.globalVariables,blockNumber})}async buildGlobalVariablesForNewCheckpoint(l2Tips,proposedCheckpointData,blockNumber){let checkpointedCheckpointNumber=l2Tips.checkpointed.checkpoint.number,proposedCheckpointNumber=proposedCheckpointData?.checkpointNumber??checkpointedCheckpointNumber,targetSlot=this.computeTargetSlot(proposedCheckpointData),plan=await this.buildSimulationOverridesPlan(proposedCheckpointData,checkpointedCheckpointNumber),checkpointGlobalVariables=await this.globalVariableBuilder.buildCheckpointGlobalVariables(EthAddress.ZERO,AztecAddress.ZERO,targetSlot,plan);return{globalVariables:GlobalVariables.from({blockNumber,...checkpointGlobalVariables}),targetCheckpoint:CheckpointNumber(proposedCheckpointNumber+1)}}computeTargetSlot(proposedCheckpointData){let slotFromNextL1Timestamp=this.epochCache.getEpochAndSlotInNextL1Slot().slot+import_epoch_cache.PROPOSER_PIPELINING_SLOT_OFFSET,slotAfterProposedCheckpoint=proposedCheckpointData?proposedCheckpointData.header.slotNumber+1:void 0;return SlotNumber(Math.max(...compactArray([slotFromNextL1Timestamp,slotAfterProposedCheckpoint])))}async buildSimulationOverridesPlan(proposedCheckpointData,checkpointedCheckpointNumber){let rollup=this.rollupContract;if(rollup){if(proposedCheckpointData)return buildCheckpointSimulationOverridesPlan({checkpointNumber:CheckpointNumber(proposedCheckpointData.checkpointNumber+1),proposedCheckpointData,checkpointedCheckpointNumber,rollup,signatureContext:this.signatureContext,log:this.log});let validationStatus=await this.blockSource.getPendingChainValidationStatus();if(!validationStatus.valid)return buildCheckpointSimulationOverridesPlan({checkpointNumber:CheckpointNumber(checkpointedCheckpointNumber+1),invalidateToPendingCheckpointNumber:CheckpointNumber(validationStatus.checkpoint.checkpointNumber-1),checkpointedCheckpointNumber,rollup,signatureContext:this.signatureContext,log:this.log})}return new SimulationOverridesBuilder2().withChainTips({pending:checkpointedCheckpointNumber,proven:checkpointedCheckpointNumber}).build()}};function applyDecs2203RFactory3(){function createAddInitializerMethod(initializers,decoratorFinishedRef){return __name(function(initializer3){assertNotFinished(decoratorFinishedRef,"addInitializer"),assertCallable(initializer3,"An initializer"),initializers.push(initializer3)},"addInitializer")}__name(createAddInitializerMethod,"createAddInitializerMethod");function memberDec(dec,name,desc,initializers,kind,isStatic,isPrivate,metadata,value){var kindStr;switch(kind){case 1:kindStr="accessor";break;case 2:kindStr="method";break;case 3:kindStr="getter";break;case 4:kindStr="setter";break;default:kindStr="field"}var ctx={kind:kindStr,name:isPrivate?"#"+name:name,static:isStatic,private:isPrivate,metadata},decoratorFinishedRef={v:!1};ctx.addInitializer=createAddInitializerMethod(initializers,decoratorFinishedRef);var get,set2;kind===0?isPrivate?(get=desc.get,set2=desc.set):(get=__name(function(){return this[name]},"get"),set2=__name(function(v){this[name]=v},"set")):kind===2?get=__name(function(){return desc.value},"get"):((kind===1||kind===3)&&(get=__name(function(){return desc.get.call(this)},"get")),(kind===1||kind===4)&&(set2=__name(function(v){desc.set.call(this,v)},"set"))),ctx.access=get&&set2?{get,set:set2}:get?{get}:{set:set2};try{return dec(value,ctx)}finally{decoratorFinishedRef.v=!0}}__name(memberDec,"memberDec");function assertNotFinished(decoratorFinishedRef,fnName){if(decoratorFinishedRef.v)throw new Error("attempted to call "+fnName+" after decoration was finished")}__name(assertNotFinished,"assertNotFinished");function assertCallable(fn,hint){if(typeof fn!="function")throw new TypeError(hint+" must be a function")}__name(assertCallable,"assertCallable");function assertValidReturnValue(kind,value){var type=typeof value;if(kind===1){if(type!=="object"||value===null)throw new TypeError("accessor decorators must return an object with get, set, or init properties or void 0");value.get!==void 0&&assertCallable(value.get,"accessor.get"),value.set!==void 0&&assertCallable(value.set,"accessor.set"),value.init!==void 0&&assertCallable(value.init,"accessor.init")}else if(type!=="function"){var hint;throw kind===0?hint="field":kind===10?hint="class":hint="method",new TypeError(hint+" decorators must return a function or void 0")}}__name(assertValidReturnValue,"assertValidReturnValue");function applyMemberDec(ret2,base,decInfo,name,kind,isStatic,isPrivate,initializers,metadata){var decs=decInfo[0],desc,init2,value;isPrivate?kind===0||kind===1?desc={get:decInfo[3],set:decInfo[4]}:kind===3?desc={get:decInfo[3]}:kind===4?desc={set:decInfo[3]}:desc={value:decInfo[3]}:kind!==0&&(desc=Object.getOwnPropertyDescriptor(base,name)),kind===1?value={get:desc.get,set:desc.set}:kind===2?value=desc.value:kind===3?value=desc.get:kind===4&&(value=desc.set);var newValue,get,set2;if(typeof decs=="function")newValue=memberDec(decs,name,desc,initializers,kind,isStatic,isPrivate,metadata,value),newValue!==void 0&&(assertValidReturnValue(kind,newValue),kind===0?init2=newValue:kind===1?(init2=newValue.init,get=newValue.get||value.get,set2=newValue.set||value.set,value={get,set:set2}):value=newValue);else for(var i=decs.length-1;i>=0;i--){var dec=decs[i];if(newValue=memberDec(dec,name,desc,initializers,kind,isStatic,isPrivate,metadata,value),newValue!==void 0){assertValidReturnValue(kind,newValue);var newInit;kind===0?newInit=newValue:kind===1?(newInit=newValue.init,get=newValue.get||value.get,set2=newValue.set||value.set,value={get,set:set2}):value=newValue,newInit!==void 0&&(init2===void 0?init2=newInit:typeof init2=="function"?init2=[init2,newInit]:init2.push(newInit))}}if(kind===0||kind===1){if(init2===void 0)init2=__name(function(instance,init3){return init3},"init");else if(typeof init2!="function"){var ownInitializers=init2;init2=__name(function(instance,init3){for(var value2=init3,i2=0;i2<ownInitializers.length;i2++)value2=ownInitializers[i2].call(instance,value2);return value2},"init")}else{var originalInitializer=init2;init2=__name(function(instance,init3){return originalInitializer.call(instance,init3)},"init")}ret2.push(init2)}kind!==0&&(kind===1?(desc.get=value.get,desc.set=value.set):kind===2?desc.value=value:kind===3?desc.get=value:kind===4&&(desc.set=value),isPrivate?kind===1?(ret2.push(function(instance,args){return value.get.call(instance,args)}),ret2.push(function(instance,args){return value.set.call(instance,args)})):kind===2?ret2.push(value):ret2.push(function(instance,args){return value.call(instance,args)}):Object.defineProperty(base,name,desc))}__name(applyMemberDec,"applyMemberDec");function applyMemberDecs(Class2,decInfos,metadata){for(var ret2=[],protoInitializers,staticInitializers,existingProtoNonFields=new Map,existingStaticNonFields=new Map,i=0;i<decInfos.length;i++){var decInfo=decInfos[i];if(Array.isArray(decInfo)){var kind=decInfo[1],name=decInfo[2],isPrivate=decInfo.length>3,isStatic=kind>=5,base,initializers;if(isStatic?(base=Class2,kind=kind-5,staticInitializers=staticInitializers||[],initializers=staticInitializers):(base=Class2.prototype,protoInitializers=protoInitializers||[],initializers=protoInitializers),kind!==0&&!isPrivate){var existingNonFields=isStatic?existingStaticNonFields:existingProtoNonFields,existingKind=existingNonFields.get(name)||0;if(existingKind===!0||existingKind===3&&kind!==4||existingKind===4&&kind!==3)throw new Error("Attempted to decorate a public method/accessor that has the same name as a previously decorated public method/accessor. This is not currently supported by the decorators plugin. Property name was: "+name);!existingKind&&kind>2?existingNonFields.set(name,kind):existingNonFields.set(name,!0)}applyMemberDec(ret2,base,decInfo,name,kind,isStatic,isPrivate,initializers,metadata)}}return pushInitializers(ret2,protoInitializers),pushInitializers(ret2,staticInitializers),ret2}__name(applyMemberDecs,"applyMemberDecs");function pushInitializers(ret2,initializers){initializers&&ret2.push(function(instance){for(var i=0;i<initializers.length;i++)initializers[i].call(instance);return instance})}__name(pushInitializers,"pushInitializers");function applyClassDecs(targetClass,classDecs,metadata){if(classDecs.length>0){for(var initializers=[],newClass=targetClass,name=targetClass.name,i=classDecs.length-1;i>=0;i--){var decoratorFinishedRef={v:!1};try{var nextNewClass=classDecs[i](newClass,{kind:"class",name,addInitializer:createAddInitializerMethod(initializers,decoratorFinishedRef),metadata})}finally{decoratorFinishedRef.v=!0}nextNewClass!==void 0&&(assertValidReturnValue(10,nextNewClass),newClass=nextNewClass)}return[defineMetadata(newClass,metadata),function(){for(var i2=0;i2<initializers.length;i2++)initializers[i2].call(newClass)}]}}__name(applyClassDecs,"applyClassDecs");function defineMetadata(Class2,metadata){return Object.defineProperty(Class2,Symbol.metadata||Symbol.for("Symbol.metadata"),{configurable:!0,enumerable:!0,value:metadata})}return __name(defineMetadata,"defineMetadata"),__name(function(targetClass,memberDecs,classDecs,parentClass){if(parentClass!==void 0)var parentMetadata=parentClass[Symbol.metadata||Symbol.for("Symbol.metadata")];var metadata=Object.create(parentMetadata===void 0?null:parentMetadata),e2=applyMemberDecs(targetClass,memberDecs,metadata);return classDecs.length||defineMetadata(targetClass,metadata),{e:e2,get c(){return applyClassDecs(targetClass,classDecs,metadata)}}},"applyDecs2203R")}__name(applyDecs2203RFactory3,"applyDecs2203RFactory");function _apply_decs_2203_r3(targetClass,memberDecs,classDecs,parentClass){return(_apply_decs_2203_r3=applyDecs2203RFactory3())(targetClass,memberDecs,classDecs,parentClass)}__name(_apply_decs_2203_r3,"_apply_decs_2203_r");var _dec3,_initProto3;_dec3=trackSpan("AztecNodeService.simulatePublicCalls",tx=>({[Attributes.TX_HASH]:tx.getTxHash().toString()}));var AztecNodeService=class{static{__name(this,"AztecNodeService")}static{({e:[_initProto3]}=_apply_decs_2203_r3(this,[[_dec3,2,"simulatePublicCalls"]],[]))}metrics;isUploadingSnapshot=(_initProto3(this),!1);sequencerPausedMinTxsPerBlock;nodePublicCallsSimulator;worldStateQueries;blockProvider;txReceiptBuilder;tracer;config;p2pClient;blockSource;logsSource;contractDataSource;l1ToL2MessageSource;worldStateSynchronizer;sequencer;proverNode;slasherClient;validatorsSentinel;stopStartedWatchers;l1ChainId;version;globalVariableBuilder;rollupContract;feeProvider;epochCache;packageVersion;peerProofVerifier;rpcProofVerifier;telemetry;log;blobClient;validatorClient;keyStoreManager;debugLogStore;automineSequencer;constructor(deps){if(this.config=deps.config,this.p2pClient=deps.p2pClient,this.blockSource=deps.blockSource,this.logsSource=deps.logsSource,this.contractDataSource=deps.contractDataSource,this.l1ToL2MessageSource=deps.l1ToL2MessageSource,this.worldStateSynchronizer=deps.worldStateSynchronizer,this.sequencer=deps.sequencer,this.proverNode=deps.proverNode,this.slasherClient=deps.slasherClient,this.validatorsSentinel=deps.validatorsSentinel,this.stopStartedWatchers=deps.stopStartedWatchers,this.l1ChainId=deps.l1ChainId,this.version=deps.version,this.globalVariableBuilder=deps.globalVariableBuilder,this.rollupContract=deps.rollupContract,this.feeProvider=deps.feeProvider,this.epochCache=deps.epochCache,this.packageVersion=deps.packageVersion,this.peerProofVerifier=deps.peerProofVerifier,this.rpcProofVerifier=deps.rpcProofVerifier,this.telemetry=deps.telemetry??getTelemetryClient(),this.log=deps.log??createLogger("node"),this.blobClient=deps.blobClient,this.validatorClient=deps.validatorClient,this.keyStoreManager=deps.keyStoreManager,this.debugLogStore=deps.debugLogStore??new NullDebugLogStore,this.automineSequencer=deps.automineSequencer,this.metrics=new NodeMetrics(this.telemetry,"AztecNodeService"),this.tracer=this.telemetry.getTracer("AztecNodeService"),this.nodePublicCallsSimulator=new NodePublicCallsSimulator({blockSource:this.blockSource,worldStateSynchronizer:this.worldStateSynchronizer,l1ToL2MessageSource:this.l1ToL2MessageSource,contractDataSource:this.contractDataSource,globalVariableBuilder:this.globalVariableBuilder,rollupContract:this.rollupContract,epochCache:this.epochCache,signatureContext:{chainId:this.l1ChainId,rollupAddress:this.config.rollupAddress},config:this.config,telemetry:this.telemetry,log:this.log.createChild("public-calls-simulator")}),this.worldStateQueries=new NodeWorldStateQueries({worldStateSynchronizer:this.worldStateSynchronizer,blockSource:this.blockSource,l1ToL2MessageSource:this.l1ToL2MessageSource,log:this.log.createChild("world-state-queries")}),this.blockProvider=new NodeBlockProvider(this.blockSource),this.txReceiptBuilder=new NodeTxReceiptBuilder({p2pClient:this.p2pClient,blockSource:this.blockSource,debugLogStore:this.debugLogStore}),this.log.info(`Aztec Node version: ${this.packageVersion}`),this.log.info(`Aztec Node started on chain 0x${this.l1ChainId.toString(16)}`,pickL1ContractAddresses(this.config)),this.debugLogStore.isEnabled&&this.config.realProofs)throw new Error("debugLogStore should never be enabled when realProofs are set")}getProofVerifier(){return this.rpcProofVerifier}async getWorldStateSyncStatus(){return(await this.worldStateSynchronizer.status()).syncSummary}getChainTips(){return this.blockSource.getL2Tips()}getL1Constants(){return this.blockSource.getL1Constants()}getSyncedL2SlotNumber(){return this.blockSource.getSyncedL2SlotNumber()}getSyncedL2EpochNumber(){return this.blockSource.getSyncedL2EpochNumber()}getSyncedL1Timestamp(){return this.blockSource.getL1Timestamp()}getCheckpointsData(query){return this.blockSource.getCheckpointsData(query)}async getBlockNumber(tip){return tip===void 0||tip==="proposed"?this.blockSource.getBlockNumber():await this.blockSource.getBlockNumber({tag:tip})??BlockNumber.ZERO}async getCheckpointNumber(tip){let tips=await this.blockSource.getL2Tips();switch(tip){case void 0:case"checkpointed":return tips.checkpointed.checkpoint.number;case"proven":return tips.proven.checkpoint.number;case"finalized":return tips.finalized.checkpoint.number}}getBlock(param,options={}){return this.blockProvider.getBlock(param,options)}getBlockData(param){return this.blockProvider.getBlockData(param)}getBlocks(from,limit,options={}){return this.blockProvider.getBlocks(from,limit,options)}getCheckpoint(param,options={}){return this.blockProvider.getCheckpoint(param,options)}getCheckpoints(from,limit,options={}){return this.blockProvider.getCheckpoints(from,limit,options)}getSequencer(){return this.sequencer}getAutomineSequencer(){return this.automineSequencer}getProverNode(){return this.proverNode}getBlockSource(){return this.blockSource}getContractDataSource(){return this.contractDataSource}getP2P(){return this.p2pClient}getL1ContractAddresses(){return Promise.resolve(pickL1ContractAddresses(this.config))}getEncodedEnr(){return Promise.resolve(this.p2pClient.getEnr()?.encodeTxt())}async getAllowedPublicSetup(){return[...await(0,import_p2p2.getDefaultAllowedSetupFunctions)(),...this.config.txPublicSetupAllowListExtend??[]]}isReady(){return Promise.resolve(this.p2pClient.isReady()??!1)}async getNodeInfo(){let[nodeVersion,rollupVersion,chainId,enr,contractAddresses,protocolContractAddresses,l1Constants]=await Promise.all([this.getNodeVersion(),this.getVersion(),this.getChainId(),this.getEncodedEnr(),this.getL1ContractAddresses(),this.getProtocolContractAddresses(),this.blockSource.getL1Constants()]),maxTxGas=getNetworkTxGasLimits(this.config,l1Constants);return{nodeVersion,l1ChainId:chainId,rollupVersion,enr,l1ContractAddresses:contractAddresses,protocolContractAddresses,realProofs:!!this.config.realProofs,txsLimits:{gas:{daGas:maxTxGas.daGas,l2Gas:maxTxGas.l2Gas}}}}async getCurrentMinFees(){return await this.feeProvider.getCurrentMinFees()}async getPredictedMinFees(manaUsage){return await this.feeProvider.getPredictedMinFees(manaUsage)}async getMaxPriorityFees(){for await(let tx of this.p2pClient.iteratePendingTxs({includeProof:!1}))return tx.getGasSettings().maxPriorityFeesPerGas;return GasFees.from({feePerDaGas:0n,feePerL2Gas:0n})}getNodeVersion(){return Promise.resolve(this.packageVersion)}getVersion(){return Promise.resolve(this.version)}getChainId(){return Promise.resolve(this.l1ChainId)}getContractClass(id){return this.contractDataSource.getContractClass(id)}async getContract(address,referenceBlock="latest"){let blockData=await this.getBlockData(referenceBlock);if(!blockData)throw new Error(`Reference block ${inspectBlockParameter(referenceBlock)} not found when querying contract ${address}. If the node API has been queried with an anchor block hash, possibly a reorg has occurred.`);return this.contractDataSource.getContract(address,blockData.header.globalVariables.timestamp)}getPrivateLogsByTags(query){return this.logsSource.getPrivateLogsByTags(query)}getPublicLogsByTags(query){return this.logsSource.getPublicLogsByTags(query)}async sendTx(tx){await this.#sendTx(tx)}async#sendTx(tx){let timer=new Timer,txHash=tx.getTxHash().toString(),valid=await this.isValidTx(tx);if(valid.result!=="valid"){let reason=valid.reason.join(", ");throw this.metrics.receivedTx(timer.ms(),!1),this.log.warn(`Received invalid tx ${txHash}: ${reason}`,{txHash}),new Error(`Invalid tx: ${reason}`)}try{await this.p2pClient.sendTx(tx)}catch(err){throw this.metrics.receivedTx(timer.ms(),!1),this.log.warn(`Mempool rejected tx ${txHash}: ${err.message}`,{txHash}),err}let duration3=timer.ms();this.metrics.receivedTx(duration3,!0),this.log.info(`Received tx ${txHash} in ${duration3}ms`,{txHash})}getTxReceipt(txHash,options){return this.txReceiptBuilder.getTxReceipt(txHash,options)}getTxEffect(txHash){return this.blockSource.getTxEffect(txHash)}async stop(){this.log.info("Stopping Aztec Node"),await this.stopStartedWatchers(),await tryStop(this.slasherClient),await Promise.all([tryStop(this.peerProofVerifier),tryStop(this.rpcProofVerifier)]),await tryStop(this.sequencer),await tryStop(this.automineSequencer),await tryStop(this.proverNode),await tryStop(this.p2pClient),await tryStop(this.worldStateSynchronizer),await tryStop(this.blockSource),await tryStop(this.blobClient),await tryStop(this.telemetry),this.log.info("Stopped Aztec Node")}getBlobClient(){return this.blobClient}getPendingTxs(limit,after,options){return this.p2pClient.getPendingTxs(limit,after,options)}getPendingTxCount(){return this.p2pClient.getPendingTxCount()}getPeers(includePending){return this.p2pClient.getPeers(includePending)}getCheckpointAttestationsForSlot(slot,proposalPayloadHash){return this.p2pClient.getCheckpointAttestationsForSlot(slot,proposalPayloadHash)}getProposalsForSlot(slot){return this.p2pClient.getProposalsForSlot(slot)}getTxByHash(txHash,options){return this.p2pClient.getTxByHashFromPool(txHash,{includeProof:!!options?.includeProof})}async getTxsByHash(txHashes,options){let txs=await this.p2pClient.getTxsByHashFromPool(txHashes,{includeProof:!!options?.includeProof});return compactArray(txs)}findLeavesIndexes(referenceBlock,treeId,leafValues){return this.worldStateQueries.findLeavesIndexes(referenceBlock,treeId,leafValues)}getBlockHashMembershipWitness(referenceBlock,blockHash){return this.worldStateQueries.getBlockHashMembershipWitness(referenceBlock,blockHash)}getNoteHashMembershipWitness(referenceBlock,noteHash){return this.worldStateQueries.getNoteHashMembershipWitness(referenceBlock,noteHash)}getL1ToL2MessageMembershipWitness(referenceBlock,l1ToL2Message){return this.worldStateQueries.getL1ToL2MessageMembershipWitness(referenceBlock,l1ToL2Message)}getL1ToL2MessageCheckpoint(l1ToL2Message){return this.worldStateQueries.getL1ToL2MessageCheckpoint(l1ToL2Message)}getL2ToL1Messages(epoch){return this.worldStateQueries.getL2ToL1Messages(epoch)}getL2ToL1MembershipWitness(txHash,message,messageIndexInTx){return this.worldStateQueries.getL2ToL1MembershipWitness(txHash,message,messageIndexInTx)}getNullifierMembershipWitness(referenceBlock,nullifier){return this.worldStateQueries.getNullifierMembershipWitness(referenceBlock,nullifier)}getLowNullifierMembershipWitness(referenceBlock,nullifier){return this.worldStateQueries.getLowNullifierMembershipWitness(referenceBlock,nullifier)}getPublicDataWitness(referenceBlock,leafSlot){return this.worldStateQueries.getPublicDataWitness(referenceBlock,leafSlot)}getPublicStorageAt(referenceBlock,contract,slot){return this.worldStateQueries.getPublicStorageAt(referenceBlock,contract,slot)}simulatePublicCalls(tx,skipFeeEnforcement=!1,overrides){return this.nodePublicCallsSimulator.simulate(tx,skipFeeEnforcement,overrides)}async isValidTx(tx,{isSimulation,skipFeeEnforcement}={}){let db=this.worldStateSynchronizer.getCommitted(),verifier=isSimulation?void 0:this.rpcProofVerifier,{ts:nextSlotTimestamp}=this.epochCache.getEpochAndSlotInNextL1Slot(),blockNumber=BlockNumber(await this.blockSource.getBlockNumber()+1),l1Constants=await this.blockSource.getL1Constants(),networkTxGasLimits=getNetworkTxGasLimits(this.config,l1Constants);return await(0,import_p2p2.createTxValidatorForAcceptingTxsOverRPC)(db,this.contractDataSource,verifier,{timestamp:nextSlotTimestamp,blockNumber,l1ChainId:this.l1ChainId,rollupVersion:this.version,setupAllowList:[...await(0,import_p2p2.getDefaultAllowedSetupFunctions)(),...this.config.txPublicSetupAllowListExtend??[]],gasFees:await this.getCurrentMinFees(),skipFeeEnforcement,isSimulation,txsPermitted:!this.config.disableTransactions,maxTxL2Gas:networkTxGasLimits.l2Gas,maxTxDAGas:networkTxGasLimits.daGas},this.log.getBindings()).validateTx(tx)}getConfig(){let keys=AztecNodeAdminConfigSchema.keyof().options;return Promise.resolve(pick2(this.config,...keys))}async setConfig(config2){let newConfig={...this.config,...config2},sequencerUpdate={...config2};this.sequencerPausedMinTxsPerBlock!==void 0&&sequencerUpdate.minTxsPerBlock!==void 0&&(this.sequencerPausedMinTxsPerBlock=sequencerUpdate.minTxsPerBlock,delete sequencerUpdate.minTxsPerBlock),this.sequencer?.updateConfig(sequencerUpdate),this.automineSequencer?.updateConfig(sequencerUpdate),this.slasherClient?.updateConfig(config2),this.validatorsSentinel?.updateConfig(config2),await this.p2pClient.updateP2PConfig(config2);let archiver=this.blockSource;if("updateConfig"in archiver&&archiver.updateConfig(config2),newConfig.realProofs!==this.config.realProofs)if(await Promise.all([tryStop(this.peerProofVerifier),tryStop(this.rpcProofVerifier)]),newConfig.realProofs){this.peerProofVerifier=await BatchChonkVerifier.new(newConfig,newConfig.bbChonkVerifyMaxBatch,"peer");let rpcVerifier=await BBCircuitVerifier.new(newConfig);this.rpcProofVerifier=new QueuedIVCVerifier(rpcVerifier,newConfig.numConcurrentIVCVerifiers)}else this.peerProofVerifier=new TestCircuitVerifier,this.rpcProofVerifier=new TestCircuitVerifier;this.config=newConfig}getProtocolContractAddresses(){return Promise.resolve({classRegistry:ProtocolContractAddress.ContractClassRegistry,feeJuice:ProtocolContractAddress.FeeJuice,instanceRegistry:ProtocolContractAddress.ContractInstanceRegistry,multiCallEntrypoint:STANDARD_MULTI_CALL_ENTRYPOINT_ADDRESS})}registerContractFunctionSignatures(signatures){return this.contractDataSource.registerContractFunctionSignatures(signatures)}getValidatorsStats(){return this.validatorsSentinel?.computeStats()??Promise.resolve({stats:{},slotWindow:0})}getValidatorStats(validatorAddress,fromSlot,toSlot){return this.validatorsSentinel?.getValidatorStats(validatorAddress,fromSlot,toSlot)??Promise.resolve(void 0)}async startSnapshotUpload(location){let archiver=this.blockSource;if(!("backupTo"in archiver))throw this.metrics.recordSnapshotError(),new Error("Archiver implementation does not support backups. Cannot generate snapshot.");if(!archiver.isInitialSyncComplete())throw this.metrics.recordSnapshotError(),new Error("Archiver initial sync not complete. Cannot start snapshot.");if(!await archiver.getL2Tips().then(tips=>tips.proposed.hash))throw this.metrics.recordSnapshotError(),new Error("Archiver has no latest L2 block hash downloaded. Cannot start snapshot.");if(this.isUploadingSnapshot)throw this.metrics.recordSnapshotError(),new Error("Snapshot upload already in progress. Cannot start another one until complete.");this.isUploadingSnapshot=!0;let timer=new Timer;return(0,import_actions.uploadSnapshot)(location,this.blockSource,this.worldStateSynchronizer,this.config,this.log).then(()=>{this.isUploadingSnapshot=!1,this.metrics.recordSnapshot(timer.ms())}).catch(err=>{this.isUploadingSnapshot=!1,this.metrics.recordSnapshotError(),this.log.error(`Error uploading snapshot: ${err}`)}),Promise.resolve()}async rollbackTo(targetBlock,force,resumeSync=!0){let archiver=this.blockSource;if(!("rollbackTo"in archiver))throw new Error("Archiver implementation does not support rollbacks.");let finalizedBlock=await archiver.getL2Tips().then(tips=>tips.finalized.block.number);if(targetBlock<finalizedBlock)if(force)this.log.warn(`Clearing world state database to allow rolling back behind finalized block ${finalizedBlock}`),await this.worldStateSynchronizer.clear(),await this.p2pClient.clear();else throw new Error(`Cannot rollback to block ${targetBlock} as it is before finalized ${finalizedBlock}`);try{this.log.info("Pausing archiver and world state sync to start rollback"),await archiver.stop(),await this.worldStateSynchronizer.stopSync();let currentBlock=await archiver.getBlockNumber(),blocksToUnwind=currentBlock-targetBlock;this.log.info(`Unwinding ${count(blocksToUnwind,"block")} from L2 block ${currentBlock} to ${targetBlock}`),await archiver.rollbackTo(targetBlock),this.log.info("Unwinding complete.")}catch(err){throw this.log.error("Error during rollback",err),err}finally{resumeSync?(this.log.info("Resuming world state and archiver sync."),this.worldStateSynchronizer.resumeSync(),archiver.resume()):this.log.info("Sync left paused after rollback (resumeSync=false).")}}async pauseSync(){this.log.info("Pausing archiver and world state sync"),await this.blockSource.stop(),await this.worldStateSynchronizer.stopSync()}resumeSync(){return this.log.info("Resuming world state and archiver sync."),this.worldStateSynchronizer.resumeSync(),this.blockSource.resume(),Promise.resolve()}pauseSequencer(){if(this.automineSequencer)return this.automineSequencer.pause(),Promise.resolve();if(this.sequencer)return this.sequencerPausedMinTxsPerBlock===void 0&&(this.sequencerPausedMinTxsPerBlock=this.sequencer.getSequencer().getConfig().minTxsPerBlock??0,this.sequencer.updateConfig({minTxsPerBlock:Number.MAX_SAFE_INTEGER}),this.log.info("Sequencer paused (minTxsPerBlock set to MAX_SAFE_INTEGER)",{previousMinTxsPerBlock:this.sequencerPausedMinTxsPerBlock})),Promise.resolve();throw new BadRequestError("Cannot pause sequencer: no sequencer is running")}resumeSequencer(){if(this.automineSequencer)return this.automineSequencer.resume(),Promise.resolve();if(this.sequencer){if(this.sequencerPausedMinTxsPerBlock!==void 0){let restored=this.sequencerPausedMinTxsPerBlock;this.sequencerPausedMinTxsPerBlock=void 0,this.sequencer.updateConfig({minTxsPerBlock:restored}),this.log.info("Sequencer resumed (minTxsPerBlock restored)",{minTxsPerBlock:restored})}return Promise.resolve()}throw new BadRequestError("Cannot resume sequencer: no sequencer is running")}getSlashOffenses(round){if(!this.slasherClient)throw new Error("Slasher client not enabled");return round==="all"?this.slasherClient.getOffenses():this.slasherClient.gatherOffensesForRound(round==="current"?void 0:BigInt(round))}async reloadKeystore(){if(!this.config.keyStoreDirectory?.length)throw new BadRequestError("Cannot reload keystore: node is not using a file-based keystore. Set KEY_STORE_DIRECTORY to use file-based keystores.");if(!this.validatorClient)throw new BadRequestError("Cannot reload keystore: validator is not enabled.");this.log.info("Reloading keystore from disk");let keyStores=(0,import_node_keystore2.loadKeystores)(this.config.keyStoreDirectory),newManager=new import_node_keystore2.KeystoreManager((0,import_node_keystore2.mergeKeystores)(keyStores));if(await newManager.validateSigners(),import_validator_client.ValidatorClient.validateKeyStoreConfiguration(newManager,this.log),this.keyStoreManager&&this.sequencer){let oldAdapter=import_validator_client.NodeKeystoreAdapter.fromKeyStoreManager(this.keyStoreManager),availablePublishers=new Set(oldAdapter.getAttesterAddresses().flatMap(a=>oldAdapter.getPublisherAddresses(a).map(p=>p.toString().toLowerCase()))),newAdapter2=import_validator_client.NodeKeystoreAdapter.fromKeyStoreManager(newManager);for(let attester of newAdapter2.getAttesterAddresses()){let pubs=newAdapter2.getPublisherAddresses(attester);if(pubs.length>0&&!pubs.some(p=>availablePublishers.has(p.toString().toLowerCase())))throw new BadRequestError(`Cannot reload keystore: validator ${attester} has publisher keys [${pubs.map(p=>p.toString()).join(", ")}] but none match the L1 signers initialized at startup [${[...availablePublishers].join(", ")}]. Publishers cannot be hot-reloaded \u2014 use an existing publisher key or restart the node.`)}}let newAdapter=import_validator_client.NodeKeystoreAdapter.fromKeyStoreManager(newManager),newAddresses=newAdapter.getAttesterAddresses(),oldAddresses=this.keyStoreManager?import_validator_client.NodeKeystoreAdapter.fromKeyStoreManager(this.keyStoreManager).getAttesterAddresses():[],oldSet=new Set(oldAddresses.map(a=>a.toString())),newSet=new Set(newAddresses.map(a=>a.toString())),added=newAddresses.filter(a=>!oldSet.has(a.toString())),removed=oldAddresses.filter(a=>!newSet.has(a.toString()));if(added.length>0&&this.log.info(`Keystore reload: adding attester keys: ${added.map(a=>a.toString()).join(", ")}`),removed.length>0&&this.log.info(`Keystore reload: removing attester keys: ${removed.map(a=>a.toString()).join(", ")}`),added.length===0&&removed.length===0&&this.log.info("Keystore reload: attester keys unchanged"),this.validatorClient.reloadKeystore(newManager),this.sequencer&&this.sequencer.updatePublisherNodeKeyStore(newAdapter),this.slasherClient&&!this.config.slashSelfAllowed){let slashValidatorsNever=unique([...this.config.slashValidatorsNever??[],...newAddresses].map(a=>a.toString())).map(EthAddress.fromString);this.slasherClient.updateConfig({slashValidatorsNever})}this.keyStoreManager=newManager,this.log.info("Keystore reloaded: coinbase, feeRecipient, and attester keys updated")}async mineBlock(){if(this.automineSequencer){await this.automineSequencer.buildEmptyBlock();return}if(!this.sequencer)throw new BadRequestError("Cannot mine block: no sequencer is running");let currentBlockNumber=await this.getBlockNumber(),{slotDuration}=await this.blockSource.getL1Constants(),timeoutSeconds=Math.ceil(slotDuration*1.5),originalMinTxsPerBlock=this.sequencer.getSequencer().getConfig().minTxsPerBlock;this.sequencer.updateConfig({minTxsPerBlock:0});try{this.sequencer.trigger(),await retryUntil(async()=>await this.getBlockNumber()>currentBlockNumber?!0:void 0,"mineBlock",timeoutSeconds,.1)}finally{this.sequencer.updateConfig({minTxsPerBlock:originalMinTxsPerBlock})}}async prove(upToCheckpoint){if(!this.automineSequencer)throw new BadRequestError("Cannot prove checkpoint: no automine sequencer is running");return await this.automineSequencer.prove(upToCheckpoint)}async warpL2TimeAtLeastTo(targetTimestamp){if(!this.automineSequencer)throw new BadRequestError("Cannot warp L2 time: no automine sequencer is running");await this.automineSequencer.warpTo(targetTimestamp)}async warpL2TimeAtLeastBy(duration3){if(!this.automineSequencer)throw new BadRequestError("Cannot warp L2 time: no automine sequencer is running");await this.automineSequencer.warpBy(duration3)}getWorldState(block){return this.worldStateQueries.getWorldState(block)}};var import_client22=__toESM(require_empty_stub(),1);var import_epoch_cache2=__toESM(require_empty_stub(),1);import{createEthereumChain}from"@aztec/ethereum/chain";import{getPublicClient,makeL1HttpTransport}from"@aztec/ethereum/client";import{RegistryContract,RollupContract as RollupContract2}from"@aztec/ethereum/contracts";import{pickL1ContractAddresses as pickL1ContractAddresses2}from"@aztec/ethereum/l1-contract-addresses";var import_node_keystore3=__toESM(require_empty_stub(),1),import_actions2=__toESM(require_empty_stub(),1),import_factories3=__toESM(require_empty_stub(),1),import_p2p4=__toESM(require_empty_stub(),1),import_prover_node=__toESM(require_empty_stub(),1),import_config33=__toESM(require_empty_stub(),1),import_sequencer_client=__toESM(require_empty_stub(),1),import_automine=__toESM(require_empty_stub(),1),import_slasher4=__toESM(require_empty_stub(),1);var import_validator_client2=__toESM(require_empty_stub(),1);import{createPublicClient}from"viem";var import_slasher3=__toESM(require_empty_stub(),1);var DummyP2P=class{static{__name(this,"DummyP2P")}validateTxsReceivedInBlockProposal(_txs){return Promise.resolve()}clear(){throw new Error('DummyP2P does not implement "clear".')}getPendingTxs(){throw new Error('DummyP2P does not implement "getPendingTxs"')}getEncodedEnr(){throw new Error('DummyP2P does not implement "getEncodedEnr"')}getPeers(_includePending){throw new Error('DummyP2P does not implement "getPeers"')}getGossipMeshPeerCount(_topicType){return Promise.resolve(0)}broadcastProposal(_proposal){throw new Error('DummyP2P does not implement "broadcastProposal"')}broadcastCheckpointProposal(_proposal){throw new Error('DummyP2P does not implement "broadcastCheckpointProposal"')}broadcastCheckpointAttestations(_attestations){throw new Error('DummyP2P does not implement "broadcastCheckpointAttestations"')}registerBlockProposalHandler(_handler){throw new Error('DummyP2P does not implement "registerBlockProposalHandler"')}registerValidatorCheckpointProposalHandler(_handler){throw new Error('DummyP2P does not implement "registerValidatorCheckpointProposalHandler"')}registerAllNodesCheckpointProposalHandler(_handler){throw new Error('DummyP2P does not implement "registerAllNodesCheckpointProposalHandler"')}requestTxs(_txHashes){throw new Error('DummyP2P does not implement "requestTxs"')}requestTxByHash(_txHash){throw new Error('DummyP2P does not implement "requestTxByHash"')}sendTx(_tx){throw new Error('DummyP2P does not implement "sendTx"')}handleFailedExecution(_txHashes){throw new Error('DummyP2P does not implement "handleFailedExecution"')}getTxByHashFromPool(_txHash){throw new Error('DummyP2P does not implement "getTxByHashFromPool"')}getTxByHash(_txHash){throw new Error('DummyP2P does not implement "getTxByHash"')}getArchivedTxByHash(_txHash){throw new Error('DummyP2P does not implement "getArchivedTxByHash"')}getTxStatus(_txHash){return Promise.resolve("mined")}iteratePendingTxs(){throw new Error('DummyP2P does not implement "iteratePendingTxs"')}iterateEligiblePendingTxs(){throw new Error('DummyP2P does not implement "iterateEligiblePendingTxs"')}getPendingTxCount(){throw new Error('DummyP2P does not implement "getPendingTxCount"')}hasEligiblePendingTxs(_minCount){throw new Error('DummyP2P does not implement "hasEligiblePendingTxs"')}start(){throw new Error('DummyP2P does not implement "start"')}stop(){throw new Error('DummyP2P does not implement "stop"')}isReady(){throw new Error('DummyP2P does not implement "isReady"')}getStatus(){throw new Error('DummyP2P does not implement "getStatus"')}getEnr(){throw new Error('DummyP2P does not implement "getEnr"')}isP2PClient(){throw new Error('DummyP2P does not implement "isP2PClient"')}getTxProvider(){throw new Error('DummyP2P does not implement "getTxProvider"')}getTxsByHash(_txHashes){throw new Error('DummyP2P does not implement "getTxsByHash"')}getCheckpointAttestationsForSlot(_slot,_proposalPayloadHash){throw new Error('DummyP2P does not implement "getCheckpointAttestationsForSlot"')}addOwnCheckpointAttestations(_attestations){throw new Error('DummyP2P does not implement "addOwnCheckpointAttestations"')}getProposalsForSlot(_slot){return Promise.resolve({blockProposals:[],checkpointProposals:[]})}hasCheckpointProposalForSlot(_slot){return Promise.resolve(!1)}getL2BlockHash(_number2){throw new Error('DummyP2P does not implement "getL2BlockHash"')}updateP2PConfig(_config){throw new Error('DummyP2P does not implement "updateP2PConfig"')}getL2Tips(){throw new Error('DummyP2P does not implement "getL2Tips"')}handleBlockStreamEvent(_event){throw new Error('DummyP2P does not implement "handleBlockStreamEvent"')}sync(){throw new Error('DummyP2P does not implement "sync"')}getTxsByHashFromPool(_txHashes){throw new Error('DummyP2P does not implement "getTxsByHashFromPool"')}hasTxsInPool(_txHashes){throw new Error('DummyP2P does not implement "hasTxsInPool"')}getSyncedLatestBlockNum(){throw new Error('DummyP2P does not implement "getSyncedLatestBlockNum"')}getSyncedProvenBlockNum(){throw new Error('DummyP2P does not implement "getSyncedProvenBlockNum"')}getSyncedLatestSlot(){throw new Error('DummyP2P does not implement "getSyncedLatestSlot"')}protectTxs(_txHashes,_blockHeader){throw new Error('DummyP2P does not implement "protectTxs".')}prepareForSlot(_slotNumber){return Promise.resolve()}addReqRespSubProtocol(_subProtocol,_handler){throw new Error('DummyP2P does not implement "addReqRespSubProtocol".')}handleAuthRequestFromPeer(_authRequest,_peerId){throw new Error('DummyP2P does not implement "handleAuthRequestFromPeer".')}registerThisValidatorAddresses(_address){}registerDuplicateProposalCallback(_callback){throw new Error('DummyP2P does not implement "registerDuplicateProposalCallback"')}registerOversizedProposalCallback(_callback){throw new Error('DummyP2P does not implement "registerOversizedProposalCallback"')}registerDuplicateAttestationCallback(_callback){throw new Error('DummyP2P does not implement "registerDuplicateAttestationCallback"')}registerCheckpointAttestationCallback(_callback){throw new Error('DummyP2P does not implement "registerCheckpointAttestationCallback"')}hasBlockProposalsForSlot(_slot){throw new Error('DummyP2P does not implement "hasBlockProposalsForSlot"')}};var TXEFeeProvider=class{static{__name(this,"TXEFeeProvider")}getCurrentMinFees(){return Promise.resolve(new GasFees(0,0))}getPredictedMinFees(){return Promise.resolve(times(FEE_ORACLE_LAG,()=>new GasFees(0,0)))}},TXEGlobalVariablesBuilder=class{static{__name(this,"TXEGlobalVariablesBuilder")}buildCheckpointGlobalVariables(_coinbase,_feeRecipient,_slotNumber,_simulationOverridesPlan){let vars=makeGlobalVariables();return Promise.resolve({chainId:vars.chainId,version:vars.version,slotNumber:vars.slotNumber,timestamp:vars.timestamp,coinbase:vars.coinbase,feeRecipient:vars.feeRecipient,gasFees:vars.gasFees})}};var MockEpochCache=class{static{__name(this,"MockEpochCache")}getCommittee(_slot="now"){return Promise.resolve({committee:void 0,seed:0n,epoch:EpochNumber.ZERO,isEscapeHatchOpen:!1})}getSlotNow(){return SlotNumber(0)}getTargetSlot(){return SlotNumber(0)}getEpochNow(){return EpochNumber.ZERO}getTargetEpoch(){return EpochNumber.ZERO}getEpochAndSlotNow(){return{epoch:EpochNumber.ZERO,slot:SlotNumber(0),ts:0n,nowMs:0n}}getEpochAndSlotInNextL1Slot(){return{epoch:EpochNumber.ZERO,slot:SlotNumber(0),ts:0n,nowSeconds:0n}}getTargetEpochAndSlotInNextL1Slot(){return this.getEpochAndSlotInNextL1Slot()}getProposerIndexEncoding(_epoch,_slot,_seed){return"0x00"}computeProposerIndex(_slot,_epoch,_seed,_size2){return 0n}getCurrentAndNextSlot(){return{currentSlot:SlotNumber(0),nextSlot:SlotNumber(0)}}getTargetAndNextSlot(){return{targetSlot:SlotNumber(0),nextSlot:SlotNumber(0)}}getProposerAttesterAddressInSlot(_slot){return Promise.resolve(void 0)}isInCommittee(_slot,_validator){return Promise.resolve(!1)}getRegisteredValidators(){return Promise.resolve([])}filterInCommittee(_slot,_validators){return Promise.resolve([])}isEscapeHatchOpen(_epoch){return Promise.resolve(!1)}isEscapeHatchOpenAtSlot(_slot){return Promise.resolve(!1)}getL1Constants(){return EmptyL1RollupConstants}};var TXESynchronizer=class{constructor(nativeWorldStateService){this.nativeWorldStateService=nativeWorldStateService}static{__name(this,"TXESynchronizer")}blockNumber=BlockNumber.ZERO;static async create(){let nativeWorldStateService=await NativeWorldStateService.ephemeral();return new this(nativeWorldStateService)}async handleL2Block(block,l1ToL2Messages=[]){await this.nativeWorldStateService.handleL2BlockAndMessages(block,padArrayEnd(l1ToL2Messages,Fr.ZERO,1024)),this.blockNumber=block.header.globalVariables.blockNumber}syncImmediate(_minBlockNumber,_blockHash){return Promise.resolve(this.blockNumber)}getCommitted(){return this.nativeWorldStateService.getCommitted()}fork(block){return this.nativeWorldStateService.fork(block?BlockNumber(block):void 0)}getSnapshot(blockNumber){return this.nativeWorldStateService.getSnapshot(BlockNumber(blockNumber))}getVerifiedSnapshot(blockNumber,_blockHash){return Promise.resolve(this.getSnapshot(blockNumber))}backupTo(dstPath,compact2){return this.nativeWorldStateService.backupTo(dstPath,compact2)}start(){throw new Error('TXE Synchronizer does not implement "start"')}status(){throw new Error('TXE Synchronizer does not implement "status"')}stop(){throw new Error('TXE Synchronizer does not implement "stop"')}stopSync(){throw new Error('TXE Synchronizer does not implement "stopSync"')}resumeSync(){throw new Error('TXE Synchronizer does not implement "resumeSync"')}clear(){throw new Error('TXE Synchronizer does not implement "clear"')}};var VERSION7=1,CHAIN_ID=1,PACKAGE_VERSION="txe",TXEStateMachine=class{constructor(node,synchronizer,archiver,anchorBlockStore,contractSyncService,contractClassService,txResolver){this.node=node;this.synchronizer=synchronizer;this.archiver=archiver;this.anchorBlockStore=anchorBlockStore;this.contractSyncService=contractSyncService;this.contractClassService=contractClassService;this.txResolver=txResolver}static{__name(this,"TXEStateMachine")}static async create(archiver,anchorBlockStore,contractStore,noteStore){let synchronizer=await TXESynchronizer.create(),aztecNodeConfig={},log2=createLogger("txe_node"),node=new AztecNodeService({config:aztecNodeConfig,p2pClient:new DummyP2P,blockSource:archiver,logsSource:archiver,contractDataSource:archiver,l1ToL2MessageSource:archiver,worldStateSynchronizer:synchronizer,sequencer:void 0,proverNode:void 0,slasherClient:void 0,validatorsSentinel:void 0,stopStartedWatchers:__name(async()=>{},"stopStartedWatchers"),l1ChainId:CHAIN_ID,version:VERSION7,globalVariableBuilder:new TXEGlobalVariablesBuilder,rollupContract:void 0,feeProvider:new TXEFeeProvider,epochCache:new MockEpochCache,packageVersion:PACKAGE_VERSION,peerProofVerifier:new TestCircuitVerifier,rpcProofVerifier:new TestCircuitVerifier,telemetry:void 0,log:log2}),contractClassService=new ContractClassService(node,contractStore),contractSyncService=new ContractSyncService(node,contractStore,contractClassService,noteStore,createLogger("txe:contract_sync")),txResolver=new TxResolverService(node);return new this(node,synchronizer,archiver,anchorBlockStore,contractSyncService,contractClassService,txResolver)}get l2TipsProvider(){let node=this.node;return{getL2Tips:__name(()=>node.getChainTips(),"getL2Tips")}}async handleL2Block(block,l1ToL2Messages=[]){let checkpointNumber=CheckpointNumber.fromBlockNumber(block.number),checkpoint=new Checkpoint(block.archive,CheckpointHeader.from({lastArchiveRoot:block.header.lastArchive.root,inHash:Fr.ZERO,blobsHash:Fr.ZERO,blockHeadersHash:Fr.ZERO,epochOutHash:Fr.ZERO,slotNumber:block.header.globalVariables.slotNumber,timestamp:block.header.globalVariables.timestamp,coinbase:block.header.globalVariables.coinbase,feeRecipient:block.header.globalVariables.feeRecipient,gasFees:block.header.globalVariables.gasFees,totalManaUsed:block.header.totalManaUsed,accumulatedFees:block.header.totalFees}),[block],checkpointNumber),publishedCheckpoint=new PublishedCheckpoint(checkpoint,new L1PublishedData(BigInt(block.header.globalVariables.blockNumber),block.header.globalVariables.timestamp,block.header.globalVariables.blockNumber.toString()),[]);this.contractSyncService.wipe(),await Promise.all([this.synchronizer.handleL2Block(block,l1ToL2Messages),this.archiver.addCheckpoints([publishedCheckpoint],void 0),this.anchorBlockStore.setHeader(block.header)])}};async function makeTxEffect(noteCache,txBlockNumber){let txEffect=TxEffect.empty();noteCache.finish();let nonceGenerator=noteCache.getNonceGenerator();return txEffect.noteHashes=await Promise.all(noteCache.getAllNotes().map(async(pendingNote,i)=>computeUniqueNoteHash(await computeNoteHashNonce(nonceGenerator,i),await siloNoteHash(pendingNote.note.contractAddress,pendingNote.noteHashForConsumption)))),txEffect.nullifiers=noteCache.getAllNullifiers(),txEffect.txHash=new TxHash(new Fr(txBlockNumber)),txEffect}__name(makeTxEffect,"makeTxEffect");var TXEAccountStore=class{static{__name(this,"TXEAccountStore")}#accounts;constructor(store){this.#accounts=store.openMap("accounts")}async getAccount(key){let completeAddress=await this.#accounts.getAsync(key.toString());if(!completeAddress)throw new Error(`Account not found: ${key.toString()}`);return CompleteAddress.fromBuffer(completeAddress)}async setAccount(key,value){await this.#accounts.set(key.toString(),value.toBuffer())}};function emptyLastCallState(){return{offchainEffects:[],queried:!1,txHash:Fr.ZERO,anchorBlockTimestamp:0n}}__name(emptyLastCallState,"emptyLastCallState");var TXESession=class _TXESession{constructor(logger3,sessionStore,stateMachine,oracleHandler,contractStore,noteStore,keyStore,addressStore,accountStore,senderTaggingStore,recipientTaggingStore,taggingSecretSourcesStore,capsuleStore,factStore,privateEventStore,jobCoordinator,currentJobId,chainId,version2,nextBlockTimestamp,artifactResolver,rootPath,packageName){this.logger=logger3;this.sessionStore=sessionStore;this.stateMachine=stateMachine;this.oracleHandler=oracleHandler;this.contractStore=contractStore;this.noteStore=noteStore;this.keyStore=keyStore;this.addressStore=addressStore;this.accountStore=accountStore;this.senderTaggingStore=senderTaggingStore;this.recipientTaggingStore=recipientTaggingStore;this.taggingSecretSourcesStore=taggingSecretSourcesStore;this.capsuleStore=capsuleStore;this.factStore=factStore;this.privateEventStore=privateEventStore;this.jobCoordinator=jobCoordinator;this.currentJobId=currentJobId;this.chainId=chainId;this.version=version2;this.nextBlockTimestamp=nextBlockTimestamp;this.artifactResolver=artifactResolver;this.rootPath=rootPath;this.packageName=packageName}static{__name(this,"TXESession")}state={name:"TOP_LEVEL"};authwits=new Map;taggingSecretStrategy=void 0;lastCallInfo=emptyLastCallState();txeOracleVersion;disposed=!1;async dispose(){if(!this.disposed){this.disposed=!0;try{await this.stateMachine.synchronizer.nativeWorldStateService.close()}catch(err){this.logger.warn("Error closing native world state during session dispose",err)}try{await this.sessionStore.close()}catch(err){this.logger.warn("Error closing session LMDB during dispose",err)}}}static async init(contractStore,artifactResolver,rootPath,packageName){let store=await openEphemeralStore("txe-session",void 0,2),addressStore=new AddressStore(store),privateEventStore=new PrivateEventStore(store),noteStore=new NoteStore(store),senderTaggingStore=new SenderTaggingStore(store),recipientTaggingStore=new RecipientTaggingStore(store),taggingSecretSourcesStore=new TaggingSecretSourcesStore(store),capsuleStore=new CapsuleStore(store),factStore=new FactStore(store),keyStore=new KeyStore(store),accountStore=new TXEAccountStore(store),jobCoordinator=new JobCoordinator(store);jobCoordinator.registerStores([capsuleStore,factStore,senderTaggingStore,recipientTaggingStore,privateEventStore,noteStore]);let archiver=new TXEArchiver(store),anchorBlockStore=new AnchorBlockStore(store),stateMachine=await TXEStateMachine.create(archiver,anchorBlockStore,contractStore,noteStore),nextBlockTimestamp=BigInt(Math.floor(new Date().getTime()/1e3)),version2=new Fr(await stateMachine.node.getVersion()),chainId=new Fr(await stateMachine.node.getChainId()),initialJobId=jobCoordinator.beginJob(),logger3=createLogger("txe:session"),topLevelOracleHandler=new TXEOracleTopLevelContext(stateMachine,contractStore,noteStore,keyStore,addressStore,accountStore,senderTaggingStore,recipientTaggingStore,taggingSecretSourcesStore,capsuleStore,factStore,privateEventStore,nextBlockTimestamp,version2,chainId,new Map,void 0,artifactResolver,rootPath,packageName);return await topLevelOracleHandler.mineDeploymentNullifiers([STANDARD_AUTH_REGISTRY_ADDRESS]),new _TXESession(logger3,store,stateMachine,topLevelOracleHandler,contractStore,noteStore,keyStore,addressStore,accountStore,senderTaggingStore,recipientTaggingStore,taggingSecretSourcesStore,capsuleStore,factStore,privateEventStore,jobCoordinator,initialJobId,version2,chainId,nextBlockTimestamp,artifactResolver,rootPath,packageName)}processFunction(functionName,inputs){try{if(Object.hasOwn(LEGACY_ORACLE_REGISTRY,functionName))return callTxeLegacyHandler(functionName,inputs,this.oracleHandler);let translator=new RPCTranslator(this,this.oracleHandler),validatedFunctionName=external_exports.string().refine(fn=>typeof translator[fn]=="function"&&!fn.startsWith("handlerAs")&&fn!=="constructor").parse(functionName);return translator[validatedFunctionName](...inputs)}catch(error2){if(error2 instanceof external_exports.ZodError){let versionHint;throw this.txeOracleVersion?this.txeOracleVersion.minor>3?versionHint=` The test uses Aztec.nr test oracle version ${this.txeOracleVersion.major}.${this.txeOracleVersion.minor}, but this test environment only supports up to ${2}.${3}. Upgrade the Aztec CLI to a compatible version. See https://docs.aztec.network/errors/12`:versionHint=` The test's oracle version (${this.txeOracleVersion.major}.${this.txeOracleVersion.minor}) is compatible with this test environment (${2}.${3}), so this oracle should be available. This is an unexpected error, please report it. See https://docs.aztec.network/errors/13`:versionHint=" The test appears to use an older version of Aztec.nr that does not support test environment oracle versioning. Update Aztec.nr to a compatible version. See https://docs.aztec.network/errors/12",new Error(`Unknown oracle '${functionName}'.${versionHint}`)}else throw error2 instanceof Error?new Error(`Execution error while processing function ${functionName} in state ${this.state.name}: ${error2.message}`):new Error(`Unknown execution error while processing function ${functionName} in state ${this.state.name}`)}}async cycleJob(){return await this.jobCoordinator.commitJob(this.currentJobId),this.currentJobId=this.jobCoordinator.beginJob(),this.currentJobId}resetLastCall(){let notQueriedMessageCount=this.lastCallInfo.queried?0:this.lastCallInfo.offchainEffects.filter(payload=>payload[0]?.equals(OFFCHAIN_MESSAGE_IDENTIFIER)).length;notQueriedMessageCount>0&&this.logger.warn(`Dropping ${notQueriedMessageCount} unqueried offchain message(s) from the previous top-level call. To deliver them, call \`env.offchain_messages()\` and forward the result to the recipient contract's \`offchain_receive\` utility before issuing another top-level call. To intentionally discard, assign to \`let _ = env.offchain_messages()\` to silence this warning.`),this.lastCallInfo=emptyLastCallState()}recordOffchainEffect(data){this.lastCallInfo.offchainEffects.push(data)}setLastCallContext(txHash,anchorBlockTimestamp){this.lastCallInfo.txHash=txHash,this.lastCallInfo.anchorBlockTimestamp=anchorBlockTimestamp}async withTopLevelCallTracking(work){this.resetLastCall();let anchorBlockTimestamp=(await this.stateMachine.node.getBlockData("latest")).header.globalVariables.timestamp,{result,txHash}=await work();return this.setLastCallContext(txHash??Fr.ZERO,anchorBlockTimestamp),result}getLastCallOffchainEffects(){this.lastCallInfo.queried=!0;let effects=this.lastCallInfo.offchainEffects;if(effects.length>MAX_OFFCHAIN_EFFECTS_PER_TXE_QUERY)throw new Error(`${effects.length} offchain effects exceed max ${MAX_OFFCHAIN_EFFECTS_PER_TXE_QUERY}`);if(effects.some(e2=>e2.length>MAX_OFFCHAIN_EFFECT_LEN))throw new Error(`Some offchain effect has length larger than max ${MAX_OFFCHAIN_EFFECT_LEN}`);return{effects}}getLastCallContext(){let{txHash,anchorBlockTimestamp}=this.lastCallInfo;return{txHash,anchorBlockTimestamp}}async executePrivateCall(from,targetContractAddress,functionSelector,args,argsHash,isStaticCall,additionalScopes,authorizedUtilityCallTargets,gasSettings){let handler=this.handlerAsTxe();return await this.withTopLevelCallTracking(async()=>{let{returnValues,offchainEffects}=await handler.privateCallNewFlow(from?.value,targetContractAddress,functionSelector,args,argsHash,isStaticCall,additionalScopes,this.currentJobId,authorizedUtilityCallTargets,gasSettings);for(let data of offchainEffects)this.recordOffchainEffect(data);if(await this.cycleJob(),isStaticCall)return{result:returnValues};let{txHash}=await handler.getLastTxEffects();return{result:returnValues,txHash:txHash.hash}})}async executeUtilityFunction(from,targetContractAddress,functionSelector,args,authorizedUtilityCallTargets){let handler=this.handlerAsTxe();return await this.withTopLevelCallTracking(async()=>{let returnValues=await handler.executeUtilityFunction(from?.value,targetContractAddress,functionSelector,args,this.currentJobId,authorizedUtilityCallTargets);return await this.cycleJob(),{result:returnValues}})}async executePublicCall(from,targetContractAddress,calldata,isStaticCall,gasSettings){let handler=this.handlerAsTxe();return await this.withTopLevelCallTracking(async()=>{let returnValues=await handler.publicCallNewFlow(from?.value,targetContractAddress,calldata,isStaticCall,gasSettings);if(await this.cycleJob(),isStaticCall)return{result:returnValues};let{txHash}=await handler.getLastTxEffects();return{result:returnValues,txHash:txHash.hash}})}async getPrivateEvents(selector,contractAddress,scope){let handler=this.handlerAsTxe();return await handler.syncContractNonOracleMethod(contractAddress,scope,this.currentJobId),await this.cycleJob(),handler.getPrivateEvents(selector,contractAddress,scope)}handlerAsTxe(){if(!("isTxe"in this.oracleHandler))throw new UnavailableOracleError2("Txe");return this.oracleHandler}setTxeOracleVersion(major2,minor){if(major2!==2){let hint=major2>2?"The test was compiled with a newer version of Aztec.nr than your test environment supports. Upgrade your test environment to a compatible version.":"The test was compiled with an older version of Aztec.nr than your test environment supports. Recompile the test with a compatible version of Aztec.nr.";throw new Error(`Incompatible test environment version: ${hint} See https://docs.aztec.network/errors/12 (expected test oracle major version ${2}, got ${major2})`)}this.txeOracleVersion={major:major2,minor},this.logger.debug(`Test compiled with test oracle version ${major2}.${minor}`)}async enterTopLevelState(){switch(this.state.name){case"PRIVATE":{await this.exitPrivateState();break}case"PUBLIC":{await this.exitPublicState();break}case"UTILITY":{this.exitUtilityContext();break}case"TOP_LEVEL":throw new Error("Expected to be in state other than TOP_LEVEL");default:this.state}await this.cycleJob(),this.oracleHandler=new TXEOracleTopLevelContext(this.stateMachine,this.contractStore,this.noteStore,this.keyStore,this.addressStore,this.accountStore,this.senderTaggingStore,this.recipientTaggingStore,this.taggingSecretSourcesStore,this.capsuleStore,this.factStore,this.privateEventStore,this.nextBlockTimestamp,this.version,this.chainId,this.authwits,this.taggingSecretStrategy,this.artifactResolver,this.rootPath,this.packageName),this.state={name:"TOP_LEVEL"},this.logger.debug(`Entered state ${this.state.name}`)}async enterPrivateState(contractAddressOpt,anchorBlockNumberOpt,gasSettings){let contractAddress=contractAddressOpt?.value??DEFAULT_ADDRESS,anchorBlockNumber=anchorBlockNumberOpt?.value;this.exitTopLevelState(),this.resetLastCall();let anchorBlock=await this.stateMachine.node.getBlock(anchorBlockNumber??"latest").then(b=>b?.header);await new NoteService(this.noteStore,this.stateMachine.node,anchorBlock,this.currentJobId).syncNoteNullifiers(contractAddress,await this.keyStore.getAccounts());let latestBlock=await this.stateMachine.node.getBlock("latest").then(b=>b?.header),nextBlockGlobalVariables=makeGlobalVariables(void 0,{blockNumber:BlockNumber(latestBlock.globalVariables.blockNumber+1),timestamp:this.nextBlockTimestamp,version:this.version,chainId:this.chainId}),txRequestHash=getSingleTxBlockRequestHash(nextBlockGlobalVariables.blockNumber),protocolNullifier=await computeProtocolNullifier(txRequestHash),noteCache=new ExecutionNoteCache(protocolNullifier),taggingIndexCache=new ExecutionTaggingIndexCache,utilityExecutor=this.utilityExecutorForContractSync(anchorBlock),transientArrayService=new TransientArrayService,anchoredContractData=new AnchoredContractData(this.contractStore,this.stateMachine.contractClassService,anchorBlock),taggingSecretStrategy=this.taggingSecretStrategy;return this.oracleHandler=new TXEPrivateExecutionOracle({argsHash:Fr.ZERO,txContext:new TxContext(this.chainId,this.version,gasSettings),callContext:new CallContext(AztecAddress.ZERO,contractAddress,FunctionSelector.empty(),!1),anchorBlockHeader:anchorBlock,utilityExecutor,authWitnesses:[],capsules:[],executionCache:new HashedValuesCache,noteCache,taggingIndexCache,anchoredContractData,noteStore:this.noteStore,keyStore:this.keyStore,addressStore:this.addressStore,aztecNode:this.stateMachine.node,senderTaggingStore:this.senderTaggingStore,recipientTaggingStore:this.recipientTaggingStore,taggingSecretSourcesStore:this.taggingSecretSourcesStore,capsuleService:new CapsuleService(this.capsuleStore,await this.keyStore.getAccounts()),factService:new FactService(this.factStore,await this.keyStore.getAccounts()),privateEventStore:this.privateEventStore,contractSyncService:this.stateMachine.contractSyncService,l2TipsStore:this.stateMachine.l2TipsProvider,jobId:this.currentJobId,scopes:await this.keyStore.getAccounts(),txResolver:this.stateMachine.txResolver,simulator:new WASMSimulator,hooks:composeHooks({resolveTaggingSecretStrategy:taggingSecretStrategy?()=>Promise.resolve(taggingSecretStrategy):void 0}),transientArrayService}),this.state={name:"PRIVATE",nextBlockGlobalVariables,noteCache,taggingIndexCache},this.logger.debug(`Entered state ${this.state.name}`),this.setLastCallContext(Fr.ZERO,anchorBlock.globalVariables.timestamp),this.oracleHandler.getPrivateContextInputs()}async enterPublicState(contractAddressOpt){let contractAddress=contractAddressOpt?.value??DEFAULT_ADDRESS;this.exitTopLevelState(),this.resetLastCall();let latestHeader=(await this.stateMachine.node.getBlockData("latest")).header,globalVariables=makeGlobalVariables(void 0,{blockNumber:BlockNumber(latestHeader.globalVariables.blockNumber+1),timestamp:this.nextBlockTimestamp,version:this.version,chainId:this.chainId});this.oracleHandler=new TXEOraclePublicContext(contractAddress,await this.stateMachine.synchronizer.nativeWorldStateService.fork(),getSingleTxBlockRequestHash(globalVariables.blockNumber),globalVariables,this.contractStore),this.state={name:"PUBLIC"},this.logger.debug(`Entered state ${this.state.name}`),this.setLastCallContext(Fr.ZERO,latestHeader.globalVariables.timestamp)}async enterUtilityState(contractAddressOpt){let contractAddress=contractAddressOpt?.value??DEFAULT_ADDRESS;this.exitTopLevelState(),this.resetLastCall();let anchorBlockHeader=await this.stateMachine.anchorBlockStore.getBlockHeader();await new NoteService(this.noteStore,this.stateMachine.node,anchorBlockHeader,this.currentJobId).syncNoteNullifiers(contractAddress,await this.keyStore.getAccounts()),this.oracleHandler=new UtilityExecutionOracle({callContext:CallContext.from({msgSender:AztecAddress.NULL_MSG_SENDER,contractAddress,functionSelector:FunctionSelector.empty(),isStaticCall:!0}),authWitnesses:[],capsules:[],anchorBlockHeader,anchoredContractData:new AnchoredContractData(this.contractStore,this.stateMachine.contractClassService,anchorBlockHeader),noteStore:this.noteStore,keyStore:this.keyStore,addressStore:this.addressStore,aztecNode:this.stateMachine.node,recipientTaggingStore:this.recipientTaggingStore,taggingSecretSourcesStore:this.taggingSecretSourcesStore,capsuleService:new CapsuleService(this.capsuleStore,await this.keyStore.getAccounts()),factService:new FactService(this.factStore,await this.keyStore.getAccounts()),privateEventStore:this.privateEventStore,txResolver:this.stateMachine.txResolver,contractSyncService:this.stateMachine.contractSyncService,l2TipsStore:this.stateMachine.l2TipsProvider,jobId:this.currentJobId,scopes:await this.keyStore.getAccounts(),simulator:new WASMSimulator,utilityExecutor:this.utilityExecutorForContractSync(anchorBlockHeader),transientArrayService:new TransientArrayService}),this.state={name:"UTILITY"},this.logger.debug(`Entered state ${this.state.name}`),this.setLastCallContext(Fr.ZERO,anchorBlockHeader.globalVariables.timestamp)}exitTopLevelState(){if(this.state.name!="TOP_LEVEL")throw new Error(`Expected to be in state 'TOP_LEVEL', but got '${this.state.name}' instead`);[this.nextBlockTimestamp,this.authwits,this.taggingSecretStrategy]=this.oracleHandler.close()}async exitPrivateState(){if(this.state.name!="PRIVATE")throw new Error(`Expected to be in state 'PRIVATE', but got '${this.state.name}' instead`);this.logger.debug("Exiting Private state, building block with collected side effects",{blockNumber:this.state.nextBlockGlobalVariables.blockNumber});let txEffect=await makeTxEffect(this.state.noteCache,this.state.nextBlockGlobalVariables.blockNumber),forkedWorldTrees=await this.stateMachine.synchronizer.nativeWorldStateService.fork();await insertTxEffectIntoWorldTrees(txEffect,forkedWorldTrees);let block=await makeTXEBlock(forkedWorldTrees,this.state.nextBlockGlobalVariables,[txEffect]);await this.stateMachine.handleL2Block(block),await forkedWorldTrees.close(),this.logger.debug("Exited PublicContext with built block",{blockNumber:block.number,txEffects:block.body.txEffects})}async exitPublicState(){if(this.state.name!="PUBLIC")throw new Error(`Expected to be in state 'PUBLIC', but got '${this.state.name}' instead`);let block=await this.oracleHandler.close();await this.stateMachine.handleL2Block(block)}exitUtilityContext(){if(this.state.name!="UTILITY")throw new Error(`Expected to be in state 'UTILITY', but got '${this.state.name}' instead`)}utilityExecutorForContractSync(anchorBlock){return async(call,scopes)=>{let anchoredContractData=new AnchoredContractData(this.contractStore,this.stateMachine.contractClassService,anchorBlock),entryPointArtifact=await anchoredContractData.getFunctionArtifactWithDebugMetadata(call.to,call.selector);if(!entryPointArtifact)throw new Error(`Cannot run function ${call.selector} on ${call.to}: the contract is not registered.`);if(entryPointArtifact.functionType!==FunctionType.UTILITY)throw new Error(`Cannot run ${entryPointArtifact.functionType} function as utility`);try{let simulator=new WASMSimulator,oracle=new UtilityExecutionOracle({callContext:CallContext.from({msgSender:AztecAddress.NULL_MSG_SENDER,contractAddress:call.to,functionSelector:call.selector,isStaticCall:!0}),authWitnesses:[],capsules:[],anchorBlockHeader:anchorBlock,anchoredContractData,noteStore:this.noteStore,keyStore:this.keyStore,addressStore:this.addressStore,aztecNode:this.stateMachine.node,recipientTaggingStore:this.recipientTaggingStore,taggingSecretSourcesStore:this.taggingSecretSourcesStore,capsuleService:new CapsuleService(this.capsuleStore,scopes),factService:new FactService(this.factStore,scopes),privateEventStore:this.privateEventStore,txResolver:this.stateMachine.txResolver,contractSyncService:this.stateMachine.contractSyncService,l2TipsStore:this.stateMachine.l2TipsProvider,jobId:this.currentJobId,scopes,simulator,utilityExecutor:this.utilityExecutorForContractSync(anchorBlock),transientArrayService:new TransientArrayService});await simulator.executeUserCircuit(toACVMWitness(0,call.args),entryPointArtifact,buildACIRCallback(oracle)).catch(err=>{throw err.message=resolveAssertionMessageFromError(err,entryPointArtifact),new ExecutionError(err.message,{contractAddress:call.to,functionSelector:call.selector},extractCallStack(err,entryPointArtifact.debug),{cause:err})})}catch(err){throw createSimulationError(err instanceof Error?err:new Error("Unknown error contract data sync"))}}}};var ForeignCallSingleSchema=external_exports.string(),ForeignCallArraySchema=external_exports.array(external_exports.string()),ForeignCallArgsSchema=external_exports.array(external_exports.union([ForeignCallSingleSchema,ForeignCallArraySchema,ContractArtifactSchema,ContractInstanceWithAddressSchema])),ForeignCallResultSchema=external_exports.object({values:external_exports.array(external_exports.union([ForeignCallSingleSchema,ForeignCallArraySchema]))});var ContractClassRegistryContractArtifact={name:"ContractClassRegistry",aztecVersion:"dev",functions:[{functionType:FunctionType.PRIVATE,name:"publish",isOnlySelf:!1,isStatic:!1,isInitializer:!1,parameters:[{name:"artifact_hash",type:{kind:"field"},visibility:"private"},{name:"private_functions_root",type:{kind:"field"},visibility:"private"},{name:"public_bytecode_commitment",type:{kind:"field"},visibility:"private"}],returnTypes:[],errorTypes:{"10965409165809799877":{error_kind:"string",string:"Given in_len to absorb is larger than the input array len"},"12469291177396340830":{error_kind:"string",string:"call to assert_max_bit_size"},"14990209321349310352":{error_kind:"string",string:"attempt to add with overflow"},"15669273164684982983":{error_kind:"string",string:"num_permutations is greater than MAX_PERMUTATIONS"},"15835548349546956319":{error_kind:"string",string:"Field failed to decompose into specified 32 limbs"},"16431471497789672479":{error_kind:"string",string:"Index out of bounds"},"16450579948625159707":{error_kind:"string",string:"Sponge must be in cache_size=1"},"17655676068928457687":{error_kind:"string",string:"Reader did not read all data"},"1998584279744703196":{error_kind:"string",string:"attempt to subtract with overflow"},"361444214588792908":{error_kind:"string",string:"attempt to multiply with overflow"},"922421554006670918":{error_kind:"string",string:"num_items is greater than MAX_ITEMS"},"9475115977882098926":{error_kind:"string",string:"Extra bytes in the last field of the bytecode"}},bytecode:Buffer.from([]),debugSymbols:""},{functionType:FunctionType.PUBLIC,name:"public_dispatch",isOnlySelf:!1,isStatic:!1,isInitializer:!1,parameters:[{name:"selector",type:{kind:"field"},visibility:"private"}],returnTypes:[],errorTypes:{"1335198680857977525":{error_kind:"string",string:"No public functions"}},bytecode:Buffer.from([]),debugSymbols:""}],nonDispatchPublicFunctions:[],outputs:{structs:{},globals:{}},storageLayout:{},fileMap:{}};var ContractInstanceRegistryContractArtifact={name:"ContractInstanceRegistry",aztecVersion:"dev",functions:[{functionType:FunctionType.PUBLIC,name:"public_dispatch",isOnlySelf:!1,isStatic:!1,isInitializer:!1,parameters:[{name:"selector",type:{kind:"field"},visibility:"private"}],returnTypes:[],errorTypes:{"11194752367584870169":{error_kind:"fmtstring",length:27,item_types:[{kind:"field"}]},"12579274401768182412":{error_kind:"string",string:"New contract class is not registered"},"13455385521185560676":{error_kind:"string",string:"Storage slot 0 not allowed. Storage slots must start from 1."},"14990209321349310352":{error_kind:"string",string:"attempt to add with overflow"},"15353471697975175405":{error_kind:"string",string:"msg.sender is not deployed"},"16431471497789672479":{error_kind:"string",string:"Index out of bounds"},"1998584279744703196":{error_kind:"string",string:"attempt to subtract with overflow"},"5755400808989454547":{error_kind:"string",string:"Function get_update_delay can only be called statically"},"6804164082532189961":{error_kind:"string",string:"New update delay is too low"}},bytecode:Buffer.from([]),debugSymbols:""},{functionType:FunctionType.PRIVATE,name:"publish_for_public_execution",isOnlySelf:!1,isStatic:!1,isInitializer:!1,parameters:[{name:"salt",type:{kind:"field"},visibility:"private"},{name:"contract_class_id",type:{kind:"struct",fields:[{name:"inner",type:{kind:"field"}}],path:"aztec::protocol_types::contract_class_id::ContractClassId"},visibility:"private"},{name:"initialization_hash",type:{kind:"field"},visibility:"private"},{name:"immutables_hash",type:{kind:"field"},visibility:"private"},{name:"public_keys",type:{kind:"struct",fields:[{name:"npk_m_hash",type:{kind:"field"}},{name:"ivpk_m",type:{kind:"struct",fields:[{name:"inner",type:{kind:"struct",fields:[{name:"x",type:{kind:"field"}},{name:"y",type:{kind:"field"}}],path:"std::embedded_curve_ops::EmbeddedCurvePoint"}}],path:"aztec::protocol_types::public_keys::IvpkM"}},{name:"ovpk_m_hash",type:{kind:"field"}},{name:"tpk_m_hash",type:{kind:"field"}},{name:"mspk_m_hash",type:{kind:"field"}},{name:"fbpk_m_hash",type:{kind:"field"}}],path:"aztec::protocol_types::public_keys::PublicKeys"},visibility:"private"},{name:"universal_deploy",type:{kind:"boolean"},visibility:"private"}],returnTypes:[],errorTypes:{"12469291177396340830":{error_kind:"string",string:"call to assert_max_bit_size"},"14483585040754951598":{error_kind:"string",string:"IvpkM is the point at infinity"},"14990209321349310352":{error_kind:"string",string:"attempt to add with overflow"},"718532354304118388":{error_kind:"string",string:"Point not on curve"}},bytecode:Buffer.from([]),debugSymbols:""}],nonDispatchPublicFunctions:[{functionType:FunctionType.PUBLIC,name:"get_update_delay",isOnlySelf:!1,isStatic:!0,isInitializer:!1,parameters:[],returnTypes:[{kind:"integer",sign:"unsigned",width:64}],errorTypes:{"13455385521185560676":{error_kind:"string",string:"Storage slot 0 not allowed. Storage slots must start from 1."},"5755400808989454547":{error_kind:"string",string:"Function get_update_delay can only be called statically"}}},{functionType:FunctionType.PUBLIC,name:"set_update_delay",isOnlySelf:!1,isStatic:!1,isInitializer:!1,parameters:[{name:"new_update_delay",type:{kind:"integer",sign:"unsigned",width:64},visibility:"private"}],returnTypes:[],errorTypes:{"13455385521185560676":{error_kind:"string",string:"Storage slot 0 not allowed. Storage slots must start from 1."},"14990209321349310352":{error_kind:"string",string:"attempt to add with overflow"},"15353471697975175405":{error_kind:"string",string:"msg.sender is not deployed"},"16431471497789672479":{error_kind:"string",string:"Index out of bounds"},"1998584279744703196":{error_kind:"string",string:"attempt to subtract with overflow"},"6804164082532189961":{error_kind:"string",string:"New update delay is too low"}}},{functionType:FunctionType.PUBLIC,name:"update",isOnlySelf:!1,isStatic:!1,isInitializer:!1,parameters:[{name:"new_contract_class_id",type:{kind:"struct",fields:[{name:"inner",type:{kind:"field"}}],path:"aztec::protocol_types::contract_class_id::ContractClassId"},visibility:"private"}],returnTypes:[],errorTypes:{"12579274401768182412":{error_kind:"string",string:"New contract class is not registered"},"13455385521185560676":{error_kind:"string",string:"Storage slot 0 not allowed. Storage slots must start from 1."},"14990209321349310352":{error_kind:"string",string:"attempt to add with overflow"},"15353471697975175405":{error_kind:"string",string:"msg.sender is not deployed"},"16431471497789672479":{error_kind:"string",string:"Index out of bounds"},"1998584279744703196":{error_kind:"string",string:"attempt to subtract with overflow"}}}],outputs:{structs:{},globals:{}},storageLayout:{},fileMap:{}};var DefaultWaitOpts={ignoreDroppedReceiptsFor:5,timeout:300,interval:1};var DefaultWaitForProvenOpts={provenTimeout:600,interval:DefaultWaitOpts.interval};import{createHash as createHash2}from"crypto";import{createReadStream}from"fs";import{readFile,readdir}from"fs/promises";import{join as join4,parse as parse3}from"path";var AsyncCache=class{static{__name(this,"AsyncCache")}#cache=new Map;#inFlight=new Map;getOrCompute(key,compute){let cached2=this.#cache.get(key);if(cached2!==void 0)return Promise.resolve(cached2);let pending=this.#inFlight.get(key);return pending||(pending=(async()=>{try{let value=await compute();return this.#cache.set(key,value),value}finally{this.#inFlight.delete(key)}})(),this.#inFlight.set(key,pending)),pending}},TXEArtifactResolver=class{constructor(contractStore,schnorrClassId){this.contractStore=contractStore;this.schnorrClassId=schnorrClassId}static{__name(this,"TXEArtifactResolver")}#deployments=new AsyncCache;#artifacts=new AsyncCache;#logger=createLogger("txe:artifact_resolver");resolveAccountArtifact(secret){return this.#deployments.getOrCompute(`SchnorrAccountContract-${secret}`,()=>this.#computeAccountArtifact(secret))}async resolveDeployArtifact({rootPath,packageName,contractPath,initializer:initializer3,args,secret,salt,deployer}){let publicKeys=secret.equals(Fr.ZERO)?PublicKeys.default():(await deriveKeys(secret)).publicKeys,publicKeysHash=await publicKeys.hash(),artifactPath=await this.#resolveArtifactPath(rootPath,packageName,contractPath),fileHash=await this.#fastHashFile(artifactPath),{dir:contractDirectory,base:contractFilename}=parse3(contractPath),cacheKey=`${contractDirectory??""}-${contractFilename}-${initializer3}-${args.map(arg=>arg.toString()).join("-")}-${publicKeysHash}-${salt}-${deployer}-${fileHash}`;return this.#deployments.getOrCompute(cacheKey,()=>this.#computeDeployArtifact(artifactPath,fileHash,initializer3,args,salt,publicKeys,publicKeysHash,deployer))}async#resolveArtifactPath(rootPath,packageName,contractPath){let{dir:contractDirectory,base:contractFilename}=parse3(contractPath);if(contractDirectory)if(contractDirectory.includes("@")){let[workspace,pkg]=contractDirectory.split("@"),targetPath=join4(rootPath,workspace,"/target");return this.#logger.debug(`Looking for compiled artifact in workspace ${targetPath}`),join4(targetPath,`${pkg}-${contractFilename}.json`)}else{let targetPath=join4(rootPath,contractDirectory,"/target");this.#logger.debug(`Looking for compiled artifact in ${targetPath}`);let[artifactPath]=(await readdir(targetPath)).filter(file2=>file2.endsWith(`-${contractFilename}.json`));return artifactPath}else return join4(rootPath,"./target",`${packageName}-${contractFilename}.json`)}async#computeAccountArtifact(secret){let[artifactFromStore,classWithPreimage]=await Promise.all([this.contractStore.getContractArtifact(this.schnorrClassId),this.contractStore.getContractClassWithPreimage(this.schnorrClassId)]);if(!artifactFromStore||!classWithPreimage)throw new Error(`SchnorrAccount not found in shared contract store at class id ${this.schnorrClassId.toString()}`);let artifact={...artifactFromStore,artifactHash:classWithPreimage.artifactHash},keys=await deriveKeys(secret),args=[keys.publicKeys.ivpkM.x,keys.publicKeys.ivpkM.y],instance=await getContractInstanceFromInstantiationParams(artifact,{constructorArgs:args,skipArgsDecoding:!0,salt:Fr.ONE,publicKeys:keys.publicKeys,constructorArtifact:"constructor",deployer:AztecAddress.ZERO});return{artifact,instance}}async#computeDeployArtifact(artifactPath,fileHash,initializer3,args,salt,publicKeys,publicKeysHash,deployer){let artifact=await this.#artifacts.getOrCompute(fileHash,async()=>{this.#logger.debug(`Loading compiled artifact ${artifactPath}`);let artifactJSON=JSON.parse(await readFile(artifactPath,"utf-8")),artifactWithoutHash=loadContractArtifact(artifactJSON);return{...artifactWithoutHash,artifactHash:await computeArtifactHash(artifactWithoutHash)}});this.#logger.debug(`Deploy ${artifact.name} with initializer ${initializer3}(${args}) and public keys hash ${publicKeysHash}`);let instance=await getContractInstanceFromInstantiationParams(artifact,{constructorArgs:args,skipArgsDecoding:!0,salt,publicKeys,constructorArtifact:initializer3||void 0,deployer});return{artifact,instance}}#fastHashFile(path){return new Promise(resolve=>{let fd=createReadStream(path),hash5=createHash2("sha1");hash5.setEncoding("hex"),fd.on("end",function(){hash5.end(),resolve(hash5.read())}),fd.pipe(hash5)})}};var TXE_REQUIRED_PROTOCOL_CONTRACTS=["ContractClassRegistry","ContractInstanceRegistry","FeeJuice"],sessions=new Map,TXEForeignCallInputSchema=zodFor()(external_exports.object({session_id:external_exports.number().nonnegative(),function:external_exports.string(),root_path:external_exports.string(),package_name:external_exports.string(),inputs:ForeignCallArgsSchema})),TXEDispatcher=class{constructor(logger3,opts){this.logger=logger3;this.contractStoreSourceDir=opts.contractStoreSourceDir,this.schnorrClassId=Fr.fromString(opts.schnorrClassId)}static{__name(this,"TXEDispatcher")}contractStore;artifactResolver;contractStoreSourceDir;schnorrClassId;async warmUp(){if(this.contractStore)return;let t0=Date.now(),kvStore=await cloneEphemeralStoreFrom(join5(this.contractStoreSourceDir,"data.mdb"),"txe-contracts",void 0,2);this.contractStore=new ContractStore(kvStore),this.artifactResolver=new TXEArtifactResolver(this.contractStore,this.schnorrClassId),this.logger.debug("Cloned shared protocol-contracts store",{totalMs:Date.now()-t0})}async resolve_foreign_call(callData){let{session_id:sessionId,function:functionName,inputs,root_path:rootPath,package_name:packageName}=callData;return this.logger.debug(`Calling ${functionName} on session ${sessionId}`),sessions.has(sessionId)||(this.logger.debug(`Creating new session ${sessionId}`),await this.warmUp(),sessions.set(sessionId,await TXESession.init(this.contractStore,this.artifactResolver,rootPath,packageName))),await sessions.get(sessionId).processFunction(functionName,inputs)}async disposeSession(sessionId){let session=sessions.get(sessionId);session&&(sessions.delete(sessionId),await session.dispose())}};function activeSessionCount(){return sessions.size}__name(activeSessionCount,"activeSessionCount");var TXEDispatcherApiSchema={resolve_foreign_call:external_exports.function({input:external_exports.tuple([TXEForeignCallInputSchema]),output:ForeignCallResultSchema}),disposeSession:external_exports.function({input:external_exports.tuple([external_exports.number().nonnegative()]),output:external_exports.void()})};export{createLogger,ZodError,external_exports,Fr,schemaHasMethod,getSchemaParameters,parseWithOptionals,require_inherits,sha256ToField,promiseWithResolvers,jsonStringify,loadContractArtifact,getContractClassFromArtifact,openEphemeralStore,LazyProtocolContractsProvider,ContractStore,getStandardAuthRegistry,getStandardHandshakeRegistry,TXE_REQUIRED_PROTOCOL_CONTRACTS,TXEDispatcher,activeSessionCount,TXEDispatcherApiSchema};
|