@aztec/txe 5.0.0-nightly.20260708 → 5.0.0-nightly.20260709
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/SchnorrAccount-Z2WDW5N7.js +3 -0
- package/dest/SchnorrAccount-Z2WDW5N7.js.map +7 -0
- package/dest/{SchnorrInitializerlessAccount-3AKXYJQI.js → SchnorrInitializerlessAccount-3V4B7CP6.js} +1 -1
- package/dest/{SchnorrInitializerlessAccount-3AKXYJQI.js.map → SchnorrInitializerlessAccount-3V4B7CP6.js.map} +1 -1
- package/dest/bin/index.js +1 -1
- package/dest/{chunk-HLH2NBQI.js → chunk-23X4GHAA.js} +4 -4
- package/dest/{chunk-HLH2NBQI.js.map → chunk-23X4GHAA.js.map} +3 -3
- package/dest/{chunk-2LYGEVHI.js → chunk-Y75V5534.js} +2 -2
- package/dest/metafile.json +139 -62
- package/dest/oracle/interfaces.d.ts +6 -2
- package/dest/oracle/interfaces.d.ts.map +1 -1
- package/dest/oracle/tagging_secret_strategy.d.ts +12 -0
- package/dest/oracle/tagging_secret_strategy.d.ts.map +1 -0
- package/dest/oracle/tagging_secret_strategy.js +12 -0
- package/dest/oracle/txe_oracle_registry.d.ts +3 -3
- package/dest/oracle/txe_oracle_registry.d.ts.map +1 -1
- package/dest/oracle/txe_oracle_registry.js +7 -3
- package/dest/oracle/txe_oracle_top_level_context.d.ts +6 -5
- package/dest/oracle/txe_oracle_top_level_context.d.ts.map +1 -1
- package/dest/oracle/txe_oracle_top_level_context.js +17 -10
- package/dest/oracle/txe_oracle_version.d.ts +3 -3
- package/dest/oracle/txe_oracle_version.js +3 -3
- package/dest/rpc_translator.d.ts +3 -3
- package/dest/rpc_translator.d.ts.map +1 -1
- package/dest/rpc_translator.js +6 -6
- package/dest/server.bundle.js +1 -1
- package/dest/txe_session.d.ts +2 -2
- package/dest/txe_session.d.ts.map +1 -1
- package/dest/txe_session.js +8 -8
- package/dest/worker.bundle.js +1 -1
- package/package.json +17 -17
- package/src/oracle/interfaces.ts +8 -1
- package/src/oracle/tagging_secret_strategy.ts +25 -0
- package/src/oracle/txe_oracle_registry.ts +6 -3
- package/src/oracle/txe_oracle_top_level_context.ts +19 -9
- package/src/oracle/txe_oracle_version.ts +3 -3
- package/src/rpc_translator.ts +8 -7
- package/src/txe_session.ts +10 -8
- package/dest/SchnorrAccount-Y2WZTBJF.js +0 -3
- package/dest/SchnorrAccount-Y2WZTBJF.js.map +0 -7
- /package/dest/{chunk-2LYGEVHI.js.map → chunk-Y75V5534.js.map} +0 -0
|
@@ -126,7 +126,7 @@ ${err.message}`);else throw err}}__name(getFunctionDebugMetadata,"getFunctionDeb
|
|
|
126
126
|
}`}};var L2ToL1Message=class _L2ToL1Message{static{__name(this,"L2ToL1Message")}recipient;content;constructor(recipient,content){this.recipient=recipient,this.content=content}static get schema(){return external_exports.object({recipient:schemas.EthAddress,content:schemas.Fr}).transform(({recipient,content})=>new _L2ToL1Message(recipient,content))}static empty(){return new _L2ToL1Message(EthAddress.ZERO,Fr.zero())}static fromPlainObject(obj){return new _L2ToL1Message(EthAddress.fromPlainObject(obj.recipient),Fr.fromPlainObject(obj.content))}equals(other){return this.recipient.equals(other.recipient)&&this.content.equals(other.content)}toBuffer(sink){if(!sink)return BufferSink.serialize(this);serializeToSink(sink,this.recipient,this.content)}toFields(){return[this.recipient.toField(),this.content]}static fromFields(fields){let reader=FieldReader.asReader(fields);return new _L2ToL1Message(reader.readObject(EthAddress),reader.readField())}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _L2ToL1Message(reader.readObject(EthAddress),reader.readObject(Fr))}isEmpty(){return this.recipient.isZero()&&this.content.isZero()}scope(contractAddress){return new ScopedL2ToL1Message(this,contractAddress)}},CountedL2ToL1Message=class _CountedL2ToL1Message{static{__name(this,"CountedL2ToL1Message")}message;counter;constructor(message,counter){this.message=message,this.counter=counter}static get schema(){return external_exports.object({message:L2ToL1Message.schema,counter:external_exports.number().int().nonnegative()}).transform(({message,counter})=>new _CountedL2ToL1Message(message,counter))}static empty(){return new _CountedL2ToL1Message(L2ToL1Message.empty(),0)}isEmpty(){return this.message.isEmpty()&&!this.counter}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _CountedL2ToL1Message(reader.readObject(L2ToL1Message),reader.readNumber())}toBuffer(sink){if(!sink)return BufferSink.serialize(this);serializeToSink(sink,this.message,this.counter)}static fromFields(fields){let reader=FieldReader.asReader(fields);return new _CountedL2ToL1Message(reader.readObject(L2ToL1Message),reader.readU32())}toFields(){return serializeToFields(this.message,this.counter)}},ScopedL2ToL1Message=class _ScopedL2ToL1Message{static{__name(this,"ScopedL2ToL1Message")}message;contractAddress;constructor(message,contractAddress){this.message=message,this.contractAddress=contractAddress}static get schema(){return external_exports.object({message:L2ToL1Message.schema,contractAddress:AztecAddress.schema}).transform(({message,contractAddress})=>new _ScopedL2ToL1Message(message,contractAddress))}static empty(){return new _ScopedL2ToL1Message(L2ToL1Message.empty(),AztecAddress.ZERO)}equals(other){return this.message.equals(other.message)&&this.contractAddress.equals(other.contractAddress)}static fromPlainObject(obj){return new _ScopedL2ToL1Message(L2ToL1Message.fromPlainObject(obj.message),AztecAddress.fromPlainObject(obj.contractAddress))}isEmpty(){return this.message.isEmpty()&&this.contractAddress.isZero()}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _ScopedL2ToL1Message(reader.readObject(L2ToL1Message),reader.readObject(AztecAddress))}toBuffer(sink){if(!sink)return BufferSink.serialize(this);serializeToSink(sink,this.message,this.contractAddress)}static fromFields(fields){let reader=FieldReader.asReader(fields);return new _ScopedL2ToL1Message(reader.readObject(L2ToL1Message),reader.readObject(AztecAddress))}toFields(){return serializeToFields(this.message,this.contractAddress)}},ScopedCountedL2ToL1Message=class _ScopedCountedL2ToL1Message{static{__name(this,"ScopedCountedL2ToL1Message")}inner;contractAddress;constructor(inner,contractAddress){this.inner=inner,this.contractAddress=contractAddress}static get schema(){return external_exports.object({inner:CountedL2ToL1Message.schema,contractAddress:AztecAddress.schema}).transform(({inner,contractAddress})=>new _ScopedCountedL2ToL1Message(inner,contractAddress))}static empty(){return new _ScopedCountedL2ToL1Message(CountedL2ToL1Message.empty(),AztecAddress.ZERO)}isEmpty(){return this.inner.isEmpty()&&this.contractAddress.isZero()}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _ScopedCountedL2ToL1Message(reader.readObject(CountedL2ToL1Message),reader.readObject(AztecAddress))}toBuffer(sink){if(!sink)return BufferSink.serialize(this);serializeToSink(sink,this.inner,this.contractAddress)}static fromFields(fields){let reader=FieldReader.asReader(fields);return new _ScopedCountedL2ToL1Message(reader.readObject(CountedL2ToL1Message),reader.readObject(AztecAddress))}toFields(){return serializeToFields(this.inner,this.contractAddress)}};import{inspect as inspect20}from"util";var _computedKey20;_computedKey20=inspect20.custom;var ClaimedLengthArray=class _ClaimedLengthArray{static{__name(this,"ClaimedLengthArray")}array;claimedLength;constructor(array2,claimedLength){this.array=array2,this.claimedLength=claimedLength}static fromBuffer(buffer,deserializer,arrayLength){let reader=BufferReader.asReader(buffer),array2=reader.readArray(arrayLength,deserializer),claimedLength=reader.readNumber();return new _ClaimedLengthArray(array2,claimedLength)}toBuffer(){return serializeToBuffer(this.array,this.claimedLength)}static fromFields(fields,deserializer,arrayLength){let reader=FieldReader.asReader(fields),array2=reader.readArray(arrayLength,deserializer),claimedLength=reader.readU32();return new _ClaimedLengthArray(array2,claimedLength)}toFields(){return serializeToFields(this.array,this.claimedLength)}static empty(elem,arraySize){let array2=Array(arraySize).fill(elem.empty());return new _ClaimedLengthArray(array2,0)}isEmpty(){return this.claimedLength===0}getActiveItems(){return this.array.slice(0,this.claimedLength)}getSize(){return this.toBuffer().length}[_computedKey20](){return`ClaimedLengthArray {
|
|
127
127
|
array: [${this.getActiveItems().map(x=>inspect20(x)).join(", ")}],
|
|
128
128
|
claimedLength: ${this.claimedLength},
|
|
129
|
-
`}};function ClaimedLengthArrayFromBuffer(deserializer,arrayLength){return{fromBuffer:__name(reader=>ClaimedLengthArray.fromBuffer(reader,deserializer,arrayLength),"fromBuffer")}}__name(ClaimedLengthArrayFromBuffer,"ClaimedLengthArrayFromBuffer");function ClaimedLengthArrayFromFields(deserializer,arrayLength){return{fromFields:__name(reader=>ClaimedLengthArray.fromFields(reader,deserializer,arrayLength),"fromFields")}}__name(ClaimedLengthArrayFromFields,"ClaimedLengthArrayFromFields");var ReadRequest=class _ReadRequest{static{__name(this,"ReadRequest")}value;counter;constructor(value,counter){this.value=value,this.counter=counter}toBuffer(){return serializeToBuffer(this.value,this.counter)}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _ReadRequest(Fr.fromBuffer(reader),reader.readNumber())}toFields(){return[this.value,new Fr(this.counter)]}static fromFields(fields){let reader=FieldReader.asReader(fields);return new _ReadRequest(reader.readField(),reader.readU32())}isEmpty(){return this.value.isZero()&&!this.counter}static empty(){return new _ReadRequest(Fr.zero(),0)}scope(contractAddress){return new ScopedReadRequest(this,contractAddress)}},ScopedReadRequest=class _ScopedReadRequest{static{__name(this,"ScopedReadRequest")}readRequest;contractAddress;constructor(readRequest,contractAddress){this.readRequest=readRequest,this.contractAddress=contractAddress}get value(){return this.readRequest.value}get counter(){return this.readRequest.counter}toBuffer(){return serializeToBuffer(this.readRequest,this.contractAddress)}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _ScopedReadRequest(ReadRequest.fromBuffer(reader),AztecAddress.fromBuffer(reader))}toFields(){return[...this.readRequest.toFields(),this.contractAddress.toField()]}static fromFields(fields){let reader=FieldReader.asReader(fields);return new _ScopedReadRequest(reader.readObject(ReadRequest),AztecAddress.fromFieldUnsafe(reader.readField()))}isEmpty(){return this.readRequest.isEmpty()&&this.contractAddress.isZero()}static empty(){return new _ScopedReadRequest(ReadRequest.empty(),AztecAddress.ZERO)}};var NoteHash=class _NoteHash{static{__name(this,"NoteHash")}value;counter;constructor(value,counter){this.value=value,this.counter=counter}toFields(){return[this.value,new Fr(this.counter)]}static fromFields(fields){let reader=FieldReader.asReader(fields);return new _NoteHash(reader.readField(),reader.readU32())}isEmpty(){return this.value.isZero()&&!this.counter}static empty(){return new _NoteHash(Fr.zero(),0)}toBuffer(){return serializeToBuffer(this.value,this.counter)}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _NoteHash(Fr.fromBuffer(reader),reader.readNumber())}toString(){return`value=${this.value} counter=${this.counter}`}scope(contractAddress){return new ScopedNoteHash(this,contractAddress)}},ScopedNoteHash=class _ScopedNoteHash{static{__name(this,"ScopedNoteHash")}noteHash;contractAddress;constructor(noteHash,contractAddress){this.noteHash=noteHash,this.contractAddress=contractAddress}get counter(){return this.noteHash.counter}get value(){return this.noteHash.value}toFields(){return[...this.noteHash.toFields(),this.contractAddress.toField()]}static fromFields(fields){let reader=FieldReader.asReader(fields);return new _ScopedNoteHash(reader.readObject(NoteHash),AztecAddress.fromFieldUnsafe(reader.readField()))}isEmpty(){return this.noteHash.isEmpty()&&this.contractAddress.isZero()}static empty(){return new _ScopedNoteHash(NoteHash.empty(),AztecAddress.ZERO)}toBuffer(){return serializeToBuffer(this.noteHash,this.contractAddress)}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _ScopedNoteHash(NoteHash.fromBuffer(reader),AztecAddress.fromBuffer(reader))}toString(){return`noteHash=${this.noteHash} contractAddress=${this.contractAddress}`}};var Nullifier=class _Nullifier{static{__name(this,"Nullifier")}value;noteHash;counter;constructor(value,noteHash,counter){this.value=value,this.noteHash=noteHash,this.counter=counter}toFields(){return[this.value,this.noteHash,new Fr(this.counter)]}static fromFields(fields){let reader=FieldReader.asReader(fields);return new _Nullifier(reader.readField(),reader.readField(),reader.readU32())}isEmpty(){return this.value.isZero()&&this.noteHash.isZero()&&!this.counter}static empty(){return new _Nullifier(Fr.zero(),Fr.zero(),0)}toBuffer(){return serializeToBuffer(this.value,this.noteHash,this.counter)}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _Nullifier(Fr.fromBuffer(reader),Fr.fromBuffer(reader),reader.readNumber())}toString(){return`value=${this.value} noteHash=${this.noteHash} counter=${this.counter}`}scope(contractAddress){return new ScopedNullifier(this,contractAddress)}},ScopedNullifier=class _ScopedNullifier{static{__name(this,"ScopedNullifier")}nullifier;contractAddress;constructor(nullifier,contractAddress){this.nullifier=nullifier,this.contractAddress=contractAddress}get counter(){return this.nullifier.counter}get value(){return this.nullifier.value}get nullifiedNoteHash(){return this.nullifier.noteHash}toFields(){return[...this.nullifier.toFields(),this.contractAddress.toField()]}static fromFields(fields){let reader=FieldReader.asReader(fields);return new _ScopedNullifier(reader.readObject(Nullifier),AztecAddress.fromFieldUnsafe(reader.readField()))}isEmpty(){return this.nullifier.isEmpty()&&this.contractAddress.isZero()}static empty(){return new _ScopedNullifier(Nullifier.empty(),AztecAddress.ZERO)}toBuffer(){return serializeToBuffer(this.nullifier,this.contractAddress)}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _ScopedNullifier(Nullifier.fromBuffer(reader),AztecAddress.fromBuffer(reader))}toString(){return`nullifier=${this.nullifier} contractAddress=${this.contractAddress}`}};import{inspect as inspect21}from"util";var import_hash=__toESM(require_hash(),1);function sha256(data){return Buffer.from(import_hash.default.sha256().update(data).digest())}__name(sha256,"sha256");function sha256Trunc(data){return truncateAndPad(sha256(data))}__name(sha256Trunc,"sha256Trunc");function sha256ToField(data){let buffer=serializeToBuffer(data);return Fr.fromBuffer(sha256Trunc(buffer))}__name(sha256ToField,"sha256ToField");function sha256Compression(state,inputs){if(state.length!==8)throw new Error("`state` argument to SHA256 compression must be of length 8");if(inputs.length!==16)throw new Error("`inputs` argument to SHA256 compression must be of length 16");let W=new Array(64),k=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],i=0;for(i=0;i<16;i++)W[i]=inputs[i];for(i=16;i<W.length;i++)W[i]=sum32_4(W[i-16],W[i-7],g0_256(W[i-15]),g1_256(W[i-2]));let a=state[0],b=state[1],c2=state[2],d=state[3],e2=state[4],f=state[5],g=state[6],h=state[7];for(let i2=0;i2<64;i2++){let T1=sum32_5(h,s1_256(e2),ch32(e2,f,g),k[i2],W[i2]),T2=sum32(s0_256(a),maj32(a,b,c2));h=g,g=f,f=e2,e2=sum32(d,T1),d=c2,c2=b,b=a,a=sum32(T1,T2)}return state[0]=sum32(state[0],a),state[1]=sum32(state[1],b),state[2]=sum32(state[2],c2),state[3]=sum32(state[3],d),state[4]=sum32(state[4],e2),state[5]=sum32(state[5],f),state[6]=sum32(state[6],g),state[7]=sum32(state[7],h),state}__name(sha256Compression,"sha256Compression");function rotr32(w,b){return w>>>b|w<<32-b}__name(rotr32,"rotr32");function sum32(a,b){return a+b>>>0}__name(sum32,"sum32");function sum32_4(a,b,c2,d){return a+b+c2+d>>>0}__name(sum32_4,"sum32_4");function sum32_5(a,b,c2,d,e2){return a+b+c2+d+e2>>>0}__name(sum32_5,"sum32_5");function ch32(x,y,z2){return x&y^~x&z2}__name(ch32,"ch32");function maj32(x,y,z2){return x&y^x&z2^y&z2}__name(maj32,"maj32");function s0_256(x){return rotr32(x,2)^rotr32(x,13)^rotr32(x,22)}__name(s0_256,"s0_256");function s1_256(x){return rotr32(x,6)^rotr32(x,11)^rotr32(x,25)}__name(s1_256,"s1_256");function g0_256(x){return rotr32(x,7)^rotr32(x,18)^x>>>3}__name(g0_256,"g0_256");function g1_256(x){return rotr32(x,17)^rotr32(x,19)^x>>>10}__name(g1_256,"g1_256");function computeMerkleHash(left,right){return poseidon2HashWithSeparator([left,right],DomainSeparator.MERKLE_HASH)}__name(computeMerkleHash,"computeMerkleHash");async function hashVK(keyAsFields){return await poseidon2Hash(keyAsFields)}__name(hashVK,"hashVK");function computeNoteHashNonce(nullifierZero,noteHashIndex){return poseidon2HashWithSeparator([nullifierZero,noteHashIndex],DomainSeparator.NOTE_HASH_NONCE)}__name(computeNoteHashNonce,"computeNoteHashNonce");function siloNoteHash(contract,noteHash){return poseidon2HashWithSeparator([contract,noteHash],DomainSeparator.SILOED_NOTE_HASH)}__name(siloNoteHash,"siloNoteHash");function computeUniqueNoteHash(noteNonce,siloedNoteHash){return poseidon2HashWithSeparator([noteNonce,siloedNoteHash],DomainSeparator.UNIQUE_NOTE_HASH)}__name(computeUniqueNoteHash,"computeUniqueNoteHash");function siloNullifier(contract,innerNullifier){return poseidon2HashWithSeparator([contract,innerNullifier],DomainSeparator.SILOED_NULLIFIER)}__name(siloNullifier,"siloNullifier");function computeProtocolNullifier(txRequestHash){return siloNullifier(AztecAddress.NULL_MSG_SENDER,txRequestHash)}__name(computeProtocolNullifier,"computeProtocolNullifier");function computeLogTag(rawTag,domSep){return poseidon2HashWithSeparator([new Fr(rawTag)],domSep)}__name(computeLogTag,"computeLogTag");function computePrivateEventCommitment(randomness,eventSelector,content){return poseidon2HashWithSeparator([randomness,eventSelector,...content],DomainSeparator.EVENT_COMMITMENT)}__name(computePrivateEventCommitment,"computePrivateEventCommitment");function computeSiloedPrivateLogFirstField(contract,field){return poseidon2HashWithSeparator([contract,field],DomainSeparator.PRIVATE_LOG_FIRST_FIELD)}__name(computeSiloedPrivateLogFirstField,"computeSiloedPrivateLogFirstField");function computePublicDataTreeLeafSlot(contractAddress,storageSlot){return poseidon2HashWithSeparator([contractAddress,storageSlot],DomainSeparator.PUBLIC_LEAF_SLOT)}__name(computePublicDataTreeLeafSlot,"computePublicDataTreeLeafSlot");function computeVarArgsHash(args){return args.length===0?Promise.resolve(Fr.ZERO):poseidon2HashWithSeparator(args,DomainSeparator.FUNCTION_ARGS)}__name(computeVarArgsHash,"computeVarArgsHash");function computeCalldataHash(calldata){return poseidon2HashWithSeparator(calldata,DomainSeparator.PUBLIC_CALLDATA)}__name(computeCalldataHash,"computeCalldataHash");async function computeL1ToL2MessageNullifier(contract,messageHash,secret){let innerMessageNullifier=await poseidon2HashWithSeparator([messageHash,secret],DomainSeparator.MESSAGE_NULLIFIER);return siloNullifier(contract,innerMessageNullifier)}__name(computeL1ToL2MessageNullifier,"computeL1ToL2MessageNullifier");function computeL2ToL1MessageHash({l2Sender,l1Recipient,content,rollupVersion,chainId}){return sha256ToField([l2Sender,rollupVersion,l1Recipient,chainId,content])}__name(computeL2ToL1MessageHash,"computeL2ToL1MessageHash");function deriveStorageSlotInMap(mapSlot,key){return poseidon2HashWithSeparator([mapSlot,key.toField()],DomainSeparator.PUBLIC_STORAGE_MAP_SLOT)}__name(deriveStorageSlotInMap,"deriveStorageSlotInMap");var _computedKey21,_computedKey111;_computedKey21=inspect21.custom;var PublicCallRequest=class _PublicCallRequest{static{__name(this,"PublicCallRequest")}msgSender;contractAddress;isStaticCall;calldataHash;constructor(msgSender,contractAddress,isStaticCall,calldataHash){this.msgSender=msgSender,this.contractAddress=contractAddress,this.isStaticCall=isStaticCall,this.calldataHash=calldataHash}static get schema(){return external_exports.object({msgSender:AztecAddress.schema,contractAddress:AztecAddress.schema,isStaticCall:external_exports.boolean(),calldataHash:schemas.Fr}).transform(({msgSender,contractAddress,isStaticCall,calldataHash})=>new _PublicCallRequest(msgSender,contractAddress,isStaticCall,calldataHash))}getSize(){return this.isEmpty()?0:this.toBuffer().length}static from(fields){return new _PublicCallRequest(..._PublicCallRequest.getFields(fields))}static getFields(fields){return[fields.msgSender,fields.contractAddress,fields.isStaticCall,fields.calldataHash]}static fromFields(fields){let reader=FieldReader.asReader(fields);return new _PublicCallRequest(reader.readObject(AztecAddress),reader.readObject(AztecAddress),reader.readBoolean(),reader.readField())}toFields(){let fields=serializeToFields(..._PublicCallRequest.getFields(this));if(fields.length!==4)throw new Error(`Invalid number of fields for PublicCallRequest. Expected ${4}, got ${fields.length}`);return fields}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _PublicCallRequest(reader.readObject(AztecAddress),reader.readObject(AztecAddress),reader.readBoolean(),reader.readObject(Fr))}toBuffer(sink){if(!sink)return BufferSink.serialize(this);serializeToSink(sink,..._PublicCallRequest.getFields(this))}static empty(){return new _PublicCallRequest(AztecAddress.ZERO,AztecAddress.ZERO,!1,Fr.ZERO)}static fromPlainObject(obj){return new _PublicCallRequest(AztecAddress.fromPlainObject(obj.msgSender),AztecAddress.fromPlainObject(obj.contractAddress),obj.isStaticCall,Fr.fromPlainObject(obj.calldataHash))}isEmpty(){return this.msgSender.isZero()&&this.contractAddress.isZero()&&!this.isStaticCall&&this.calldataHash.isEmpty()}[_computedKey21](){return`PublicCallRequest {
|
|
129
|
+
`}};function ClaimedLengthArrayFromBuffer(deserializer,arrayLength){return{fromBuffer:__name(reader=>ClaimedLengthArray.fromBuffer(reader,deserializer,arrayLength),"fromBuffer")}}__name(ClaimedLengthArrayFromBuffer,"ClaimedLengthArrayFromBuffer");function ClaimedLengthArrayFromFields(deserializer,arrayLength){return{fromFields:__name(reader=>ClaimedLengthArray.fromFields(reader,deserializer,arrayLength),"fromFields")}}__name(ClaimedLengthArrayFromFields,"ClaimedLengthArrayFromFields");var ReadRequest=class _ReadRequest{static{__name(this,"ReadRequest")}value;counter;constructor(value,counter){this.value=value,this.counter=counter}toBuffer(){return serializeToBuffer(this.value,this.counter)}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _ReadRequest(Fr.fromBuffer(reader),reader.readNumber())}toFields(){return[this.value,new Fr(this.counter)]}static fromFields(fields){let reader=FieldReader.asReader(fields);return new _ReadRequest(reader.readField(),reader.readU32())}isEmpty(){return this.value.isZero()&&!this.counter}static empty(){return new _ReadRequest(Fr.zero(),0)}scope(contractAddress){return new ScopedReadRequest(this,contractAddress)}},ScopedReadRequest=class _ScopedReadRequest{static{__name(this,"ScopedReadRequest")}readRequest;contractAddress;constructor(readRequest,contractAddress){this.readRequest=readRequest,this.contractAddress=contractAddress}get value(){return this.readRequest.value}get counter(){return this.readRequest.counter}toBuffer(){return serializeToBuffer(this.readRequest,this.contractAddress)}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _ScopedReadRequest(ReadRequest.fromBuffer(reader),AztecAddress.fromBuffer(reader))}toFields(){return[...this.readRequest.toFields(),this.contractAddress.toField()]}static fromFields(fields){let reader=FieldReader.asReader(fields);return new _ScopedReadRequest(reader.readObject(ReadRequest),AztecAddress.fromFieldUnsafe(reader.readField()))}isEmpty(){return this.readRequest.isEmpty()&&this.contractAddress.isZero()}static empty(){return new _ScopedReadRequest(ReadRequest.empty(),AztecAddress.ZERO)}};var NoteHash=class _NoteHash{static{__name(this,"NoteHash")}value;counter;constructor(value,counter){this.value=value,this.counter=counter}toFields(){return[this.value,new Fr(this.counter)]}static fromFields(fields){let reader=FieldReader.asReader(fields);return new _NoteHash(reader.readField(),reader.readU32())}isEmpty(){return this.value.isZero()&&!this.counter}static empty(){return new _NoteHash(Fr.zero(),0)}toBuffer(){return serializeToBuffer(this.value,this.counter)}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _NoteHash(Fr.fromBuffer(reader),reader.readNumber())}toString(){return`value=${this.value} counter=${this.counter}`}scope(contractAddress){return new ScopedNoteHash(this,contractAddress)}},ScopedNoteHash=class _ScopedNoteHash{static{__name(this,"ScopedNoteHash")}noteHash;contractAddress;constructor(noteHash,contractAddress){this.noteHash=noteHash,this.contractAddress=contractAddress}get counter(){return this.noteHash.counter}get value(){return this.noteHash.value}toFields(){return[...this.noteHash.toFields(),this.contractAddress.toField()]}static fromFields(fields){let reader=FieldReader.asReader(fields);return new _ScopedNoteHash(reader.readObject(NoteHash),AztecAddress.fromFieldUnsafe(reader.readField()))}isEmpty(){return this.noteHash.isEmpty()&&this.contractAddress.isZero()}static empty(){return new _ScopedNoteHash(NoteHash.empty(),AztecAddress.ZERO)}toBuffer(){return serializeToBuffer(this.noteHash,this.contractAddress)}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _ScopedNoteHash(NoteHash.fromBuffer(reader),AztecAddress.fromBuffer(reader))}toString(){return`noteHash=${this.noteHash} contractAddress=${this.contractAddress}`}};var Nullifier=class _Nullifier{static{__name(this,"Nullifier")}value;noteHash;counter;constructor(value,noteHash,counter){this.value=value,this.noteHash=noteHash,this.counter=counter}toFields(){return[this.value,this.noteHash,new Fr(this.counter)]}static fromFields(fields){let reader=FieldReader.asReader(fields);return new _Nullifier(reader.readField(),reader.readField(),reader.readU32())}isEmpty(){return this.value.isZero()&&this.noteHash.isZero()&&!this.counter}static empty(){return new _Nullifier(Fr.zero(),Fr.zero(),0)}toBuffer(){return serializeToBuffer(this.value,this.noteHash,this.counter)}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _Nullifier(Fr.fromBuffer(reader),Fr.fromBuffer(reader),reader.readNumber())}toString(){return`value=${this.value} noteHash=${this.noteHash} counter=${this.counter}`}scope(contractAddress){return new ScopedNullifier(this,contractAddress)}},ScopedNullifier=class _ScopedNullifier{static{__name(this,"ScopedNullifier")}nullifier;contractAddress;constructor(nullifier,contractAddress){this.nullifier=nullifier,this.contractAddress=contractAddress}get counter(){return this.nullifier.counter}get value(){return this.nullifier.value}get nullifiedNoteHash(){return this.nullifier.noteHash}toFields(){return[...this.nullifier.toFields(),this.contractAddress.toField()]}static fromFields(fields){let reader=FieldReader.asReader(fields);return new _ScopedNullifier(reader.readObject(Nullifier),AztecAddress.fromFieldUnsafe(reader.readField()))}isEmpty(){return this.nullifier.isEmpty()&&this.contractAddress.isZero()}static empty(){return new _ScopedNullifier(Nullifier.empty(),AztecAddress.ZERO)}toBuffer(){return serializeToBuffer(this.nullifier,this.contractAddress)}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _ScopedNullifier(Nullifier.fromBuffer(reader),AztecAddress.fromBuffer(reader))}toString(){return`nullifier=${this.nullifier} contractAddress=${this.contractAddress}`}};import{inspect as inspect21}from"util";var import_hash=__toESM(require_hash(),1);function sha256(data){return Buffer.from(import_hash.default.sha256().update(data).digest())}__name(sha256,"sha256");function sha256Trunc(data){return truncateAndPad(sha256(data))}__name(sha256Trunc,"sha256Trunc");function sha256ToField(data){let buffer=serializeToBuffer(data);return Fr.fromBuffer(sha256Trunc(buffer))}__name(sha256ToField,"sha256ToField");function sha256Compression(state,inputs){if(state.length!==8)throw new Error("`state` argument to SHA256 compression must be of length 8");if(inputs.length!==16)throw new Error("`inputs` argument to SHA256 compression must be of length 16");let W=new Array(64),k=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],i=0;for(i=0;i<16;i++)W[i]=inputs[i];for(i=16;i<W.length;i++)W[i]=sum32_4(W[i-16],W[i-7],g0_256(W[i-15]),g1_256(W[i-2]));let a=state[0],b=state[1],c2=state[2],d=state[3],e2=state[4],f=state[5],g=state[6],h=state[7];for(let i2=0;i2<64;i2++){let T1=sum32_5(h,s1_256(e2),ch32(e2,f,g),k[i2],W[i2]),T2=sum32(s0_256(a),maj32(a,b,c2));h=g,g=f,f=e2,e2=sum32(d,T1),d=c2,c2=b,b=a,a=sum32(T1,T2)}return state[0]=sum32(state[0],a),state[1]=sum32(state[1],b),state[2]=sum32(state[2],c2),state[3]=sum32(state[3],d),state[4]=sum32(state[4],e2),state[5]=sum32(state[5],f),state[6]=sum32(state[6],g),state[7]=sum32(state[7],h),state}__name(sha256Compression,"sha256Compression");function rotr32(w,b){return w>>>b|w<<32-b}__name(rotr32,"rotr32");function sum32(a,b){return a+b>>>0}__name(sum32,"sum32");function sum32_4(a,b,c2,d){return a+b+c2+d>>>0}__name(sum32_4,"sum32_4");function sum32_5(a,b,c2,d,e2){return a+b+c2+d+e2>>>0}__name(sum32_5,"sum32_5");function ch32(x,y,z2){return x&y^~x&z2}__name(ch32,"ch32");function maj32(x,y,z2){return x&y^x&z2^y&z2}__name(maj32,"maj32");function s0_256(x){return rotr32(x,2)^rotr32(x,13)^rotr32(x,22)}__name(s0_256,"s0_256");function s1_256(x){return rotr32(x,6)^rotr32(x,11)^rotr32(x,25)}__name(s1_256,"s1_256");function g0_256(x){return rotr32(x,7)^rotr32(x,18)^x>>>3}__name(g0_256,"g0_256");function g1_256(x){return rotr32(x,17)^rotr32(x,19)^x>>>10}__name(g1_256,"g1_256");function computeMerkleHash(left,right){return poseidon2HashWithSeparator([left,right],DomainSeparator.MERKLE_HASH)}__name(computeMerkleHash,"computeMerkleHash");async function hashVK(keyAsFields){return await poseidon2Hash(keyAsFields)}__name(hashVK,"hashVK");function computeNoteHashNonce(nullifierZero,noteHashIndex){return poseidon2HashWithSeparator([nullifierZero,noteHashIndex],DomainSeparator.NOTE_HASH_NONCE)}__name(computeNoteHashNonce,"computeNoteHashNonce");function siloNoteHash(contract,noteHash){return poseidon2HashWithSeparator([contract,noteHash],DomainSeparator.SILOED_NOTE_HASH)}__name(siloNoteHash,"siloNoteHash");function computeUniqueNoteHash(noteNonce,siloedNoteHash){return poseidon2HashWithSeparator([noteNonce,siloedNoteHash],DomainSeparator.UNIQUE_NOTE_HASH)}__name(computeUniqueNoteHash,"computeUniqueNoteHash");function siloNullifier(contract,innerNullifier){return poseidon2HashWithSeparator([contract,innerNullifier],DomainSeparator.SILOED_NULLIFIER)}__name(siloNullifier,"siloNullifier");function computeProtocolNullifier(txRequestHash){return siloNullifier(AztecAddress.NULL_MSG_SENDER,txRequestHash)}__name(computeProtocolNullifier,"computeProtocolNullifier");function computeLogTag(rawTag,domSep){return poseidon2HashWithSeparator([new Fr(rawTag)],domSep)}__name(computeLogTag,"computeLogTag");function computePrivateEventCommitment(randomness,eventSelector,content){return poseidon2HashWithSeparator([randomness,eventSelector,...content],DomainSeparator.EVENT_COMMITMENT)}__name(computePrivateEventCommitment,"computePrivateEventCommitment");function computeSiloedPrivateLogFirstField(contract,field){return poseidon2HashWithSeparator([contract,field],DomainSeparator.PRIVATE_LOG_FIRST_FIELD)}__name(computeSiloedPrivateLogFirstField,"computeSiloedPrivateLogFirstField");function computePublicDataTreeLeafSlot(contractAddress,storageSlot){return poseidon2HashWithSeparator([contractAddress,storageSlot],DomainSeparator.PUBLIC_LEAF_SLOT)}__name(computePublicDataTreeLeafSlot,"computePublicDataTreeLeafSlot");function computeVarArgsHash(args){return args.length===0?Promise.resolve(Fr.ZERO):poseidon2HashWithSeparator(args,DomainSeparator.FUNCTION_ARGS)}__name(computeVarArgsHash,"computeVarArgsHash");function computeCalldataHash(calldata){return poseidon2HashWithSeparator(calldata,DomainSeparator.PUBLIC_CALLDATA)}__name(computeCalldataHash,"computeCalldataHash");function computeL2ToL1MessageHash({l2Sender,l1Recipient,content,rollupVersion,chainId}){return sha256ToField([l2Sender,rollupVersion,l1Recipient,chainId,content])}__name(computeL2ToL1MessageHash,"computeL2ToL1MessageHash");function deriveStorageSlotInMap(mapSlot,key){return poseidon2HashWithSeparator([mapSlot,key.toField()],DomainSeparator.PUBLIC_STORAGE_MAP_SLOT)}__name(deriveStorageSlotInMap,"deriveStorageSlotInMap");var _computedKey21,_computedKey111;_computedKey21=inspect21.custom;var PublicCallRequest=class _PublicCallRequest{static{__name(this,"PublicCallRequest")}msgSender;contractAddress;isStaticCall;calldataHash;constructor(msgSender,contractAddress,isStaticCall,calldataHash){this.msgSender=msgSender,this.contractAddress=contractAddress,this.isStaticCall=isStaticCall,this.calldataHash=calldataHash}static get schema(){return external_exports.object({msgSender:AztecAddress.schema,contractAddress:AztecAddress.schema,isStaticCall:external_exports.boolean(),calldataHash:schemas.Fr}).transform(({msgSender,contractAddress,isStaticCall,calldataHash})=>new _PublicCallRequest(msgSender,contractAddress,isStaticCall,calldataHash))}getSize(){return this.isEmpty()?0:this.toBuffer().length}static from(fields){return new _PublicCallRequest(..._PublicCallRequest.getFields(fields))}static getFields(fields){return[fields.msgSender,fields.contractAddress,fields.isStaticCall,fields.calldataHash]}static fromFields(fields){let reader=FieldReader.asReader(fields);return new _PublicCallRequest(reader.readObject(AztecAddress),reader.readObject(AztecAddress),reader.readBoolean(),reader.readField())}toFields(){let fields=serializeToFields(..._PublicCallRequest.getFields(this));if(fields.length!==4)throw new Error(`Invalid number of fields for PublicCallRequest. Expected ${4}, got ${fields.length}`);return fields}static fromBuffer(buffer){let reader=BufferReader.asReader(buffer);return new _PublicCallRequest(reader.readObject(AztecAddress),reader.readObject(AztecAddress),reader.readBoolean(),reader.readObject(Fr))}toBuffer(sink){if(!sink)return BufferSink.serialize(this);serializeToSink(sink,..._PublicCallRequest.getFields(this))}static empty(){return new _PublicCallRequest(AztecAddress.ZERO,AztecAddress.ZERO,!1,Fr.ZERO)}static fromPlainObject(obj){return new _PublicCallRequest(AztecAddress.fromPlainObject(obj.msgSender),AztecAddress.fromPlainObject(obj.contractAddress),obj.isStaticCall,Fr.fromPlainObject(obj.calldataHash))}isEmpty(){return this.msgSender.isZero()&&this.contractAddress.isZero()&&!this.isStaticCall&&this.calldataHash.isEmpty()}[_computedKey21](){return`PublicCallRequest {
|
|
130
130
|
msgSender: ${this.msgSender}
|
|
131
131
|
contractAddress: ${this.contractAddress}
|
|
132
132
|
isStaticCall: ${this.isStaticCall}
|
|
@@ -207,9 +207,9 @@ 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,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}.
|
|
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())}};function computeFeeJuiceMessageNullifier(messageHash,secret){return poseidon2HashWithSeparator([messageHash,secret],DomainSeparator.MESSAGE_NULLIFIER)}__name(computeFeeJuiceMessageNullifier,"computeFeeJuiceMessageNullifier");async function getL1ToL2MessageWitness(node,messageHash,unsiloedNullifier,referenceBlock="latest"){let l1ToL2ResponsePromise=node.getL1ToL2MessageMembershipWitness(referenceBlock,messageHash),nullifierResponsePromise=unsiloedNullifier?siloNullifier(unsiloedNullifier.contractAddress,unsiloedNullifier.nullifier).then(siloed=>node.findLeavesIndexes(referenceBlock,MerkleTreeId.NULLIFIER_TREE,[siloed])):void 0,l1ToL2Response=await l1ToL2ResponsePromise;if(!l1ToL2Response)throw new Error(`No L1 to L2 message found for message hash ${messageHash.toString()}`);if((await nullifierResponsePromise)?.[0]!==void 0)throw new Error(`No non-nullified L1 to L2 message found for message hash ${messageHash.toString()}`);return l1ToL2Response}__name(getL1ToL2MessageWitness,"getL1ToL2MessageWitness");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 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 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 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 assertAbsentSecret(kind,secret),{type:"non-interactive-handshake"};case INTERACTIVE_HANDSHAKE:return assertAbsentSecret(kind,secret),{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 assertAbsentSecret(kind,secret){if(!secret.isZero())throw new Error(`Resolved tagging strategy ${kind} must not include a secret`)}__name(assertAbsentSecret,"assertAbsentSecret");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_getL1ToL2MembershipWitness:{modernOracle:"aztec_utl_getL1ToL2MembershipWitnessV2",params:{legacyType:[{name:"contractAddress",type:AZTEC_ADDRESS},{name:"messageHash",type:FIELD},{name:"secret",type:FIELD}],mapping:__name(async([contractAddress,messageHash,secret])=>[messageHash,Option.some({contractAddress,nullifier:await computeFeeJuiceMessageNullifier(messageHash,secret)})],"mapping")}},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_getL1ToL2MembershipWitnessV2:makeEntry({params:[{name:"messageHash",type:FIELD},{name:"nullifier",type:OPTION(STRUCT([{name:"contractAddress",type:AZTEC_ADDRESS},{name:"nullifier",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?await 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>6?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}.${6}. 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}.${6}), 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 DEFAULT_TAGGING_SECRET_STRATEGY={type:"non-interactive-handshake"};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,INTERACTIVE_HANDSHAKE_REQUEST_KIND=sha256ToField([Buffer.from("HANDSHAKE_REGISTRY::INTERACTIVE_HANDSHAKE_REQUEST")]);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 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(...).
|
|
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 getL1ToL2MembershipWitnessV2(messageHash,nullifier){let[messageIndex,siblingPath]=await getL1ToL2MessageWitness(this.aztecNode,messageHash,nullifier.value,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 DEFAULT_TAGGING_SECRET_STRATEGY;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
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)
|
|
@@ -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,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};
|
|
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 makeResolveTaggingSecretStrategyHook(strategies){if(strategies.size!==0)return({deliveryMode})=>Promise.resolve(strategies.get(deliveryMode)??DEFAULT_TAGGING_SECRET_STRATEGY)}__name(makeResolveTaggingSecretStrategyHook,"makeResolveTaggingSecretStrategyHook");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_setTaggingSecretStrategies:makeEntry({params:[{name:"unconstrainedStrategy",type:OPTION(TAGGING_SECRET_STRATEGY)},{name:"constrainedStrategy",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,taggingSecretStrategies,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.taggingSecretStrategies=taggingSecretStrategies;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)}setTaggingSecretStrategies(unconstrainedStrategy,constrainedStrategy){let apply=__name((mode,strategy)=>{strategy.isSome()?this.taggingSecretStrategies.set(mode,strategy.value):this.taggingSecretStrategies.delete(mode)},"apply");apply(AppTaggingSecretKind.UNCONSTRAINED,unconstrainedStrategy),apply(AppTaggingSecretKind.CONSTRAINED,constrainedStrategy)}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,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:makeResolveTaggingSecretStrategyHook(this.taggingSecretStrategies)}),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.taggingSecretStrategies]}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_setTaggingSecretStrategies(...inputs){return callTxeHandler({oracle:"aztec_txe_setTaggingSecretStrategies",inputs,handler:__name(([unconstrainedStrategy,constrainedStrategy])=>this.handlerAsTxe().setTaggingSecretStrategies(unconstrainedStrategy,constrainedStrategy),"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_getL1ToL2MembershipWitnessV2(...inputs){return callTxeHandler({oracle:"aztec_utl_getL1ToL2MembershipWitnessV2",inputs,handler:__name(([messageHash,nullifier])=>this.handlerAsUtility().getL1ToL2MembershipWitnessV2(messageHash,nullifier),"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;taggingSecretStrategies=new Map;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,new Map,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>0?versionHint=` The test uses Aztec.nr test oracle version ${this.txeOracleVersion.major}.${this.txeOracleVersion.minor}, but this test environment only supports up to ${3}.${0}. 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 (${3}.${0}), 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!==3){let hint=major2>3?"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 ${3}, 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.taggingSecretStrategies,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);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:makeResolveTaggingSecretStrategyHook(this.taggingSecretStrategies)}),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.taggingSecretStrategies]=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};
|