@aztec/txe 5.1.0 → 5.2.0-nightly.20260724
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/bin/index.js +1 -1
- package/dest/{chunk-PUJMQKDX.js → chunk-FUJ7SFX4.js} +2 -2
- package/dest/{chunk-PUJMQKDX.js.map → chunk-FUJ7SFX4.js.map} +2 -2
- package/dest/{chunk-NP3YMCNL.js → chunk-JOGDJDWJ.js} +1 -1
- package/dest/{chunk-NP3YMCNL.js.map → chunk-JOGDJDWJ.js.map} +3 -3
- package/dest/metafile.json +21 -21
- package/dest/server.bundle.js +1 -1
- package/dest/worker.bundle.js +1 -1
- package/package.json +17 -17
|
@@ -207,7 +207,7 @@ 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;txRequestSalt;constructor(callContext,anchorBlockHeader,txContext,startSideEffectCounter,txRequestSalt){this.callContext=callContext,this.anchorBlockHeader=anchorBlockHeader,this.txContext=txContext,this.startSideEffectCounter=startSideEffectCounter,this.txRequestSalt=txRequestSalt}static empty(){return new _PrivateContextInputs(CallContext.empty(),BlockHeader.empty(),TxContext.empty(),0,Fr.ZERO)}toFields(){return serializeToFields([this.callContext,this.anchorBlockHeader,this.txContext,this.startSideEffectCounter,this.txRequestSalt])}};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 originBlockStateFromNumber(value){if(!(value in OriginBlockState)){let validNames=Object.keys(OriginBlockState).filter(k=>isNaN(Number(k)));throw new Error(`Invalid OriginBlockState value ${value}, expected one of ${validNames.join(", ")}`)}return value}__name(originBlockStateFromNumber,"originBlockStateFromNumber");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;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 nonceGenerator=this.protocolNullifier,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}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(){return[this.protocolNullifier,...this.getEmittedNullifiers()]}getNonceGenerator(){return this.protocolNullifier}#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");function LEAF(mapping){return{...mapping,label:mapping.kind}}__name(LEAF,"LEAF");function SCALAR(mapping){return LEAF({...mapping,shape:["scalar"]})}__name(SCALAR,"SCALAR");var FIELD=SCALAR({kind:"field",serialization:{fn:__name(v=>[v],"fn")},deserialization:{fn:__name(([reader])=>reader.readField(),"fn")}}),BOOL=SCALAR({kind:"bool",serialization:{fn:__name(v=>[new Fr(v?1n:0n)],"fn")},deserialization:{fn:__name(([reader])=>!reader.readField().isZero(),"fn")}}),U32=SCALAR({kind:"u32",serialization:{fn:__name(v=>[new Fr(v)],"fn")},deserialization:{fn:__name(([reader])=>Number(uintFromField(reader.readField(),32)),"fn")}}),BLOCK_NUMBER=ALIAS(U32,{wrap:__name(v=>BlockNumber(v),"wrap"),unwrap:__name(v=>v,"unwrap")}),U8=SCALAR({kind:"u8",serialization:{fn:__name(byte=>[new Fr(byte)],"fn")},deserialization:{fn:__name(([reader])=>Number(uintFromField(reader.readField(),8)),"fn")}}),DELIVERY_MODE=SCALAR({kind:"onchain-delivery-mode",deserialization:{fn:__name(readers=>appTaggingSecretKindFromDeliveryMode(U8.deserialization.fn(readers)),"fn")}}),RESOLVED_TAGGING_STRATEGY=LEAF({kind:"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=ALIAS(FIELD,{wrap:__name(f=>f.toBigInt(),"wrap"),unwrap:__name(v=>new Fr(v),"unwrap")}),U64=SCALAR({kind:"u64",serialization:{fn:__name(v=>[new Fr(v)],"fn")},deserialization:{fn:__name(([reader])=>uintFromField(reader.readField(),64),"fn")}}),U128=SCALAR({kind:"u128",serialization:{fn:__name(v=>[new Fr(v)],"fn")},deserialization:{fn:__name(([reader])=>uintFromField(reader.readField(),128),"fn")}}),LEAF_INDEX=ALIAS(FIELD,{wrap:__name(f=>f.toNumber(),"wrap"),unwrap:__name(v=>new Fr(v),"unwrap")}),STR=LEAF({kind:"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=SCALAR({kind:"aztec-address",serialization:{fn:__name(v=>[v.toField()],"fn")},deserialization:{fn:__name(([reader])=>AztecAddress.fromFieldUnsafe(reader.readField()),"fn")}}),BLOCK_HASH=ALIAS(FIELD,{wrap:__name(f=>new BlockHash(f),"wrap"),unwrap:__name(v=>new Fr(v.toBuffer()),"unwrap")}),FUNCTION_SELECTOR=SCALAR({kind:"function-selector",serialization:{fn:__name(v=>[v.toField()],"fn")},deserialization:{fn:__name(([reader])=>FunctionSelector.fromField(reader.readField()),"fn")}}),NOTE_SELECTOR=ALIAS(FIELD,{wrap:__name(f=>NoteSelector.fromField(f),"wrap"),unwrap:__name(v=>v.toField(),"unwrap")}),TX_HASH=ALIAS(FIELD,{wrap:__name(f=>TxHash.fromField(f),"wrap"),unwrap:__name(v=>v.hash,"unwrap")}),TAG=ALIAS(FIELD,{wrap:__name(f=>new Tag(f),"wrap"),unwrap:__name(v=>v.value,"unwrap")}),POINT=STRUCT([{name:"x",type:FIELD},{name:"y",type:FIELD}]),LOG_SOURCE=SCALAR({kind:"log-source",serialization:{fn:__name(v=>[new Fr(v)],"fn")},deserialization:{fn:__name(([reader])=>logSourceFromField(reader.readField()),"fn")}}),ETH_ADDRESS=SCALAR({kind:"eth-address",serialization:{fn:__name(v=>[v.toField()],"fn")},deserialization:{fn:__name(([reader])=>EthAddress.fromField(reader.readField()),"fn")}}),SLOT_NUMBER=ALIAS(FIELD,{unwrap:__name(v=>new Fr(v),"unwrap")}),APPEND_ONLY_TREE_SNAPSHOT=STRUCT([{name:"root",type:FIELD},{name:"nextAvailableLeafIndex",type:LEAF_INDEX}]),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:U128},{name:"feePerL2Gas",type:U128}]),GLOBAL_VARIABLES=STRUCT([{name:"chainId",type:FIELD},{name:"version",type:FIELD},{name:"blockNumber",type:BLOCK_NUMBER},{name:"slotNumber",type:SLOT_NUMBER},{name:"timestamp",type:U64},{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}]),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:U8},{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=LEAF({kind:"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=LEAF({kind:"note-validation-request",deserialization:{fn:__name(([reader])=>NoteValidationRequest.fromFields(reader),"fn")},shape:["variable"]}),EVENT_VALIDATION_REQUEST=LEAF({kind:"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:U64},{name:"blockHash",type:BLOCK_HASH}]),RESOLVED_TX=STRUCT([{name:"txHash",type:TX_HASH},{name:"uniqueNoteHashesInTx",type:FIXED_BOUNDED_VEC(FIELD,64)},{name:"firstNullifierInTx",type:FIELD},{name:"blockNumber",type:U32},{name:"blockHash",type:FIELD}]),PENDING_TAGGED_LOG=STRUCT([{name:"log",type:FIXED_BOUNDED_VEC(FIELD,16)},{name:"context",type:RESOLVED_TX}]),ORIGIN_BLOCK=STRUCT([{name:"blockNumber",type:U32},{name:"blockHash",type:FIELD}]),ORIGIN_BLOCK_STATE=SCALAR({kind:"origin-block-state",serialization:{fn:__name(v=>[new Fr(v)],"fn")},deserialization:{fn:__name(([reader])=>originBlockStateFromNumber(reader.readField().toNumber()),"fn")}}),RETRACTABLE_FACT_ORIGIN=STRUCT([{name:"blockNumber",type:U32},{name:"blockHash",type:FIELD},{name:"blockState",type:ORIGIN_BLOCK_STATE}]),FACT=STRUCT([{name:"factTypeId",type:FIELD},{name:"payload",type:EPHEMERAL_ARRAY(FIELD)},{name:"originBlock",type:OPTION(RETRACTABLE_FACT_ORIGIN)}]),FACT_COLLECTION=STRUCT([{name:"contractAddress",type:AZTEC_ADDRESS},{name:"scope",type:AZTEC_ADDRESS},{name:"factCollectionTypeId",type:FIELD},{name:"factCollectionId",type:FIELD},{name:"facts",type:EPHEMERAL_ARRAY(FACT)}]),PROVIDED_SECRET=STRUCT([{name:"secret",type:FIELD},{name:"mode",type:DELIVERY_MODE}]);function ALIAS(base,conversions){let{wrap,unwrap}=conversions;return{kind:base.kind,label:base.label,serialization:base.serialization&&unwrap?{fn:__name(value=>base.serialization.fn(unwrap(value)),"fn")}:void 0,deserialization:base.deserialization&&wrap?{fn:__name(readers=>wrap(base.deserialization.fn(readers)),"fn")}:void 0,shape:base.shape}}__name(ALIAS,"ALIAS");function SIBLING_PATH(height){return LEAF({kind:`array(field,${height})`,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",label:`array(${inner.label})`,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",label:`array(${element.label},${length})`,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",label:`bounded-vec(${inner.label})`,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",label:`bounded-vec(${element.label},${maxLength})`,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",label:`option(${inner.label})`,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 EPHEMERAL_ARRAY(element){let rowElement=element.deserialization?{kind:element.kind,label:element.label,deserialization:{fn:__name(([rowReader])=>deserializeElement(element,rowReader.readFieldArray(rowReader.remainingFields())),"fn")},shape:["variable"]}:void 0;return{kind:"ephemeral-array",label:`ephemeral-array(${element.label})`,inner:element,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",label:`{${structFieldLabels(fields)}}`,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 isStructMapping(type){return type.kind==="struct"}__name(isStructMapping,"isStructMapping");function structFieldLabels(fields){return fields.map(f=>isStructMapping(f.type)?structFieldLabels(f.type.fields):f.type.label).join(",")}__name(structFieldLabels,"structFieldLabels");function uintFromField(field,bits){let max=2n**BigInt(bits)-1n,value=field.toBigInt();if(value>max)throw new Error(`u${bits} overflow: value ${value} exceeds max (${max})`);return value}__name(uintFromField,"uintFromField");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_areBlockHashesInArchive:makeEntry({params:[{name:"anchorBlockHash",type:BLOCK_HASH},{name:"blockHashes",type:EPHEMERAL_ARRAY(BLOCK_HASH)}],returnType:EPHEMERAL_ARRAY(BOOL)}),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_getTxEffects:makeEntry({params:[{name:"txHashes",type:EPHEMERAL_ARRAY(TX_HASH)}],returnType:EPHEMERAL_ARRAY(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(U8)},{name:"iv",type:FIXED_ARRAY(U8,16)},{name:"symKey",type:FIXED_ARRAY(U8,16)}],returnType:OPTION(BOUNDED_VEC(U8))}),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>8?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}.${8}. 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}.${8}), 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)+38,returnsSize=839,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.mergePendingIndexes(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 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 rangeKey=__name((fromBlock,toBlock)=>`${fromBlock??""}-${toBlock??""}`,"rangeKey"),LogService=class _LogService{static{__name(this,"LogService")}aztecNode;anchorBlockHeader;l2TipsStore;keyStore;recipientTaggingStore;taggingSecretSourcesStore;addressStore;scopes;jobId;log;constructor(aztecNode,anchorBlockHeader,l2TipsStore,keyStore,recipientTaggingStore,taggingSecretSourcesStore,addressStore,scopes,jobId,bindings){this.aztecNode=aztecNode,this.anchorBlockHeader=anchorBlockHeader,this.l2TipsStore=l2TipsStore,this.keyStore=keyStore,this.recipientTaggingStore=recipientTaggingStore,this.taggingSecretSourcesStore=taggingSecretSourcesStore,this.addressStore=addressStore,this.scopes=scopes,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){assertAllowedScope(recipient,this.scopes),this.log.verbose(`Fetching tagged logs for contract ${contractAddress.toString()} and recipient ${recipient.toString()}`);let l2Tips=await this.l2TipsStore.getL2Tips(),combinedSecrets=[...await this.#getPointDerivedSecrets(contractAddress,recipient),...providedSecrets],secrets=Array.from(new Map(combinedSecrets.map(secret=>[secret.toString(),secret])).values());return(await syncTaggedPrivateLogs(secrets,this.aztecNode,this.recipientTaggingStore,this.anchorBlockHeader,l2Tips.finalized.block.number,this.jobId)).map(log2=>{let noteHashes=log2.noteHashes,nullifiers=log2.nullifiers;if(nullifiers.length===0)throw new Error(`Log for tx ${log2.txHash} returned no nullifiers from the node`);return{log:log2.logData,context:{txHash:log2.txHash,uniqueNoteHashesInTx:noteHashes,firstNullifierInTx:nullifiers[0],blockNumber:log2.blockNumber,blockHash: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 AztecNodeReadCache=class{static{__name(this,"AztecNodeReadCache")}aztecNode;cache;constructor(aztecNode){this.aztecNode=aztecNode,this.cache=new Map}getBlock(block){return this.#cachedRead(`block:${this.#keyPart(block)}`,()=>this.aztecNode.getBlock(block))}getTxReceiptWithEffect(txHash){return this.#cachedRead(`tx-receipt-with-effect:${txHash.toString()}`,()=>this.aztecNode.getTxReceipt(txHash,{includeTxEffect:!0}))}getBlockHashMembershipWitness(referenceBlock,blockHash){return this.#cachedRead(`block-hash-membership-witness:${this.#keyPart(referenceBlock)}:${blockHash.toString()}`,()=>this.aztecNode.getBlockHashMembershipWitness(referenceBlock,blockHash))}getPublicDataWitness(referenceBlock,leafSlot){return this.#cachedRead(`public-data-witness:${this.#keyPart(referenceBlock)}:${leafSlot.toString()}`,()=>this.aztecNode.getPublicDataWitness(referenceBlock,leafSlot))}getPublicStorageAt(referenceBlock,contractAddress,storageSlot){return this.#cachedRead(`public-storage:${this.#keyPart(referenceBlock)}:${contractAddress.toString()}:${storageSlot.toString()}`,()=>this.aztecNode.getPublicStorageAt(referenceBlock,contractAddress,storageSlot))}getPublicStorageRange(referenceBlock,contractAddress,startStorageSlot,numberOfElements){let slots=Array(numberOfElements).fill(0).map((_,i)=>new Fr(startStorageSlot.value+BigInt(i)));return Promise.all(slots.map(storageSlot=>this.getPublicStorageAt(referenceBlock,contractAddress,storageSlot)))}#cachedRead(key,fetch2){let cached2=this.cache.get(key);if(cached2)return cached2;let promise2=fetch2();return promise2.catch(()=>this.cache.delete(key)),this.cache.set(key,promise2),promise2}#keyPart(value){if(["string","number","bigint","boolean"].includes(typeof value))return String(value);if(value&&typeof value=="object"){let toString=value.toString;return toString&&toString!==Object.prototype.toString?toString.call(value):JSON.stringify(value,(_key,nested)=>typeof nested=="bigint"?nested.toString():nested)}return String(value)}};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;aztecNodeReadCache;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,this.aztecNodeReadCache=new AztecNodeReadCache(args.aztecNode)}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.aztecNodeReadCache.getBlockHashMembershipWitness(referenceBlockHash,blockHash));return witness?Option.some(witness):Option.none()}async areBlockHashesInArchive(referenceBlockHash,blockHashes){let hashes=blockHashes.readAll(this.ephemeralArrayService),memberships=await this.#queryWithBlockHashNotAfterAnchor(referenceBlockHash,()=>Promise.all(hashes.map(blockHash=>this.aztecNodeReadCache.getBlockHashMembershipWitness(referenceBlockHash,blockHash).then(Boolean))));return EphemeralArray.fromValues(this.ephemeralArrayService,memberships)}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.aztecNodeReadCache.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;txRequestSalt;constructor(callContext,anchorBlockHeader,txContext,startSideEffectCounter,txRequestSalt){this.callContext=callContext,this.anchorBlockHeader=anchorBlockHeader,this.txContext=txContext,this.startSideEffectCounter=startSideEffectCounter,this.txRequestSalt=txRequestSalt}static empty(){return new _PrivateContextInputs(CallContext.empty(),BlockHeader.empty(),TxContext.empty(),0,Fr.ZERO)}toFields(){return serializeToFields([this.callContext,this.anchorBlockHeader,this.txContext,this.startSideEffectCounter,this.txRequestSalt])}};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 originBlockStateFromNumber(value){if(!(value in OriginBlockState)){let validNames=Object.keys(OriginBlockState).filter(k=>isNaN(Number(k)));throw new Error(`Invalid OriginBlockState value ${value}, expected one of ${validNames.join(", ")}`)}return value}__name(originBlockStateFromNumber,"originBlockStateFromNumber");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;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 nonceGenerator=this.protocolNullifier,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}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(){return[this.protocolNullifier,...this.getEmittedNullifiers()]}getNonceGenerator(){return this.protocolNullifier}#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");function LEAF(mapping){return{...mapping,label:mapping.kind}}__name(LEAF,"LEAF");function SCALAR(mapping){return LEAF({...mapping,shape:["scalar"]})}__name(SCALAR,"SCALAR");var FIELD=SCALAR({kind:"field",serialization:{fn:__name(v=>[v],"fn")},deserialization:{fn:__name(([reader])=>reader.readField(),"fn")}}),BOOL=SCALAR({kind:"bool",serialization:{fn:__name(v=>[new Fr(v?1n:0n)],"fn")},deserialization:{fn:__name(([reader])=>!reader.readField().isZero(),"fn")}}),U32=SCALAR({kind:"u32",serialization:{fn:__name(v=>[new Fr(v)],"fn")},deserialization:{fn:__name(([reader])=>Number(uintFromField(reader.readField(),32)),"fn")}}),BLOCK_NUMBER=ALIAS(U32,{wrap:__name(v=>BlockNumber(v),"wrap"),unwrap:__name(v=>v,"unwrap")}),U8=SCALAR({kind:"u8",serialization:{fn:__name(byte=>[new Fr(byte)],"fn")},deserialization:{fn:__name(([reader])=>Number(uintFromField(reader.readField(),8)),"fn")}}),DELIVERY_MODE=SCALAR({kind:"onchain-delivery-mode",deserialization:{fn:__name(readers=>appTaggingSecretKindFromDeliveryMode(U8.deserialization.fn(readers)),"fn")}}),RESOLVED_TAGGING_STRATEGY=LEAF({kind:"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=ALIAS(FIELD,{wrap:__name(f=>f.toBigInt(),"wrap"),unwrap:__name(v=>new Fr(v),"unwrap")}),U64=SCALAR({kind:"u64",serialization:{fn:__name(v=>[new Fr(v)],"fn")},deserialization:{fn:__name(([reader])=>uintFromField(reader.readField(),64),"fn")}}),U128=SCALAR({kind:"u128",serialization:{fn:__name(v=>[new Fr(v)],"fn")},deserialization:{fn:__name(([reader])=>uintFromField(reader.readField(),128),"fn")}}),LEAF_INDEX=ALIAS(FIELD,{wrap:__name(f=>f.toNumber(),"wrap"),unwrap:__name(v=>new Fr(v),"unwrap")}),STR=LEAF({kind:"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=SCALAR({kind:"aztec-address",serialization:{fn:__name(v=>[v.toField()],"fn")},deserialization:{fn:__name(([reader])=>AztecAddress.fromFieldUnsafe(reader.readField()),"fn")}}),BLOCK_HASH=ALIAS(FIELD,{wrap:__name(f=>new BlockHash(f),"wrap"),unwrap:__name(v=>new Fr(v.toBuffer()),"unwrap")}),FUNCTION_SELECTOR=SCALAR({kind:"function-selector",serialization:{fn:__name(v=>[v.toField()],"fn")},deserialization:{fn:__name(([reader])=>FunctionSelector.fromField(reader.readField()),"fn")}}),NOTE_SELECTOR=ALIAS(FIELD,{wrap:__name(f=>NoteSelector.fromField(f),"wrap"),unwrap:__name(v=>v.toField(),"unwrap")}),TX_HASH=ALIAS(FIELD,{wrap:__name(f=>TxHash.fromField(f),"wrap"),unwrap:__name(v=>v.hash,"unwrap")}),TAG=ALIAS(FIELD,{wrap:__name(f=>new Tag(f),"wrap"),unwrap:__name(v=>v.value,"unwrap")}),POINT=STRUCT([{name:"x",type:FIELD},{name:"y",type:FIELD}]),LOG_SOURCE=SCALAR({kind:"log-source",serialization:{fn:__name(v=>[new Fr(v)],"fn")},deserialization:{fn:__name(([reader])=>logSourceFromField(reader.readField()),"fn")}}),ETH_ADDRESS=SCALAR({kind:"eth-address",serialization:{fn:__name(v=>[v.toField()],"fn")},deserialization:{fn:__name(([reader])=>EthAddress.fromField(reader.readField()),"fn")}}),SLOT_NUMBER=ALIAS(FIELD,{unwrap:__name(v=>new Fr(v),"unwrap")}),APPEND_ONLY_TREE_SNAPSHOT=STRUCT([{name:"root",type:FIELD},{name:"nextAvailableLeafIndex",type:LEAF_INDEX}]),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:U128},{name:"feePerL2Gas",type:U128}]),GLOBAL_VARIABLES=STRUCT([{name:"chainId",type:FIELD},{name:"version",type:FIELD},{name:"blockNumber",type:BLOCK_NUMBER},{name:"slotNumber",type:SLOT_NUMBER},{name:"timestamp",type:U64},{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}]),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:U8},{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=LEAF({kind:"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=LEAF({kind:"note-validation-request",deserialization:{fn:__name(([reader])=>NoteValidationRequest.fromFields(reader),"fn")},shape:["variable"]}),EVENT_VALIDATION_REQUEST=LEAF({kind:"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:U64},{name:"blockHash",type:BLOCK_HASH}]),RESOLVED_TX=STRUCT([{name:"txHash",type:TX_HASH},{name:"uniqueNoteHashesInTx",type:FIXED_BOUNDED_VEC(FIELD,64)},{name:"firstNullifierInTx",type:FIELD},{name:"blockNumber",type:U32},{name:"blockHash",type:FIELD}]),PENDING_TAGGED_LOG=STRUCT([{name:"log",type:FIXED_BOUNDED_VEC(FIELD,16)},{name:"context",type:RESOLVED_TX}]),ORIGIN_BLOCK=STRUCT([{name:"blockNumber",type:U32},{name:"blockHash",type:FIELD}]),ORIGIN_BLOCK_STATE=SCALAR({kind:"origin-block-state",serialization:{fn:__name(v=>[new Fr(v)],"fn")},deserialization:{fn:__name(([reader])=>originBlockStateFromNumber(reader.readField().toNumber()),"fn")}}),RETRACTABLE_FACT_ORIGIN=STRUCT([{name:"blockNumber",type:U32},{name:"blockHash",type:FIELD},{name:"blockState",type:ORIGIN_BLOCK_STATE}]),FACT=STRUCT([{name:"factTypeId",type:FIELD},{name:"payload",type:EPHEMERAL_ARRAY(FIELD)},{name:"originBlock",type:OPTION(RETRACTABLE_FACT_ORIGIN)}]),FACT_COLLECTION=STRUCT([{name:"contractAddress",type:AZTEC_ADDRESS},{name:"scope",type:AZTEC_ADDRESS},{name:"factCollectionTypeId",type:FIELD},{name:"factCollectionId",type:FIELD},{name:"facts",type:EPHEMERAL_ARRAY(FACT)}]),PROVIDED_SECRET=STRUCT([{name:"secret",type:FIELD},{name:"mode",type:DELIVERY_MODE}]);function ALIAS(base,conversions){let{wrap,unwrap}=conversions;return{kind:base.kind,label:base.label,serialization:base.serialization&&unwrap?{fn:__name(value=>base.serialization.fn(unwrap(value)),"fn")}:void 0,deserialization:base.deserialization&&wrap?{fn:__name(readers=>wrap(base.deserialization.fn(readers)),"fn")}:void 0,shape:base.shape}}__name(ALIAS,"ALIAS");function SIBLING_PATH(height){return LEAF({kind:`array(field,${height})`,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",label:`array(${inner.label})`,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",label:`array(${element.label},${length})`,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",label:`bounded-vec(${inner.label})`,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",label:`bounded-vec(${element.label},${maxLength})`,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",label:`option(${inner.label})`,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 EPHEMERAL_ARRAY(element){let rowElement=element.deserialization?{kind:element.kind,label:element.label,deserialization:{fn:__name(([rowReader])=>deserializeElement(element,rowReader.readFieldArray(rowReader.remainingFields())),"fn")},shape:["variable"]}:void 0;return{kind:"ephemeral-array",label:`ephemeral-array(${element.label})`,inner:element,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",label:`{${structFieldLabels(fields)}}`,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 isStructMapping(type){return type.kind==="struct"}__name(isStructMapping,"isStructMapping");function structFieldLabels(fields){return fields.map(f=>isStructMapping(f.type)?structFieldLabels(f.type.fields):f.type.label).join(",")}__name(structFieldLabels,"structFieldLabels");function uintFromField(field,bits){let max=2n**BigInt(bits)-1n,value=field.toBigInt();if(value>max)throw new Error(`u${bits} overflow: value ${value} exceeds max (${max})`);return value}__name(uintFromField,"uintFromField");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_areBlockHashesInArchive:makeEntry({params:[{name:"anchorBlockHash",type:BLOCK_HASH},{name:"blockHashes",type:EPHEMERAL_ARRAY(BLOCK_HASH)}],returnType:EPHEMERAL_ARRAY(BOOL)}),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_getTxEffects:makeEntry({params:[{name:"txHashes",type:EPHEMERAL_ARRAY(TX_HASH)}],returnType:EPHEMERAL_ARRAY(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(U8)},{name:"iv",type:FIXED_ARRAY(U8,16)},{name:"symKey",type:FIXED_ARRAY(U8,16)}],returnType:OPTION(BOUNDED_VEC(U8))}),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>8?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}.${8}. 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}.${8}), 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)+38,returnsSize=839,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,INITIAL_CONSTRAINED_PROBE_LEN=2;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];if(logsFoundWithSecret.length!==0)return allLogs.push(...logsFoundWithSecret.map(({log:log2})=>log2)),pendingSecret.kind===AppTaggingSecretKind.CONSTRAINED?await processConstrainedResults(pendingSecret,logsFoundWithSecret,taggingStore,currentTimestamp,finalizedBlockNumber,jobId):await 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),boundEnd=(currentHighestFinalizedIndex??0)+UNFINALIZED_TAGGING_INDEXES_WINDOW_LEN+1;if(secret.kind===AppTaggingSecretKind.CONSTRAINED){let start2=currentHighestFinalizedIndex===void 0?0:currentHighestFinalizedIndex+1;return{kind:AppTaggingSecretKind.CONSTRAINED,secret,start:start2,end:Math.min(boundEnd,start2+INITIAL_CONSTRAINED_PROBE_LEN),boundEnd,probeLen:INITIAL_CONSTRAINED_PROBE_LEN}}let highestAgedIndex=await taggingStore.getHighestAgedIndex(secret,jobId),start=highestAgedIndex===void 0?0:highestAgedIndex+1;return{kind:AppTaggingSecretKind.UNCONSTRAINED,secret,start,end:boundEnd}}))}__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);highestFinalizedIndex!==void 0&&await taggingStore.updateHighestFinalizedIndex(pending.secret,highestFinalizedIndex,jobId);let probeFullyConsumed=firstMissingIndex>=pending.end,boundEnd=highestFinalizedIndex!==void 0?Math.max(pending.boundEnd,highestFinalizedIndex+UNFINALIZED_TAGGING_INDEXES_WINDOW_LEN+1):pending.boundEnd,nextProbeLen=Math.min(pending.probeLen*2,UNFINALIZED_TAGGING_INDEXES_WINDOW_LEN);if(probeFullyConsumed&&pending.end<boundEnd)return{kind:AppTaggingSecretKind.CONSTRAINED,secret:pending.secret,start:pending.end,end:Math.min(boundEnd,pending.end+nextProbeLen),boundEnd,probeLen:nextProbeLen}}__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)return;if(highestAgedIndex!==void 0&&highestAgedIndex>highestFinalizedIndex)throw new Error(`Highest aged index (${highestAgedIndex}) must not exceed highest finalized index (${highestFinalizedIndex})`);await taggingStore.updateHighestFinalizedIndex(pending.secret,highestFinalizedIndex,jobId);let end=highestFinalizedIndex+UNFINALIZED_TAGGING_INDEXES_WINDOW_LEN+1;return{kind:AppTaggingSecretKind.UNCONSTRAINED,secret:pending.secret,start:pending.end,end}}__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.mergePendingIndexes(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 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 rangeKey=__name((fromBlock,toBlock)=>`${fromBlock??""}-${toBlock??""}`,"rangeKey"),LogService=class _LogService{static{__name(this,"LogService")}aztecNode;anchorBlockHeader;l2TipsStore;keyStore;recipientTaggingStore;taggingSecretSourcesStore;addressStore;scopes;jobId;log;constructor(aztecNode,anchorBlockHeader,l2TipsStore,keyStore,recipientTaggingStore,taggingSecretSourcesStore,addressStore,scopes,jobId,bindings){this.aztecNode=aztecNode,this.anchorBlockHeader=anchorBlockHeader,this.l2TipsStore=l2TipsStore,this.keyStore=keyStore,this.recipientTaggingStore=recipientTaggingStore,this.taggingSecretSourcesStore=taggingSecretSourcesStore,this.addressStore=addressStore,this.scopes=scopes,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){assertAllowedScope(recipient,this.scopes),this.log.verbose(`Fetching tagged logs for contract ${contractAddress.toString()} and recipient ${recipient.toString()}`);let l2Tips=await this.l2TipsStore.getL2Tips(),combinedSecrets=[...await this.#getPointDerivedSecrets(contractAddress,recipient),...providedSecrets],secrets=Array.from(new Map(combinedSecrets.map(secret=>[secret.toString(),secret])).values());return(await syncTaggedPrivateLogs(secrets,this.aztecNode,this.recipientTaggingStore,this.anchorBlockHeader,l2Tips.finalized.block.number,this.jobId)).map(log2=>{let noteHashes=log2.noteHashes,nullifiers=log2.nullifiers;if(nullifiers.length===0)throw new Error(`Log for tx ${log2.txHash} returned no nullifiers from the node`);return{log:log2.logData,context:{txHash:log2.txHash,uniqueNoteHashesInTx:noteHashes,firstNullifierInTx:nullifiers[0],blockNumber:log2.blockNumber,blockHash: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 AztecNodeReadCache=class{static{__name(this,"AztecNodeReadCache")}aztecNode;cache;constructor(aztecNode){this.aztecNode=aztecNode,this.cache=new Map}getBlock(block){return this.#cachedRead(`block:${this.#keyPart(block)}`,()=>this.aztecNode.getBlock(block))}getTxReceiptWithEffect(txHash){return this.#cachedRead(`tx-receipt-with-effect:${txHash.toString()}`,()=>this.aztecNode.getTxReceipt(txHash,{includeTxEffect:!0}))}getBlockHashMembershipWitness(referenceBlock,blockHash){return this.#cachedRead(`block-hash-membership-witness:${this.#keyPart(referenceBlock)}:${blockHash.toString()}`,()=>this.aztecNode.getBlockHashMembershipWitness(referenceBlock,blockHash))}getPublicDataWitness(referenceBlock,leafSlot){return this.#cachedRead(`public-data-witness:${this.#keyPart(referenceBlock)}:${leafSlot.toString()}`,()=>this.aztecNode.getPublicDataWitness(referenceBlock,leafSlot))}getPublicStorageAt(referenceBlock,contractAddress,storageSlot){return this.#cachedRead(`public-storage:${this.#keyPart(referenceBlock)}:${contractAddress.toString()}:${storageSlot.toString()}`,()=>this.aztecNode.getPublicStorageAt(referenceBlock,contractAddress,storageSlot))}getPublicStorageRange(referenceBlock,contractAddress,startStorageSlot,numberOfElements){let slots=Array(numberOfElements).fill(0).map((_,i)=>new Fr(startStorageSlot.value+BigInt(i)));return Promise.all(slots.map(storageSlot=>this.getPublicStorageAt(referenceBlock,contractAddress,storageSlot)))}#cachedRead(key,fetch2){let cached2=this.cache.get(key);if(cached2)return cached2;let promise2=fetch2();return promise2.catch(()=>this.cache.delete(key)),this.cache.set(key,promise2),promise2}#keyPart(value){if(["string","number","bigint","boolean"].includes(typeof value))return String(value);if(value&&typeof value=="object"){let toString=value.toString;return toString&&toString!==Object.prototype.toString?toString.call(value):JSON.stringify(value,(_key,nested)=>typeof nested=="bigint"?nested.toString():nested)}return String(value)}};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;aztecNodeReadCache;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,this.aztecNodeReadCache=new AztecNodeReadCache(args.aztecNode)}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.aztecNodeReadCache.getBlockHashMembershipWitness(referenceBlockHash,blockHash));return witness?Option.some(witness):Option.none()}async areBlockHashesInArchive(referenceBlockHash,blockHashes){let hashes=blockHashes.readAll(this.ephemeralArrayService),memberships=await this.#queryWithBlockHashNotAfterAnchor(referenceBlockHash,()=>Promise.all(hashes.map(blockHash=>this.aztecNodeReadCache.getBlockHashMembershipWitness(referenceBlockHash,blockHash).then(Boolean))));return EphemeralArray.fromValues(this.ephemeralArrayService,memberships)}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.aztecNodeReadCache.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
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 values=await this.aztecNodeReadCache.getPublicStorageRange(blockHash,contractAddress,startStorageSlot,numberOfElements);return this.logger.debug(`Oracle storage read: start=${startStorageSlot.toString()} count=${numberOfElements} 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.scopes,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");return await this.#getTxEffectOption(txHash)}async getTxEffects(txHashes){let hashes=txHashes.readAll(this.ephemeralArrayService);if(hashes.find(txHash=>txHash.hash.isZero()))throw new Error("Invalid tx hash passed into aztec_utl_getTxEffects oracle handler");let uniqueTxHashes=uniqueBy(hashes,h=>h.toString()),options=await Promise.all(uniqueTxHashes.map(txHash=>this.#getTxEffectOption(txHash))),optionsByHash=new Map(uniqueTxHashes.map((txHash,i)=>[txHash.toString(),options[i]]));return EphemeralArray.fromValues(this.ephemeralArrayService,hashes.map(txHash=>optionsByHash.get(txHash.toString())))}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),Buffer.from(iv),Buffer.from(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}`);assertAllowedScope(address,this.scopes);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.aztecNodeReadCache.getTxReceiptWithEffect(h)));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#getTxEffectOption(txHash){let receipt=await this.aztecNodeReadCache.getTxReceiptWithEffect(txHash);return!receipt.isMined()||!receipt.txEffect||receipt.blockNumber>this.anchorBlockHeader.getBlockNumber()?Option.none():Option.some(this.#toTxEffectData(receipt.txEffect))}#toTxEffectData(txEffect){return{...txEffect,revertCode:txEffect.revertCode.getCode(),publicLogs:FlatPublicLogs.fromLogs(txEffect.publicLogs),contractClassLogs:txEffect.contractClassLogs.map(log2=>({contractAddress:log2.contractAddress,fields:log2.fields.toFields(),emittedLength:log2.emittedLength}))}}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.aztecNodeReadCache.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;txRequestSalt;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.txRequestSalt=args.txRequestSalt,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,this.txRequestSalt)}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!==38)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){assertAllowedScope(sender,this.scopes);let senderCompleteAddress=await this.getCompleteAddressOrFail(sender),senderIvsk=await this.keyStore.getMasterIncomingViewingSecretKey(sender),extendedSecret=await AppTaggingSecret.computeViaEcdh(senderCompleteAddress,senderIvsk,recipient,this.contractAddress,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#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,txRequestSalt:this.txRequestSalt,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.unshift(nonceGenerator),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,isPrivateOnlyTx&&(meteredDAFields+=2);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{txHash:data.txHash,uniqueNoteHashesInTx:data.noteHashes,firstNullifierInTx:data.nullifiers[0],blockNumber:txEffect.l2BlockNumber,blockHash: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){return this.#storePendingIndexes(ranges,txHash,jobId,!1)}mergePendingIndexes(ranges,txHash,jobId){return this.#storePendingIndexes(ranges,txHash,jobId,!0)}#storePendingIndexes(ranges,txHash,jobId,mergeExisting){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}.
|